@steve31415/baselib 3.61.0 → 3.62.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -6,7 +6,7 @@ What it provides and why: `docs/SPEC.md`. How it's put together:
6
6
  `~/migration/research/base-services-design.md`.
7
7
 
8
8
  Server subpath exports: `config`, `log`, `auth`, `oauth-resource`, `connector`, `s2s`, `db`, `http`, `sync`,
9
- `app-update`, `llm`, `email`, `twitter`, `hub` (the connection hub's server core, app notifier and daemon-token mint; `hub/testing` a local hub for tests), `hub-daemon` (the daemons' hub client), `code-manifest` and
9
+ `app-update`, `llm`, `email`, `twitter`, `hub` (the connection hub's server core, app notifier, per-request hint batch `HubHints` and daemon-token mint; `hub/testing` a local hub for tests), `hub-daemon` (the daemons' hub client), `code-manifest` and
10
10
  `client-version`. Browser exports: `log-browser`, `rum`, `slow-fetch`, `sync-browser`, `app-update-browser`, and
11
11
  `extension-self-update`.
12
12
 
@@ -0,0 +1,40 @@
1
+ import type { MiddlewareHandler } from 'hono';
2
+ import type { AppHint, HubNotifier } from './notify.js';
3
+ /** How long a run's first hint waits for others to fold into its send. */
4
+ export declare const HUB_HINT_WINDOW_MS = 25;
5
+ export interface HubHintsOptions {
6
+ notifier: HubNotifier;
7
+ /** Default HUB_HINT_WINDOW_MS. */
8
+ windowMs?: number;
9
+ }
10
+ export interface HubHintsMiddlewareOptions {
11
+ /** Send `{user: '*', kind: 'build_changed'}` in the batch of the first
12
+ * request this copy serves other than `/health`, once per HubHints. For an
13
+ * app with no deploy-hook announcement: a copy receives load-balancer
14
+ * traffic only once its revision serves, so its first real request is when
15
+ * it knows its build is the one open pages should check for (design §14.3:
16
+ * announced through the app's own notifier, never from the deploy hook). A
17
+ * second copy, or a copy started from zero, announces too, costing each
18
+ * open page one build check that finds nothing new. */
19
+ announceBuild?: boolean;
20
+ }
21
+ export declare class HubHints {
22
+ private readonly notifier;
23
+ private readonly windowMs;
24
+ private readonly scope;
25
+ private buildAnnounced;
26
+ constructor(opts: HubHintsOptions);
27
+ /** Runs `work` with its own hint batch. Settles as `work` does (its value,
28
+ * or its error) once `work` has ended and every send it started has
29
+ * settled; a hint raised before `work` threw is still sent. */
30
+ run<T>(work: () => Promise<T>): Promise<T>;
31
+ /** Runs each request inside `run`, so it answers only after its hints have
32
+ * gone. Mount it after the request logger (so a request's logged duration
33
+ * includes the sends) and before every route that commits. */
34
+ middleware(opts?: HubHintsMiddlewareOptions): MiddlewareHandler;
35
+ /** Call after the commit the hint describes. Inside an open run the hint
36
+ * joins its window and the promise resolves at once (the run awaits the
37
+ * send); outside, it is sent now and the promise resolves once it has
38
+ * gone, so background work can await it. Never rejects. */
39
+ send(hint: AppHint): Promise<void>;
40
+ }
@@ -0,0 +1,107 @@
1
+ // One windowed hint batch per request (design §5.3: hints "coalesced once per
2
+ // request", sent after the commit and awaited inside the request so a
3
+ // throttled Cloud Run instance still has CPU for them). Consolidates the
4
+ // helpers radar, lurch, coder, chime, reader, notes and todo each wrote by
5
+ // hand on top of HubNotifier in session 5.
6
+ //
7
+ // Inside `run` (or the Hono `middleware`, which runs each request in one), a
8
+ // hint is not sent at once: the first opens a window of `windowMs` (25 ms),
9
+ // hints raised in the window fold into it (HubNotifyBatch's per-user-and-kind
10
+ // coalescing), and when the window closes they go in one send. A hint after a
11
+ // send has started opens a new window, so a request that works for minutes (a
12
+ // tick, a calendar sync) delivers each commit's hint within ~25 ms rather
13
+ // than holding them to its end. When the work ends, an open window is sent at
14
+ // once, and `run` settles only after every send it started has settled. A
15
+ // hint raised outside any run, or by a callback that outlives its run, is sent
16
+ // at once. HubNotifier bounds each send at 1 s, never throws, and opens a
17
+ // circuit after repeated failures, so a hub outage costs a request at most
18
+ // that second.
19
+ import { AsyncLocalStorage } from 'node:async_hooks';
20
+ /** How long a run's first hint waits for others to fold into its send. */
21
+ export const HUB_HINT_WINDOW_MS = 25;
22
+ /** One run's hints. */
23
+ class RunHints {
24
+ notifier;
25
+ windowMs;
26
+ batch;
27
+ pending = false;
28
+ timer = null;
29
+ sends = new Set();
30
+ closed = false;
31
+ constructor(notifier, windowMs) {
32
+ this.notifier = notifier;
33
+ this.windowMs = windowMs;
34
+ this.batch = notifier.batch();
35
+ }
36
+ add(hint) {
37
+ this.batch.add(hint);
38
+ this.pending = true;
39
+ this.timer ??= setTimeout(() => this.flush(), this.windowMs);
40
+ }
41
+ /** Send what has collected; close() awaits it. */
42
+ flush() {
43
+ if (this.timer)
44
+ clearTimeout(this.timer);
45
+ this.timer = null;
46
+ if (!this.pending)
47
+ return;
48
+ const batch = this.batch;
49
+ this.batch = this.notifier.batch();
50
+ this.pending = false;
51
+ const send = batch.flush().finally(() => this.sends.delete(send));
52
+ this.sends.add(send);
53
+ }
54
+ /** The work has ended: send the open window and wait for every send. */
55
+ async close() {
56
+ this.closed = true;
57
+ this.flush();
58
+ while (this.sends.size > 0)
59
+ await Promise.all([...this.sends]);
60
+ }
61
+ }
62
+ export class HubHints {
63
+ notifier;
64
+ windowMs;
65
+ scope = new AsyncLocalStorage();
66
+ buildAnnounced = false;
67
+ constructor(opts) {
68
+ this.notifier = opts.notifier;
69
+ this.windowMs = opts.windowMs ?? HUB_HINT_WINDOW_MS;
70
+ }
71
+ /** Runs `work` with its own hint batch. Settles as `work` does (its value,
72
+ * or its error) once `work` has ended and every send it started has
73
+ * settled; a hint raised before `work` threw is still sent. */
74
+ async run(work) {
75
+ const hints = new RunHints(this.notifier, this.windowMs);
76
+ try {
77
+ return await this.scope.run(hints, work);
78
+ }
79
+ finally {
80
+ await hints.close();
81
+ }
82
+ }
83
+ /** Runs each request inside `run`, so it answers only after its hints have
84
+ * gone. Mount it after the request logger (so a request's logged duration
85
+ * includes the sends) and before every route that commits. */
86
+ middleware(opts = {}) {
87
+ return (c, next) => this.run(async () => {
88
+ if (opts.announceBuild && !this.buildAnnounced && c.req.path !== '/health') {
89
+ this.buildAnnounced = true;
90
+ void this.send({ user: '*', kind: 'build_changed' });
91
+ }
92
+ await next();
93
+ });
94
+ }
95
+ /** Call after the commit the hint describes. Inside an open run the hint
96
+ * joins its window and the promise resolves at once (the run awaits the
97
+ * send); outside, it is sent now and the promise resolves once it has
98
+ * gone, so background work can await it. Never rejects. */
99
+ send(hint) {
100
+ const hints = this.scope.getStore();
101
+ if (hints && !hints.closed) {
102
+ hints.add(hint);
103
+ return Promise.resolve();
104
+ }
105
+ return this.notifier.notify(hint);
106
+ }
107
+ }
@@ -1,4 +1,5 @@
1
1
  export * from './types.js';
