@venizia/ignis-worker 0.4.3 → 0.4.4

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.
Files changed (83) hide show
  1. package/LICENSE.md +2 -5
  2. package/README.md +13 -0
  3. package/package.json +9 -15
  4. package/dist/cjs/applications/common/index.d.ts +0 -2
  5. package/dist/cjs/applications/common/index.d.ts.map +0 -1
  6. package/dist/cjs/applications/common/index.js +0 -18
  7. package/dist/cjs/applications/common/index.js.map +0 -1
  8. package/dist/cjs/applications/common/types.d.ts +0 -10
  9. package/dist/cjs/applications/common/types.d.ts.map +0 -1
  10. package/dist/cjs/applications/common/types.js +0 -3
  11. package/dist/cjs/applications/common/types.js.map +0 -1
  12. package/dist/cjs/applications/index.d.ts +0 -3
  13. package/dist/cjs/applications/index.d.ts.map +0 -1
  14. package/dist/cjs/applications/index.js +0 -19
  15. package/dist/cjs/applications/index.js.map +0 -1
  16. package/dist/cjs/applications/worker.d.ts +0 -79
  17. package/dist/cjs/applications/worker.d.ts.map +0 -1
  18. package/dist/cjs/applications/worker.js +0 -190
  19. package/dist/cjs/applications/worker.js.map +0 -1
  20. package/dist/cjs/envelope/common/index.d.ts +0 -2
  21. package/dist/cjs/envelope/common/index.d.ts.map +0 -1
  22. package/dist/cjs/envelope/common/index.js +0 -18
  23. package/dist/cjs/envelope/common/index.js.map +0 -1
  24. package/dist/cjs/envelope/common/types.d.ts +0 -37
  25. package/dist/cjs/envelope/common/types.d.ts.map +0 -1
  26. package/dist/cjs/envelope/common/types.js +0 -3
  27. package/dist/cjs/envelope/common/types.js.map +0 -1
  28. package/dist/cjs/envelope/encode.d.ts +0 -61
  29. package/dist/cjs/envelope/encode.d.ts.map +0 -1
  30. package/dist/cjs/envelope/encode.js +0 -116
  31. package/dist/cjs/envelope/encode.js.map +0 -1
  32. package/dist/cjs/envelope/index.d.ts +0 -3
  33. package/dist/cjs/envelope/index.d.ts.map +0 -1
  34. package/dist/cjs/envelope/index.js +0 -19
  35. package/dist/cjs/envelope/index.js.map +0 -1
  36. package/dist/cjs/index.d.ts +0 -5
  37. package/dist/cjs/index.d.ts.map +0 -1
  38. package/dist/cjs/index.js +0 -21
  39. package/dist/cjs/index.js.map +0 -1
  40. package/dist/cjs/transport/common/index.d.ts +0 -2
  41. package/dist/cjs/transport/common/index.d.ts.map +0 -1
  42. package/dist/cjs/transport/common/index.js +0 -18
  43. package/dist/cjs/transport/common/index.js.map +0 -1
  44. package/dist/cjs/transport/common/types.d.ts +0 -6
  45. package/dist/cjs/transport/common/types.d.ts.map +0 -1
  46. package/dist/cjs/transport/common/types.js +0 -3
  47. package/dist/cjs/transport/common/types.js.map +0 -1
  48. package/dist/cjs/transport/fetch-bridge.d.ts +0 -41
  49. package/dist/cjs/transport/fetch-bridge.d.ts.map +0 -1
  50. package/dist/cjs/transport/fetch-bridge.js +0 -104
  51. package/dist/cjs/transport/fetch-bridge.js.map +0 -1
  52. package/dist/cjs/transport/in-process.d.ts +0 -23
  53. package/dist/cjs/transport/in-process.d.ts.map +0 -1
  54. package/dist/cjs/transport/in-process.js +0 -47
  55. package/dist/cjs/transport/in-process.js.map +0 -1
  56. package/dist/cjs/transport/index.d.ts +0 -6
  57. package/dist/cjs/transport/index.d.ts.map +0 -1
  58. package/dist/cjs/transport/index.js +0 -22
  59. package/dist/cjs/transport/index.js.map +0 -1
  60. package/dist/cjs/transport/shared/common/constants.d.ts +0 -14
  61. package/dist/cjs/transport/shared/common/constants.d.ts.map +0 -1
  62. package/dist/cjs/transport/shared/common/constants.js +0 -19
  63. package/dist/cjs/transport/shared/common/constants.js.map +0 -1
  64. package/dist/cjs/transport/shared/common/index.d.ts +0 -3
  65. package/dist/cjs/transport/shared/common/index.d.ts.map +0 -1
  66. package/dist/cjs/transport/shared/common/index.js +0 -19
  67. package/dist/cjs/transport/shared/common/index.js.map +0 -1
  68. package/dist/cjs/transport/shared/common/types.d.ts +0 -35
  69. package/dist/cjs/transport/shared/common/types.d.ts.map +0 -1
  70. package/dist/cjs/transport/shared/common/types.js +0 -3
  71. package/dist/cjs/transport/shared/common/types.js.map +0 -1
  72. package/dist/cjs/transport/shared/index.d.ts +0 -4
  73. package/dist/cjs/transport/shared/index.d.ts.map +0 -1
  74. package/dist/cjs/transport/shared/index.js +0 -11
  75. package/dist/cjs/transport/shared/index.js.map +0 -1
  76. package/dist/cjs/transport/shared/transport.d.ts +0 -87
  77. package/dist/cjs/transport/shared/transport.d.ts.map +0 -1
  78. package/dist/cjs/transport/shared/transport.js +0 -384
  79. package/dist/cjs/transport/shared/transport.js.map +0 -1
  80. package/dist/cjs/transport/worker.d.ts +0 -62
  81. package/dist/cjs/transport/worker.d.ts.map +0 -1
  82. package/dist/cjs/transport/worker.js +0 -224
  83. package/dist/cjs/transport/worker.js.map +0 -1
