@webpieces/core-util 0.4.1002 → 0.4.1004

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@webpieces/core-util",
3
- "version": "0.4.1002",
3
+ "version": "0.4.1004",
4
4
  "description": "Utility functions for WebPieces - works in browser and Node.js",
5
5
  "type": "commonjs",
6
6
  "main": "./src/index.js",
@@ -1,5 +1,14 @@
1
1
  import { CallContext } from './CallStrategy';
2
- /** Transport deadline. The race bounds even transports that ignore cancellation. */
2
+ import { DeadlineScheduler } from './DeadlineScheduler';
3
+ /**
4
+ * Transport deadline. The race bounds even transports that ignore cancellation, and a body read that
5
+ * never ends: the deadline covers everything inside `work` — URL resolution, filters, auth, the send
6
+ * and the response body — exactly as the caller's per-attempt budget says.
7
+ *
8
+ * Timing comes from the caller's {@link DeadlineScheduler} (#1445), never from a global timer, so a
9
+ * React Native client whose JS timers pause while the phone is locked can still be cancelled by a
10
+ * native-delivered deadline.
11
+ */
3
12
  export declare class CallDeadline {
4
13
  /**
5
14
  * AbortController.abort(reason) is not portable: React Native's abort-controller 3 signal has
@@ -7,7 +16,7 @@ export declare class CallDeadline {
7
16
  */
8
17
  private static readonly failures;
9
18
  static validate(timeoutMs: number): void;
10
- static run<T>(timeoutMs: number, context: CallContext, work: (signal: AbortSignal) => Promise<T>): Promise<T>;
19
+ static run<T>(timeoutMs: number, context: CallContext, deadlines: DeadlineScheduler, work: (signal: AbortSignal) => Promise<T>): Promise<T>;
11
20
  /** Throw the exact deadline failure without relying on optional AbortSignal extensions. */
12
21
  static throwIfAborted(signal: AbortSignal): void;
13
22
  }
@@ -2,7 +2,74 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.CallDeadline = void 0;
4
4
  const ApiCallTimeoutError_1 = require("./ApiCallTimeoutError");
5
- /** Transport deadline. The race bounds even transports that ignore cancellation. */
5
+ /**
6
+ * The state of ONE deadline-bounded run. Every transition is guarded so a late native callback, a
7
+ * settlement racing the deadline, or a synchronous failure each act at most once.
8
+ */
9
+ class DeadlineRun {
10
+ timeoutMs;
11
+ context;
12
+ deadlines;
13
+ failures;
14
+ failure;
15
+ settled = false;
16
+ timer;
17
+ controller = new AbortController();
18
+ startedAt;
19
+ rejectExpired;
20
+ expiry;
21
+ constructor(timeoutMs, context, deadlines, failures) {
22
+ this.timeoutMs = timeoutMs;
23
+ this.context = context;
24
+ this.deadlines = deadlines;
25
+ this.failures = failures;
26
+ this.startedAt = deadlines.now();
27
+ this.expiry = new Promise((_resolve, reject) => {
28
+ this.rejectExpired = reject;
29
+ });
30
+ }
31
+ /** May throw synchronously; nothing was scheduled then, so there is nothing to release. */
32
+ start() {
33
+ this.timer = this.deadlines.schedule(this.timeoutMs, this.expire);
34
+ }
35
+ /** The scheduler's callback. Ignored once the run settled: a late native delivery is harmless. */
36
+ expire = () => {
37
+ if (this.settled || this.failure !== undefined)
38
+ return;
39
+ const error = new ApiCallTimeoutError_1.ApiCallTimeoutError(this.timeoutMs, this.context);
40
+ this.failure = error;
41
+ this.failures.set(this.controller.signal, error);
42
+ this.rejectExpired(error);
43
+ this.controller.abort(error);
44
+ };
45
+ /**
46
+ * Called when the work settles. If the scheduler never delivered (JS suspended, native callback
47
+ * lost) but the budget is spent on the scheduler's clock, the result arrived AFTER its deadline:
48
+ * fail it with the same typed timeout rather than returning it.
49
+ */
50
+ expireIfOverdue() {
51
+ if (this.deadlines.now() - this.startedAt >= this.timeoutMs)
52
+ this.expire();
53
+ if (this.failure !== undefined)
54
+ throw this.failure;
55
+ }
56
+ /** Exactly once per run, on every settlement path that had a timer to release. */
57
+ finish() {
58
+ if (this.settled)
59
+ return;
60
+ this.settled = true;
61
+ this.timer?.cancel();
62
+ }
63
+ }
64
+ /**
65
+ * Transport deadline. The race bounds even transports that ignore cancellation, and a body read that
66
+ * never ends: the deadline covers everything inside `work` — URL resolution, filters, auth, the send
67
+ * and the response body — exactly as the caller's per-attempt budget says.
68
+ *
69
+ * Timing comes from the caller's {@link DeadlineScheduler} (#1445), never from a global timer, so a
70
+ * React Native client whose JS timers pause while the phone is locked can still be cancelled by a
71
+ * native-delivered deadline.
72
+ */
6
73
  class CallDeadline {
7
74
  /**
8
75
  * AbortController.abort(reason) is not portable: React Native's abort-controller 3 signal has
@@ -16,28 +83,27 @@ class CallDeadline {
16
83
  }
17
84
  }
18
85
  // webpieces-disable no-function-outside-class -- stateless transport helper
19
- static async run(timeoutMs, context, work) {
86
+ static async run(timeoutMs, context, deadlines, work) {
20
87
  CallDeadline.validate(timeoutMs);
21
- const controller = new AbortController();
22
- let timer;
23
- const expired = new Promise((_resolve, reject) => {
24
- timer = setTimeout(() => {
25
- const error = new ApiCallTimeoutError_1.ApiCallTimeoutError(timeoutMs, context);
26
- CallDeadline.failures.set(controller.signal, error);
27
- reject(error);
28
- controller.abort(error);
29
- }, timeoutMs);
88
+ const run = new DeadlineRun(timeoutMs, context, deadlines, CallDeadline.failures);
89
+ run.start();
90
+ const guarded = Promise.resolve()
91
+ .then(() => work(run.controller.signal))
92
+ .then((value) => {
93
+ run.expireIfOverdue();
94
+ return value;
95
+ }, (err) => {
96
+ run.expireIfOverdue();
97
+ // eslint-disable-next-line @webpieces/no-unmanaged-exceptions -- rethrows the work's own failure unchanged
98
+ throw err;
30
99
  });
31
- // webpieces-disable no-unmanaged-exceptions -- release the timer on every settlement
100
+ // webpieces-disable no-unmanaged-exceptions -- release the scheduled deadline on every settlement
32
101
  // eslint-disable-next-line @webpieces/no-unmanaged-exceptions
33
102
  try {
34
- return await Promise.race([
35
- expired,
36
- Promise.resolve().then(() => work(controller.signal)),
37
- ]);
103
+ return await Promise.race([run.expiry, guarded]);
38
104
  }
39
105
  finally {
40
- clearTimeout(timer);
106
+ run.finish();
41
107
  }
42
108
  }
43
109
  /** Throw the exact deadline failure without relying on optional AbortSignal extensions. */
@@ -1 +1 @@
1
- {"version":3,"file":"CallDeadline.js","s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AAE,CAAC,IAAI,CAAC,UAAU,CAAC,MAAM,CAAC,CAAC;aACxD,CAAC,CAAC;QACP,CAAC;gBAAS,CAAC;YACP,YAAY,CAAC,KAAK,CAAC,CAAC;QACxB,CAAC;IACL,CAAC;IAED,2FAA2F;IAC3F,2EAA2E;IAC3E,MAAM,CAAC,cAAc,CAAC,MAAmB;QACrC,IAAI,CAAC,MAAM,CAAC,OAAO;YAAE,OAAO;QAC5B,MAAM,CACF,YAAY,CAAC,QAAQ,CAAC,GAAG,CAAC,MAAM,CAAC;YACjC,IAAI,KAAK,CAAC,oDAAoD,CAAC,CAClE,CAAC;IACN,CAAC;;AArDL,oCAsDC","sourcesContent":["import { CallContext } from './CallStrategy';\nimport { ApiCallTimeoutError } from './ApiCallTimeoutError';\n\n/** Transport deadline. The race bounds even transports that ignore cancellation. */\nexport class CallDeadline {\n /**\n * AbortController.abort(reason) is not portable: React Native's abort-controller 3 signal has\n * neither `reason` nor `throwIfAborted`. Keep the typed failure beside the signal instead.\n */\n private static readonly failures = new WeakMap<AbortSignal, Error>();\n\n // webpieces-disable no-function-outside-class -- stateless transport helper\n static validate(timeoutMs: number): void {\n if (!Number.isFinite(timeoutMs) || timeoutMs <= 0 || timeoutMs > 2_147_483_647) {\n throw new RangeError('timeoutMs must be positive, finite, and at most 2147483647');\n }\n }\n\n // webpieces-disable no-function-outside-class -- stateless transport helper\n static async run<T>(\n timeoutMs: number,\n context: CallContext,\n work: (signal: AbortSignal) => Promise<T>,\n ): Promise<T> {\n CallDeadline.validate(timeoutMs);\n const controller = new AbortController();\n let timer: ReturnType<typeof setTimeout> | undefined;\n const expired = new Promise<never>(\n (_resolve: (value: never) => void, reject: (error: Error) => void) => {\n timer = setTimeout(() => {\n const error = new ApiCallTimeoutError(timeoutMs, context);\n CallDeadline.failures.set(controller.signal, error);\n reject(error);\n controller.abort(error);\n }, timeoutMs);\n },\n );\n // webpieces-disable no-unmanaged-exceptions -- release the timer on every settlement\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n return await Promise.race([\n expired,\n Promise.resolve().then(() => work(controller.signal)),\n ]);\n } finally {\n clearTimeout(timer);\n }\n }\n\n /** Throw the exact deadline failure without relying on optional AbortSignal extensions. */\n // webpieces-disable no-function-outside-class -- portable transport helper\n static throwIfAborted(signal: AbortSignal): void {\n if (!signal.aborted) return;\n throw (\n CallDeadline.failures.get(signal) ??\n new Error('The operation was aborted before it could complete')\n );\n }\n}\n"]}
1
+ {"version":3,"file":"CallDeadline.js","sourceRoot":"","sources":["../../../../../../packages/core/core-util/src/http/CallDeadline.ts"],"names":[],"mappings":";;;AACA,+DAA4D;AAG5D;;;GAGG;AACH,MAAM,WAAW;IAUQ;IACA;IACA;IACA;IAZb,OAAO,CAAkC;IACzC,OAAO,GAAG,KAAK,CAAC;IAChB,KAAK,CAA4B;IAChC,UAAU,GAAG,IAAI,eAAe,EAAE,CAAC;IACnC,SAAS,CAAS;IACnB,aAAa,CAA0B;IACtC,MAAM,CAAiB;IAEhC,YACqB,SAAiB,EACjB,OAAoB,EACpB,SAA4B,EAC5B,QAAqC;QAHrC,cAAS,GAAT,SAAS,CAAQ;QACjB,YAAO,GAAP,OAAO,CAAa;QACpB,cAAS,GAAT,SAAS,CAAmB;QAC5B,aAAQ,GAAR,QAAQ,CAA6B;QAEtD,IAAI,CAAC,SAAS,GAAG,SAAS,CAAC,GAAG,EAAE,CAAC;QACjC,IAAI,CAAC,MAAM,GAAG,IAAI,OAAO,CACrB,CAAC,QAAgC,EAAE,MAA8B,EAAE,EAAE;YACjE,IAAI,CAAC,aAAa,GAAG,MAAM,CAAC;QAChC,CAAC,CACJ,CAAC;IACN,CAAC;IAED,2FAA2F;IAC3F,KAAK;QACD,IAAI,CAAC,KAAK,GAAG,IAAI,CAAC,SAAS,CAAC,QAAQ,CAAC,IAAI,CAAC,SAAS,EAAE,IAAI,CAAC,MAAM,CAAC,CAAC;IACtE,CAAC;IAED,kGAAkG;IACzF,MAAM,GAAG,GAAS,EAAE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lineScheduler, DeadlineTimer } from './DeadlineScheduler';\n\n/**\n * The state of ONE deadline-bounded run. Every transition is guarded so a late native callback, a\n * settlement racing the deadline, or a synchronous failure each act at most once.\n */\nclass DeadlineRun {\n private failure: ApiCallTimeoutError | undefined;\n private settled = false;\n private timer: DeadlineTimer | undefined;\n readonly controller = new AbortController();\n readonly startedAt: number;\n private rejectExpired!: (error: Error) => void;\n readonly expiry: Promise<never>;\n\n constructor(\n private readonly timeoutMs: number,\n private readonly context: CallContext,\n private readonly deadlines: DeadlineScheduler,\n private readonly failures: WeakMap<AbortSignal, Error>,\n ) {\n this.startedAt = deadlines.now();\n this.expiry = new Promise<never>(\n (_resolve: (value: never) => void, reject: (error: Error) => void) => {\n this.rejectExpired = reject;\n },\n );\n }\n\n /** May throw synchronously; nothing was scheduled then, so there is nothing to release. */\n start(): void {\n this.timer = this.deadlines.schedule(this.timeoutMs, this.expire);\n }\n\n /** The scheduler's callback. Ignored once the run settled: a late native delivery is harmless. */\n readonly expire = (): void => {\n if (this.settled || this.failure !== undefined) return;\n const error = new ApiCallTimeoutError(this.timeoutMs, this.context);\n this.failure = error;\n this.failures.set(this.controller.signal, error);\n this.rejectExpired(error);\n this.controller.abort(error);\n };\n\n /**\n * Called when the work settles. If the scheduler never delivered (JS suspended, native callback\n * lost) but the budget is spent on the scheduler's clock, the result arrived AFTER its deadline:\n * fail it with the same typed timeout rather than returning it.\n */\n expireIfOverdue(): void {\n if (this.deadlines.now() - this.startedAt >= this.timeoutMs) this.expire();\n if (this.failure !== undefined) throw this.failure;\n }\n\n /** Exactly once per run, on every settlement path that had a timer to release. */\n finish(): void {\n if (this.settled) return;\n this.settled = true;\n this.timer?.cancel();\n }\n}\n\n/**\n * Transport deadline. The race bounds even transports that ignore cancellation, and a body read that\n * never ends: the deadline covers everything inside `work` — URL resolution, filters, auth, the send\n * and the response body — exactly as the caller's per-attempt budget says.\n *\n * Timing comes from the caller's {@link DeadlineScheduler} (#1445), never from a global timer, so a\n * React Native client whose JS timers pause while the phone is locked can still be cancelled by a\n * native-delivered deadline.\n */\nexport class CallDeadline {\n /**\n * AbortController.abort(reason) is not portable: React Native's abort-controller 3 signal has\n * neither `reason` nor `throwIfAborted`. Keep the typed failure beside the signal instead.\n */\n private static readonly failures = new WeakMap<AbortSignal, Error>();\n\n // webpieces-disable no-function-outside-class -- stateless transport helper\n static validate(timeoutMs: number): void {\n if (!Number.isFinite(timeoutMs) || timeoutMs <= 0 || timeoutMs > 2_147_483_647) {\n throw new RangeError('timeoutMs must be positive, finite, and at most 2147483647');\n }\n }\n\n // webpieces-disable no-function-outside-class -- stateless transport helper\n static async run<T>(\n timeoutMs: number,\n context: CallContext,\n deadlines: DeadlineScheduler,\n work: (signal: AbortSignal) => Promise<T>,\n ): Promise<T> {\n CallDeadline.validate(timeoutMs);\n const run = new DeadlineRun(timeoutMs, context, deadlines, CallDeadline.failures);\n run.start();\n const guarded = Promise.resolve()\n .then(() => work(run.controller.signal))\n .then(\n (value: T): T => {\n run.expireIfOverdue();\n return value;\n },\n (err: Error): never => {\n run.expireIfOverdue();\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions -- rethrows the work's own failure unchanged\n throw err;\n },\n );\n // webpieces-disable no-unmanaged-exceptions -- release the scheduled deadline on every settlement\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n return await Promise.race([run.expiry, guarded]);\n } finally {\n run.finish();\n }\n }\n\n /** Throw the exact deadline failure without relying on optional AbortSignal extensions. */\n // webpieces-disable no-function-outside-class -- portable transport helper\n static throwIfAborted(signal: AbortSignal): void {\n if (!signal.aborted) return;\n throw (\n CallDeadline.failures.get(signal) ??\n new Error('The operation was aborted before it could complete')\n );\n }\n}\n"]}
@@ -1,4 +1,5 @@
1
1
  import { EndpointOperation } from './HttpEndpointOptions';