2
2
  export * from './server.js';
3
3
  export * from './notify.js';
4
+ export * from './hints.js';
4
5
  export * from './mint.js';
package/dist/hub/index.js CHANGED
@@ -1,4 +1,5 @@
1
1
  export * from './types.js';
2
2
  export * from './server.js';
3
3
  export * from './notify.js';
4
+ export * from './hints.js';
4
5
  export * from './mint.js';
package/dist/log-core.js CHANGED
@@ -14,8 +14,8 @@ const CODE_MAX = 100;
14
14
  /** An Error's `code` property when it is a primitive worth a column: a
15
15
  * string (capped) or a finite number. Anything else is dropped, since an
16
16
  * object there would mint `meta.error.code.*` keys from data. */
17
- function errorCode(err) {
18
- const code = err.code;
17
+ function errorCode(err, key = 'code') {
18
+ const code = readProp(err, key);
19
19
  if (typeof code === 'string')
20
20
  return truncate(code, CODE_MAX);
21
21
  if (typeof code === 'number' && Number.isFinite(code))
@@ -57,8 +57,67 @@ export function serializeError(err) {
57
57
  }
58
58
  return out;
59
59
  }
60
+ if (typeof err === 'object' && err !== null)
61
+ return serializeNonErrorObject(err);
60
62
  return { name: 'NonError', message: truncate(String(err), 2000) };
61
63
  }