@@ -1,14 +0,0 @@
1
- export declare const DEFAULT_CHANNEL_NAME = "ignis.bff";
2
- export declare const DEFAULT_TIMEOUT_MS = 30000;
3
- /** Which part this tab plays. `ELECTING` is the brief window before the lock answers. */
4
- export declare class BffRoles {
5
- static readonly ELECTING = "electing";
6
- static readonly LEADER = "leader";
7
- static readonly FOLLOWER = "follower";
8
- }
9
- export declare class ChannelMessageKinds {
10
- static readonly REQUEST = "ignis.bff.request";
11
- static readonly RESPONSE = "ignis.bff.response";
12
- static readonly ERROR = "ignis.bff.error";
13
- }
14
- //# sourceMappingURL=constants.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"constants.d.ts","sourceRoot":"","sources":["../../../../../src/transport/shared/common/constants.ts"],"names":[],"mappings":"AAAA,eAAO,MAAM,oBAAoB,cAAc,CAAC;AAChD,eAAO,MAAM,kBAAkB,QAAS,CAAC;AAEzC,yFAAyF;AACzF,qBAAa,QAAQ;IACnB,MAAM,CAAC,QAAQ,CAAC,QAAQ,cAAc;IACtC,MAAM,CAAC,QAAQ,CAAC,MAAM,YAAY;IAClC,MAAM,CAAC,QAAQ,CAAC,QAAQ,cAAc;CACvC;AAED,qBAAa,mBAAmB;IAC9B,MAAM,CAAC,QAAQ,CAAC,OAAO,uBAAuB;IAC9C,MAAM,CAAC,QAAQ,CAAC,QAAQ,wBAAwB;IAChD,MAAM,CAAC,QAAQ,CAAC,KAAK,qBAAqB;CAC3C"}
@@ -1,19 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.ChannelMessageKinds = exports.BffRoles = exports.DEFAULT_TIMEOUT_MS = exports.DEFAULT_CHANNEL_NAME = void 0;
4
- exports.DEFAULT_CHANNEL_NAME = 'ignis.bff';
5
- exports.DEFAULT_TIMEOUT_MS = 30_000;
6
- /** Which part this tab plays. `ELECTING` is the brief window before the lock answers. */
7
- class BffRoles {
8
- static { this.ELECTING = 'electing'; }
9
- static { this.LEADER = 'leader'; }
10
- static { this.FOLLOWER = 'follower'; }
11
- }
12
- exports.BffRoles = BffRoles;
13
- class ChannelMessageKinds {
14
- static { this.REQUEST = 'ignis.bff.request'; }
15
- static { this.RESPONSE = 'ignis.bff.response'; }
16
- static { this.ERROR = 'ignis.bff.error'; }
17
- }
18
- exports.ChannelMessageKinds = ChannelMessageKinds;
19
- //# sourceMappingURL=constants.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"constants.js","sourceRoot":"","sources":["../../../../../src/transport/shared/common/constants.ts"],"names":[],"mappings":";;;AAAa,QAAA,oBAAoB,GAAG,WAAW,CAAC;AACnC,QAAA,kBAAkB,GAAG,MAAM,CAAC;AAEzC,yFAAyF;AACzF,MAAa,QAAQ;aACH,aAAQ,GAAG,UAAU,CAAC;aACtB,WAAM,GAAG,QAAQ,CAAC;aAClB,aAAQ,GAAG,UAAU,CAAC;;AAHxC,4BAIC;AAED,MAAa,mBAAmB;aACd,YAAO,GAAG,mBAAmB,CAAC;aAC9B,aAAQ,GAAG,oBAAoB,CAAC;aAChC,UAAK,GAAG,iBAAiB,CAAC;;AAH5C,kDAIC","sourcesContent":["export const DEFAULT_CHANNEL_NAME = 'ignis.bff';\nexport const DEFAULT_TIMEOUT_MS = 30_000;\n\n/** Which part this tab plays. `ELECTING` is the brief window before the lock answers. */\nexport class BffRoles {\n static readonly ELECTING = 'electing';\n static readonly LEADER = 'leader';\n static readonly FOLLOWER = 'follower';\n}\n\nexport class ChannelMessageKinds {\n static readonly REQUEST = 'ignis.bff.request';\n static readonly RESPONSE = 'ignis.bff.response';\n static readonly ERROR = 'ignis.bff.error';\n}\n"]}
@@ -1,3 +0,0 @@
1
- export * from './constants';
2
- export * from './types';
3
- //# sourceMappingURL=index.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../../../src/transport/shared/common/index.ts"],"names":[],"mappings":"AAAA,cAAc,aAAa,CAAC;AAC5B,cAAc,SAAS,CAAC"}
@@ -1,19 +0,0 @@
1
- "use strict";
2
- var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
- if (k2 === undefined) k2 = k;
4
- var desc = Object.getOwnPropertyDescriptor(m, k);
5
- if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
- desc = { enumerable: true, get: function() { return m[k]; } };
7
- }
8
- Object.defineProperty(o, k2, desc);
9
- }) : (function(o, m, k, k2) {
10
- if (k2 === undefined) k2 = k;
11
- o[k2] = m[k];
12
- }));
13
- var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
- for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
- };
16
- Object.defineProperty(exports, "__esModule", { value: true });
17
- __exportStar(require("./constants"), exports);
18
- __exportStar(require("./types"), exports);
19
- //# sourceMappingURL=index.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../../../../../src/transport/shared/common/index.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;AAAA,8CAA4B;AAC5B,0CAAwB","sourcesContent":["export * from './constants';\nexport * from './types';\n"]}
@@ -1,35 +0,0 @@
1
- import type { TConstValue } from '@venizia/ignis-helpers/common';
2
- import type { IBffErrorEnvelope, IBffRequestEnvelope, IBffResponseEnvelope } from '../../../envelope/common';
3
- import { type BffRoles, type ChannelMessageKinds } from './constants';
4
- export type TBffRole = TConstValue<typeof BffRoles>;
5
- /**
6
- * There is deliberately no "a new leader is ready" broadcast. A follower cannot act on one safely:
7
- * BroadcastChannel does not order messages across senders, so a request posted around the moment of
8
- * promotion may well be answered by the new leader - and a follower that failed its in-flight
9
- * requests on hearing the announcement would turn some of those successes into errors. The request
10
- * timeout is the one honest answer for that window.
11
- */
12
- export type TChannelMessage = {
13
- kind: typeof ChannelMessageKinds.REQUEST;
14
- envelope: IBffRequestEnvelope;
15
- } | {
16
- kind: typeof ChannelMessageKinds.RESPONSE;
17
- envelope: IBffResponseEnvelope;
18
- } | {
19
- kind: typeof ChannelMessageKinds.ERROR;
20
- envelope: IBffErrorEnvelope;
21
- };
22
- export interface IPendingRequest {
23
- resolve: (response: Response) => void;
24
- reject: (error: unknown) => void;
25
- release: () => void;
26
- }
27
- export interface ISharedBffTransportOptions {
28
- /** Builds the Worker. Called ONLY by whichever tab wins the election - the others never start one. */
29
- createWorker: () => Worker;
30
- /** Distinguishes independent BFFs on one origin. The lock name is derived from it. */
31
- channelName?: string;
32
- timeoutMs?: number;
33
- scope?: string;
34
- }
35
- //# sourceMappingURL=types.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../../../../../src/transport/shared/common/types.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,+BAA+B,CAAC;AACjE,OAAO,KAAK,EACV,iBAAiB,EACjB,mBAAmB,EACnB,oBAAoB,EACrB,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EAAE,KAAK,QAAQ,EAAE,KAAK,mBAAmB,EAAE,MAAM,aAAa,CAAC;AAEtE,MAAM,MAAM,QAAQ,GAAG,WAAW,CAAC,OAAO,QAAQ,CAAC,CAAC;AAEpD;;;;;;GAMG;AACH,MAAM,MAAM,eAAe,GACvB;IAAE,IAAI,EAAE,OAAO,mBAAmB,CAAC,OAAO,CAAC;IAAC,QAAQ,EAAE,mBAAmB,CAAA;CAAE,GAC3E;IAAE,IAAI,EAAE,OAAO,mBAAmB,CAAC,QAAQ,CAAC;IAAC,QAAQ,EAAE,oBAAoB,CAAA;CAAE,GAC7E;IAAE,IAAI,EAAE,OAAO,mBAAmB,CAAC,KAAK,CAAC;IAAC,QAAQ,EAAE,iBAAiB,CAAA;CAAE,CAAC;AAE5E,MAAM,WAAW,eAAe;IAC9B,OAAO,EAAE,CAAC,QAAQ,EAAE,QAAQ,KAAK,IAAI,CAAC;IACtC,MAAM,EAAE,CAAC,KAAK,EAAE,OAAO,KAAK,IAAI,CAAC;IACjC,OAAO,EAAE,MAAM,IAAI,CAAC;CACrB;AAED,MAAM,WAAW,0BAA0B;IACzC,sGAAsG;IACtG,YAAY,EAAE,MAAM,MAAM,CAAC;IAC3B,sFAAsF;IACtF,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,KAAK,CAAC,EAAE,MAAM,CAAC;CAChB"}
@@ -1,3 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- //# sourceMappingURL=types.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"types.js","sourceRoot":"","sources":["../../../../../src/transport/shared/common/types.ts"],"names":[],"mappings":"","sourcesContent":["import type { TConstValue } from '@venizia/ignis-helpers/common';\nimport type {\n IBffErrorEnvelope,\n IBffRequestEnvelope,\n IBffResponseEnvelope,\n} from '@/envelope/common';\nimport { type BffRoles, type ChannelMessageKinds } from './constants';\n\nexport type TBffRole = TConstValue<typeof BffRoles>;\n\n/**\n * There is deliberately no \"a new leader is ready\" broadcast. A follower cannot act on one safely:\n * BroadcastChannel does not order messages across senders, so a request posted around the moment of\n * promotion may well be answered by the new leader - and a follower that failed its in-flight\n * requests on hearing the announcement would turn some of those successes into errors. The request\n * timeout is the one honest answer for that window.\n */\nexport type TChannelMessage =\n | { kind: typeof ChannelMessageKinds.REQUEST; envelope: IBffRequestEnvelope }\n | { kind: typeof ChannelMessageKinds.RESPONSE; envelope: IBffResponseEnvelope }\n | { kind: typeof ChannelMessageKinds.ERROR; envelope: IBffErrorEnvelope };\n\nexport interface IPendingRequest {\n resolve: (response: Response) => void;\n reject: (error: unknown) => void;\n release: () => void;\n}\n\nexport interface ISharedBffTransportOptions {\n /** Builds the Worker. Called ONLY by whichever tab wins the election - the others never start one. */\n createWorker: () => Worker;\n /** Distinguishes independent BFFs on one origin. The lock name is derived from it. */\n channelName?: string;\n timeoutMs?: number;\n scope?: string;\n}\n"]}
@@ -1,4 +0,0 @@
1
- export { BffRoles } from './common/constants';
2
- export type { ISharedBffTransportOptions, TBffRole } from './common/types';
3
- export { SharedBffTransport } from './transport';
4
- //# sourceMappingURL=index.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../../src/transport/shared/index.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,QAAQ,EAAE,MAAM,oBAAoB,CAAC;AAC9C,YAAY,EAAE,0BAA0B,EAAE,QAAQ,EAAE,MAAM,gBAAgB,CAAC;AAC3E,OAAO,EAAE,kBAAkB,EAAE,MAAM,aAAa,CAAC"}
@@ -1,11 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.SharedBffTransport = exports.BffRoles = void 0;
4
- // `export * from './common'` would also publish five module-private names - `DEFAULT_CHANNEL_NAME`,
5
- // `DEFAULT_TIMEOUT_MS`, `ChannelMessageKinds`, `TChannelMessage`, `IPendingRequest` - through
6
- // `transport/index.ts`.
7
- var constants_1 = require("./common/constants");
8
- Object.defineProperty(exports, "BffRoles", { enumerable: true, get: function () { return constants_1.BffRoles; } });
9
- var transport_1 = require("./transport");
10
- Object.defineProperty(exports, "SharedBffTransport", { enumerable: true, get: function () { return transport_1.SharedBffTransport; } });
11
- //# sourceMappingURL=index.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../../../../src/transport/shared/index.ts"],"names":[],"mappings":";;;AAAA,oGAAoG;AACpG,8FAA8F;AAC9F,wBAAwB;AACxB,gDAA8C;AAArC,qGAAA,QAAQ,OAAA;AAEjB,yCAAiD;AAAxC,+GAAA,kBAAkB,OAAA","sourcesContent":["// `export * from './common'` would also publish five module-private names - `DEFAULT_CHANNEL_NAME`,\n// `DEFAULT_TIMEOUT_MS`, `ChannelMessageKinds`, `TChannelMessage`, `IPendingRequest` - through\n// `transport/index.ts`.\nexport { BffRoles } from './common/constants';\nexport type { ISharedBffTransportOptions, TBffRole } from './common/types';\nexport { SharedBffTransport } from './transport';\n"]}
@@ -1,87 +0,0 @@
1
- import { BaseHelper } from '@venizia/ignis-helpers/core';
2
- import type { IBffTransport } from '../common/types';
3
- import type { ISharedBffTransportOptions, TBffRole } from './common';
4
- /**
5
- * One BFF for every tab of an origin, instead of one per tab.
6
- *
7
- * The problem it solves is not a framework limitation, it is a storage one. PGlite in
8
- * `opfs-ahp://` mode holds an exclusive access handle on the database file, and OPFS access handles
9
- * are exclusive PER ORIGIN. Measured in Chromium with two tabs of the same page: the first tab
10
- * works, and the second never boots its database -
11
- * `Failed to execute 'createSyncAccessHandle' on 'FileSystemFileHandle': Access Handles cannot be
12
- * created if there is another open Access Handle or Writable stream associated with the same file`.
13
- * The first tab is unaffected, and closing it lets the second recover on reload - so the failure is
14
- * contained and self-healing, but the second tab is simply dead until then.
15
- *
16
- * So exactly one tab may own the database. This transport elects that tab with the Web Locks API,
17
- * gives it the Worker, and forwards every other tab's request to it over a `BroadcastChannel`,
18
- * carried in the same envelope the Worker itself speaks. When the leader's tab closes, the lock is
19
- * released by the browser and a follower is promoted automatically - no heartbeat, no timeout, no
20
- * stale-leader window to reason about.
21
- *
22
- * A host with no `navigator.locks` runs single-tab, exactly as before. That is not a compromise:
23
- * measured on a plain-http origin, `navigator.locks` and `navigator.storage.getDirectory` are BOTH
24
- * undefined, because both are secure-context only. Wherever OPFS works the lock exists, and where it
25
- * does not the database could not have started either.
26
- */
27
- export declare class SharedBffTransport extends BaseHelper implements IBffTransport {
28
- private readonly createWorker;
29
- private readonly channel;
30
- private readonly lockName;
31
- private readonly timeoutMs;
32
- private readonly requestIdGenerator;
33
- private readonly pendingRequests;
34
- private role;
35
- private leaderTransport?;
36
- private isClosed;
37
- /**
38
- * Held because THIS class created it. `WorkerBffTransport.close()` deliberately leaves a worker
39
- * running - it did not create the one it was handed - so without this reference the worker would
40
- * outlive `close()` still holding the exclusive OPFS access handle, while the lock has already
41
- * gone to another tab that opens the same database.
42
- */
43
- private leaderWorker?;
44
- /** Set when `createWorker()` throws, so callers get that failure instead of parking forever. */
45
- private leaderStartupError?;
46
- /** Resolving this releases the Web Lock, which is what promotes a follower. */
47
- private releaseLeadership?;
48
- /** Drops this tab out of the lock QUEUE on close, so a closed transport cannot be promoted. */
49
- private readonly leadershipQueueAbort;
50
- /** Callers parked in `fetch()` while the election is still running. */
51
- private roleWaiters;
52
- constructor(opts: ISharedBffTransportOptions);
53
- getRole(): TBffRole;
54
- fetch(opts: {
55
- request: Request;
56
- }): Promise<Response>;
57
- close(): void;
58
- private elect;
59
- private becomeLeader;
60
- private becomeFollower;
61
- private heldUntilClosed;
62
- private whenRoleSettled;
63
- private settleRoleWaiters;
64
- /**
65
- * The caller's `AbortSignal` is honoured HERE as well as in `WorkerBffTransport`. Without it the
66
- * same page code behaves differently depending on which tab won the lock: abort works in the
67
- * leader and silently does nothing in every follower, so a data provider that aborts on unmount
68
- * leaves promises pending for the full timeout in every tab but one.
69
- *
70
- * Aborting settles the CALLER. It does not cancel the leader's work - there is no cancel message,
71
- * and a write already dispatched cannot be taken back.
72
- */
73
- private fetchViaLeader;
74
- /** `signal.reason` first, the way `globalThis.fetch` rejects, so a custom abort reason survives. */
75
- private toAbortError;
76
- private takePending;
77
- private rejectAllPending;
78
- /**
79
- * A `BroadcastChannel` never delivers a message to the instance that sent it, so a leader does not
80
- * hear its own answers and a follower does not hear its own requests. Every tab does hear every
81
- * OTHER tab, which is why a response is matched by id and silently ignored when it belongs to
82
- * someone else.
83
- */
84
- private readonly handleChannelMessage;
85
- private serveAsLeader;
86
- }
87
- //# sourceMappingURL=transport.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"transport.d.ts","sourceRoot":"","sources":["../../../../src/transport/shared/transport.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAgC,MAAM,6BAA6B,CAAC;AAGvF,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,iBAAiB,CAAC;AAGrD,OAAO,KAAK,EAEV,0BAA0B,EAC1B,QAAQ,EAET,MAAM,UAAU,CAAC;AAElB;;;;;;;;;;;;;;;;;;;;;;GAsBG;AACH,qBAAa,kBAAmB,SAAQ,UAAW,YAAW,aAAa;IACzE,OAAO,CAAC,QAAQ,CAAC,YAAY,CAAe;IAC5C,OAAO,CAAC,QAAQ,CAAC,OAAO,CAAmB;IAC3C,OAAO,CAAC,QAAQ,CAAC,QAAQ,CAAS;IAClC,OAAO,CAAC,QAAQ,CAAC,SAAS,CAAS;IACnC,OAAO,CAAC,QAAQ,CAAC,kBAAkB,CAAqB;IACxD,OAAO,CAAC,QAAQ,CAAC,eAAe,CAAsC;IAEtE,OAAO,CAAC,IAAI,CAA+B;IAC3C,OAAO,CAAC,eAAe,CAAC,CAAqB;IAC7C,OAAO,CAAC,QAAQ,CAAS;IAEzB;;;;;OAKG;IACH,OAAO,CAAC,YAAY,CAAC,CAAS;IAE9B,gGAAgG;IAChG,OAAO,CAAC,kBAAkB,CAAC,CAAU;IAErC,+EAA+E;IAC/E,OAAO,CAAC,iBAAiB,CAAC,CAAa;IAEvC,+FAA+F;IAC/F,OAAO,CAAC,QAAQ,CAAC,oBAAoB,CAAyB;IAE9D,uEAAuE;IACvE,OAAO,CAAC,WAAW,CAAyB;gBAEhC,IAAI,EAAE,0BAA0B;IAkC5C,OAAO,IAAI,QAAQ;IAIb,KAAK,CAAC,IAAI,EAAE;QAAE,OAAO,EAAE,OAAO,CAAA;KAAE,GAAG,OAAO,CAAC,QAAQ,CAAC;IAkC1D,KAAK,IAAI,IAAI;YA+BC,KAAK;IA4DnB,OAAO,CAAC,YAAY;IA6BpB,OAAO,CAAC,cAAc;IAKtB,OAAO,CAAC,eAAe;IAMvB,OAAO,CAAC,eAAe;IAUvB,OAAO,CAAC,iBAAiB;IASzB;;;;;;;;OAQG;YACW,cAAc;IAoD5B,oGAAoG;IACpG,OAAO,CAAC,YAAY;IAOpB,OAAO,CAAC,WAAW;IAWnB,OAAO,CAAC,gBAAgB;IAWxB;;;;;OAKG;IACH,OAAO,CAAC,QAAQ,CAAC,oBAAoB,CA4EnC;YAEY,aAAa;CAyB5B"}
@@ -1,384 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.SharedBffTransport = void 0;
4
- const core_1 = require("@venizia/ignis-helpers/core");
5
- const encode_1 = require("../../envelope/encode");
6
- const worker_1 = require("../worker");
7
- const common_1 = require("./common");
8
- /**
9
- * One BFF for every tab of an origin, instead of one per tab.
10
- *
11
- * The problem it solves is not a framework limitation, it is a storage one. PGlite in
12
- * `opfs-ahp://` mode holds an exclusive access handle on the database file, and OPFS access handles
13
- * are exclusive PER ORIGIN. Measured in Chromium with two tabs of the same page: the first tab
14
- * works, and the second never boots its database -
15
- * `Failed to execute 'createSyncAccessHandle' on 'FileSystemFileHandle': Access Handles cannot be
16
- * created if there is another open Access Handle or Writable stream associated with the same file`.
17
- * The first tab is unaffected, and closing it lets the second recover on reload - so the failure is
18
- * contained and self-healing, but the second tab is simply dead until then.
19
- *
20
- * So exactly one tab may own the database. This transport elects that tab with the Web Locks API,
21
- * gives it the Worker, and forwards every other tab's request to it over a `BroadcastChannel`,
22
- * carried in the same envelope the Worker itself speaks. When the leader's tab closes, the lock is
23
- * released by the browser and a follower is promoted automatically - no heartbeat, no timeout, no
24
- * stale-leader window to reason about.
25
- *
26
- * A host with no `navigator.locks` runs single-tab, exactly as before. That is not a compromise:
27
- * measured on a plain-http origin, `navigator.locks` and `navigator.storage.getDirectory` are BOTH
28
- * undefined, because both are secure-context only. Wherever OPFS works the lock exists, and where it
29
- * does not the database could not have started either.
30
- */
31
- class SharedBffTransport extends core_1.BaseHelper {
32
- constructor(opts) {
33
- super({ scope: opts.scope ?? SharedBffTransport.name });
34
- this.pendingRequests = new Map();
35
- this.role = common_1.BffRoles.ELECTING;
36
- this.isClosed = false;
37
- /** Drops this tab out of the lock QUEUE on close, so a closed transport cannot be promoted. */
38
- this.leadershipQueueAbort = new AbortController();
39
- /** Callers parked in `fetch()` while the election is still running. */
40
- this.roleWaiters = [];
41
- /**
42
- * A `BroadcastChannel` never delivers a message to the instance that sent it, so a leader does not
43
- * hear its own answers and a follower does not hear its own requests. Every tab does hear every
44
- * OTHER tab, which is why a response is matched by id and silently ignored when it belongs to
45
- * someone else.
46
- */
47
- this.handleChannelMessage = (event) => {
48
- const message = event.data;
49
- switch (message?.kind) {
50
- case common_1.ChannelMessageKinds.REQUEST: {
51
- if (this.role !== common_1.BffRoles.LEADER) {
52
- return;
53
- }
54
- // `serveAsLeader` answers its own failures on the channel; this catch is for the one case
55
- // it cannot - the channel itself refusing the message, e.g. a body that will not clone.
56
- this.serveAsLeader({ envelope: message.envelope }).catch((error) => {
57
- this.logger
58
- .for(this.serveAsLeader.name)
59
- .error('Could not answer a follower at all | id: %s | error: %s', message.envelope.id, error);
60
- });
61
- return;
62
- }
63
- // Both decodes are guarded. The channel is origin-wide and its name is the application's, not
64
- // a secret, and version skew is the realistic trigger: a long-lived tab on v1 and a new tab
65
- // on v2 share the same channel and lock BY DESIGN. An envelope this build cannot read must
66
- // fail its caller, never leave the promise unsettled for the full timeout.
67
- case common_1.ChannelMessageKinds.RESPONSE: {
68
- const pending = this.takePending({ id: message.envelope.id });
69
- if (!pending) {
70
- return;
71
- }
72
- try {
73
- pending.resolve(encode_1.BffEnvelope.decodeResponse({ envelope: message.envelope }));
74
- }
75
- catch (error) {
76
- this.logger
77
- .for(this.handleChannelMessage.name)
78
- .error('Undecodable response envelope | id: %s | error: %s', message.envelope.id, error);
79
- pending.reject((0, core_1.getError)({
80
- message: `[SharedBffTransport] The leader's response could not be decoded | id: ${message.envelope.id}`,
81
- cause: error,
82
- }));
83
- }
84
- return;
85
- }
86
- case common_1.ChannelMessageKinds.ERROR: {
87
- const pending = this.takePending({ id: message.envelope.id });
88
- if (!pending) {
89
- return;
90
- }
91
- try {
92
- pending.reject(encode_1.BffEnvelope.decodeError({ envelope: message.envelope }));
93
- }
94
- catch (error) {
95
- pending.reject((0, core_1.getError)({
96
- message: `[SharedBffTransport] The leader's error envelope could not be decoded | id: ${message.envelope.id}`,
97
- cause: error,
98
- }));
99
- }
100
- return;
101
- }
102
- default: {
103
- return;
104
- }
105
- }
106
- };
107
- const channelName = opts.channelName ?? common_1.DEFAULT_CHANNEL_NAME;
108
- this.createWorker = opts.createWorker;
109
- this.timeoutMs = opts.timeoutMs ?? common_1.DEFAULT_TIMEOUT_MS;
110
- this.lockName = `${channelName}.leader`;
111
- this.requestIdGenerator = new core_1.RequestIdGenerator({ scope: SharedBffTransport.name });
112
- // Attached BEFORE the election starts: a tab that becomes leader a moment later must not miss a
113
- // request a follower posted while it was still deciding.
114
- this.channel = new BroadcastChannel(channelName);
115
- this.channel.addEventListener('message', this.handleChannelMessage);
116
- // A failed election must not leave `fetch()` parked forever waiting for a role that never
117
- // arrives: this tab falls back to serving itself, which is the pre-election behaviour.
118
- this.elect().catch((error) => {
119
- // `close()` aborts the queued lock request, and the rejection that produces is the expected
120
- // end of the election - not a failure to report.
121
- if (this.isClosed) {
122
- return;
123
- }
124
- this.logger
125
- .for(this.elect.name)
126
- .error('Leader election failed, falling back to single-tab | error: %s', error);
127
- if (this.role === common_1.BffRoles.ELECTING) {
128
- this.becomeLeader();
129
- }
130
- });
131
- }
132
- getRole() {
133
- return this.role;
134
- }
135
- async fetch(opts) {
136
- if (this.isClosed) {
137
- throw (0, core_1.getError)({
138
- message: '[SharedBffTransport] The transport is closed | open a new one to make requests',
139
- });
140
- }
141
- await this.whenRoleSettled();
142
- // Re-checked AFTER the await: `close()` can land while the election is still running, and
143
- // posting then reaches a channel that is already closed - the caller would get a raw
144
- // `DOMException` instead of this error, and a pending entry plus a live timer would be left
145
- // behind on a transport nothing can settle.
146
- if (this.isClosed) {
147
- throw (0, core_1.getError)({
148
- message: '[SharedBffTransport] The transport is closed | open a new one to make requests',
149
- });
150
- }
151
- if (this.leaderStartupError) {
152
- throw (0, core_1.getError)({
153
- message: '[SharedBffTransport] This tab leads but its BFF worker never started | reload the page',
154
- cause: this.leaderStartupError,
155
- });
156
- }
157
- if (this.role === common_1.BffRoles.LEADER && this.leaderTransport) {
158
- return this.leaderTransport.fetch(opts);
159
- }
160
- return this.fetchViaLeader(opts);
161
- }
162
- close() {
163
- this.isClosed = true;
164
- // A follower is parked in the lock QUEUE rather than holding anything. Without this it stays
165
- // queued after close, and the browser would eventually hand leadership to a dead transport -
166
- // which returns straight away, but only after the tab that could have served was skipped.
167
- this.leadershipQueueAbort.abort();
168
- // ORDER IS THE POINT, and it is the opposite of the obvious one. The worker has to be GONE
169
- // before the lock is released: releasing first promotes another tab, which opens the same OPFS
170
- // database while this worker still holds the exclusive access handle - the exact failure this
171
- // transport exists to prevent, reintroduced by its own teardown.
172
- //
173
- // `terminate()` is abrupt by design. It is no worse than the tab-close path the browser already
174
- // takes on every leader, and leaving the worker alive is strictly worse than an abrupt stop.
175
- this.leaderTransport?.close();
176
- this.leaderTransport = undefined;
177
- this.leaderWorker?.terminate();
178
- this.leaderWorker = undefined;
179
- // Only now: the next tab may open the database.
180
- this.releaseLeadership?.();
181
- this.releaseLeadership = undefined;
182
- this.channel.removeEventListener('message', this.handleChannelMessage);
183
- this.channel.close();
184
- this.rejectAllPending({ reason: 'the transport was closed' });
185
- this.settleRoleWaiters();
186
- }
187
- async elect() {
188
- const locks = globalThis.navigator?.locks;
189
- if (!locks) {
190
- this.logger
191
- .for(this.elect.name)
192
- .warn('navigator.locks is unavailable - running single-tab | a second tab cannot open the same OPFS database');
193
- this.becomeLeader();
194
- return;
195
- }
196
- // `ifAvailable` answers NOW instead of queueing, which is what lets this tab find out it is a
197
- // follower rather than hanging until the current leader goes away.
198
- const hasWon = await locks.request(this.lockName, { ifAvailable: true }, async (lock) => {
199
- if (!lock) {
200
- return false;
201
- }
202
- // Symmetric with the queued branch below, and not defensive padding. A real `LockManager`
203
- // grants from a queued task - it never runs this callback synchronously inside `request()` -
204
- // so `close()` can land between the constructor and this line. Without the guard a CLOSED
205
- // transport starts a worker, reports itself leader, and then holds the lock for the lifetime
206
- // of the page: `close()` has already read and cleared `releaseLeadership`, so the assignment
207
- // `heldUntilClosed()` makes below can never be resolved by anything. No other tab is ever
208
- // promoted, and this one answers nobody - its channel listener is already detached.
209
- //
210
- // Returning true, not false: this tab DID hold the lock. Returning releases it immediately,
211
- // which is exactly what a closed transport should do with it.
212
- if (this.isClosed) {
213
- return true;
214
- }
215
- this.becomeLeader();
216
- await this.heldUntilClosed();
217
- return true;
218
- });
219
- if (hasWon || this.isClosed) {
220
- return;
221
- }
222
- this.becomeFollower();
223
- // Queues behind the current leader. The browser releases its lock when that tab goes away - a
224
- // crash included - so this resolves without anything having to detect the death.
225
- await locks.request(this.lockName, { signal: this.leadershipQueueAbort.signal }, async () => {
226
- if (this.isClosed) {
227
- return;
228
- }
229
- this.logger
230
- .for(this.elect.name)
231
- .info('Promoted to leader | previous leader released the lock');
232
- this.becomeLeader();
233
- await this.heldUntilClosed();
234
- });
235
- }
236
- becomeLeader() {
237
- // Anything this tab had in flight was addressed to the leader that just went away. It cannot be
238
- // replayed - a write may well have been applied - so it is failed explicitly rather than left
239
- // to run out its timeout under a leader that will never answer it.
240
- this.rejectAllPending({
241
- reason: 'the leader serving it went away before this tab was promoted',
242
- });
243
- try {
244
- this.leaderWorker = this.createWorker();
245
- this.leaderTransport = new worker_1.WorkerBffTransport({
246
- worker: this.leaderWorker,
247
- timeoutMs: this.timeoutMs,
248
- });
249
- }
250
- catch (error) {
251
- // A CSP refusal or a bad worker URL must still SETTLE the role. `whenRoleSettled()` has no
252
- // timeout of its own and the per-request timer is armed only inside `fetchViaLeader()`, which
253
- // this tab never reaches - so leaving the role unsettled hangs every caller forever, with no
254
- // error and no log per request.
255
- this.leaderStartupError = error;
256
- this.logger
257
- .for(this.becomeLeader.name)
258
- .error('Could not start the BFF worker | error: %s', error);
259
- }
260
- this.role = common_1.BffRoles.LEADER;
261
- this.settleRoleWaiters();
262
- }
263
- becomeFollower() {
264
- this.role = common_1.BffRoles.FOLLOWER;
265
- this.settleRoleWaiters();
266
- }
267
- heldUntilClosed() {
268
- return new Promise((resolve) => {
269
- this.releaseLeadership = resolve;
270
- });
271
- }
272
- whenRoleSettled() {
273
- if (this.role !== common_1.BffRoles.ELECTING) {
274
- return Promise.resolve();
275
- }
276
- return new Promise((resolve) => {
277
- this.roleWaiters.push(resolve);
278
- });
279
- }
280
- settleRoleWaiters() {
281
- const waiters = this.roleWaiters;
282
- this.roleWaiters = [];
283
- for (const waiter of waiters) {
284
- waiter();
285
- }
286
- }
287
- /**
288
- * The caller's `AbortSignal` is honoured HERE as well as in `WorkerBffTransport`. Without it the
289
- * same page code behaves differently depending on which tab won the lock: abort works in the
290
- * leader and silently does nothing in every follower, so a data provider that aborts on unmount
291
- * leaves promises pending for the full timeout in every tab but one.
292
- *
293
- * Aborting settles the CALLER. It does not cancel the leader's work - there is no cancel message,
294
- * and a write already dispatched cannot be taken back.
295
- */
296
- async fetchViaLeader(opts) {
297
- const { signal } = opts.request;
298
- if (signal?.aborted) {
299
- throw this.toAbortError({ signal });
300
- }
301
- const id = this.requestIdGenerator.nextId();
302
- const envelope = await encode_1.BffEnvelope.encodeRequest({
303
- request: opts.request,
304
- id,
305
- url: encode_1.BffEnvelope.toSyntheticUrl({ url: opts.request.url }),
306
- });
307
- return new Promise((resolve, reject) => {
308
- const timer = setTimeout(() => {
309
- this.takePending({ id })?.reject((0, core_1.getError)({
310
- message: `[SharedBffTransport] Timed out waiting for the leader tab | id: ${id} | timeoutMs: ${this.timeoutMs}`,
311
- }));
312
- }, this.timeoutMs);
313
- const handleAbort = () => {
314
- this.takePending({ id })?.reject(this.toAbortError({ signal }));
315
- };
316
- signal?.addEventListener('abort', handleAbort);
317
- this.pendingRequests.set(id, {
318
- resolve,
319
- reject,
320
- release: () => {
321
- clearTimeout(timer);
322
- signal?.removeEventListener('abort', handleAbort);
323
- },
324
- });
325
- // Buffering the body took an await, and `addEventListener('abort')` never fires on a signal
326
- // that aborted before it was attached - without this re-read that window loses the abort.
327
- if (signal?.aborted) {
328
- handleAbort();
329
- return;
330
- }
331
- this.channel.postMessage({
332
- kind: common_1.ChannelMessageKinds.REQUEST,
333
- envelope,
334
- });
335
- });
336
- }
337
- /** `signal.reason` first, the way `globalThis.fetch` rejects, so a custom abort reason survives. */
338
- toAbortError(opts) {
339
- return (opts.signal?.reason ??
340
- (0, core_1.getError)({ message: '[SharedBffTransport] The request was aborted by its caller' }));
341
- }
342
- takePending(opts) {
343
- const pending = this.pendingRequests.get(opts.id);
344
- if (!pending) {
345
- return undefined;
346
- }
347
- this.pendingRequests.delete(opts.id);
348
- pending.release();
349
- return pending;
350
- }
351
- rejectAllPending(opts) {
352
- const pendingRequestsKeys = [...this.pendingRequests.keys()];
353
- for (const id of pendingRequestsKeys) {
354
- this.takePending({ id })?.reject((0, core_1.getError)({
355
- message: `[SharedBffTransport] Request abandoned | id: ${id} | reason: ${opts.reason}`,
356
- }));
357
- }
358
- }
359
- async serveAsLeader(opts) {
360
- const { envelope } = opts;
361
- try {
362
- const response = await this.leaderTransport.fetch({
363
- request: encode_1.BffEnvelope.decodeRequest({ envelope }),
364
- });
365
- this.channel.postMessage({
366
- kind: common_1.ChannelMessageKinds.RESPONSE,
367
- envelope: await encode_1.BffEnvelope.encodeResponse({ response, id: envelope.id }),
368
- });
369
- }
370
- catch (error) {
371
- // The follower gets the failure as a failure, rather than waiting out a timeout that would
372
- // tell it nothing about what went wrong.
373
- this.logger
374
- .for(this.serveAsLeader.name)
375
- .error('Failed to serve a follower request | id: %s | error: %s', envelope.id, error);
376
- this.channel.postMessage({
377
- kind: common_1.ChannelMessageKinds.ERROR,
378
- envelope: encode_1.BffEnvelope.encodeError({ id: envelope.id, error }),
379
- });
380
- }
381
- }
382
- }
383
- exports.SharedBffTransport = SharedBffTransport;
384
- //# sourceMappingURL=transport.js.map