fsanyoto commited on
Commit
51693ae
Β·
verified Β·
1 Parent(s): 9486685

Deploy AIOS web (React glide grid + FastAPI slice)

Browse files
Files changed (4) hide show
  1. RELEASES.json +1 -1
  2. VERSION +1 -1
  3. api/main.py +6 -2
  4. platform/harness/meta_store.py +74 -14
RELEASES.json CHANGED
@@ -1,5 +1,5 @@
1
  {
2
- "current": "1be950d",
3
  "releases": [
4
  {
5
  "version": "v24",
 
1
  {
2
+ "current": "cbcf005",
3
  "releases": [
4
  {
5
  "version": "v24",
VERSION CHANGED
@@ -1 +1 @@
1
- 1be950d
 
1
+ cbcf005
api/main.py CHANGED
@@ -447,8 +447,12 @@ def _pull_meta(why):
447
  print(f"[aios-api] meta sync skipped ({why}): no META_ADS_ACCESS_TOKEN in this "
448
  f"deployment - the connector is idle, not broken")
449
  return
450
- os.environ.setdefault("META_INSIGHTS_DAYS", "7")
451
- rep = _meta.sync("royal-imports", log=lambda *_a: None)
 
 
 
 
452
  for p in rep.get("problems") or []:
453
  print(f"[aios-api] meta sync PROBLEM ({why}): {p}")
454
  print(f"[aios-api] meta sync done ({why}): "
 
447
  print(f"[aios-api] meta sync skipped ({why}): no META_ADS_ACCESS_TOKEN in this "
448
  f"deployment - the connector is idle, not broken")
449
  return
450
+ # β›” PASSED, NOT SET IN THE ENVIRONMENT. `meta_store.INSIGHTS_DAYS` binds at
451
+ # IMPORT, so an `os.environ.setdefault` here executed after the module was
452
+ # already loaded and changed NOTHING: every boot pulled 90 days instead of 7,
453
+ # which is the slow path that trips the per-ad-account rate limit and never
454
+ # finishes. A knob read at import cannot be turned by a caller at runtime.
455
+ rep = _meta.sync("royal-imports", log=lambda *_a: None, insights_days=7)
456
  for p in rep.get("problems") or []:
457
  print(f"[aios-api] meta sync PROBLEM ({why}): {p}")
458
  print(f"[aios-api] meta sync done ({why}): "
platform/harness/meta_store.py CHANGED
@@ -310,7 +310,40 @@ def _cell(value):
310
  return json.dumps(value, separators=(",", ":"), ensure_ascii=False)
311
 
312
 
313
- def _coltype(name):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
314
  if name in _INT:
315
  return "BIGINT"
316
  if name in _DBL:
@@ -318,15 +351,31 @@ def _coltype(name):
318
  return "VARCHAR" # ids included β€” see the header
319
 
320
 
321
- def _ensure(con, table, fields):
322
- cols = ", ".join(f"{f} {_coltype(f)}" for f in fields)
323
- con.execute(f"CREATE TABLE IF NOT EXISTS {table} (id VARCHAR PRIMARY KEY, {cols})"
324
- if "id" not in fields else
325
- f"CREATE TABLE IF NOT EXISTS {table} ({cols})")
326
- have = {r[1] for r in con.execute(f"PRAGMA table_info('{table}')").fetchall()}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
327
  for f in fields:
328
  if f not in have:
329
- con.execute(f"ALTER TABLE {table} ADD COLUMN {f} {_coltype(f)}")
330
 
331
 
332
  def _upsert(con, table, fields, rows):
@@ -344,13 +393,22 @@ def _upsert(con, table, fields, rows):
344
  return len(rows)
345
 
346
 
347
- def sync(tenant_key="royal-imports", tok=None, log=print, insights=True):
348
  """Pull every level into the tenant's mirror. -> a report dict; raises only on a bad token.
349
 
350
  Idempotent: re-running updates rows in place. Safe to call at boot and on the resync loop,
351
  exactly as `odoo_relational.refresh` is.
352
  """
353
  tok = tok or token()
 
 
 
 
 
 
 
 
 
354
  report = {"tenant": tenant_key, "tables": {}, "problems": [], "accounts": []}
355
  if not tok:
356
  report["problems"].append(
@@ -381,7 +439,7 @@ def sync(tenant_key="royal-imports", tok=None, log=print, insights=True):
381
  got, hit = _walk(f"{aid}/{edge}", tok, log, fields=",".join(fields), limit=PAGE)
382
  rows.extend(got)
383
  capped = capped or hit
384
- _ensure(con, table, fields)
385
  n = _upsert(con, table, fields, rows)
386
  total = con.execute(f"SELECT count(*) FROM {table}").fetchone()[0]
387
  report["tables"][table] = {"pulled": n, "in_mirror": total, "capped": capped}
@@ -394,7 +452,7 @@ def sync(tenant_key="royal-imports", tok=None, log=print, insights=True):
394
  if insights:
395
  rows, capped = [], False
396
  for acct in accts:
397
- for since, until in _slices(INSIGHTS_DAYS, INSIGHTS_SLICE):
398
  got, hit = _walk(f"{acct['id']}/insights", tok, log,
399
  fields=",".join(INSIGHT_FIELDS), level=INSIGHTS_LEVEL,
400
  time_increment="1", limit=INSIGHTS_PAGE,
@@ -407,7 +465,7 @@ def sync(tenant_key="royal-imports", tok=None, log=print, insights=True):
407
  r["id"] = ":".join(str(r.get(k) or "") for k in
408
  (f"{INSIGHTS_LEVEL}_id", "date_start", "date_stop"))
409
  fields = ["id"] + INSIGHT_FIELDS
410
- _ensure(con, INSIGHTS_TABLE, fields)
411
  n = _upsert(con, INSIGHTS_TABLE, fields, rows)
412
  total = con.execute(f"SELECT count(*) FROM {INSIGHTS_TABLE}").fetchone()[0]
413
  report["tables"][INSIGHTS_TABLE] = {"pulled": n, "in_mirror": total, "capped": capped}
@@ -415,7 +473,7 @@ def sync(tenant_key="royal-imports", tok=None, log=print, insights=True):
415
  + (" !! PAGE CAP HIT" if capped else ""))
416
 
417
  con.execute("INSERT OR REPLACE INTO _sync_state VALUES (?,?,?,?,?,?)",
418
- ["meta", "done", 0, f"{INSIGHTS_DAYS}d/{INSIGHTS_SLICE}d@{INSIGHTS_LEVEL}",
419
  sum(t["in_mirror"] for t in report["tables"].values()),
420
  time.strftime("%Y-%m-%d %H:%M:%S")])
421
  return report
@@ -442,6 +500,8 @@ def main(argv=None):
442
  ap.add_argument("--status", action="store_true")
443
  ap.add_argument("--tenant", default="royal-imports")
444
  ap.add_argument("--no-insights", action="store_true")
 
 
445
  a = ap.parse_args(argv)
446
  if a.status:
447
  for k, v in status(a.tenant).items():
@@ -450,7 +510,7 @@ def main(argv=None):
450
  if not a.sync:
451
  ap.print_help()
452
  return 2
453
- rep = sync(a.tenant, insights=not a.no_insights)
454
  for p in rep["problems"]:
455
  print(" PROBLEM:", p)
456
  print(f" accounts: {len(rep['accounts'])} tables: {len(rep['tables'])}")
 
310
  return json.dumps(value, separators=(",", ":"), ensure_ascii=False)
311
 
312
 
313
+ def _coltype(name, rows=None):
314
+ """The DuckDB type for one column β€” decided by the DATA when there is data, by the name only
315
+ as a fallback.
316
+
317
+ β›” THE NAME LIST WAS WRONG AND ONLY THE API COULD SAY SO. `cost_per_unique_click`,
318
+ `cost_per_action_type`, `purchase_roas` and friends READ like money and are **arrays of
319
+ action-type objects** on the Insights edge:
320
+ [{"action_type":"outbound_click","value":"1.459854"}]
321
+ Typed DOUBLE from `_DBL`, the insert died with `Conversion Error: Could not convert string
322
+ '[{...}]' to DOUBLE` β€” after five entity tables had already been written, so the sync looked
323
+ like it worked and then blew up on the last table.
324
+ ⭐ Same principle the field CATALOG is built on, applied one layer down: **ask the response,
325
+ do not assert from a list.** A value that ever arrives as a list or dict is JSON TEXT, because
326
+ that is what `_cell` stores; anything else falls back to the measured name hints.
327
+ """
328
+ if rows:
329
+ seen, kinds = 0, set()
330
+ for r in rows:
331
+ v = r.get(name)
332
+ if v is None or v == "":
333
+ continue
334
+ kinds.add("json" if isinstance(v, (list, dict)) else
335
+ "bool" if isinstance(v, bool) else
336
+ "int" if isinstance(v, int) else
337
+ "float" if isinstance(v, float) else "str")
338
+ seen += 1
339
+ if seen >= 200:
340
+ break
341
+ if kinds:
342
+ if "json" in kinds or "str" in kinds:
343
+ return "VARCHAR" # a JSON blob, or a numeric STRING
344
+ if kinds <= {"int", "bool"}:
345
+ return "BIGINT" if name in _INT else ("VARCHAR" if "bool" in kinds else "BIGINT")
346
+ return "DOUBLE"
347
  if name in _INT:
348
  return "BIGINT"
349
  if name in _DBL:
 
351
  return "VARCHAR" # ids included β€” see the header
352
 
353
 
354
+ def _ensure(con, table, fields, rows=None):
355
+ """Create or widen the table, with every column typed from `rows` when they are available.
356
+
357
+ ⚠ AN EXISTING COLUMN WHOSE TYPE IS NOW WRONG IS REBUILT, NOT PATCHED. DuckDB cannot retype a
358
+ column in place, and this table is DERIVED data that can be re-pulled in minutes β€” so a type
359
+ disagreement drops and recreates rather than limping on with a column that refuses every
360
+ insert. The alternative is a mirror that is permanently unwritable for one bad guess.
361
+ """
362
+ want = {f: _coltype(f, rows) for f in fields}
363
+ have = {r[1]: str(r[2]).upper() for r in con.execute(f"PRAGMA table_info('{table}')").fetchall()}
364
+ if have:
365
+ clash = [f for f, ty in want.items() if f in have and have[f] != ty
366
+ and not (have[f].startswith("VARCHAR") and ty == "VARCHAR")]
367
+ if clash:
368
+ con.execute(f"DROP TABLE {table}")
369
+ have = {}
370
+ if not have:
371
+ cols = ", ".join(f"{f} {want[f]}" for f in fields)
372
+ con.execute(f"CREATE TABLE IF NOT EXISTS {table} (id VARCHAR PRIMARY KEY, {cols})"
373
+ if "id" not in fields else
374
+ f"CREATE TABLE IF NOT EXISTS {table} ({cols})")
375
+ return
376
  for f in fields:
377
  if f not in have:
378
+ con.execute(f"ALTER TABLE {table} ADD COLUMN {f} {want[f]}")
379
 
380
 
381
  def _upsert(con, table, fields, rows):
 
393
  return len(rows)
394
 
395
 
396
+ def sync(tenant_key="royal-imports", tok=None, log=print, insights=True, insights_days=None):
397
  """Pull every level into the tenant's mirror. -> a report dict; raises only on a bad token.
398
 
399
  Idempotent: re-running updates rows in place. Safe to call at boot and on the resync loop,
400
  exactly as `odoo_relational.refresh` is.
401
  """
402
  tok = tok or token()
403
+ # β›” THE WINDOW IS A PARAMETER, NOT AN ENVIRONMENT READ AT CALL TIME β€” and the difference cost a
404
+ # live deploy. `INSIGHTS_DAYS` binds at IMPORT (module scope), so `main._pull_meta`'s
405
+ # `os.environ.setdefault("META_INSIGHTS_DAYS", "7")` executed AFTER this module was already
406
+ # imported and changed nothing: every boot pulled **90 days**, not 7, which is the slow path
407
+ # that trips the per-ad-account rate limit and never finishes. The comment beside that call
408
+ # claimed a short window the code could not deliver.
409
+ # ⭐ The shape: **a knob read at import cannot be turned by a caller at runtime.** Passing it
410
+ # makes the caller's intent effective instead of aspirational; the env var stays the DEFAULT.
411
+ days = int(insights_days or INSIGHTS_DAYS)
412
  report = {"tenant": tenant_key, "tables": {}, "problems": [], "accounts": []}
413
  if not tok:
414
  report["problems"].append(
 
439
  got, hit = _walk(f"{aid}/{edge}", tok, log, fields=",".join(fields), limit=PAGE)
440
  rows.extend(got)
441
  capped = capped or hit
442
+ _ensure(con, table, fields, rows)
443
  n = _upsert(con, table, fields, rows)
444
  total = con.execute(f"SELECT count(*) FROM {table}").fetchone()[0]
445
  report["tables"][table] = {"pulled": n, "in_mirror": total, "capped": capped}
 
452
  if insights:
453
  rows, capped = [], False
454
  for acct in accts:
455
+ for since, until in _slices(days, INSIGHTS_SLICE):
456
  got, hit = _walk(f"{acct['id']}/insights", tok, log,
457
  fields=",".join(INSIGHT_FIELDS), level=INSIGHTS_LEVEL,
458
  time_increment="1", limit=INSIGHTS_PAGE,
 
465
  r["id"] = ":".join(str(r.get(k) or "") for k in
466
  (f"{INSIGHTS_LEVEL}_id", "date_start", "date_stop"))
467
  fields = ["id"] + INSIGHT_FIELDS
468
+ _ensure(con, INSIGHTS_TABLE, fields, rows)
469
  n = _upsert(con, INSIGHTS_TABLE, fields, rows)
470
  total = con.execute(f"SELECT count(*) FROM {INSIGHTS_TABLE}").fetchone()[0]
471
  report["tables"][INSIGHTS_TABLE] = {"pulled": n, "in_mirror": total, "capped": capped}
 
473
  + (" !! PAGE CAP HIT" if capped else ""))
474
 
475
  con.execute("INSERT OR REPLACE INTO _sync_state VALUES (?,?,?,?,?,?)",
476
+ ["meta", "done", 0, f"{days}d/{INSIGHTS_SLICE}d@{INSIGHTS_LEVEL}",
477
  sum(t["in_mirror"] for t in report["tables"].values()),
478
  time.strftime("%Y-%m-%d %H:%M:%S")])
479
  return report
 
500
  ap.add_argument("--status", action="store_true")
501
  ap.add_argument("--tenant", default="royal-imports")
502
  ap.add_argument("--no-insights", action="store_true")
503
+ ap.add_argument("--insights-days", type=int, default=None,
504
+ help="override the Insights window for THIS run (default INSIGHTS_DAYS); the env var is the default, this is the caller's say")
505
  a = ap.parse_args(argv)
506
  if a.status:
507
  for k, v in status(a.tenant).items():
 
510
  if not a.sync:
511
  ap.print_help()
512
  return 2
513
+ rep = sync(a.tenant, insights=not a.no_insights, insights_days=a.insights_days)
514
  for p in rep["problems"]:
515
  print(" PROBLEM:", p)
516
  print(f" accounts: {len(rep['accounts'])} tables: {len(rep['tables'])}")