fsanyoto commited on
Commit
efda0e6
·
verified ·
1 Parent(s): 7360a73

Cost: focus checks use Pg revisions; legacy polls stay database-free

Browse files
api/deps.py CHANGED
@@ -674,10 +674,12 @@ def require_changes_session(request: Request, response: Response) -> Session | N
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
 
 
674
  """
675
  if store.backend() != "pg":
676
  return require_session(request, response)
677
+ if request.headers.get("x-aios-change-check") == "focus-v1":
678
+ return require_session(request, response)
679
  raw = request.cookies.get(aios_session.COOKIE_NAME)
680
  claims = aios_session.read(raw) if raw else None
681
  if not claims or not str(claims.get("t") or "").strip() or not str(claims.get("u") or "").strip():
682
+ raise err(401, "invalid_session", "your session has expired — sign in again")
683
  return None
684
 
685
 
api/routes_changes.py CHANGED
@@ -199,13 +199,13 @@ def _may_watch(session, scope):
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
 
199
 
200
  @router.get("/changes")
201
  def changes(scope: str = "", session: Session | None = Depends(require_changes_session)):
202
+ """Serve legacy change checks without making Pg a resident client."""
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" and session is None:
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
web/src/customer-grid/apiBridge.ts CHANGED
@@ -52,8 +52,9 @@ import {
52
  checkTenant,
53
  signal,
54
  } from "../apiContract";
55
- import { setStandaloneSink } from "./hostBridge";
56
- import type { ChangeTokens } from "./liveWorkspace";
 
57
  import { CUSTOMER_TOPIC } from "./types";
58
  import type { CustomersPayload, Field, FilterNode, GridLimit, GridWorkspace, HostEvent, Row,
59
  SortSpec, TopicConfig } from "./types";
@@ -593,8 +594,10 @@ export async function fetchWorkspace(
593
  export async function fetchChangeTokens(scope: string): Promise<ChangeTokens | null> {
594
  let res: Response;
595
  try {
596
- res = await fetch(`${API_V1}/changes?scope=${encodeURIComponent(scope)}`,
597
- { credentials: CREDENTIALS });
 
 
598
  } catch {
599
  return null;
600
  }
@@ -609,49 +612,84 @@ export async function fetchChangeTokens(scope: string): Promise<ChangeTokens | n
609
  return out;
610
  }
611
 
612
- /**
613
- * A grid reloads only when the person returns to the tab or window. There is no timer and no
614
- * background token request.
615
- */
616
- interface ChangeWatch {
617
- listeners: Set<(changed: string[]) => void>;
 
 
 
 
 
 
 
 
618
  }
619
 
620
- const changeWatches = new Map<string, ChangeWatch>();
621
- let visibilityBound = false;
622
- const RETURN_REFRESH_BUCKETS = ["rows", "overlay", "shared"];
623
-
624
- function refreshVisibleChanges(): void {
625
- if (document.visibilityState !== "visible") return;
626
- for (const watched of changeWatches.values())
627
- for (const listener of watched.listeners) listener([...RETURN_REFRESH_BUCKETS]);
628
- }
629
 
630
  /**
631
- * Watch one scope for user-return refreshes. Returns its unsubscribe.
632
- * A forgotten tab creates no database traffic; own writes update the current tab from their
633
- * response, and a change made elsewhere is refreshed when the person returns to this tab.
 
 
 
 
 
634
  */
635
  export function subscribeChanges(scope: string,
636
  onChange: (changed: string[]) => void): () => void {
637
  if (typeof window === "undefined") return () => {};
638
  let watch = changeWatches.get(scope);
639
  if (!watch) {
640
- const w0: ChangeWatch = { listeners: new Set() };
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
641
  watch = w0;
642
  changeWatches.set(scope, w0);
643
  }
644
- const w = watch;
645
- w.listeners.add(onChange);
646
- if (!visibilityBound) {
647
- visibilityBound = true;
648
- window.addEventListener("visibilitychange", refreshVisibleChanges);
649
- window.addEventListener("focus", refreshVisibleChanges);
650
- }
 
 
 
 
 
651
 
652
  return () => {
653
  w.listeners.delete(onChange);
654
- if (w.listeners.size === 0) changeWatches.delete(scope);
 
 
 
 
655
  };
656
  }
657
 
 
52
  checkTenant,
53
  signal,
54
  } from "../apiContract";
55
+ import { setStandaloneSink } from "./hostBridge";
56
+ import { changedBuckets } from "./liveWorkspace";
57
+ import type { ChangeTokens } from "./liveWorkspace";
58
  import { CUSTOMER_TOPIC } from "./types";
59
  import type { CustomersPayload, Field, FilterNode, GridLimit, GridWorkspace, HostEvent, Row,
60
  SortSpec, TopicConfig } from "./types";
 
594
  export async function fetchChangeTokens(scope: string): Promise<ChangeTokens | null> {
595
  let res: Response;
596
  try {
597
+ res = await fetch(`${API_V1}/changes?scope=${encodeURIComponent(scope)}`,
598
+ // This header marks a current, user-return check. Legacy bundles lack it,
599
+ // so their former 10-second requests remain database-free on Pg.
600
+ { credentials: CREDENTIALS, headers: { "X-AIOS-Change-Check": "focus-v1" } });
601
  } catch {
602
  return null;
603
  }
 
612
  return out;
613
  }
614
 
615
+ /**
616
+ * A grid reloads only when the person returns to the tab or window. There is no timer and no
617
+ * background token request.
618
+ */
619
+
620
+ interface ChangeWatch {
621
+ listeners: Set<(changed: string[]) => void>;
622
+ tokens: ChangeTokens | null;
623
+ inFlight: boolean;
624
+ refresh: () => Promise<void>;
625
+ /** ⭐ ONE poll implementation per watch, held here so the interval and the visibility handler
626
+ * call the SAME function. The visibility handler used to re-inline the body, which quietly
627
+ * skipped `inFlight` — so returning to a tab whose poll was still outstanding stacked a second
628
+ * request on top of it, exactly what that guard exists to prevent. */
629
  }
630
 
631
+ const changeWatches = new Map<string, ChangeWatch>();
632
+ let visibilityBound = false;
633
+ function refreshVisibleChanges(): void {
634
+ if (document.visibilityState !== "visible") return;
635
+ for (const watched of changeWatches.values())
636
+ void watched.refresh();
637
+ }
 
 
638
 
639
  /**
640
+ * Watch one scope for server-side changes. Returns its unsubscribe.
641
+ *
642
+ * ⭐ ONE WATCH PER SCOPE, REFCOUNTED. A linked-record grid can mount a second `useCustomerData` on
643
+ * the same surface, and both listeners share one mount baseline and one return-to-tab refresh.
644
+ *
645
+ * ⛔ IT NEVER POLLS. Own writes update the current tab from their response; a change made elsewhere
646
+ * is checked when the person returns to this tab or focuses its window. A forgotten tab left open
647
+ * overnight creates no database traffic.
648
  */
649
  export function subscribeChanges(scope: string,
650
  onChange: (changed: string[]) => void): () => void {
651
  if (typeof window === "undefined") return () => {};
652
  let watch = changeWatches.get(scope);
653
  if (!watch) {
654
+ const w0: ChangeWatch = {
655
+ listeners: new Set(), tokens: null, inFlight: false,
656
+ refresh: async () => {
657
+ if (w0.inFlight || document.visibilityState !== "visible") return;
658
+ w0.inFlight = true;
659
+ try {
660
+ const next = await fetchChangeTokens(scope);
661
+ const changed = changedBuckets(w0.tokens, next);
662
+ if (next) w0.tokens = next;
663
+ if (changed.length)
664
+ for (const listener of [...w0.listeners]) listener(changed);
665
+ } finally {
666
+ w0.inFlight = false;
667
+ }
668
+ },
669
+ };
670
  watch = w0;
671
  changeWatches.set(scope, w0);
672
  }
673
+ const w = watch;
674
+ w.listeners.add(onChange);
675
+
676
+ // One tiny revision baseline after the necessary initial data load lets later user returns
677
+ // preserve the browser cache when nothing changed. It is never an interval.
678
+ if (w.tokens === null && !w.inFlight) void w.refresh();
679
+
680
+ if (!visibilityBound) {
681
+ visibilityBound = true;
682
+ window.addEventListener("visibilitychange", refreshVisibleChanges);
683
+ window.addEventListener("focus", refreshVisibleChanges);
684
+ }
685
 
686
  return () => {
687
  w.listeners.delete(onChange);
688
+ if (w.listeners.size === 0) {
689
+ // ⚠ The tokens are DROPPED with the last listener. A remount must re-baseline rather than
690
+ // compare against a token from before it was unmounted.
691
+ changeWatches.delete(scope);
692
+ }
693
  };
694
  }
695