fsanyoto commited on
Commit
63c73d3
Β·
verified Β·
1 Parent(s): 8caabf7

Cost hotfix: make grid refresh user-driven

Browse files

Remove client token polling and make legacy Pg change checks cookie-only and database-free.

api/deps.py CHANGED
@@ -27,6 +27,7 @@ if str(_RI) not in sys.path:
27
  sys.path.insert(0, str(_RI))
28
 
29
  import core.perms as perms # noqa: E402
 
30
  import core.users as users # noqa: E402
31
  from harness import runtime # noqa: E402
32
 
@@ -663,6 +664,23 @@ def require_session(request: Request, response: Response) -> Session:
663
  return Session(tenant=claims["t"], user=user, claims=claims, runtime=rt)
664
 
665
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
666
  def module_gate(module_key):
667
  """A dependency that 401s without a session and 403s without the grant for `module_key`."""
668
  def _dep(session: Session = Depends(require_session)) -> Session:
 
27
  sys.path.insert(0, str(_RI))
28
 
29
  import core.perms as perms # noqa: E402
30
+ import core.store as store # noqa: E402
31
  import core.users as users # noqa: E402
32
  from harness import runtime # noqa: E402
33
 
 
664
  return Session(tenant=claims["t"], user=user, claims=claims, runtime=rt)
665
 
666
 
667
+ def require_changes_session(request: Request, response: Response) -> Session | None:
668
+ """Authenticate the passive Pg change endpoint without reopening the database.
669
+
670
+ Pg change tokens are intentionally disabled: a current client refreshes the data it is viewing
671
+ on focus, while an already-open legacy client may still call this route every ten seconds. A
672
+ verified signed cookie is enough to return that no-data response; resolving the account record
673
+ would itself turn those legacy requests into a permanent Neon keepalive.
674
+ """
675
+ if store.backend() != "pg":
676
+ return require_session(request, response)
677
+ raw = request.cookies.get(aios_session.COOKIE_NAME)
678
+ claims = aios_session.read(raw) if raw else None
679
+ if not claims or not str(claims.get("t") or "").strip() or not str(claims.get("u") or "").strip():
680
+ raise err(401, "invalid_session", "your session has expired ? sign in again")
681
+ return None
682
+
683
+
684
  def module_gate(module_key):
685
  """A dependency that 401s without a session and 403s without the grant for `module_key`."""
686
  def _dep(session: Session = Depends(require_session)) -> Session:
api/routes_changes.py CHANGED
@@ -63,7 +63,7 @@ import core.user_tables as user_tables
63
  import modules.customer_data as customer_data
64
  import modules.product_data as product_data
65
 
66
- from deps import Session, err, require_session
67
 
68
  router = APIRouter(prefix="/api/v1")
69
 
@@ -198,16 +198,20 @@ def _may_watch(session, scope):
198
 
199
 
200
  @router.get("/changes")
201
- def changes(scope: str = "", session: Session = Depends(require_session)):
202
  """One tiny read per tab per interval. The response is small, uncacheable and boring."""
203
  names = buckets_for(scope)
204
  if names is None:
205
  raise err(400, "bad_scope", "name the table you are watching, e.g. ?scope=customer")
 
 
 
 
206
  # β›” W29-T82 β€” THE SAME REFUSAL EVERY SIBLING DOOR GIVES, word for word. A session that may
207
  # not open this table must not be able to tell whether it exists, and "404 unknown_table" is
208
  # the sentence the other five row doors answer with. A different code here would itself be
209
  # the tell.
210
- if names and not _may_watch(session, _clean_scope(scope)):
211
  raise err(404, "unknown_table", f"no database {_clean_scope(scope)!r} here")
212
  if not names:
213
  # β›” A well-formed scope this map does not know is a 404, NOT an empty `tokens` object.
 
63
  import modules.customer_data as customer_data
64
  import modules.product_data as product_data
65
 
66
+ from deps import Session, err, require_changes_session, require_session
67
 
68
  router = APIRouter(prefix="/api/v1")
69
 
 
198
 
199
 
200
  @router.get("/changes")
201
+ def changes(scope: str = "", session: Session | None = Depends(require_changes_session)):
202
  """One tiny read per tab per interval. The response is small, uncacheable and boring."""
203
  names = buckets_for(scope)
204
  if names is None:
205
  raise err(400, "bad_scope", "name the table you are watching, e.g. ?scope=customer")
206
+ # Pg clients refresh data on user focus. Returning null tokens is database-free so an old
207
+ # browser bundle cannot keep Neon awake while the current no-poll bundle rolls out.
208
+ if names and store.backend() == "pg":
209
+ return {"scope": _clean_scope(scope), "tokens": {label: None for label in names}, "backend": "pg"}
210
  # β›” W29-T82 β€” THE SAME REFUSAL EVERY SIBLING DOOR GIVES, word for word. A session that may
211
  # not open this table must not be able to tell whether it exists, and "404 unknown_table" is
212
  # the sentence the other five row doors answer with. A different code here would itself be
213
  # the tell.