64
+ /** A property read that a throwing getter cannot turn into a logging failure. */
65
+ function readProp(o, key) {
66
+ try {
67
+ return o[key];
68
+ }
69
+ catch {
70
+ return undefined;
71
+ }
72
+ }
73
+ function constructorName(o) {
74
+ const name = readProp(o, 'constructor')?.name;
75
+ return typeof name === 'string' && name !== '' && name !== 'Object' ? name : undefined;
76
+ }
77
+ /** A thrown or rejected object that is not an Error. The common case is an
78
+ * event: puppeteer-core's connect() rejects with the ws library's
79
+ * ErrorEvent, whose `type`, `message` and `error` are prototype getters, so
80
+ * String() gives "[object Object]" and JSON "{}" — which hid a Cloudflare
81
+ * 401 (radar task 6262f4fb, 2026-11-08). Read the conventional fields
82
+ * directly; fall back to JSON, then to the constructor's name. The name
83
+ * stays 'NonError' so patterns keyed on it keep matching. */
84
+ function serializeNonErrorObject(o) {
85
+ const ctor = constructorName(o);
86
+ const message = readProp(o, 'message');
87
+ const type = readProp(o, 'type');
88
+ let text;
89
+ if (typeof message === 'string' && message !== '') {
90
+ const label = ctor === undefined ? '' : typeof type === 'string' && type !== '' ? `${ctor} (${type}): ` : `${ctor}: `;
91
+ text = label + message;
92
+ }
93
+ else {
94
+ let json;
95
+ try {
96
+ json = JSON.stringify(o);
97
+ }
98
+ catch {
99
+ // circular or a throwing toJSON: fall through
100
+ }
101
+ if (typeof json === 'string' && json !== '{}')
102
+ text = json;
103
+ else if (ctor !== undefined)
104
+ text = `${ctor} {}`;
105
+ else
106
+ text = json ?? '{}';
107
+ }
108
+ const out = { name: 'NonError', message: truncate(text, 2000) };
109
+ const code = errorCode(o) ?? errorCode(o, 'status');
110
+ if (code !== undefined)
111
+ out.code = code;
112
+ const inner = readProp(o, 'error');
113
+ if (inner instanceof Error) {
114
+ out.cause = { name: inner.name, message: inner.message };
115
+ const innerCode = errorCode(inner);
116
+ if (innerCode !== undefined)
117
+ out.cause.code = innerCode;
118
+ }
119
+ return out;
120
+ }
62
121
  export function truncate(s, max) {
63
122
  return s.length <= max ? s : s.slice(0, max) + `…[+${s.length - max}]`;
64
123
  }
@@ -12,6 +12,16 @@ export interface EventLogEngineOptions<C extends EventBody, S extends EventBody>
12
12
  retentionDays?: number;
13
13
  randomGuid?: () => string;
14
14
  now?: () => number;
15
+ /** Called after every `apply` whose outcome is `applied` or `duplicate`
16
+ * (committed now, or by an earlier attempt), with the scope key and that
17
+ * outcome, whoever called the engine: the POST route, a socket session, a
18
+ * server-side writer. The connection hub's `sync_available` seam (a
19
+ * duplicate must hint too: the retry of a write whose first attempt
20
+ * committed). Per event, so in a batch a later event's
21
+ * `SyncUnavailableError` does not hide the events committed before it.
22
+ * Synchronous and must not throw; a throw is logged as ERROR
23
+ * `sync.on_applied_failed` and the apply still returns its outcome. */
24
+ onApplied?: (scopeKey: string, outcome: CommittedApplyOutcome<S>) => void;
15
25
  }
16
26
  export type ApplyOutcome<S extends EventBody> = {
17
27
  kind: 'applied';
@@ -26,6 +36,10 @@ export type ApplyOutcome<S extends EventBody> = {
26
36
  message: string;
27
37
  };
28
38
  };
