petter2025 commited on
Commit
30bcdd5
·
1 Parent(s): ea4be14

Upload folder using huggingface_hub

Browse files
Files changed (1) hide show
  1. app/main.py +31 -28
app/main.py CHANGED
@@ -285,8 +285,8 @@ async def lifespan(app: FastAPI):
285
  # the health endpoint answers, the deploy succeeds, and API
286
  # requests get a clean 503 from enforce_quota until the database
287
  # is reachable -- at which point they recover with no redeploy.
288
- postgres_ready = tracker.warm_up()
289
- if not postgres_ready:
290
  logger.error(
291
  "Usage tracker started WITHOUT a Postgres connection: api_keys "
292
  "is unreachable, so API-key validation and quota enforcement "
@@ -302,7 +302,7 @@ async def lifespan(app: FastAPI):
302
  # kills the process -- reintroducing the crash loop the warm-up
303
  # above exists to prevent.
304
  api_keys_json = os.getenv("ARF_API_KEYS", "{}")
305
- if not postgres_ready and api_keys_json not in ("", "{}"):
306
  logger.warning(
307
  "Skipping ARF_API_KEYS seeding: Postgres is unreachable. "
308
  "Seeded keys will not exist until the database recovers "
@@ -311,38 +311,41 @@ async def lifespan(app: FastAPI):
311
  api_keys_json = "{}"
312
  try:
313
  api_keys = json.loads(api_keys_json)
314
- for key, tier_str in api_keys.items():
315
- try:
316
- tier = Tier(tier_str.lower())
317
- # Previously called get_or_create_api_key(key, tier)
318
- # -- tier was silently accepted as tenant_id, so
319
- # every seeded key of the same tier collided onto
320
- # one bogus tenant_id. These are demo/env-seeded
321
- # keys with no real TenantDB row, but each still
322
- # needs its own tenant_id to avoid cross-key
323
- # contamination in tenant-scoped state elsewhere
324
- # (BetaStateDB, IntentDB, decision audit log). A
325
- # fixed-length key prefix isn't safe here: keys
326
- # generated elsewhere in this codebase share an
327
- # 8-char prefix ("sk_live_"/"sk_free_"), so a
328
- # prefix-based id would collide the same way the
329
- # original bug did. Hash the whole key instead.
330
- tenant_id = "env-seed-" + hashlib.sha256(key.encode()).hexdigest()[:16]
331
- tracker.get_or_create_api_key(key, tenant_id=tenant_id, tier=tier)
332
- logger.info(f"Seeded API key for tier {tier.value}")
333
- except ValueError:
334
- logger.warning(
335
- f"Invalid tier '{tier_str}' for key {key}, skipping"
336
- )
 
337
  except json.JSONDecodeError:
338
  logger.warning(
339
  "ARF_API_KEYS environment variable is not valid JSON; skipping seeding."
340
  )
341
  app.state.usage_tracker = tracker
342
- if postgres_ready:
343
  logger.info("✅ Usage tracker ready.")
344
- else:
345
  logger.warning("⚠️ Usage tracker started in degraded mode (no Postgres).")
 
 
346
  except Exception as e:
347
  # Still fail closed on genuine configuration errors -- a missing
348
  # or too-short ARF_KEY_PEPPER, an unset DATABASE_URL. Those never
 
285
  # the health endpoint answers, the deploy succeeds, and API
286
  # requests get a clean 503 from enforce_quota until the database
287
  # is reachable -- at which point they recover with no redeploy.
288
+ postgres_ready = tracker.warm_up() if tracker else False
289
+ if tracker and not postgres_ready:
290
  logger.error(
291
  "Usage tracker started WITHOUT a Postgres connection: api_keys "
292
  "is unreachable, so API-key validation and quota enforcement "
 
302
  # kills the process -- reintroducing the crash loop the warm-up
303
  # above exists to prevent.
304
  api_keys_json = os.getenv("ARF_API_KEYS", "{}")
305
+ if tracker and not postgres_ready and api_keys_json not in ("", "{}"):
306
  logger.warning(
307
  "Skipping ARF_API_KEYS seeding: Postgres is unreachable. "
308
  "Seeded keys will not exist until the database recovers "
 
311
  api_keys_json = "{}"
312
  try:
313
  api_keys = json.loads(api_keys_json)
314
+ if tracker:
315
+ for key, tier_str in api_keys.items():
316
+ try:
317
+ tier = Tier(tier_str.lower())
318
+ # Previously called get_or_create_api_key(key, tier)
319
+ # -- tier was silently accepted as tenant_id, so
320
+ # every seeded key of the same tier collided onto
321
+ # one bogus tenant_id. These are demo/env-seeded
322
+ # keys with no real TenantDB row, but each still
323
+ # needs its own tenant_id to avoid cross-key
324
+ # contamination in tenant-scoped state elsewhere
325
+ # (BetaStateDB, IntentDB, decision audit log). A
326
+ # fixed-length key prefix isn't safe here: keys
327
+ # generated elsewhere in this codebase share an
328
+ # 8-char prefix ("sk_live_"/"sk_free_"), so a
329
+ # prefix-based id would collide the same way the
330
+ # original bug did. Hash the whole key instead.
331
+ tenant_id = "env-seed-" + hashlib.sha256(key.encode()).hexdigest()[:16]
332
+ tracker.get_or_create_api_key(key, tenant_id=tenant_id, tier=tier)
333
+ logger.info(f"Seeded API key for tier {tier.value}")
334
+ except ValueError:
335
+ logger.warning(
336
+ f"Invalid tier '{tier_str}' for key {key}, skipping"
337
+ )
338
  except json.JSONDecodeError:
339
  logger.warning(
340
  "ARF_API_KEYS environment variable is not valid JSON; skipping seeding."
341
  )
342
  app.state.usage_tracker = tracker
343
+ if tracker and postgres_ready:
344
  logger.info("✅ Usage tracker ready.")
345
+ elif tracker:
346
  logger.warning("⚠️ Usage tracker started in degraded mode (no Postgres).")
347
+ else:
348
+ logger.error("❌ Usage tracker is None; API-key validation and quota enforcement will not work.")
349
  except Exception as e:
350
  # Still fail closed on genuine configuration errors -- a missing
351
  # or too-short ARF_KEY_PEPPER, an unset DATABASE_URL. Those never