2
+ import { DeadlineScheduler } from './DeadlineScheduler';
2
3
  /** One bounded attempt. Only an explicitly registered strategy may retry it. */
3
4
  export type Attempt<T> = (timeoutMs: number) => Promise<T>;
4
5
  /**
@@ -29,5 +30,11 @@ export declare class CallContext {
29
30
  /** REQUIRED — the contract CLASS; see {@link CallContext.contract}. */
30
31
  contract: Function);
31
32
  }
32
- /** Owns all timing and retry decisions. No public cancellation signal. */
33
- export type CallStrategy<T> = (call: Attempt<T>, ctx: CallContext) => Promise<T>;
33
+ /**
34
+ * Owns all timing and retry decisions. No public cancellation signal.
35
+ *
36
+ * `deadlines` is the calling CLIENT's clock (#1445): a strategy that waits between attempts waits
37
+ * through it, never through a bare `setTimeout`, so a React Native client configured with a
38
+ * native-backed scheduler is not left parked on a paused JS timer between attempts.
39
+ */
40
+ export type CallStrategy<T> = (call: Attempt<T>, ctx: CallContext, deadlines: DeadlineScheduler) => Promise<T>;
@@ -1 +1 @@
1
- {"version":3,"file":"CallStrategy.js","sourceRoot":"","sources":["../../../../../../packages/core/core-util/src/http/CallStrategy.ts"],"names":[],"mappings":";;;AAKA;;;;;;;;GAQG;AACH,MAAa,WAAW;IAcA;IACA;IACA;IAHpB,YACoB,OAAe,EACf,UAAkB,EAClB,SAA4B;IAC5C,uEAAuE;IACvE,QAAkB;QAJF,YAAO,GAAP,OAAO,CAAQ;QACf,eAAU,GAAV,UAAU,CAAQ;QAClB,cAAS,GAAT,SAAS,CAAmB;QAI5C,MAAM,CAAC,cAAc,CAAC,IAAI,EAAE,UAAU,EAAE,EAAE,KAAK,EAAE,QAAQ,EAAE,UAAU,EAAE,KAAK,EAAE,CAAC,CAAC;IACpF,CAAC;CACJ;AAtBD,kCAsBC","sourcesContent":["import { EndpointOperation } from './HttpEndpointOptions';\n\n/** One bounded attempt. Only an explicitly registered strategy may retry it. */\nexport type Attempt<T> = (timeoutMs: number) => Promise<T>;\n\n/**\n * Contract identity for diagnostics; registry keys use the class itself.\n *\n * `operation` is the endpoint's declared `@Endpoint` side-effect contract (`READ`,\n * `WRITE_IDEMPOTENT` or `WRITE`). A {@link CallStrategy} reads it to decide whether a retry is safe,\n * and `ApiCallTimeoutError` reads it to choose the text it shows an end user. A transport with\n * no declared operation (IPC contracts declare none) passes `WRITE`: the conservative answer, since\n * it never invites a blind retry of something that may already have happened.\n */\nexport class CallContext {\n /**\n * The contract CLASS the call belongs to — the key of the `CallScope` ladder, so a strategy's\n * per-attempt error classification resolves the classifier registered for THIS contract.\n * REQUIRED and never `undefined`: every transport knows its contract class (HTTP and Cloud Tasks\n * clients hold it, the IPC client proxy holds its `@WpInternal` class), and\n * `ClientRegistry.execute` re-keys the context a strategy sees onto the class it was given.\n *\n * NON-enumerable on purpose: this context rides on `ApiCallTimeoutError`, which is logged and\n * compared as data, and a class reference is not data.\n */\n declare readonly contract: Function;\n\n constructor(\n public readonly apiName: string,\n public readonly methodName: string,\n public readonly operation: EndpointOperation,\n /** REQUIRED — the contract CLASS; see {@link CallContext.contract}. */\n contract: Function,\n ) {\n Object.defineProperty(this, 'contract', { value: contract, enumerable: false });\n }\n}\n\n/** Owns all timing and retry decisions. No public cancellation signal. */\nexport type CallStrategy<T> = (call: Attempt<T>, ctx: CallContext) => Promise<T>;\n"]}
1
+ {"version":3,"file":"CallStrategy.js","sourceRoot":"","sources":["../../../../../../packages/core/core-util/src/http/CallStrategy.ts"],"names":[],"mappings":";;;AAMA;;;;;;;;GAQG;AACH,MAAa,WAAW;IAcA;IACA;IACA;IAHpB,YACoB,OAAe,EACf,UAAkB,EAClB,SAA4B;IAC5C,uEAAuE;IACvE,QAAkB;QAJF,YAAO,GAAP,OAAO,CAAQ;QACf,eAAU,GAAV,UAAU,CAAQ;QAClB,cAAS,GAAT,SAAS,CAAmB;QAI5C,MAAM,CAAC,cAAc,CAAC,IAAI,EAAE,UAAU,EAAE,EAAE,KAAK,EAAE,QAAQ,EAAE,UAAU,EAAE,KAAK,EAAE,CAAC,CAAC;IACpF,CAAC;CACJ;AAtBD,kCAsBC","sourcesContent":["import { EndpointOperation } from './HttpEndpointOptions';\nimport { DeadlineScheduler } from './DeadlineScheduler';\n\n/** One bounded attempt. Only an explicitly registered strategy may retry it. */\nexport type Attempt<T> = (timeoutMs: number) => Promise<T>;\n\n/**\n * Contract identity for diagnostics; registry keys use the class itself.\n *\n * `operation` is the endpoint's declared `@Endpoint` side-effect contract (`READ`,\n * `WRITE_IDEMPOTENT` or `WRITE`). A {@link CallStrategy} reads it to decide whether a retry is safe,\n * and `ApiCallTimeoutError` reads it to choose the text it shows an end user. A transport with\n * no declared operation (IPC contracts declare none) passes `WRITE`: the conservative answer, since\n * it never invites a blind retry of something that may already have happened.\n */\nexport class CallContext {\n /**\n * The contract CLASS the call belongs to — the key of the `CallScope` ladder, so a strategy's\n * per-attempt error classification resolves the classifier registered for THIS contract.\n * REQUIRED and never `undefined`: every transport knows its contract class (HTTP and Cloud Tasks\n * clients hold it, the IPC client proxy holds its `@WpInternal` class), and\n * `ClientRegistry.execute` re-keys the context a strategy sees onto the class it was given.\n *\n * NON-enumerable on purpose: this context rides on `ApiCallTimeoutError`, which is logged and\n * compared as data, and a class reference is not data.\n */\n declare readonly contract: Function;\n\n constructor(\n public readonly apiName: string,\n public readonly methodName: string,\n public readonly operation: EndpointOperation,\n /** REQUIRED — the contract CLASS; see {@link CallContext.contract}. */\n contract: Function,\n ) {\n Object.defineProperty(this, 'contract', { value: contract, enumerable: false });\n }\n}\n\n/**\n * Owns all timing and retry decisions. No public cancellation signal.\n *\n * `deadlines` is the calling CLIENT's clock (#1445): a strategy that waits between attempts waits\n * through it, never through a bare `setTimeout`, so a React Native client configured with a\n * native-backed scheduler is not left parked on a paused JS timer between attempts.\n */\nexport type CallStrategy<T> = (\n call: Attempt<T>,\n ctx: CallContext,\n deadlines: DeadlineScheduler,\n) => Promise<T>;\n"]}
@@ -1,5 +1,6 @@
1
1
  import { Attempt, CallContext, CallStrategy } from './CallStrategy';