39
+ /** An apply outcome whose event is in the log. */
40
+ export type CommittedApplyOutcome<S extends EventBody> = Exclude<ApplyOutcome<S>, {
41
+ kind: 'rejected';
42
+ }>;
29
43
  export type CatchupOutcome<S extends EventBody> = {
30
44
  kind: 'events';
31
45
  events: SyncEvent<S>[];
@@ -42,6 +56,7 @@ export declare class EventLogEngine<C extends EventBody, S extends EventBody> {
42
56
  private readonly retentionDays;
43
57
  private readonly randomGuid;
44
58
  private readonly now;
59
+ private readonly onApplied?;
45
60
  constructor(options: EventLogEngineOptions<C, S>);
46
61
  /** Apply one event. Domain validation failures (`SyncError`) are stable
47
62
  * rejections. An unexpected failure is retried once, because event GUID
@@ -50,6 +65,8 @@ export declare class EventLogEngine<C extends EventBody, S extends EventBody> {
50
65
  * rejected as `internal`, and any other throws `SyncUnavailableError`: no
51
66
  * verdict, the caller must make the client re-send. */
52
67
  apply(scopeKey: string, clientGuid: string | null, event: ClientEvent<C>): Promise<ApplyOutcome<S>>;
68
+ private notifyApplied;
69
+ private applyWithRetry;
53
70
  private rejectedOutcome;
54
71
  private applyOnce;
55
72
  currentSeq(scopeKey: string): Promise<number>;
@@ -62,6 +62,7 @@ export class EventLogEngine {
62
62
  retentionDays;
63
63
  randomGuid;
64
64
  now;
65
+ onApplied;
65
66
  constructor(options) {
66
67
  this.pool = options.pool;
67
68
  this.logger = options.logger;
@@ -71,6 +72,7 @@ export class EventLogEngine {
71
72
  this.retentionDays = options.retentionDays ?? DEFAULT_RETENTION_DAYS;
72
73
  this.randomGuid = options.randomGuid ?? randomUUID;
73
74
  this.now = options.now ?? Date.now;
75
+ this.onApplied = options.onApplied;
74
76
  }
75
77
  /** Apply one event. Domain validation failures (`SyncError`) are stable
76
78
  * rejections. An unexpected failure is retried once, because event GUID
@@ -79,6 +81,20 @@ export class EventLogEngine {
79
81
  * rejected as `internal`, and any other throws `SyncUnavailableError`: no
80
82
  * verdict, the caller must make the client re-send. */
81
83
  async apply(scopeKey, clientGuid, event) {
84
+ const outcome = await this.applyWithRetry(scopeKey, clientGuid, event);
85
+ if (this.onApplied && outcome.kind !== 'rejected')
86
+ this.notifyApplied(scopeKey, outcome);
87
+ return outcome;
88
+ }
89
+ notifyApplied(scopeKey, outcome) {
90
+ try {
91
+ this.onApplied(scopeKey, outcome);
92
+ }
93
+ catch (error) {
94
+ this.logger.error('sync.on_applied_failed', { scopeKey, outcome: outcome.kind, error });
95
+ }
96
+ }
97
+ async applyWithRetry(scopeKey, clientGuid, event) {
82
98
  try {
83
99
  return await this.applyOnce(scopeKey, clientGuid, event);
84
100
  }
@@ -2,3 +2,4 @@ export * from './outbox.js';
2
2
  export * from './client.js';
3
3
  export * from './quiet-status.js';
4
4
  export * from './hub.js';
5
+ export * from './page-hub-url.js';
@@ -2,3 +2,4 @@ export * from './outbox.js';
2
2
  export * from './client.js';
3
3
  export * from './quiet-status.js';
4
4
  export * from './hub.js';
5
+ export * from './page-hub-url.js';
@@ -0,0 +1,4 @@
1
+ /** The meta tag's name. */
2
+ export declare const PAGE_HUB_URL_META = "pw-hub-url";
3
+ /** The tag's trimmed content, or undefined when the tag is absent or empty. */
4
+ export declare function pageHubUrl(doc?: Pick<Document, 'querySelector'>): string | undefined;
@@ -0,0 +1,11 @@
1
+ // The connection hub's base URL from the page shell's `pw-hub-url` meta tag.
2
+ // An app's server writes the tag only when it has HUB_URL; a client handed the
3
+ // result as `hubUrl` runs in hub mode (the live socket is the hub's and
4
+ // carries hints only), and with `undefined` keeps its same-origin socket.
5
+ /** The meta tag's name. */
6
+ export const PAGE_HUB_URL_META = 'pw-hub-url';
7
+ /** The tag's trimmed content, or undefined when the tag is absent or empty. */
8
+ export function pageHubUrl(doc = document) {
9
+ const content = doc.querySelector(`meta[name="${PAGE_HUB_URL_META}"]`)?.getAttribute('content')?.trim();
10
+ return content ? content : undefined;
11
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@steve31415/baselib",
3
- "version": "3.61.0",
3
+ "version": "3.62.1",
4
4
  "description": "Plasticine new-world shared platform library: logging, auth, service-to-service auth, db, HTTP, sync, app updates",
5
5
  "type": "module",
6
6
  "license": "MIT",