214
+ if names and (session is None or not _may_watch(session, _clean_scope(scope))):
215
  raise err(404, "unknown_table", f"no database {_clean_scope(scope)!r} here")
216
  if not names:
217
  # β›” A well-formed scope this map does not know is a 404, NOT an empty `tokens` object.
web/src/customer-grid/apiBridge.ts CHANGED
@@ -611,61 +611,39 @@ export async function fetchChangeTokens(scope: string): Promise<ChangeTokens | n
611
  }
612
 
613
  /**
614
- * Token checks are event driven: once at scope mount and when a person returns to the visible tab
615
- * or window. There is intentionally no recurring timer.
616
  */
617
  interface ChangeWatch {
618
- tokens: ChangeTokens | null;
619
  listeners: Set<(changed: string[]) => void>;
620
- inFlight: boolean;
621
- /** One implementation per scope so mount, focus, and visibility refreshes share the same guard. */
622
- poll: () => Promise<void>;
623
  }
624
 
625
  const changeWatches = new Map<string, ChangeWatch>();
626
  let visibilityBound = false;
 
627
 
628
  function refreshVisibleChanges(): void {
629
  if (document.visibilityState !== "visible") return;
630
  for (const watched of changeWatches.values())
631
- if (watched.listeners.size > 0) void watched.poll();
632
  }
633
 
634
  /**
635
- * Watch one scope for server-side changes. Returns its unsubscribe.
636
- *
637
- * One watch per scope is reference counted. Its initial token baseline is shared by every grid on
638
- * that scope, and a change made elsewhere is checked only when the user returns to this browser
639
- * tab or focuses its window. A forgotten tab creates no database traffic.
640
  */
641
  export function subscribeChanges(scope: string,
642
  onChange: (changed: string[]) => void): () => void {
643
  if (typeof window === "undefined") return () => {};
644
  let watch = changeWatches.get(scope);
645
  if (!watch) {
646
- const w0: ChangeWatch = {
647
- tokens: null, listeners: new Set(), inFlight: false,
648
- poll: async () => {
649
- // A slow answer must not queue another mount/focus request behind itself.
650
- if (w0.inFlight || document.visibilityState !== "visible") return;
651
- w0.inFlight = true;
652
- try {
653
- const next = await fetchChangeTokens(scope);
654
- const changed = changedBuckets(w0.tokens, next);
655
- if (next) w0.tokens = next;
656
- if (changed.length) for (const fn of [...w0.listeners]) fn(changed);
657
- } finally {
658
- w0.inFlight = false;
659
- }
660
- },
661
- };
662
  watch = w0;
663
  changeWatches.set(scope, w0);
664
  }
665
  const w = watch;
666
  w.listeners.add(onChange);
667
-
668
- if (w.tokens === null) void w.poll();
669
  if (!visibilityBound) {
670
  visibilityBound = true;
671
  window.addEventListener("visibilitychange", refreshVisibleChanges);
@@ -674,10 +652,7 @@ export function subscribeChanges(scope: string,
674
 
675
  return () => {
676
  w.listeners.delete(onChange);
677
- if (w.listeners.size === 0) {
678
- // A remount takes a new baseline rather than comparing against a stale, unobserved token.
679
- w.tokens = null;
680
- }
681
  };
682
  }
683
 
 
611
  }
612
 
613
  /**
614
+ * A grid reloads only when the person returns to the tab or window. There is no timer and no
615
+ * background token request.
616
  */
617
  interface ChangeWatch {
 
618
  listeners: Set<(changed: string[]) => void>;
 
 
 
619
  }
620
 
621
  const changeWatches = new Map<string, ChangeWatch>();
622
  let visibilityBound = false;
623
+ const RETURN_REFRESH_BUCKETS = ["rows", "overlay", "shared"];
624
 
625
  function refreshVisibleChanges(): void {
626
  if (document.visibilityState !== "visible") return;
627
  for (const watched of changeWatches.values())
628
+ for (const listener of watched.listeners) listener([...RETURN_REFRESH_BUCKETS]);
629
  }
630
 
631
  /**
632
+ * Watch one scope for user-return refreshes. Returns its unsubscribe.
633
+ * A forgotten tab creates no database traffic; own writes update the current tab from their
634
+ * response, and a change made elsewhere is refreshed when the person returns to this tab.
 
 
635
  */
636
  export function subscribeChanges(scope: string,
637
  onChange: (changed: string[]) => void): () => void {
638
  if (typeof window === "undefined") return () => {};
639
  let watch = changeWatches.get(scope);
640
  if (!watch) {
641
+ const w0: ChangeWatch = { listeners: new Set() };
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
642
  watch = w0;
643
  changeWatches.set(scope, w0);
644
  }
645
  const w = watch;
646
  w.listeners.add(onChange);
 
 
647
  if (!visibilityBound) {
648
  visibilityBound = true;
649
  window.addEventListener("visibilitychange", refreshVisibleChanges);
 
652
 
653
  return () => {
654
  w.listeners.delete(onChange);
655
+ if (w.listeners.size === 0) changeWatches.delete(scope);
 
 
 
656
  };
657
  }
658