2
2
  import { TransportDefault } from './TransportDefault';
3
+ import { DeadlineScheduler } from './DeadlineScheduler';
3
4
  import { CallScope } from './CallScope';
4
5
  /**
5
6
  * Derives a base URL for a service name that has NO registered mapping — the pluggable half of
@@ -118,8 +119,11 @@ export declare class ClientRegistry {
118
119
  *
119
120
  * Every attempt is wrapped so a retried TRANSIENT failure logs one
120
121
  * `WARN [API-client-attempt-TRANSIENT]` line (see {@link LoggedAttempts}).
122
+ *
123
+ * `deadlines` is the calling client's {@link DeadlineScheduler}, handed to whichever strategy
124
+ * runs so its backoff waits on the same clock the attempt deadlines use (#1445).
121
125
  */
122
- static execute<T>(api: Function, context: CallContext, attempt: Attempt<T>, fallback: TransportDefault): Promise<T>;
126
+ static execute<T>(api: Function, context: CallContext, attempt: Attempt<T>, fallback: TransportDefault, deadlines: DeadlineScheduler): Promise<T>;
123
127
  /**
124
128
  * The registered TIMEOUT for a call — method -> API -> ALL -> `defaultMs` — ignoring every
125
129
  * strategy. For a transport that hands timing to someone else for this call (Cloud Tasks enqueue
@@ -222,9 +222,12 @@ class ClientRegistry {
222
222
  *
223
223
  * Every attempt is wrapped so a retried TRANSIENT failure logs one
224
224
  * `WARN [API-client-attempt-TRANSIENT]` line (see {@link LoggedAttempts}).
225
+ *
226
+ * `deadlines` is the calling client's {@link DeadlineScheduler}, handed to whichever strategy
227
+ * runs so its backoff waits on the same clock the attempt deadlines use (#1445).
225
228
  */
226
229
  // webpieces-disable no-function-outside-class -- transport-independent policy execution
227
- static async execute(api, context, attempt, fallback) {
230
+ static async execute(api, context, attempt, fallback, deadlines) {
228
231
  const scoped = context.contract === api
229
232
  ? context
230
233
  : new CallStrategy_1.CallContext(context.apiName, context.methodName, context.operation, api);
@@ -232,14 +235,14 @@ class ClientRegistry {
232
235
  const rungs = ClientRegistry.policies.rungs(api, scoped.methodName);
233
236
  const strategy = rungs.find((p) => p.strategy !== undefined)?.strategy;
234
237
  if (strategy !== undefined) {
235
- return (await strategy(logged, scoped));
238
+ return (await strategy(logged, scoped, deadlines));
236
239
  }
237
240
  const timeoutMs = rungs.find((p) => p.timeoutMs !== undefined)?.timeoutMs;
238
241
  if (timeoutMs !== undefined) {
239
242
  return logged(timeoutMs);
240
243
  }
241
244
  if (fallback.strategy !== undefined) {
242
- return (await fallback.strategy(logged, scoped));
245
+ return (await fallback.strategy(logged, scoped, deadlines));
243
246
  }
244
247
  return logged(fallback.timeoutMs);
245
248
  }
@@ -1 +1 @@
1
- {"version":3,"file":"ClientRegistry.js","sourceRoot":"","sources":["../../../../../../packages/core/core-util/src/http/ClientRegistry.ts"],"names":[],"mappings":";;;AAAA,iDAAoE;AACpE,iDAA8C;AAE9C,+CAA4C;AAC5C,uDAAgD;AAChD,mDAAgD;AAChD,sDAAmD;AACnD,qDAA4D;AAC5D,kDAA4C;AAC5C,2CAAyD;AAEzD,wGAAwG;AACxG,MAAM,GAAG,GAAG,uBAAU,CAAC,SAAS,CAAC,yCAAwB,CAAC,CAAC;AAE3D,MAAM,UAAU;IACZ,SAAS,CAAU;IACnB,sFAAsF;IACtF,QAAQ,CAAyB;CACpC;AAED;;;;;;;;;GASG;AACH,MAAM,cAAc;IAKK;IACA;IALb,QAAQ,GAAG,CAAC,CAAC;IACb,gBAAgB,CAAS;IAEjC,YACqB,OAAoB,EACpB,OAAmB;QADnB,YAAO,GAAP,OAAO,CAAa;QACpB,YAAO,GAAP,OAAO,CAAY;IACrC,CAAC;IAEK,GAAG,GAAe,KAAK,EAAE,SAAiB,EAAc,EAAE;QAC/D,IAAI,CAAC,YAAY,EAAE,CAAC;QACpB,IAAI,CAAC,QAAQ,IAAI,CAAC,CAAC;QACnB,mGAAmG;QACnG,8DAA8D;QAC9D,IAAI,CAAC;YACD,OAAO,MAAM,IAAI,CAAC,OAAO,CAAC,SAAS,CAAC,CAAC;QACzC,CAAC;QAAC,OAAO,GAAY,EAAE,CAAC;YACpB,MAAM,KAAK,GAAG,IAAA,oBAAO,EAAC,GAAG,CAAC,CAAC;YAC3B,MAAM,UAAU,GAAG,IAAI,6BAAa,CAChC,QAAQ,EACR,IAAI,CAAC,OAAO,CAAC,OAAO,EACpB,IAAI,CAAC,OAAO,CAAC,UAAU,EACvB,IAAI,CAAC,OAAO,CAAC,QAAQ,CACxB,CAAC;Y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iLC","sourcesContent":["import { Attempt, CallContext, CallStrategy } from './CallStrategy';\nimport { CallDeadline } from './CallDeadline';\nimport { TransportDefault } from './TransportDefault';\nimport { ApiRegistry } from './ApiRegistry';\nimport { CallOutcome } from './ErrorClassifier';\nimport { ApiMethodInfo } from './ApiMethodInfo';\nimport { LogManager } from '../logging/LogManager';\nimport { LOG_API_CALL_LOGGER_NAME } from './ApiCallLogName';\nimport { toError } from '../lib/errorUtils';\nimport { CallScope, CallScopeLadder } from './CallScope';\n\n// The same logger LogApiCall writes its [API-*] lines to, so an attempt line sits beside the final one.\nconst log = LogManager.getLogger(LOG_API_CALL_LOGGER_NAME);\n\nclass CallPolicy {\n timeoutMs?: number;\n // webpieces-disable no-any-unknown -- global policy spans heterogeneous response DTOs\n strategy?: CallStrategy<unknown>;\n}\n\n/**\n * Counts the attempts of ONE call and logs each retried TRANSIENT failure. It wraps the attempt\n * BEFORE any strategy sees it, so an app-written strategy gets the same lines as `RetryStrategy`.\n *\n * The line for attempt N is written when attempt N+1 STARTS — i.e. only for an attempt that was\n * actually retried. The last attempt's failure is what escapes, and `LogApiCall`'s final\n * `[API-client-resp-FAIL]` line covers it, so a call that gave up after 4 attempts logs 3 attempt\n * lines and 1 FAIL line, never the last failure twice. An EXPECTED or FAILURE attempt is not logged\n * here either; the final line covers it.\n */\nclass LoggedAttempts<T> {\n private attempts = 0;\n private pendingTransient?: Error;\n\n constructor(\n private readonly context: CallContext,\n private readonly attempt: Attempt<T>,\n ) {}\n\n readonly run: Attempt<T> = async (timeoutMs: number): Promise<T> => {\n this.flushRetried();\n this.attempts += 1;\n // webpieces-disable no-unmanaged-exceptions -- observe the attempt's failure, rethrow it unchanged\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n return await this.attempt(timeoutMs);\n } catch (err: unknown) {\n const error = toError(err);\n const methodInfo = new ApiMethodInfo(\n 'client',\n this.context.apiName,\n this.context.methodName,\n this.context.contract,\n );\n this.pendingTransient =\n ApiRegistry.classify(error, methodInfo) === CallOutcome.TRANSIENT_FAILURE\n ? error\n : undefined;\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions -- rethrows the attempt's own failure unchanged\n throw err;\n }\n };\n\n private flushRetried(): void {\n const error = this.pendingTransient;\n if (error === undefined) return;\n this.pendingTransient = undefined;\n log.warn(\n `[API-client-attempt-TRANSIENT] ${this.context.apiName}.${this.context.methodName} ` +\n `attempt ${this.attempts} errorType=${error.constructor.name} error=${error.message}`,\n );\n }\n}\n\n/**\n * Derives a base URL for a service name that has NO registered mapping — the pluggable half of\n * {@link ClientRegistry} resolution. One per environment, installed once at startup:\n *\n * - `gcpCloudRunDeriver()` (@webpieces/gcp-identity) — the Cloud Run formula, read from the metadata\n * server. For code running ON GCP.\n * - `gcpCloudRunDeriver(new GcpCloudRunTarget(projectNumber, region))` — the SAME formula with the\n * values supplied from config, for code running OFF GCP that still calls Cloud Run (a CLI, CI).\n * - {@link templateDeriver} (this package, browser-safe) — pure string substitution, for AWS or\n * anything else with predictable DNS.\n * - none at all — a browser goes same-origin, and localhost/tests hand-register their mappings.\n */\nexport type ServiceUrlDeriver = (svcName: string) => Promise<string>;\n\n/**\n * ClientRegistry - the ONE place a `svcName` becomes a base URL, for every outbound client in every\n * environment. A client is built once but a URL is per-environment, so the URL belongs here rather\n * than on the client: clients carry ONLY a svcName.\n *\n * Resolution is one precedence chain, identical in the browser, in node, and in Cloud Tasks:\n *\n * 1. a registered mapping wins — the localhost port table, AWS, an external API, another region\n * or project, a host that is not Cloud Run at all. Populated at startup from per-env config.\n * 2. else the installed {@link ServiceUrlDeriver}, if any — GCP's built-in, a DNS template, or\n * your own. OPTIONAL on purpose: localhost is inherently a TABLE (helper-fsdb -> :8401,\n * helper-portal -> :8201 have per-service ports), so explicit mappings must stay sufficient on\n * their own.\n * 3. else the caller's fallback: the BROWSER goes relative (same origin — see\n * {@link ClientRegistry.tryResolve}), while node THROWS (see {@link ClientRegistry.resolve}),\n * because a server has no \"own origin\" and an unresolvable peer is a setup bug.\n *\n * Configured like {@link HeaderRegistry} / LogManager — populated once at startup, then globally\n * accessible with NO DI wiring. It is browser-safe (no `process.env`, no node-only deps), which is\n * why it lives in core-util rather than gcp-identity.\n *\n * A `svcName` should be the nx MODULE name of the service you are calling — that is the one name\n * `architecture:validate-runtime-architecture` can verify actually exists, so a typo or a rename\n * fails the build instead of failing in production. When the DEPLOYED name differs (an environment\n * prefix like `tf-`, or a Cloud Run service named unlike its module), translate it in ONE place —\n * the deriver below, or a `serviceName` alias in the module's project.json — never at the call site.\n *\n * ```ts\n * // startup, from the current environment's config:\n * ClientRegistry.addMapping('server2', 8202); // -> http://localhost:8202\n * ClientRegistry.addUrlMapping('email', 'https://email.other-region.example');\n * ClientRegistry.setDeriver(gcpCloudRunDeriver()); // everything else, on GCP\n * ```\n *\n * The OTHER half: everything ONLY an outbound call reads besides its URL — the per-call timeout and\n * strategy, for browser RPC, node RPC, and Cloud Tasks ENQUEUE. ONE implementation; every transport\n * calls {@link ClientRegistry.execute}. (What BOTH sides read — the error translator and classifier —\n * lives on `ApiRegistry`.)\n *\n * Ladder: strategy method -> API -> ALL first; ANY strategy replaces the ENTIRE timeout ladder.\n * Otherwise timeout method -> API -> ALL. Otherwise the transport's {@link TransportDefault} (its\n * timeout, and its strategy if it has one). A registered TIMEOUT is therefore a decision for a single\n * attempt and also replaces a transport's default strategy; to keep retrying with a different attempt\n * deadline, register a `RetryStrategy` instead.\n *\n * RPC has no default retry (only the application knows whether repeating a POST is safe); Cloud Tasks\n * enqueue does (see `TransportDefault`). An app opts RPC in with\n * `ClientRegistry.setStrategy(new RetryStrategy(...).run, CallScope.api(CatalogApi))` — and `RetryStrategy` never\n * retries a `WRITE`, even registered at ALL.\n */\nexport class ClientRegistry {\n /** svcName -> resolved base URL. Process-global; populated at startup per environment. */\n private static readonly mappings = new Map<string, string>();\n\n /** The fallback for svcNames with no mapping. Undefined = no derivation in this environment. */\n private static deriver: ServiceUrlDeriver | undefined;\n\n /** The timeout / strategy per {@link CallScope} — method -> API -> ALL -> the transport default. */\n private static readonly policies = new CallScopeLadder<CallPolicy>(() => new CallPolicy());\n\n /** Map a service name to `http://localhost:<port>`. */\n // webpieces-disable no-function-outside-class -- static global singleton (like HeaderRegistry/LogManager); populated once at startup, never DI-injected\n static addMapping(svcName: string, port: number): void {\n ClientRegistry.mappings.set(svcName, `http://localhost:${port}`);\n }\n\n /**\n * Map a service name to an explicit base URL (any host / any environment).\n *\n * The EMPTY STRING is a legal, meaningful mapping: it makes the service relative, i.e.\n * same-origin, because the client builds its URL as `${baseUrl}${route.path}`.\n */\n // webpieces-disable no-function-outside-class -- static global singleton (like HeaderRegistry/LogManager); populated once at startup, never DI-injected\n static addUrlMapping(svcName: string, url: string): void {\n ClientRegistry.mappings.set(svcName, url);\n }\n\n /**\n * Install the environment's {@link ServiceUrlDeriver} — how to resolve a svcName that has NO\n * mapping. Optional: an environment that registers every svcName it calls needs none.\n */\n // webpieces-disable no-function-outside-class -- static global singleton (like HeaderRegistry/LogManager); populated once at startup, never DI-injected\n static setDeriver(fn: ServiceUrlDeriver): void {\n ClientRegistry.deriver = fn;\n }\n\n /** The registered override for `svcName`, or undefined if none. Registry only — no derivation. */\n // webpieces-disable no-function-outside-class -- static global singleton (like HeaderRegistry/LogManager); populated once at startup, never DI-injected\n static tryLookup(svcName: string): string | undefined {\n return ClientRegistry.mappings.get(svcName);\n }\n\n /**\n * Resolve `svcName` to its registered base URL. THROWS if the service was never registered.\n * Registry only — it does NOT consult the deriver; prefer {@link ClientRegistry.resolve}.\n */\n // webpieces-disable no-function-outside-class -- static global singleton (like HeaderRegistry/LogManager); populated once at startup, never DI-injected\n static lookup(svcName: string): string {\n const url = ClientRegistry.tryLookup(svcName);\n if (url === undefined) {\n throw new Error(\n `No URL registered for service \"${svcName}\". Register it at startup: ` +\n `ClientRegistry.addMapping(svcName, port) for a localhost port, or ` +\n `ClientRegistry.addUrlMapping(svcName, url) for an explicit URL.`,\n );\n }\n return url;\n }\n\n /**\n * Steps 1 + 2 of the chain: the registered mapping, else the installed deriver, else undefined.\n * Non-throwing — the BROWSER uses this and treats undefined as \"\" (relative → same origin),\n * which is what a browser app calling the backend it was served from wants by default.\n *\n * Note the `!== undefined` guard: an empty-string mapping is a legal answer (\"this service is\n * same-origin\"), so it must NOT fall through to derivation.\n */\n // webpieces-disable no-function-outside-class -- static global singleton (like HeaderRegistry/LogManager); populated once at startup, never DI-injected\n static tryResolve(svcName: string): Promise<string | undefined> {\n const override = ClientRegistry.tryLookup(svcName);\n if (override !== undefined) {\n return Promise.resolve(override);\n }\n if (!ClientRegistry.deriver) {\n return Promise.resolve(undefined);\n }\n return ClientRegistry.deriver(svcName);\n }\n\n /**\n * The full chain, with node's fallback: mapping, else deriver, else THROW. A server has no \"own\n * origin\" to go relative to, so an unresolvable peer is a setup bug and must fail loudly — and\n * say how to fix it.\n */\n // webpieces-disable no-function-outside-class -- static global singleton (like HeaderRegistry/LogManager); populated once at startup, never DI-injected\n static async resolve(svcName: string): Promise<string> {\n const url = await ClientRegistry.tryResolve(svcName);\n if (url === undefined) {\n throw new Error(\n `No URL for service \"${svcName}\".\\n` +\n ` - localhost/AWS: ClientRegistry.addMapping('${svcName}', 8401)\\n` +\n ` or ClientRegistry.addUrlMapping('${svcName}', 'https://...')\\n` +\n ` - GCP: install a deriver — ClientRegistry.setDeriver(gcpCloudRunDeriver())\\n` +\n ` - deployed name differs from the module name (e.g. a 'tf-' prefix)? Translate it ONCE\\n` +\n ` in the deriver — setDeriver(s => gcpCloudRunDeriver()('tf-' + s)) — so every call\\n` +\n ` site keeps naming the MODULE, which architecture:validate-runtime-architecture checks`,\n );\n }\n return url;\n }\n\n // webpieces-disable no-function-outside-class -- process-global startup registry\n static setTimeout(timeoutMs: number | undefined, scope: CallScope): void {\n if (timeoutMs !== undefined) CallDeadline.validate(timeoutMs);\n ClientRegistry.policies.at(scope).timeoutMs = timeoutMs;\n }\n\n // webpieces-disable no-function-outside-class -- process-global startup registry\n static setStrategy(\n // webpieces-disable no-any-unknown -- registry strategies span heterogeneous response DTOs\n strategy: CallStrategy<unknown> | undefined,\n scope: CallScope,\n ): void {\n ClientRegistry.policies.at(scope).strategy = strategy;\n }\n\n /**\n * Run one call under its registered policy. `context` names the method (its `methodName` selects\n * the per-method policy) and carries the endpoint's declared operation, so the SAME context a\n * strategy sees is the one the transport's deadline puts on an `ApiCallTimeoutError`. The context\n * a strategy sees always carries `api` as its {@link CallContext.contract}, so the error\n * classification inside a strategy resolves on the same ladder.\n *\n * Every attempt is wrapped so a retried TRANSIENT failure logs one\n * `WARN [API-client-attempt-TRANSIENT]` line (see {@link LoggedAttempts}).\n */\n // webpieces-disable no-function-outside-class -- transport-independent policy execution\n static async execute<T>(\n api: Function,\n context: CallContext,\n attempt: Attempt<T>,\n fallback: TransportDefault,\n ): Promise<T> {\n const scoped =\n context.contract === api\n ? context\n : new CallContext(context.apiName, context.methodName, context.operation, api);\n const logged = new LoggedAttempts<T>(scoped, attempt).run;\n const rungs = ClientRegistry.policies.rungs(api, scoped.methodName);\n const strategy = rungs.find((p: CallPolicy) => p.strategy !== undefined)?.strategy;\n if (strategy !== undefined) {\n return (await strategy(logged, scoped)) as T;\n }\n const timeoutMs = rungs.find((p: CallPolicy) => p.timeoutMs !== undefined)?.timeoutMs;\n if (timeoutMs !== undefined) {\n return logged(timeoutMs);\n }\n if (fallback.strategy !== undefined) {\n return (await fallback.strategy(logged, scoped)) as T;\n }\n return logged(fallback.timeoutMs);\n }\n\n /**\n * The registered TIMEOUT for a call — method -> API -> ALL -> `defaultMs` — ignoring every\n * strategy. For a transport that hands timing to someone else for this call (Cloud Tasks enqueue\n * with caller-supplied gax `CallOptions`) and still needs ONE safety cap so a hung channel cannot\n * block forever. Raise it with {@link ClientRegistry.setTimeout}.\n */\n // webpieces-disable no-function-outside-class -- process-global registry lookup\n static resolveTimeout(api: Function, methodName: string, defaultMs: number): number {\n const rungs = ClientRegistry.policies.rungs(api, methodName);\n return rungs.find((p: CallPolicy) => p.timeoutMs !== undefined)?.timeoutMs ?? defaultMs;\n }\n\n /**\n * Put the process-globals back to the state a fresh process starts in. For TESTS, so one spec\n * cannot leak its registrations into the next: every URL mapping, the deriver, and every\n * timeout / strategy rung. (`ApiRegistry.resetForTests()` resets the error translators and\n * classifiers.)\n */\n // webpieces-disable no-function-outside-class -- static global singleton (like HeaderRegistry/LogManager); populated once at startup, never DI-injected\n static resetForTests(): void {\n ClientRegistry.mappings.clear();\n ClientRegistry.deriver = undefined;\n ClientRegistry.policies.clear();\n }\n}\n"]}
1
+ {"version":3,"file":"ClientRegistry.js","sourceRoot":"","sources":["../../../../../../packages/core/core-util/src/http/ClientRegistry.ts"],"names":[],"mappings":";;;AAAA,iDAAoE;AACpE,iDAA8C;AAG9C,+CAA4C;AAC5C,uDAAgD;AAChD,mDAAgD;AAChD,sDAAmD;AACnD,qDAA4D;AAC5D,kDAA4C;AAC5C,2CAAyD;AAEzD,wGAAwG;AACxG,MAAM,GAAG,GAAG,uBAAU,CAAC,SAAS,CAAC,yCAAwB,CAAC,CAAC;AAE3D,MAAM,UAAU;IACZ,SAAS,CAAU;IACnB,sFAAsF;IACtF,QAAQ,CAAyB;CACpC;AAED;;;;;;;;;GASG;AACH,MAAM,cAAc;IAKK;IACA;IALb,QAAQ,GAAG,CAAC,CAAC;IACb,gBAAgB,CAAS;IAEjC,YACqB,OAAoB,EACpB,OAAmB;QADnB,YAAO,GAAP,OAAO,CAAa;QACpB,YAAO,GAAP,OAAO,CAAY;IACrC,CAAC;IAEK,GAAG,GAAe,KAAK,EAAE,SAAiB,EAAc,EAAE;QAC/D,IAAI,CAAC,YAAY,EAAE,CAAC;QACpB,IAAI,CAAC,QAAQ,IAAI,CAAC,CAAC;QACnB,mGAAmG;QACnG,8DAA8D;QAC9D,IAAI,CAAC;YACD,OAAO,MAAM,IAAI,CAAC,OAAO,CAAC,SAAS,CAAC,CAAC;QACzC,CAAC;QAAC,OAAO,GAAY,EAAE,CAAC;YACpB,MAAM,KAAK,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E,SAAS,IAAI,SAAS,CAAC;IAC5F,CAAC;IAED;;;;;OAKG;IACH,wJAAwJ;IACxJ,MAAM,CAAC,aAAa;QAChB,cAAc,CAAC,QAAQ,CAAC,KAAK,EAAE,CAAC;QAChC,cAAc,CAAC,OAAO,GAAG,SAAS,CAAC;QACnC,cAAc,CAAC,QAAQ,CAAC,KAAK,EAAE,CAAC;IACpC,CAAC;;AApLL,wCAqLC","sourcesContent":["import { Attempt, CallContext, CallStrategy } from './CallStrategy';\nimport { CallDeadline } from './CallDeadline';\nimport { TransportDefault } from './TransportDefault';\nimport { DeadlineScheduler } from './DeadlineScheduler';\nimport { ApiRegistry } from './ApiRegistry';\nimport { CallOutcome } from './ErrorClassifier';\nimport { ApiMethodInfo } from './ApiMethodInfo';\nimport { LogManager } from '../logging/LogManager';\nimport { LOG_API_CALL_LOGGER_NAME } from './ApiCallLogName';\nimport { toError } from '../lib/errorUtils';\nimport { CallScope, CallScopeLadder } from './CallScope';\n\n// The same logger LogApiCall writes its [API-*] lines to, so an attempt line sits beside the final one.\nconst log = LogManager.getLogger(LOG_API_CALL_LOGGER_NAME);\n\nclass CallPolicy {\n timeoutMs?: number;\n // webpieces-disable no-any-unknown -- global policy spans heterogeneous response DTOs\n strategy?: CallStrategy<unknown>;\n}\n\n/**\n * Counts the attempts of ONE call and logs each retried TRANSIENT failure. It wraps the attempt\n * BEFORE any strategy sees it, so an app-written strategy gets the same lines as `RetryStrategy`.\n *\n * The line for attempt N is written when attempt N+1 STARTS — i.e. only for an attempt that was\n * actually retried. The last attempt's failure is what escapes, and `LogApiCall`'s final\n * `[API-client-resp-FAIL]` line covers it, so a call that gave up after 4 attempts logs 3 attempt\n * lines and 1 FAIL line, never the last failure twice. An EXPECTED or FAILURE attempt is not logged\n * here either; the final line covers it.\n */\nclass LoggedAttempts<T> {\n private attempts = 0;\n private pendingTransient?: Error;\n\n constructor(\n private readonly context: CallContext,\n private readonly attempt: Attempt<T>,\n ) {}\n\n readonly run: Attempt<T> = async (timeoutMs: number): Promise<T> => {\n this.flushRetried();\n this.attempts += 1;\n // webpieces-disable no-unmanaged-exceptions -- observe the attempt's failure, rethrow it unchanged\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n return await this.attempt(timeoutMs);\n } catch (err: unknown) {\n const error = toError(err);\n const methodInfo = new ApiMethodInfo(\n 'client',\n this.context.apiName,\n this.context.methodName,\n this.context.contract,\n );\n this.pendingTransient =\n ApiRegistry.classify(error, methodInfo) === CallOutcome.TRANSIENT_FAILURE\n ? error\n : undefined;\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions -- rethrows the attempt's own failure unchanged\n throw err;\n }\n };\n\n private flushRetried(): void {\n const error = this.pendingTransient;\n if (error === undefined) return;\n this.pendingTransient = undefined;\n log.warn(\n `[API-client-attempt-TRANSIENT] ${this.context.apiName}.${this.context.methodName} ` +\n `attempt ${this.attempts} errorType=${error.constructor.name} error=${error.message}`,\n );\n }\n}\n\n/**\n * Derives a base URL for a service name that has NO registered mapping — the pluggable half of\n * {@link ClientRegistry} resolution. One per environment, installed once at startup:\n *\n * - `gcpCloudRunDeriver()` (@webpieces/gcp-identity) — the Cloud Run formula, read from the metadata\n * server. For code running ON GCP.\n * - `gcpCloudRunDeriver(new GcpCloudRunTarget(projectNumber, region))` — the SAME formula with the\n * values supplied from config, for code running OFF GCP that still calls Cloud Run (a CLI, CI).\n * - {@link templateDeriver} (this package, browser-safe) — pure string substitution, for AWS or\n * anything else with predictable DNS.\n * - none at all — a browser goes same-origin, and localhost/tests hand-register their mappings.\n */\nexport type ServiceUrlDeriver = (svcName: string) => Promise<string>;\n\n/**\n * ClientRegistry - the ONE place a `svcName` becomes a base URL, for every outbound client in every\n * environment. A client is built once but a URL is per-environment, so the URL belongs here rather\n * than on the client: clients carry ONLY a svcName.\n *\n * Resolution is one precedence chain, identical in the browser, in node, and in Cloud Tasks:\n *\n * 1. a registered mapping wins — the localhost port table, AWS, an external API, another region\n * or project, a host that is not Cloud Run at all. Populated at startup from per-env config.\n * 2. else the installed {@link ServiceUrlDeriver}, if any — GCP's built-in, a DNS template, or\n * your own. OPTIONAL on purpose: localhost is inherently a TABLE (helper-fsdb -> :8401,\n * helper-portal -> :8201 have per-service ports), so explicit mappings must stay sufficient on\n * their own.\n * 3. else the caller's fallback: the BROWSER goes relative (same origin — see\n * {@link ClientRegistry.tryResolve}), while node THROWS (see {@link ClientRegistry.resolve}),\n * because a server has no \"own origin\" and an unresolvable peer is a setup bug.\n *\n * Configured like {@link HeaderRegistry} / LogManager — populated once at startup, then globally\n * accessible with NO DI wiring. It is browser-safe (no `process.env`, no node-only deps), which is\n * why it lives in core-util rather than gcp-identity.\n *\n * A `svcName` should be the nx MODULE name of the service you are calling — that is the one name\n * `architecture:validate-runtime-architecture` can verify actually exists, so a typo or a rename\n * fails the build instead of failing in production. When the DEPLOYED name differs (an environment\n * prefix like `tf-`, or a Cloud Run service named unlike its module), translate it in ONE place —\n * the deriver below, or a `serviceName` alias in the module's project.json — never at the call site.\n *\n * ```ts\n * // startup, from the current environment's config:\n * ClientRegistry.addMapping('server2', 8202); // -> http://localhost:8202\n * ClientRegistry.addUrlMapping('email', 'https://email.other-region.example');\n * ClientRegistry.setDeriver(gcpCloudRunDeriver()); // everything else, on GCP\n * ```\n *\n * The OTHER half: everything ONLY an outbound call reads besides its URL — the per-call timeout and\n * strategy, for browser RPC, node RPC, and Cloud Tasks ENQUEUE. ONE implementation; every transport\n * calls {@link ClientRegistry.execute}. (What BOTH sides read — the error translator and classifier —\n * lives on `ApiRegistry`.)\n *\n * Ladder: strategy method -> API -> ALL first; ANY strategy replaces the ENTIRE timeout ladder.\n * Otherwise timeout method -> API -> ALL. Otherwise the transport's {@link TransportDefault} (its\n * timeout, and its strategy if it has one). A registered TIMEOUT is therefore a decision for a single\n * attempt and also replaces a transport's default strategy; to keep retrying with a different attempt\n * deadline, register a `RetryStrategy` instead.\n *\n * RPC has no default retry (only the application knows whether repeating a POST is safe); Cloud Tasks\n * enqueue does (see `TransportDefault`). An app opts RPC in with\n * `ClientRegistry.setStrategy(new RetryStrategy(...).run, CallScope.api(CatalogApi))` — and `RetryStrategy` never\n * retries a `WRITE`, even registered at ALL.\n */\nexport class ClientRegistry {\n /** svcName -> resolved base URL. Process-global; populated at startup per environment. */\n private static readonly mappings = new Map<string, string>();\n\n /** The fallback for svcNames with no mapping. Undefined = no derivation in this environment. */\n private static deriver: ServiceUrlDeriver | undefined;\n\n /** The timeout / strategy per {@link CallScope} — method -> API -> ALL -> the transport default. */\n private static readonly policies = new CallScopeLadder<CallPolicy>(() => new CallPolicy());\n\n /** Map a service name to `http://localhost:<port>`. */\n // webpieces-disable no-function-outside-class -- static global singleton (like HeaderRegistry/LogManager); populated once at startup, never DI-injected\n static addMapping(svcName: string, port: number): void {\n ClientRegistry.mappings.set(svcName, `http://localhost:${port}`);\n }\n\n /**\n * Map a service name to an explicit base URL (any host / any environment).\n *\n * The EMPTY STRING is a legal, meaningful mapping: it makes the service relative, i.e.\n * same-origin, because the client builds its URL as `${baseUrl}${route.path}`.\n */\n // webpieces-disable no-function-outside-class -- static global singleton (like HeaderRegistry/LogManager); populated once at startup, never DI-injected\n static addUrlMapping(svcName: string, url: string): void {\n ClientRegistry.mappings.set(svcName, url);\n }\n\n /**\n * Install the environment's {@link ServiceUrlDeriver} — how to resolve a svcName that has NO\n * mapping. Optional: an environment that registers every svcName it calls needs none.\n */\n // webpieces-disable no-function-outside-class -- static global singleton (like HeaderRegistry/LogManager); populated once at startup, never DI-injected\n static setDeriver(fn: ServiceUrlDeriver): void {\n ClientRegistry.deriver = fn;\n }\n\n /** The registered override for `svcName`, or undefined if none. Registry only — no derivation. */\n // webpieces-disable no-function-outside-class -- static global singleton (like HeaderRegistry/LogManager); populated once at startup, never DI-injected\n static tryLookup(svcName: string): string | undefined {\n return ClientRegistry.mappings.get(svcName);\n }\n\n /**\n * Resolve `svcName` to its registered base URL. THROWS if the service was never registered.\n * Registry only — it does NOT consult the deriver; prefer {@link ClientRegistry.resolve}.\n */\n // webpieces-disable no-function-outside-class -- static global singleton (like HeaderRegistry/LogManager); populated once at startup, never DI-injected\n static lookup(svcName: string): string {\n const url = ClientRegistry.tryLookup(svcName);\n if (url === undefined) {\n throw new Error(\n `No URL registered for service \"${svcName}\". Register it at startup: ` +\n `ClientRegistry.addMapping(svcName, port) for a localhost port, or ` +\n `ClientRegistry.addUrlMapping(svcName, url) for an explicit URL.`,\n );\n }\n return url;\n }\n\n /**\n * Steps 1 + 2 of the chain: the registered mapping, else the installed deriver, else undefined.\n * Non-throwing — the BROWSER uses this and treats undefined as \"\" (relative → same origin),\n * which is what a browser app calling the backend it was served from wants by default.\n *\n * Note the `!== undefined` guard: an empty-string mapping is a legal answer (\"this service is\n * same-origin\"), so it must NOT fall through to derivation.\n */\n // webpieces-disable no-function-outside-class -- static global singleton (like HeaderRegistry/LogManager); populated once at startup, never DI-injected\n static tryResolve(svcName: string): Promise<string | undefined> {\n const override = ClientRegistry.tryLookup(svcName);\n if (override !== undefined) {\n return Promise.resolve(override);\n }\n if (!ClientRegistry.deriver) {\n return Promise.resolve(undefined);\n }\n return ClientRegistry.deriver(svcName);\n }\n\n /**\n * The full chain, with node's fallback: mapping, else deriver, else THROW. A server has no \"own\n * origin\" to go relative to, so an unresolvable peer is a setup bug and must fail loudly — and\n * say how to fix it.\n */\n // webpieces-disable no-function-outside-class -- static global singleton (like HeaderRegistry/LogManager); populated once at startup, never DI-injected\n static async resolve(svcName: string): Promise<string> {\n const url = await ClientRegistry.tryResolve(svcName);\n if (url === undefined) {\n throw new Error(\n `No URL for service \"${svcName}\".\\n` +\n ` - localhost/AWS: ClientRegistry.addMapping('${svcName}', 8401)\\n` +\n ` or ClientRegistry.addUrlMapping('${svcName}', 'https://...')\\n` +\n ` - GCP: install a deriver — ClientRegistry.setDeriver(gcpCloudRunDeriver())\\n` +\n ` - deployed name differs from the module name (e.g. a 'tf-' prefix)? Translate it ONCE\\n` +\n ` in the deriver — setDeriver(s => gcpCloudRunDeriver()('tf-' + s)) — so every call\\n` +\n ` site keeps naming the MODULE, which architecture:validate-runtime-architecture checks`,\n );\n }\n return url;\n }\n\n // webpieces-disable no-function-outside-class -- process-global startup registry\n static setTimeout(timeoutMs: number | undefined, scope: CallScope): void {\n if (timeoutMs !== undefined) CallDeadline.validate(timeoutMs);\n ClientRegistry.policies.at(scope).timeoutMs = timeoutMs;\n }\n\n // webpieces-disable no-function-outside-class -- process-global startup registry\n static setStrategy(\n // webpieces-disable no-any-unknown -- registry strategies span heterogeneous response DTOs\n strategy: CallStrategy<unknown> | undefined,\n scope: CallScope,\n ): void {\n ClientRegistry.policies.at(scope).strategy = strategy;\n }\n\n /**\n * Run one call under its registered policy. `context` names the method (its `methodName` selects\n * the per-method policy) and carries the endpoint's declared operation, so the SAME context a\n * strategy sees is the one the transport's deadline puts on an `ApiCallTimeoutError`. The context\n * a strategy sees always carries `api` as its {@link CallContext.contract}, so the error\n * classification inside a strategy resolves on the same ladder.\n *\n * Every attempt is wrapped so a retried TRANSIENT failure logs one\n * `WARN [API-client-attempt-TRANSIENT]` line (see {@link LoggedAttempts}).\n *\n * `deadlines` is the calling client's {@link DeadlineScheduler}, handed to whichever strategy\n * runs so its backoff waits on the same clock the attempt deadlines use (#1445).\n */\n // webpieces-disable no-function-outside-class -- transport-independent policy execution\n static async execute<T>(\n api: Function,\n context: CallContext,\n attempt: Attempt<T>,\n fallback: TransportDefault,\n deadlines: DeadlineScheduler,\n ): Promise<T> {\n const scoped =\n context.contract === api\n ? context\n : new CallContext(context.apiName, context.methodName, context.operation, api);\n const logged = new LoggedAttempts<T>(scoped, attempt).run;\n const rungs = ClientRegistry.policies.rungs(api, scoped.methodName);\n const strategy = rungs.find((p: CallPolicy) => p.strategy !== undefined)?.strategy;\n if (strategy !== undefined) {\n return (await strategy(logged, scoped, deadlines)) as T;\n }\n const timeoutMs = rungs.find((p: CallPolicy) => p.timeoutMs !== undefined)?.timeoutMs;\n if (timeoutMs !== undefined) {\n return logged(timeoutMs);\n }\n if (fallback.strategy !== undefined) {\n return (await fallback.strategy(logged, scoped, deadlines)) as T;\n }\n return logged(fallback.timeoutMs);\n }\n\n /**\n * The registered TIMEOUT for a call — method -> API -> ALL -> `defaultMs` — ignoring every\n * strategy. For a transport that hands timing to someone else for this call (Cloud Tasks enqueue\n * with caller-supplied gax `CallOptions`) and still needs ONE safety cap so a hung channel cannot\n * block forever. Raise it with {@link ClientRegistry.setTimeout}.\n */\n // webpieces-disable no-function-outside-class -- process-global registry lookup\n static resolveTimeout(api: Function, methodName: string, defaultMs: number): number {\n const rungs = ClientRegistry.policies.rungs(api, methodName);\n return rungs.find((p: CallPolicy) => p.timeoutMs !== undefined)?.timeoutMs ?? defaultMs;\n }\n\n /**\n * Put the process-globals back to the state a fresh process starts in. For TESTS, so one spec\n * cannot leak its registrations into the next: every URL mapping, the deriver, and every\n * timeout / strategy rung. (`ApiRegistry.resetForTests()` resets the error translators and\n * classifiers.)\n */\n // webpieces-disable no-function-outside-class -- static global singleton (like HeaderRegistry/LogManager); populated once at startup, never DI-injected\n static resetForTests(): void {\n ClientRegistry.mappings.clear();\n ClientRegistry.deriver = undefined;\n ClientRegistry.policies.clear();\n }\n}\n"]}
@@ -4,6 +4,8 @@ const ClientRegistry_1 = require("./ClientRegistry");
4
4
  const CallScope_1 = require("./CallScope");
5
5
  const CallStrategy_1 = require("./CallStrategy");
6
6
  const HttpEndpointOptions_1 = require("./HttpEndpointOptions");
7
+ const TransportDefault_1 = require("./TransportDefault");
8
+ const DeadlineScheduler_1 = require("./DeadlineScheduler");
7
9
  /** An abstract SDK-wrapping `XxxApi` — the shape an api-client keys its policies by. */
8
10
  class AbstractTargetApi {
9
11
  }
@@ -57,7 +59,13 @@ class ClientRegistryCompileAssertions {
57
59
  const context = new CallStrategy_1.CallContext('Api', 'work', HttpEndpointOptions_1.WRITE, ClientRegistryCompileAssertions);
58
60
  void ClientRegistry_1.ClientRegistry.execute(ClientRegistryCompileAssertions, context, (ms) => Promise.resolve(ms),
59
61
  // @ts-expect-error execute(..., defaultMs: number) became execute(..., fallback: TransportDefault)
60
- 30_000);
62
+ 30_000, new DeadlineScheduler_1.TimerDeadlineScheduler());
63
+ }
64
+ /** The client's clock is REQUIRED: no call path may silently fall back to a global timer (#1445). */
65
+ deadlinesAreRequired() {
66
+ const context = new CallStrategy_1.CallContext('Api', 'work', HttpEndpointOptions_1.WRITE, ClientRegistryCompileAssertions);
67
+ // @ts-expect-error execute(...) takes the calling client's DeadlineScheduler as its last argument
68
+ void ClientRegistry_1.ClientRegistry.execute(ClientRegistryCompileAssertions, context, (ms) => Promise.resolve(ms), new TransportDefault_1.TransportDefault(30_000));
61
69
  }
62
70
  }
63
71
  //# sourceMappingURL=ClientRegistryCompileAssertions.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"ClientRegistryCompileAssertions.js","sourceRoot":"","sources":["../../../../../../packages/core/core-util/src/http/ClientRegistryCompileAssertions.ts"],"names":[],"mappings":";;AAAA,qDAAkD;AAClD,2CAAwC;AACxC,iDAA6C;AAC7C,+DAA8C;AAE9C,wFAAwF;AACxF,MAAe,iBAAiB;CAE/B;AAED,kDAAkD;AAClD,MAAM,iBAAiB;IACnB,IAAI;QACA,OAAO,OAAO,CAAC,OAAO,EAAE,CAAC;IAC7B,CAAC;CACJ;AAED;;;;GAIG;AACH,MAAM,+BAA+B;IACjC,iBAAiB;QACb,2DAA2D;QAC3D,+BAAc,CAAC,UAAU,CAAC,GAAG,EAAE,KAAK,CAAC,CAAC;QACtC,+FAA+F;QAC/F,+BAAc,CAAC,WAAW,CAAC,SAAS,EAAE,QAAQ,CAAC,CAAC;QAChD,oFAAoF;QACpF,+BAAc,CAAC,UAAU,CAAC,GAAG,EAAE,iBAAiB,EAAE,MAAM,CAAC,CAAC;QAC1D,0DAA0D;QAC1D,+BAAc,CAAC,UAAU,CAAC,GAAG,EAAE,iBAAiB,CAAC,CAAC;QAClD,gGAAgG;QAChG,+BAAc,CAAC,UAAU,CAAC,GAAG,EA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EAAE,CAAC;QACnC,mGAAmG;QACnG,MAAM,CACT,CAAC;IACN,CAAC;CACJ","sourcesContent":["import { ClientRegistry } from './ClientRegistry';\nimport { CallScope } from './CallScope';\nimport { CallContext } from './CallStrategy';\nimport { WRITE } from './HttpEndpointOptions';\n\n/** An abstract SDK-wrapping `XxxApi` — the shape an api-client keys its policies by. */\nabstract class AbstractTargetApi {\n abstract work(): Promise<void>;\n}\n\n/** A concrete `@ApiPath`-style contract class. */\nclass ConcreteTargetApi {\n work(): Promise<void> {\n return Promise.resolve();\n }\n}\n\n/**\n * Compiled by tsc (spec files are not), never executed. Pins the ONE spelling of a call scope —\n * `CallScope.all()` / `.api(X)` / `.method(X, 'm')` — and that the per-call timeout and strategy\n * live on `ClientRegistry`. tsc fails the build with TS2578 if any of these ever starts compiling.\n */\nclass ClientRegistryCompileAssertions {\n scopeIsACallScope(): void {\n // @ts-expect-error the 'ALL' string became CallScope.all()\n ClientRegistry.setTimeout(100, 'ALL');\n // @ts-expect-error a string is never a scope — use CallScope.all() / .api(X) / .method(X, 'm')\n ClientRegistry.setStrategy(undefined, 'random');\n // @ts-expect-error the (Api, 'method') tuple became CallScope.method(Api, 'method')\n ClientRegistry.setTimeout(100, ConcreteTargetApi, 'work');\n // @ts-expect-error a bare class became CallScope.api(Api)\n ClientRegistry.setTimeout(100, ConcreteTargetApi);\n // @ts-expect-error an object literal is not a scope — the factories are the only way to get one\n ClientRegistry.setTimeout(100, {});\n // @ts-expect-error an object literal shaped like a scope is not one either (CallScope is nominal)\n ClientRegistry.setTimeout(100, { api: ConcreteTargetApi, methodName: 'work' });\n // @ts-expect-error the constructor is private — use CallScope.all() / .api(X) / .method(X, 'm')\n void new CallScope(undefined, undefined);\n }\n\n methodNameIsChecked(): void {\n ClientRegistry.setTimeout(100, CallScope.method(ConcreteTargetApi, 'work'));\n ClientRegistry.setTimeout(100, CallScope.method(AbstractTargetApi, 'work'));\n // @ts-expect-error a misspelled method does not compile — it would silently match nothing\n ClientRegistry.setTimeout(100, CallScope.method(ConcreteTargetApi, 'wrok'));\n // @ts-expect-error a misspelled method does not compile on an abstract XxxApi either\n ClientRegistry.setStrategy(undefined, CallScope.method(AbstractTargetApi, 'wrok'));\n }\n\n callRegistryIsDeleted(): void {\n // @ts-expect-error CallRegistry is deleted: CallRegistry.setTimeout became ClientRegistry.setTimeout\n CallRegistry.setTimeout(100, CallScope.all());\n }\n\n /** A CallContext's contract is the CLASS, never undefined (#1350). */\n contractIsNeverUndefined(): void {\n // @ts-expect-error CallContext's contract is a CLASS, never undefined — pass the real contract class\n void new CallContext('Api', 'work', WRITE, undefined);\n }\n\n /** The transport fallback is a TransportDefault (timeout + optional strategy), never a bare number. */\n fallbackIsATransportDefault(): void {\n const context = new CallContext('Api', 'work', WRITE, ClientRegistryCompileAssertions);\n void ClientRegistry.execute(\n ClientRegistryCompileAssertions,\n context,\n (ms: number) => Promise.resolve(ms),\n // @ts-expect-error execute(..., defaultMs: number) became execute(..., fallback: TransportDefault)\n 30_000,\n );\n }\n}\n"]}
1
+ {"version":3,"file":"ClientRegistryCompileAssertions.js","sourceRoot":"","sources":["../../../../../../packages/core/core-util/src/http/ClientRegistryCompileAssertions.ts"],"names":[],"mappings":";;AAAA,qDAAkD;AAClD,2CAAwC;AACxC,iDAA6C;AAC7C,+DAA8C;AAC9C,yDAAsD;AACtD,2DAA6D;AAE7D,wFAAwF;AACxF,MAAe,iBAAiB;CAE/B;AAED,kDAAkD;AAClD,MAAM,iBAAiB;IACnB,IAAI;QACA,OAAO,OAAO,CAAC,OAAO,EAAE,CAAC;IAC7B,CAAC;CACJ;AAED;;;;GAIG;AACH,MAAM,+BAA+B;IACjC,iBAAiB;QACb,2DAA2D;QAC3D,+BAAc,CAAC,UAAU,CAAC,GAAG,EAAE,KAAK,CAAC,CAAC;QACtC,+FAA+F;QAC/F,+BAAc,CAAC,WAAW,CAAC,SAAS,EAAE,QAAQ,CAAC,CAAC;QAChD,oFAAoF;QACpF,+BAAc,CAAC,UAAU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AAW,CAAC,KAAK,EAAE,MAAM,EAAE,2BAAK,EAAE,+BAA+B,CAAC,CAAC;QACvF,KAAK,+BAAc,CAAC,OAAO,CACvB,+BAA+B,EAC/B,OAAO,EACP,CAAC,EAAU,EAAE,EAAE,CAAC,OAAO,CAAC,OAAO,CAAC,EAAE,CAAC;QACnC,mGAAmG;QACnG,MAAM,EACN,IAAI,0CAAsB,EAAE,CAC/B,CAAC;IACN,CAAC;IAED,qGAAqG;IACrG,oBAAoB;QAChB,MAAM,OAAO,GAAG,IAAI,0BAAW,CAAC,KAAK,EAAE,MAAM,EAAE,2BAAK,EAAE,+BAA+B,CAAC,CAAC;QACvF,kGAAkG;QAClG,KAAK,+BAAc,CAAC,OAAO,CACvB,+BAA+B,EAC/B,OAAO,EACP,CAAC,EAAU,EAAE,EAAE,CAAC,OAAO,CAAC,OAAO,CAAC,EAAE,CAAC,EACnC,IAAI,mCAAgB,CAAC,MAAM,CAAC,CAC/B,CAAC;IACN,CAAC;CACJ","sourcesContent":["import { ClientRegistry } from './ClientRegistry';\nimport { CallScope } from './CallScope';\nimport { CallContext } from './CallStrategy';\nimport { WRITE } from './HttpEndpointOptions';\nimport { TransportDefault } from './TransportDefault';\nimport { TimerDeadlineScheduler } from './DeadlineScheduler';\n\n/** An abstract SDK-wrapping `XxxApi` — the shape an api-client keys its policies by. */\nabstract class AbstractTargetApi {\n abstract work(): Promise<void>;\n}\n\n/** A concrete `@ApiPath`-style contract class. */\nclass ConcreteTargetApi {\n work(): Promise<void> {\n return Promise.resolve();\n }\n}\n\n/**\n * Compiled by tsc (spec files are not), never executed. Pins the ONE spelling of a call scope —\n * `CallScope.all()` / `.api(X)` / `.method(X, 'm')` — and that the per-call timeout and strategy\n * live on `ClientRegistry`. tsc fails the build with TS2578 if any of these ever starts compiling.\n */\nclass ClientRegistryCompileAssertions {\n scopeIsACallScope(): void {\n // @ts-expect-error the 'ALL' string became CallScope.all()\n ClientRegistry.setTimeout(100, 'ALL');\n // @ts-expect-error a string is never a scope — use CallScope.all() / .api(X) / .method(X, 'm')\n ClientRegistry.setStrategy(undefined, 'random');\n // @ts-expect-error the (Api, 'method') tuple became CallScope.method(Api, 'method')\n ClientRegistry.setTimeout(100, ConcreteTargetApi, 'work');\n // @ts-expect-error a bare class became CallScope.api(Api)\n ClientRegistry.setTimeout(100, ConcreteTargetApi);\n // @ts-expect-error an object literal is not a scope — the factories are the only way to get one\n ClientRegistry.setTimeout(100, {});\n // @ts-expect-error an object literal shaped like a scope is not one either (CallScope is nominal)\n ClientRegistry.setTimeout(100, { api: ConcreteTargetApi, methodName: 'work' });\n // @ts-expect-error the constructor is private — use CallScope.all() / .api(X) / .method(X, 'm')\n void new CallScope(undefined, undefined);\n }\n\n methodNameIsChecked(): void {\n ClientRegistry.setTimeout(100, CallScope.method(ConcreteTargetApi, 'work'));\n ClientRegistry.setTimeout(100, CallScope.method(AbstractTargetApi, 'work'));\n // @ts-expect-error a misspelled method does not compile — it would silently match nothing\n ClientRegistry.setTimeout(100, CallScope.method(ConcreteTargetApi, 'wrok'));\n // @ts-expect-error a misspelled method does not compile on an abstract XxxApi either\n ClientRegistry.setStrategy(undefined, CallScope.method(AbstractTargetApi, 'wrok'));\n }\n\n callRegistryIsDeleted(): void {\n // @ts-expect-error CallRegistry is deleted: CallRegistry.setTimeout became ClientRegistry.setTimeout\n CallRegistry.setTimeout(100, CallScope.all());\n }\n\n /** A CallContext's contract is the CLASS, never undefined (#1350). */\n contractIsNeverUndefined(): void {\n // @ts-expect-error CallContext's contract is a CLASS, never undefined — pass the real contract class\n void new CallContext('Api', 'work', WRITE, undefined);\n }\n\n /** The transport fallback is a TransportDefault (timeout + optional strategy), never a bare number. */\n fallbackIsATransportDefault(): void {\n const context = new CallContext('Api', 'work', WRITE, ClientRegistryCompileAssertions);\n void ClientRegistry.execute(\n ClientRegistryCompileAssertions,\n context,\n (ms: number) => Promise.resolve(ms),\n // @ts-expect-error execute(..., defaultMs: number) became execute(..., fallback: TransportDefault)\n 30_000,\n new TimerDeadlineScheduler(),\n );\n }\n\n /** The client's clock is REQUIRED: no call path may silently fall back to a global timer (#1445). */\n deadlinesAreRequired(): void {\n const context = new CallContext('Api', 'work', WRITE, ClientRegistryCompileAssertions);\n // @ts-expect-error execute(...) takes the calling client's DeadlineScheduler as its last argument\n void ClientRegistry.execute(\n ClientRegistryCompileAssertions,\n context,\n (ms: number) => Promise.resolve(ms),\n new TransportDefault(30_000),\n );\n }\n}\n"]}
@@ -0,0 +1,50 @@
1
+ /**
2
+ * One scheduled deadline. {@link CallDeadline} calls {@link cancel} EXACTLY ONCE per call, on every
3
+ * settlement — success, failure, abort or the deadline itself firing — so an implementation may
4
+ * release its native timer there without guarding against a second call.
5
+ */
6
+ export interface DeadlineTimer {
7
+ cancel(): void;
8
+ }
9
+ /**
10
+ * Where a call deadline's clock and wake-up come from (#1445). The ONE timing seam of the generated
11
+ * clients: {@link CallDeadline} schedules each attempt's deadline through it, and `RetryStrategy`
12
+ * waits out its backoff through it, so nothing on the call path reaches for a JS timer behind it.
13
+ *
14
+ * - Browser, Node, SSR, workers and tests: {@link TimerDeadlineScheduler} — standard
15
+ * `setTimeout` / `clearTimeout`, which is what every call used before this seam existed.
16
+ * - React Native: the APPLICATION supplies a native-backed implementation (an AlarmManager /
17
+ * Handler / DispatchSourceTimer behind a native module, say). React Native's JS timer manager
18
+ * pauses while the host is paused, so a JS-timer deadline does not fire while an Android phone is
19
+ * locked; a native-delivered callback does. Wrapping `setTimeout` again does NOT satisfy this
20
+ * contract — the scheduler exists precisely so the wake-up does not come from a JS timer.
21
+ *
22
+ * Implementation contract:
23
+ * - `schedule` may throw synchronously (the call then fails before any work starts, and nothing is
24
+ * scheduled to clean up).
25
+ * - `onExpire` may be delivered LATE, after the call already settled, or not at all while the OS has
26
+ * the process suspended. A late delivery is ignored; no delivery is covered by {@link now}: when the
27
+ * work settles and `now()` shows the budget is spent, the call is failed with the same typed
28
+ * timeout instead of returning a result that arrived after its deadline.
29
+ * - `now` is a millisecond clock used only for elapsed-time arithmetic. Prefer a monotonic clock that
30
+ * KEEPS COUNTING while the device sleeps (Android `SystemClock.elapsedRealtime`, for example), or
31
+ * `Date.now()` as a non-monotonic fallback. A clock that stops during sleep under-reports elapsed
32
+ * time and lets an expired call return late.
33
+ */
34
+ export interface DeadlineScheduler {
35
+ /** Arrange for `onExpire` to run once, `delayMs` from now. */
36
+ schedule(delayMs: number, onExpire: () => void): DeadlineTimer;
37
+ /** Milliseconds on this scheduler's clock; only differences between two readings are meaningful. */
38
+ now(): number;
39
+ }
40
+ /**
41
+ * The default {@link DeadlineScheduler} for browsers, WebView pages, Node, SSR, workers and tests:
42
+ * standard JS timers, exactly as every generated client used before #1445 made timing injectable.
43
+ *
44
+ * NOT a React Native background fix — see {@link DeadlineScheduler}. Browsers also throttle timers in
45
+ * background tabs; that is the platform's documented behavior and this class does not fight it.
46
+ */
47
+ export declare class TimerDeadlineScheduler implements DeadlineScheduler {
48
+ schedule(delayMs: number, onExpire: () => void): DeadlineTimer;
49
+ now(): number;
50
+ }
@@ -0,0 +1,32 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.TimerDeadlineScheduler = void 0;
4
+ /** A `setTimeout` handle, released through `clearTimeout`. */
5
+ class JsTimer {
6
+ handle;
7
+ constructor(handle) {
8
+ this.handle = handle;
9
+ }
10
+ cancel() {
11
+ clearTimeout(this.handle);
12
+ }
13
+ }
14
+ /**
15
+ * The default {@link DeadlineScheduler} for browsers, WebView pages, Node, SSR, workers and tests:
16
+ * standard JS timers, exactly as every generated client used before #1445 made timing injectable.
17
+ *
18
+ * NOT a React Native background fix — see {@link DeadlineScheduler}. Browsers also throttle timers in
19
+ * background tabs; that is the platform's documented behavior and this class does not fight it.
20
+ */
21
+ class TimerDeadlineScheduler {
22
+ schedule(delayMs, onExpire) {
23
+ return new JsTimer(setTimeout(onExpire, delayMs));
24
+ }
25
+ now() {
26
+ // `performance` is monotonic where it exists (browsers, Node 16+, React Native); a runtime
27
+ // without it still gets a usable — if adjustable — wall clock.
28
+ return typeof performance !== 'undefined' ? performance.now() : Date.now();
29
+ }
30
+ }
31
+ exports.TimerDeadlineScheduler = TimerDeadlineScheduler;
32
+ //# sourceMappingURL=DeadlineScheduler.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"DeadlineScheduler.js","sourceRoot":"","sources":["../../../../../../packages/core/core-util/src/http/DeadlineScheduler.ts"],"names":[],"mappings":";;;AA0CA,8DAA8D;AAC9D,MAAM,OAAO;IACoB;IAA7B,YAA6B,MAAqC;QAArC,WAAM,GAAN,MAAM,CAA+B;IAAG,CAAC;IAEtE,MAAM;QACF,YAAY,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC;IAC9B,CAAC;CACJ;AAED;;;;;;GAMG;AACH,MAAa,sBAAsB;IAC/B,QAAQ,CAAC,OAAe,EAAE,QAAoB;QAC1C,OAAO,IAAI,OAAO,CAAC,UAAU,CAAC,QAAQ,EAAE,OAAO,CAAC,CAAC,CAAC;IACtD,CAAC;IAED,GAAG;QACC,2FAA2F;QAC3F,+DAA+D;QAC/D,OAAO,OAAO,WAAW,KAAK,WAAW,CAAC,CAAC,CAAC,WAAW,CAAC,GAAG,EAAE,CAAC,CAAC,CAAC,IAAI,CAAC,GAAG,EAAE,CAAC;IAC/E,CAAC;CACJ;AAVD,wDAUC","sourcesContent":["/**\n * One scheduled deadline. {@link CallDeadline} calls {@link cancel} EXACTLY ONCE per call, on every\n * settlement — success, failure, abort or the deadline itself firing — so an implementation may\n * release its native timer there without guarding against a second call.\n */\nexport interface DeadlineTimer {\n cancel(): void;\n}\n\n/**\n * Where a call deadline's clock and wake-up come from (#1445). The ONE timing seam of the generated\n * clients: {@link CallDeadline} schedules each attempt's deadline through it, and `RetryStrategy`\n * waits out its backoff through it, so nothing on the call path reaches for a JS timer behind it.\n *\n * - Browser, Node, SSR, workers and tests: {@link TimerDeadlineScheduler} — standard\n * `setTimeout` / `clearTimeout`, which is what every call used before this seam existed.\n * - React Native: the APPLICATION supplies a native-backed implementation (an AlarmManager /\n * Handler / DispatchSourceTimer behind a native module, say). React Native's JS timer manager\n * pauses while the host is paused, so a JS-timer deadline does not fire while an Android phone is\n * locked; a native-delivered callback does. Wrapping `setTimeout` again does NOT satisfy this\n * contract — the scheduler exists precisely so the wake-up does not come from a JS timer.\n *\n * Implementation contract:\n * - `schedule` may throw synchronously (the call then fails before any work starts, and nothing is\n * scheduled to clean up).\n * - `onExpire` may be delivered LATE, after the call already settled, or not at all while the OS has\n * the process suspended. A late delivery is ignored; no delivery is covered by {@link now}: when the\n * work settles and `now()` shows the budget is spent, the call is failed with the same typed\n * timeout instead of returning a result that arrived after its deadline.\n * - `now` is a millisecond clock used only for elapsed-time arithmetic. Prefer a monotonic clock that\n * KEEPS COUNTING while the device sleeps (Android `SystemClock.elapsedRealtime`, for example), or\n * `Date.now()` as a non-monotonic fallback. A clock that stops during sleep under-reports elapsed\n * time and lets an expired call return late.\n */\nexport interface DeadlineScheduler {\n /** Arrange for `onExpire` to run once, `delayMs` from now. */\n schedule(delayMs: number, onExpire: () => void): DeadlineTimer;\n\n /** Milliseconds on this scheduler's clock; only differences between two readings are meaningful. */\n now(): number;\n}\n\n/** A `setTimeout` handle, released through `clearTimeout`. */\nclass JsTimer implements DeadlineTimer {\n constructor(private readonly handle: ReturnType<typeof setTimeout>) {}\n\n cancel(): void {\n clearTimeout(this.handle);\n }\n}\n\n/**\n * The default {@link DeadlineScheduler} for browsers, WebView pages, Node, SSR, workers and tests:\n * standard JS timers, exactly as every generated client used before #1445 made timing injectable.\n *\n * NOT a React Native background fix — see {@link DeadlineScheduler}. Browsers also throttle timers in\n * background tabs; that is the platform's documented behavior and this class does not fight it.\n */\nexport class TimerDeadlineScheduler implements DeadlineScheduler {\n schedule(delayMs: number, onExpire: () => void): DeadlineTimer {\n return new JsTimer(setTimeout(onExpire, delayMs));\n }\n\n now(): number {\n // `performance` is monotonic where it exists (browsers, Node 16+, React Native); a runtime\n // without it still gets a usable — if adjustable — wall clock.\n return typeof performance !== 'undefined' ? performance.now() : Date.now();\n }\n}\n"]}
@@ -0,0 +1,24 @@
1
+ /**
2
+ * Explicit, recursive JSON DATA in an API: a string, a number, a boolean, `null`, an array of
3
+ * JSON values, or an object whose every value is a JSON value (#1447).
4
+ *
5
+ * Like {@link Integer}, this alias is a DECLARATION for the document generator rather than a runtime
6
+ * type. `@webpieces/api-doc-model` reads the written syntax, recognises a reference to a TYPE ALIAS
7
+ * named `JsonValueDto` and publishes it as the open JSON schema
8
+ * `{ "type": ["string","number","boolean","object","array","null"], "additionalProperties": true }`
9
+ * — in every OpenAPI document and every MCP tool catalog — instead of trying to expand a
10
+ * self-referencing union, which no schema walk can do.
11
+ *
12
+ * Use it ONLY where a payload is genuinely free-form JSON whose shape a server-owned runtime
13
+ * definition validates (an extensible settings bag, a tool's opaque arguments). Every ordinary DTO
14
+ * stays a closed, named type: an undeclared key on one is still refused at the boundary, and only
15
+ * an object reached through this marker accepts any key.
16
+ *
17
+ * The marker is the alias NAME, exactly like `Integer`, because a type alias has no runtime identity
18
+ * a decorator could carry. A consumer may therefore import this one or declare its own alias of the
19
+ * same name; a CLASS or INTERFACE named `JsonValueDto` is NOT the marker and is documented as the
20
+ * ordinary DTO it is.
21
+ */
22
+ export type JsonValueDto = string | number | boolean | null | JsonValueDto[] | {
23
+ [key: string]: JsonValueDto;
24
+ };
@@ -0,0 +1,3 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ //# sourceMappingURL=JsonValueDto.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"JsonValueDto.js","sourceRoot":"","sources":["../../../../../../packages/core/core-util/src/http/JsonValueDto.ts"],"names":[],"mappings":"","sourcesContent":["/**\n * Explicit, recursive JSON DATA in an API: a string, a number, a boolean, `null`, an array of\n * JSON values, or an object whose every value is a JSON value (#1447).\n *\n * Like {@link Integer}, this alias is a DECLARATION for the document generator rather than a runtime\n * type. `@webpieces/api-doc-model` reads the written syntax, recognises a reference to a TYPE ALIAS\n * named `JsonValueDto` and publishes it as the open JSON schema\n * `{ \"type\": [\"string\",\"number\",\"boolean\",\"object\",\"array\",\"null\"], \"additionalProperties\": true }`\n * — in every OpenAPI document and every MCP tool catalog — instead of trying to expand a\n * self-referencing union, which no schema walk can do.\n *\n * Use it ONLY where a payload is genuinely free-form JSON whose shape a server-owned runtime\n * definition validates (an extensible settings bag, a tool's opaque arguments). Every ordinary DTO\n * stays a closed, named type: an undeclared key on one is still refused at the boundary, and only\n * an object reached through this marker accepts any key.\n *\n * The marker is the alias NAME, exactly like `Integer`, because a type alias has no runtime identity\n * a decorator could carry. A consumer may therefore import this one or declare its own alias of the\n * same name; a CLASS or INTERFACE named `JsonValueDto` is NOT the marker and is documented as the\n * ordinary DTO it is.\n */\nexport type JsonValueDto =\n | string\n | number\n | boolean\n | null\n | JsonValueDto[]\n | { [key: string]: JsonValueDto };\n"]}
@@ -47,6 +47,11 @@ export declare class LogApiCall {
47
47
  * 256 KB per-entry limit with room for the entry's other fields.
48
48
  */
49
49
  static readonly NODE_DEFAULT_MAX_BODY_CHARS = 50000;
50
+ /**
51
+ * What a log line carries in place of a body nested too deeply to serialize (#1447). Fixed text:
52
+ * it names neither the body nor the exception, either of which may hold a masked value.
53
+ */
54
+ static readonly NESTING_LIMIT_PLACEHOLDER = "[API body omitted: JSON serialization nesting limit exceeded]";
50
55
  /** The default for the runtime this module was loaded in, decided once. */
51
56
  static readonly RUNTIME_DEFAULT_MAX_BODY_CHARS: number;
52
57
  private static configuredMaxBodyChars;