@webpieces/core-util 0.4.1001 → 0.4.1003

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.1001",
3
+ "version": "0.4.1003",
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"]}
@@ -11,7 +11,11 @@ import { CallStrategy } from './CallStrategy';
11
11
  * registered at ALL: a transient error on a non-idempotent write may already have happened.
12
12
  *
13
13
  * Each attempt gets its own `attemptTimeoutMs` deadline. Between attempts it waits
14
- * `initialDelayMs`, then multiplies by `delayMultiplier`, capped at `maxDelayMs`.
14
+ * `initialDelayMs`, then multiplies by `delayMultiplier`, capped at `maxDelayMs`. The wait is
15
+ * scheduled on the calling client's {@link DeadlineScheduler} — never a bare `setTimeout` — so a
16
+ * React Native client with a native-backed scheduler does not stall between attempts while its JS
17
+ * timers are paused (#1445). The backoff never resets or extends an attempt's own deadline: each
18
+ * attempt is a fresh `CallDeadline.run` with exactly `attemptTimeoutMs`.
15
19
  *
16
20
  * When it RETRIED and ran out, it throws {@link ApiRetriesExhaustedError} (`cause` = the last
17
21
  * attempt's error), which is classified FAILURE so no layer above retries again. A call that made a
@@ -28,5 +32,6 @@ export declare class RetryStrategy {
28
32
  constructor(attemptTimeoutMs: number, maxRetries: number, initialDelayMs: number, delayMultiplier: number, maxDelayMs: number);
29
33
  private execute;
30
34
  private static requireWhole;
35
+ /** The backoff wait, on the client's scheduler. Its timer has fired, so there is nothing to cancel. */
31
36
  private static sleep;
32
37
  }
@@ -20,7 +20,11 @@ const errorUtils_1 = require("../lib/errorUtils");
20
20
  * registered at ALL: a transient error on a non-idempotent write may already have happened.
21
21
  *
22
22
  * Each attempt gets its own `attemptTimeoutMs` deadline. Between attempts it waits
23
- * `initialDelayMs`, then multiplies by `delayMultiplier`, capped at `maxDelayMs`.
23
+ * `initialDelayMs`, then multiplies by `delayMultiplier`, capped at `maxDelayMs`. The wait is
24
+ * scheduled on the calling client's {@link DeadlineScheduler} — never a bare `setTimeout` — so a
25
+ * React Native client with a native-backed scheduler does not stall between attempts while its JS
26
+ * timers are paused (#1445). The backoff never resets or extends an attempt's own deadline: each
27
+ * attempt is a fresh `CallDeadline.run` with exactly `attemptTimeoutMs`.
24
28
  *
25
29
  * When it RETRIED and ran out, it throws {@link ApiRetriesExhaustedError} (`cause` = the last
26
30
  * attempt's error), which is classified FAILURE so no layer above retries again. A call that made a
@@ -49,10 +53,14 @@ class RetryStrategy {
49
53
  throw new RangeError('delayMultiplier must be finite and at least 1');
50
54
  }
51
55
  // webpieces-disable no-any-unknown -- registry strategies span heterogeneous response DTOs
52
- this.run = (call, ctx) => this.execute(call, ctx);
56
+ this.run = (
57
+ // webpieces-disable no-any-unknown -- registry strategies span heterogeneous response DTOs
58
+ call, ctx, deadlines) => this.execute(call, ctx, deadlines);
53
59
  }
54
60
  // webpieces-disable no-any-unknown -- registry strategies span heterogeneous response DTOs
55
- async execute(call, ctx) {
61
+ async execute(
62
+ // webpieces-disable no-any-unknown -- registry strategies span heterogeneous response DTOs
63
+ call, ctx, deadlines) {
56
64
  const methodInfo = new ApiMethodInfo_1.ApiMethodInfo('client', ctx.apiName, ctx.methodName, ctx.contract);
57
65
  let delayMs = this.initialDelayMs;
58
66
  for (let attempt = 1;; attempt++) {
@@ -76,7 +84,7 @@ class RetryStrategy {
76
84
  }
77
85
  throw new ApiError_1.ApiRetriesExhaustedError(attempt, error);
78
86
  }
79
- await RetryStrategy.sleep(delayMs);
87
+ await RetryStrategy.sleep(deadlines, delayMs);
80
88
  delayMs = Math.min(delayMs * this.delayMultiplier, this.maxDelayMs);
81
89
  }
82
90
  }
@@ -87,9 +95,12 @@ class RetryStrategy {
87
95
  throw new RangeError(`${name} must be a non-negative integer`);
88
96
  }
89
97
  }
98
+ /** The backoff wait, on the client's scheduler. Its timer has fired, so there is nothing to cancel. */
90
99
  // webpieces-disable no-function-outside-class -- backoff timer
91
- static sleep(ms) {
92
- return new Promise((resolve) => setTimeout(resolve, ms));
100
+ static sleep(deadlines, ms) {
101
+ return new Promise((resolve) => {
102
+ deadlines.schedule(ms, resolve);
103
+ });
93
104
  }
94
105
  }
95
106
  exports.RetryStrategy = RetryStrategy;
@@ -1 +1 @@
1
- {"version":3,"file":"RetryStrategy.js","sourceRoot":"","sources":["../../../../../../packages/core/core-util/src/http/RetryStrategy.ts"],"names":[],"mappings":";;;AACA,iDAA8C;AAC9C,+CAA4C;AAC5C,uDAAgD;AAChD,mDAAgD;AAChD,+DAA8C;AAC9C,iDAA8D;AAC9D,kDAA4C;AAE5C;;;;;;;;;;;;;;;;;GAiBG;AACH,MAAa,aAAa;IAMT;IACA;IACA;IACA;IACA;IATb,mGAAmG;IACnG,2FAA2F;IAClF,GAAG,CAAwB;IAEpC,YACa,gBAAwB,EACxB,UAAkB,EAClB,cAAsB,EACtB,eAAuB,EACvB,UAAkB;QAJlB,qBAAgB,GAAhB,gBAAgB,CAAQ;QACxB,eAAU,GAAV,UAAU,CAAQ;QAClB,mBAAc,GAAd,cAAc,CAAQ;QACtB,oBAAe,GAAf,eAAe,CAAQ;QACvB,eAAU,GAAV,UAAU,CAAQ;QAE3B,2BAAY,CAAC,QAAQ,CAAC,gBAAgB,CAAC,CAAC;QACxC,aAAa,CAAC,YAAY,CAAC,YAAY,EAAE,UAAU,CAAC,CAAC;QACrD,aAAa,CAAC,YAAY,CAAC,gBAAgB,EAAE,cAAc,CAAC,CAAC;QAC7D,aAAa,CAAC,YAAY,CAAC,YAAY,EAAE,UAAU,CAAC,CAAC;QACrD,IAAI,CAAC,MAAM,CAAC,QAAQ,CAAC,eAAe,CAAC,IAAI,eAAe,GAAG,CAAC,EAAE,CAAC;YAC3D,MAAM,IAAI,UAAU,CAAC,+CAA+C,CAAC,CAAC;QAC1E,CAAC;QACD,2FAA2F;QAC3F,IAAI,CAAC,GAAG,GAAG,CAAC,IAAsB,EAAE,GAAgB,EAAoB,EAAE,CAAC,IAAI,CAAC,OAAO,CAAC,IAAI,EAAE,GAAG,CAAC,CAAC;IACvG,CAAC;IAED,2FAA2F;IACnF,KAAK,CAAC,OAAO,CAAC,IAAsB,EAAE,GAAgB;QAC1D,MAAM,UAAU,GAAG,IAAI,6BA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EAAE,CAAC;YACxC,MAAM,IAAI,UAAU,CAAC,GAAG,IAAI,iCAAiC,CAAC,CAAC;QACnE,CAAC;IACL,CAAC;IAED,+DAA+D;IACvD,MAAM,CAAC,KAAK,CAAC,EAAU;QAC3B,OAAO,IAAI,OAAO,CAAO,CAAC,OAAmB,EAAE,EAAE,CAAC,UAAU,CAAC,OAAO,EAAE,EAAE,CAAC,CAAC,CAAC;IAC/E,CAAC;CACJ;AAtED,sCAsEC","sourcesContent":["import { Attempt, CallContext, CallStrategy } from './CallStrategy';\nimport { CallDeadline } from './CallDeadline';\nimport { ApiRegistry } from './ApiRegistry';\nimport { CallOutcome } from './ErrorClassifier';\nimport { ApiMethodInfo } from './ApiMethodInfo';\nimport { WRITE } from './HttpEndpointOptions';\nimport { ApiRetriesExhaustedError } from '../errors/ApiError';\nimport { toError } from '../lib/errorUtils';\n\n/**\n * THE webpieces retry strategy, shared by every transport — register its {@link RetryStrategy.run}\n * with `ClientRegistry.setStrategy(...)`, or hand it to a `TransportDefault`.\n *\n * Two questions, two owners, and it asks both:\n *\n * - **the ERROR** — `ApiRegistry.classify(error, …)`. Only `CallOutcome.TRANSIENT_FAILURE` is\n * retried; an EXPECTED or FAILURE outcome is a definitive answer and is rethrown unchanged.\n * - **the ENDPOINT** — `CallContext.operation`. A `WRITE` is NEVER retried, even when this strategy is\n * registered at ALL: a transient error on a non-idempotent write may already have happened.\n *\n * Each attempt gets its own `attemptTimeoutMs` deadline. Between attempts it waits\n * `initialDelayMs`, then multiplies by `delayMultiplier`, capped at `maxDelayMs`.\n *\n * When it RETRIED and ran out, it throws {@link ApiRetriesExhaustedError} (`cause` = the last\n * attempt's error), which is classified FAILURE so no layer above retries again. A call that made a\n * single attempt — `maxRetries` 0, a `WRITE`, a non-transient error — rethrows its own error unchanged.\n */\nexport class RetryStrategy {\n /** The {@link CallStrategy} to register. A bound field, so `strategy.run` can be passed around. */\n // webpieces-disable no-any-unknown -- registry strategies span heterogeneous response DTOs\n readonly run: CallStrategy<unknown>;\n\n constructor(\n readonly attemptTimeoutMs: number,\n readonly maxRetries: number,\n readonly initialDelayMs: number,\n readonly delayMultiplier: number,\n readonly maxDelayMs: number,\n ) {\n CallDeadline.validate(attemptTimeoutMs);\n RetryStrategy.requireWhole('maxRetries', maxRetries);\n RetryStrategy.requireWhole('initialDelayMs', initialDelayMs);\n RetryStrategy.requireWhole('maxDelayMs', maxDelayMs);\n if (!Number.isFinite(delayMultiplier) || delayMultiplier < 1) {\n throw new RangeError('delayMultiplier must be finite and at least 1');\n }\n // webpieces-disable no-any-unknown -- registry strategies span heterogeneous response DTOs\n this.run = (call: Attempt<unknown>, ctx: CallContext): Promise<unknown> => this.execute(call, ctx);\n }\n\n // webpieces-disable no-any-unknown -- registry strategies span heterogeneous response DTOs\n private async execute(call: Attempt<unknown>, ctx: CallContext): Promise<unknown> {\n const methodInfo = new ApiMethodInfo(\n 'client',\n ctx.apiName,\n ctx.methodName,\n ctx.contract,\n );\n let delayMs = this.initialDelayMs;\n for (let attempt = 1; ; attempt++) {\n // webpieces-disable no-unmanaged-exceptions -- a strategy decides per failure whether to retry\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n return await call(this.attemptTimeoutMs);\n } catch (err: unknown) {\n const error = toError(err);\n const retryable =\n ctx.operation !== WRITE &&\n ApiRegistry.classify(error, methodInfo) === CallOutcome.TRANSIENT_FAILURE;\n if (!retryable) {\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions -- a definitive answer is rethrown unchanged\n throw err;\n }\n if (attempt > this.maxRetries) {\n if (attempt === 1) {\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions -- never retried, so nothing was exhausted\n throw err;\n }\n throw new ApiRetriesExhaustedError(attempt, error);\n }\n await RetryStrategy.sleep(delayMs);\n delayMs = Math.min(delayMs * this.delayMultiplier, this.maxDelayMs);\n }\n }\n }\n\n // webpieces-disable no-function-outside-class -- constructor argument guard\n private static requireWhole(name: string, value: number): void {\n if (!Number.isInteger(value) || value < 0) {\n throw new RangeError(`${name} must be a non-negative integer`);\n }\n }\n\n // webpieces-disable no-function-outside-class -- backoff timer\n private static sleep(ms: number): Promise<void> {\n return new Promise<void>((resolve: () => void) => setTimeout(resolve, ms));\n }\n}\n"]}
1
+ {"version":3,"file":"RetryStrategy.js","sourceRoot":"","sources":["../../../../../../packages/core/core-util/src/http/RetryStrategy.ts"],"names":[],"mappings":";;;AACA,iDAA8C;AAE9C,+CAA4C;AAC5C,uDAAgD;AAChD,mDAAgD;AAChD,+DAA8C;AAC9C,iDAA8D;AAC9D,kDAA4C;AAE5C;;;;;;;;;;;;;;;;;;;;;GAqBG;AACH,MAAa,aAAa;IAMT;IACA;IACA;IACA;IACA;IATb,mGAAmG;IACnG,2FAA2F;IAClF,GAAG,CAAwB;IAEpC,YACa,gBAAwB,EACxB,UAAkB,EAClB,cAAsB,EACtB,eAAuB,EACvB,UAAkB;QAJlB,qBAAgB,GAAhB,gBAAgB,CAAQ;QACxB,eAAU,GAAV,UAAU,CAAQ;QAClB,mBAAc,GAAd,cAAc,CAAQ;QACtB,oBAAe,GAAf,eAAe,CAAQ;QACvB,eAAU,GAAV,UAAU,CAAQ;QAE3B,2BAAY,CAAC,QAAQ,CAAC,gBAAgB,CAAC,CAAC;QACxC,aAAa,CAAC,YAAY,CAAC,YAAY,EAAE,UAAU,CAAC,CAAC;QACrD,aAAa,CAAC,YAAY,CAAC,gBAAgB,EAAE,cAAc,CAAC,CAAC;QAC7D,aAAa,CAAC,YAAY,CAAC,YAAY,EAAE,UAAU,CAAC,CAAC;QACrD,IAAI,CAAC,MAAM,CAAC,QAAQ,CAAC,eAAe,CAAC,IAAI,eAAe,GAAG,CAAC,EAAE,CAAC;YAC3D,MAAM,IAAI,UAAU,CAAC,+CAA+C,CAAC,CAAC;QAC1E,CAAC;QACD,2FAA2F;QAC3F,IAAI,CAAC,GAAG,GAAG;QACP,2FAA2F;QAC3F,IAAsB,EACtB,GAAgB,EAChB,SAA4B,EAEZ,EAA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,IAAI,CAAC,eAAe,EAAE,IAAI,CAAC,UAAU,CAAC,CAAC;YACxE,CAAC;QACL,CAAC;IACL,CAAC;IAED,4EAA4E;IACpE,MAAM,CAAC,YAAY,CAAC,IAAY,EAAE,KAAa;QACnD,IAAI,CAAC,MAAM,CAAC,SAAS,CAAC,KAAK,CAAC,IAAI,KAAK,GAAG,CAAC,EAAE,CAAC;YACxC,MAAM,IAAI,UAAU,CAAC,GAAG,IAAI,iCAAiC,CAAC,CAAC;QACnE,CAAC;IACL,CAAC;IAED,uGAAuG;IACvG,+DAA+D;IACvD,MAAM,CAAC,KAAK,CAAC,SAA4B,EAAE,EAAU;QACzD,OAAO,IAAI,OAAO,CAAO,CAAC,OAAmB,EAAE,EAAE;YAC7C,SAAS,CAAC,QAAQ,CAAC,EAAE,EAAE,OAAO,CAAC,CAAC;QACpC,CAAC,CAAC,CAAC;IACP,CAAC;CACJ;AArFD,sCAqFC","sourcesContent":["import { Attempt, CallContext, CallStrategy } from './CallStrategy';\nimport { CallDeadline } from './CallDeadline';\nimport { DeadlineScheduler } from './DeadlineScheduler';\nimport { ApiRegistry } from './ApiRegistry';\nimport { CallOutcome } from './ErrorClassifier';\nimport { ApiMethodInfo } from './ApiMethodInfo';\nimport { WRITE } from './HttpEndpointOptions';\nimport { ApiRetriesExhaustedError } from '../errors/ApiError';\nimport { toError } from '../lib/errorUtils';\n\n/**\n * THE webpieces retry strategy, shared by every transport — register its {@link RetryStrategy.run}\n * with `ClientRegistry.setStrategy(...)`, or hand it to a `TransportDefault`.\n *\n * Two questions, two owners, and it asks both:\n *\n * - **the ERROR** — `ApiRegistry.classify(error, …)`. Only `CallOutcome.TRANSIENT_FAILURE` is\n * retried; an EXPECTED or FAILURE outcome is a definitive answer and is rethrown unchanged.\n * - **the ENDPOINT** — `CallContext.operation`. A `WRITE` is NEVER retried, even when this strategy is\n * registered at ALL: a transient error on a non-idempotent write may already have happened.\n *\n * Each attempt gets its own `attemptTimeoutMs` deadline. Between attempts it waits\n * `initialDelayMs`, then multiplies by `delayMultiplier`, capped at `maxDelayMs`. The wait is\n * scheduled on the calling client's {@link DeadlineScheduler} — never a bare `setTimeout` — so a\n * React Native client with a native-backed scheduler does not stall between attempts while its JS\n * timers are paused (#1445). The backoff never resets or extends an attempt's own deadline: each\n * attempt is a fresh `CallDeadline.run` with exactly `attemptTimeoutMs`.\n *\n * When it RETRIED and ran out, it throws {@link ApiRetriesExhaustedError} (`cause` = the last\n * attempt's error), which is classified FAILURE so no layer above retries again. A call that made a\n * single attempt — `maxRetries` 0, a `WRITE`, a non-transient error — rethrows its own error unchanged.\n */\nexport class RetryStrategy {\n /** The {@link CallStrategy} to register. A bound field, so `strategy.run` can be passed around. */\n // webpieces-disable no-any-unknown -- registry strategies span heterogeneous response DTOs\n readonly run: CallStrategy<unknown>;\n\n constructor(\n readonly attemptTimeoutMs: number,\n readonly maxRetries: number,\n readonly initialDelayMs: number,\n readonly delayMultiplier: number,\n readonly maxDelayMs: number,\n ) {\n CallDeadline.validate(attemptTimeoutMs);\n RetryStrategy.requireWhole('maxRetries', maxRetries);\n RetryStrategy.requireWhole('initialDelayMs', initialDelayMs);\n RetryStrategy.requireWhole('maxDelayMs', maxDelayMs);\n if (!Number.isFinite(delayMultiplier) || delayMultiplier < 1) {\n throw new RangeError('delayMultiplier must be finite and at least 1');\n }\n // webpieces-disable no-any-unknown -- registry strategies span heterogeneous response DTOs\n this.run = (\n // webpieces-disable no-any-unknown -- registry strategies span heterogeneous response DTOs\n call: Attempt<unknown>,\n ctx: CallContext,\n deadlines: DeadlineScheduler,\n // webpieces-disable no-any-unknown -- registry strategies span heterogeneous response DTOs\n ): Promise<unknown> => this.execute(call, ctx, deadlines);\n }\n\n // webpieces-disable no-any-unknown -- registry strategies span heterogeneous response DTOs\n private async execute(\n // webpieces-disable no-any-unknown -- registry strategies span heterogeneous response DTOs\n call: Attempt<unknown>,\n ctx: CallContext,\n deadlines: DeadlineScheduler,\n // webpieces-disable no-any-unknown -- registry strategies span heterogeneous response DTOs\n ): Promise<unknown> {\n const methodInfo = new ApiMethodInfo(\n 'client',\n ctx.apiName,\n ctx.methodName,\n ctx.contract,\n );\n let delayMs = this.initialDelayMs;\n for (let attempt = 1; ; attempt++) {\n // webpieces-disable no-unmanaged-exceptions -- a strategy decides per failure whether to retry\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions\n try {\n return await call(this.attemptTimeoutMs);\n } catch (err: unknown) {\n const error = toError(err);\n const retryable =\n ctx.operation !== WRITE &&\n ApiRegistry.classify(error, methodInfo) === CallOutcome.TRANSIENT_FAILURE;\n if (!retryable) {\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions -- a definitive answer is rethrown unchanged\n throw err;\n }\n if (attempt > this.maxRetries) {\n if (attempt === 1) {\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions -- never retried, so nothing was exhausted\n throw err;\n }\n throw new ApiRetriesExhaustedError(attempt, error);\n }\n await RetryStrategy.sleep(deadlines, delayMs);\n delayMs = Math.min(delayMs * this.delayMultiplier, this.maxDelayMs);\n }\n }\n }\n\n // webpieces-disable no-function-outside-class -- constructor argument guard\n private static requireWhole(name: string, value: number): void {\n if (!Number.isInteger(value) || value < 0) {\n throw new RangeError(`${name} must be a non-negative integer`);\n }\n }\n\n /** The backoff wait, on the client's scheduler. Its timer has fired, so there is nothing to cancel. */\n // webpieces-disable no-function-outside-class -- backoff timer\n private static sleep(deadlines: DeadlineScheduler, ms: number): Promise<void> {\n return new Promise<void>((resolve: () => void) => {\n deadlines.schedule(ms, resolve);\n });\n }\n}\n"]}
package/src/index.d.ts CHANGED
@@ -68,6 +68,8 @@ export { CallScope, CallScopeLadder } from './http/CallScope';
68
68
  export { TransportDefault } from './http/TransportDefault';
69
69
  export { RetryStrategy } from './http/RetryStrategy';
70
70
  export { CallDeadline } from './http/CallDeadline';
71
+ export { TimerDeadlineScheduler } from './http/DeadlineScheduler';
72
+ export type { DeadlineScheduler, DeadlineTimer } from './http/DeadlineScheduler';
71
73
  export { CallContext } from './http/CallStrategy';
72
74
  export type { Attempt, CallStrategy } from './http/CallStrategy';
73
75
  export { ApiCallTimeoutError } from './http/ApiCallTimeoutError';
package/src/index.js CHANGED
@@ -11,9 +11,9 @@ Object.defineProperty(exports, "__esModule", { value: true });
11
11
  exports.ApiType = exports.NUMERIC_METADATA_KEYS = exports.WpMax = exports.WpMin = exports.WpInt = exports.QueryParams = exports.getHttpParameterDeclarations = exports.QueryString = exports.QueryParam = exports.PathParam = exports.METADATA_KEYS = exports.validateNoConflictingDecorators = exports.assertEveryVendorAuthEndpointRetainsRawBody = exports.isExternalOutboundApi = exports.assertExternalEndpointKinds = exports.assertEveryEndpointHasAuthMode = exports.getAuthMeta = exports.isApiPath = exports.isRawBody = exports.isFormPost = exports.getMaskSpec = exports.getEndpointKinds = exports.getEndpointKind = exports.getEndpointOperation = exports.getEndpointOptions = exports.getEndpointHttpMethod = exports.getEndpoints = exports.getApiPath = exports.MaskLog = exports.isLocalOnly = exports.WpLocalOnly = exports.MISSING_AUTH_DECORATOR_FIX = exports.WpAuth = exports.WpAuthPublic = exports.Endpoint = exports.ApiPath = exports.GCP_LOG_BUDGET_BYTES = exports.MAX_GCP_LOG_BYTES = exports.LogChunkInfo = exports.LogChunkerImpl = exports.LogChunker = exports.LogManager = exports.ConsoleLoggerFactory = exports.ConsoleLogger = exports.DESIGN_METADATA_KEYS = exports.isDocumentDesign = exports.DocumentDesign = exports.ContextTuple = exports.ContextKey = exports.toError = void 0;
12
12
  exports.verbCarriesBody = exports.HTTP_METHODS = exports.DELETE = exports.PATCH = exports.PUT = exports.POST = exports.GET = exports.registerStreamingSchemas = exports.getStreamingEndpoint = exports.WpStream = exports.StreamDirection = exports.StreamWriter = exports.StreamTransportError = exports.StreamEventValidator = exports.StreamingEndpointMetadata = exports.StreamEnvelope = exports.StreamCorrelation = exports.HttpParameterDeclaration = exports.HttpParameterBinding = exports.HttpContractMapper = exports.BoundHttpRequest = exports.StreamDisconnectedError = exports.StreamProtocolError = exports.StreamErrorControl = exports.registerStreamingCatalog = exports.StreamingSchemaCatalog = exports.getAuthorization = exports.WpAuthorization = exports.AuthorizationDeclaration = exports.AuthorizationType = exports.RouteMetadataFactory = exports.RouteMetadata = exports.IPC_METADATA_KEYS = exports.assertNotInternalApi = exports.assertInternalApi = exports.getIpcMaskSpec = exports.getIpcEndpointKind = exports.getIpcEndpoints = exports.getIpcApiId = exports.isInternalApi = exports.WpIpcEndpoint = exports.WpInternal = exports.assertApiTypeMatchesMcpTools = exports.getApiTypeEndpointNames = exports.getApiTypes = exports.DEFAULT_API_TYPES = exports.API_TYPE_METADATA_KEY = exports.MCP = exports.EXTERNAL_CUSTOMER = exports.SVC_TO_SVC = void 0;
13
13
  exports.assertApiKind = exports.getApiKind = exports.ENDPOINT_KINDS_BY_API_KIND = exports.Queue = exports.PubSub = exports.Rpc = exports.apiKey = exports.vendorAuth = exports.sharedSecret = exports.oidcSvcs = exports.oidcSameProject = exports.jwt = exports.AuthDeclaration = exports.AuthMeta = exports.GenerateOutputTarget = exports.GenerateOutputLookup = exports.GenerateLayoutProblem = exports.GeneratedApiDocsLayout = exports.McpToolDefinition = exports.McpToolCatalogError = exports.McpToolCatalogFile = exports.ObjectSchemaBuilder = exports.DtoValidationFailure = exports.ApiJsonSchemaValidator = exports.ApiJsonSchemaDiscriminator = exports.ApiJsonSchema = exports.McpToolName = exports.UNKNOWN_OPERATION = exports.operationForMcpHints = exports.mcpHintsForOperation = exports.getWpMcpTools = exports.getInvalidEndpointsForMcp = exports.WpMcpToolMetadata = exports.WpMcpToolHints = exports.WpMcpTool = exports.InvalidEndpointForMcpMetadata = exports.InvalidEndpointForMcp = exports.declaresExternalContextKeys = exports.getExternalContextKeys = exports.ExternalContextKeys = exports.NONE = exports.WRITE = exports.WRITE_IDEMPOTENT = exports.READ = exports.EXTERNAL_OUTBOUND = exports.EXTERNAL_INBOUND = exports.CRON = exports.CLOUDTASKS = exports.RPC = exports.isHttpMethod = void 0;
14
- exports.LogApiCall = exports.LogApiCallImpl = exports.ContextMgr = exports.DestinationTrust = exports.WebpiecesCoreHeaders = exports.templateDeriver = exports.WEBPIECES_DEFAULT_ERROR_CLASSIFIER = exports.WebpiecesDefaultErrorClassifier = exports.CallOutcome = exports.ReceivedApiErrorRule = exports.SurfaceEndUserStatus = exports.WEBPIECES_DEFAULT_ERROR_TRANSLATOR = exports.WebpiecesDefaultErrorTranslator = exports.HttpResponseDto = exports.HttpResponseStatus = exports.HttpHeader = exports.RuntimeLocality = exports.ServiceInfo = exports.ApiCallTimeoutError = exports.CallContext = exports.CallDeadline = exports.RetryStrategy = exports.TransportDefault = exports.CallScopeLadder = exports.CallScope = exports.ApiRegistry = exports.ClientRegistry = exports.HeaderRegistry = exports.DateTimeUtil = exports.TimeUtil = exports.DateUtil = exports.InstantUtil = exports.NetworkRejectClassifier = exports.NO_REG_CODE = exports.WRONG_COMPANY = exports.WRONG_DOMAIN = exports.EMAIL_NOT_CONFIRMED = exports.NOT_APPROVED = exports.WRONG_LOGIN = exports.WRONG_LOGIN_TYPE = exports.ENTITY_NOT_FOUND = exports.SECRETS = exports.Secrets = exports.getEndpointCaller = exports.isExternalSystemKind = exports.ExternalCaller = exports.DEFAULT_CALLER_KIND = exports.EXTERNAL_SYSTEM_KINDS = exports.getQueueName = exports.assertPubSubConventions = void 0;
15
- exports.ClientRole = exports.EndUserErrorRegistry = exports.EndUserErrorCode = exports.ApiEndUserBadRequestError = exports.ApiEndUserForbiddenError = exports.ApiEndUserNotFoundError = exports.ApiClientTooOldError = exports.ApiCodedError = exports.ApiNotImplementedError = exports.ApiUnsupportedMediaTypeError = exports.ApiPreconditionFailedError = exports.ApiUnprocessableError = exports.ApiConflictError = exports.ApiEndpointNotFoundError = exports.ApiConnectionError = exports.ApiRetriesExhaustedError = exports.ApiDependencyBackoffError = exports.ApiUnauthorizedError = exports.ApiBadRequestError = exports.ApiEndUserError = exports.ApiRequestTimeoutError = exports.ApiForbiddenError = exports.ApiRateLimitedError = exports.ApiImplementationError = exports.ApiDependencyTimeoutError = exports.ApiUnavailableError = exports.ApiBadGatewayError = exports.ApiDependencyError = exports.ApiNotFoundError = exports.ApiError = exports.FilterChain = exports.Filter = exports.SerializedError = exports.SerializedMap = exports.RecordSerializer = exports.getDoNotRecordFields = exports.DoNotRecord = exports.RecordedTestCase = exports.RecordedError = exports.RecordedEndpoint = exports.RecorderKeys = exports.ApiMethodInfo = exports.LOG_API_CALL_LOGGER_NAME = exports.ApiCallLogNameImpl = exports.ApiCallLogName = exports.HttpCallFactsHolder = exports.HttpCallFacts = exports.ApiCallInfo = exports.MaskSpec = exports.LogApiCallConfig = void 0;
16
- exports.McpInvocationContext = exports.MCP_INVOCATION_CONTEXT = exports.McpToolProfilesOptions = exports.Mcp = exports.OAuthAuthorizationErrorRedirect = exports.OAuthErrorResponse = exports.OAuthErrorBody = exports.OAuthBearerChallenge = exports.OAuthErrorExtras = exports.OAuthProtocolError = exports.OAuthText = exports.OAuthErrorStatus = exports.OAuthErrorCode = exports.ApiErrorHttpStatus = exports.RpcCallFailed = exports.ReportableApiFailure = exports.CallModeMarker = exports.CallMode = exports.ApiCallSite = exports.ApiErrorBoundary = exports.ApiErrorPayload = exports.ApiErrorCodec = void 0;
14
+ exports.LogApiCallImpl = exports.ContextMgr = exports.DestinationTrust = exports.WebpiecesCoreHeaders = exports.templateDeriver = exports.WEBPIECES_DEFAULT_ERROR_CLASSIFIER = exports.WebpiecesDefaultErrorClassifier = exports.CallOutcome = exports.ReceivedApiErrorRule = exports.SurfaceEndUserStatus = exports.WEBPIECES_DEFAULT_ERROR_TRANSLATOR = exports.WebpiecesDefaultErrorTranslator = exports.HttpResponseDto = exports.HttpResponseStatus = exports.HttpHeader = exports.RuntimeLocality = exports.ServiceInfo = exports.ApiCallTimeoutError = exports.CallContext = exports.TimerDeadlineScheduler = exports.CallDeadline = exports.RetryStrategy = exports.TransportDefault = exports.CallScopeLadder = exports.CallScope = exports.ApiRegistry = exports.ClientRegistry = exports.HeaderRegistry = exports.DateTimeUtil = exports.TimeUtil = exports.DateUtil = exports.InstantUtil = exports.NetworkRejectClassifier = exports.NO_REG_CODE = exports.WRONG_COMPANY = exports.WRONG_DOMAIN = exports.EMAIL_NOT_CONFIRMED = exports.NOT_APPROVED = exports.WRONG_LOGIN = exports.WRONG_LOGIN_TYPE = exports.ENTITY_NOT_FOUND = exports.SECRETS = exports.Secrets = exports.getEndpointCaller = exports.isExternalSystemKind = exports.ExternalCaller = exports.DEFAULT_CALLER_KIND = exports.EXTERNAL_SYSTEM_KINDS = exports.getQueueName = exports.assertPubSubConventions = void 0;
15
+ exports.EndUserErrorRegistry = exports.EndUserErrorCode = exports.ApiEndUserBadRequestError = exports.ApiEndUserForbiddenError = exports.ApiEndUserNotFoundError = exports.ApiClientTooOldError = exports.ApiCodedError = exports.ApiNotImplementedError = exports.ApiUnsupportedMediaTypeError = exports.ApiPreconditionFailedError = exports.ApiUnprocessableError = exports.ApiConflictError = exports.ApiEndpointNotFoundError = exports.ApiConnectionError = exports.ApiRetriesExhaustedError = exports.ApiDependencyBackoffError = exports.ApiUnauthorizedError = exports.ApiBadRequestError = exports.ApiEndUserError = exports.ApiRequestTimeoutError = exports.ApiForbiddenError = exports.ApiRateLimitedError = exports.ApiImplementationError = exports.ApiDependencyTimeoutError = exports.ApiUnavailableError = exports.ApiBadGatewayError = exports.ApiDependencyError = exports.ApiNotFoundError = exports.ApiError = exports.FilterChain = exports.Filter = exports.SerializedError = exports.SerializedMap = exports.RecordSerializer = exports.getDoNotRecordFields = exports.DoNotRecord = exports.RecordedTestCase = exports.RecordedError = exports.RecordedEndpoint = exports.RecorderKeys = exports.ApiMethodInfo = exports.LOG_API_CALL_LOGGER_NAME = exports.ApiCallLogNameImpl = exports.ApiCallLogName = exports.HttpCallFactsHolder = exports.HttpCallFacts = exports.ApiCallInfo = exports.MaskSpec = exports.LogApiCallConfig = exports.LogApiCall = void 0;
16
+ exports.McpInvocationContext = exports.MCP_INVOCATION_CONTEXT = exports.McpToolProfilesOptions = exports.Mcp = exports.OAuthAuthorizationErrorRedirect = exports.OAuthErrorResponse = exports.OAuthErrorBody = exports.OAuthBearerChallenge = exports.OAuthErrorExtras = exports.OAuthProtocolError = exports.OAuthText = exports.OAuthErrorStatus = exports.OAuthErrorCode = exports.ApiErrorHttpStatus = exports.RpcCallFailed = exports.ReportableApiFailure = exports.CallModeMarker = exports.CallMode = exports.ApiCallSite = exports.ApiErrorBoundary = exports.ApiErrorPayload = exports.ApiErrorCodec = exports.ClientRole = void 0;
17
17
  var errorUtils_1 = require("./lib/errorUtils");
18
18
  Object.defineProperty(exports, "toError", { enumerable: true, get: function () { return errorUtils_1.toError; } });
19
19
  var ContextKey_1 = require("./ContextKey");
@@ -259,6 +259,9 @@ var RetryStrategy_1 = require("./http/RetryStrategy");
259
259
  Object.defineProperty(exports, "RetryStrategy", { enumerable: true, get: function () { return RetryStrategy_1.RetryStrategy; } });
260
260
  var CallDeadline_1 = require("./http/CallDeadline");
261
261
  Object.defineProperty(exports, "CallDeadline", { enumerable: true, get: function () { return CallDeadline_1.CallDeadline; } });
262
+ // #1445: the injectable clock behind every call deadline and retry backoff.
263
+ var DeadlineScheduler_1 = require("./http/DeadlineScheduler");
264
+ Object.defineProperty(exports, "TimerDeadlineScheduler", { enumerable: true, get: function () { return DeadlineScheduler_1.TimerDeadlineScheduler; } });
262
265
  var CallStrategy_1 = require("./http/CallStrategy");
263
266
  Object.defineProperty(exports, "CallContext", { enumerable: true, get: function () { return CallStrategy_1.CallContext; } });
264
267
  var ApiCallTimeoutError_1 = require("./http/ApiCallTimeoutError");
package/src/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../../../../../packages/core/core-util/src/index.ts"],"names":[],"mappings":";AAAA;;;;;;;GAOG;;;;;;;;AAEH,+CAA2C;AAAlC,qGAAA,OAAO,OAAA;AAChB,2CAA0C;AAAjC,wGAAA,UAAU,OAAA;AAOnB,+CAA8C;AAArC,4GA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AAkB,OAAA;AAE3B,iGAAiG;AACjG,gGAAgG;AAChG,yDAAqF;AAA5E,gHAAA,cAAc,OAAA;AAAE,kHAAA,gBAAgB,OAAA;AAAE,2GAAA,SAAS,OAAA;AAQpD,iEAAkF;AAAzE,wHAAA,kBAAkB,OAAA;AAAE,sHAAA,gBAAgB,OAAA;AAC7C,qEAAoE;AAA3D,4HAAA,oBAAoB,OAAA;AAC7B,iEAAgF;AAAvE,oHAAA,cAAc,OAAA;AAAE,wHAAA,kBAAkB,OAAA;AAC3C,2FAA0F;AAAjF,kJAAA,+BAA+B,OAAA;AAGxC,iCAAwD;AAA/C,0FAAA,GAAG,OAAA;AAAE,6GAAA,sBAAsB,OAAA;AAGpC,mEAA0F;AAAjF,8HAAA,sBAAsB,OAAA;AAAE,4HAAA,oBAAoB,OAAA","sourcesContent":["/**\n * @webpieces/core-util\n *\n * Utility functions for WebPieces applications.\n * This package works in both browser and Node.js environments.\n *\n * @packageDocumentation\n */\n\nexport { toError } from './lib/errorUtils';\nexport { ContextKey } from './ContextKey';\nexport type {\n AnyContextKey,\n AnyTrustedContextKey,\n AnyUntrustedContextKey,\n Trust,\n} from './ContextKey';\nexport { ContextTuple } from './ContextTuple';\n\n// @DocumentDesign — DI-design-root marker. Applies to ANY project kind (server\n// controllers AND library impl classes), so it lives here (browser + Node) rather\n// than in a server-only routing package.\nexport { DocumentDesign, isDocumentDesign, DESIGN_METADATA_KEYS } from './DocumentDesign';\n\n// Logging (merged from former @webpieces/wp-logging).\n// Pluggable logging interface + a browser-safe console default; apps plug in\n// bunyan/winston/pino/etc. via LogManager.setFactory(...). Browser + Node.\nexport type { Logger, LogLevel } from './logging/Logger';\nexport type { LoggerFactory } from './logging/LoggerFactory';\nexport { ConsoleLogger } from './logging/ConsoleLogger';\nexport { ConsoleLoggerFactory } from './logging/ConsoleLoggerFactory';\nexport { LogManager } from './logging/LogManager';\nexport {\n LogChunker,\n LogChunkerImpl,\n LogChunkInfo,\n MAX_GCP_LOG_BYTES,\n GCP_LOG_BUDGET_BYTES,\n} from './logging/LogChunker';\n\n// HTTP API contract (merged from former @webpieces/http-api).\n// Shared HTTP API definition consumed by both client and server: REST\n// decorators, the API error taxonomy, datetime DTOs, platform-header\n// registry/readers, ValidateImplementation, and the test-case recorder\n// contract. Pure definitions — express-free, browser + Node safe.\n\n// API definition decorators\nexport {\n ApiPath,\n Endpoint,\n // Auth mode decorators (clean service-to-service + user JWT model)\n WpAuthPublic,\n WpAuth,\n MISSING_AUTH_DECORATOR_FIX,\n WpLocalOnly,\n isLocalOnly,\n MaskLog,\n getApiPath,\n getEndpoints,\n getEndpointHttpMethod,\n getEndpointOptions,\n getEndpointOperation,\n getEndpointKind,\n getEndpointKinds,\n getMaskSpec,\n isFormPost,\n isRawBody,\n isApiPath,\n getAuthMeta,\n assertEveryEndpointHasAuthMode,\n assertExternalEndpointKinds,\n isExternalOutboundApi,\n assertEveryVendorAuthEndpointRetainsRawBody,\n validateNoConflictingDecorators,\n METADATA_KEYS,\n} from './http/decorators';\nexport {\n PathParam,\n QueryParam,\n QueryString,\n getHttpParameterDeclarations,\n} from './http/http-parameter-decorators';\nexport { QueryParams } from './http/QueryParams';\nexport type { QueryParamValue } from './http/QueryParams';\nexport { WpInt, WpMin, WpMax, NUMERIC_METADATA_KEYS } from './http/numeric-field-decorators';\nexport type { Integer } from './http/numeric-field-decorators';\nexport {\n ApiType,\n SVC_TO_SVC,\n EXTERNAL_CUSTOMER,\n MCP,\n API_TYPE_METADATA_KEY,\n DEFAULT_API_TYPES,\n getApiTypes,\n getApiTypeEndpointNames,\n assertApiTypeMatchesMcpTools,\n} from './http/api-type';\nexport type { ApiTypeKind } from './http/api-type';\nexport {\n WpInternal,\n WpIpcEndpoint,\n isInternalApi,\n getIpcApiId,\n getIpcEndpoints,\n getIpcEndpointKind,\n getIpcMaskSpec,\n assertInternalApi,\n assertNotInternalApi,\n IPC_METADATA_KEYS,\n} from './ipc/IpcDecorators';\nexport type { IpcApiType, IpcEndpointKind, IpcEndpointOptions } from './ipc/IpcDecorators';\n// The runtime representation of ONE route (split out of decorators.ts for file size only).\nexport { RouteMetadata } from './http/RouteMetadata';\nexport { RouteMetadataFactory } from './http/RouteMetadataFactory';\nexport {\n AuthorizationType,\n AuthorizationDeclaration,\n WpAuthorization,\n getAuthorization,\n} from './http/authorization';\nexport type { AuthorizationRequirement } from './http/authorization';\nexport { StreamingSchemaCatalog, registerStreamingCatalog } from './http/StreamingSchemaCatalog';\nexport {\n StreamErrorControl,\n StreamProtocolError,\n StreamDisconnectedError,\n} from './http/StreamErrorControl';\nexport {\n BoundHttpRequest,\n HttpContractMapper,\n HttpParameterBinding,\n HttpParameterDeclaration,\n} from './http/HttpContract';\nexport {\n StreamCorrelation,\n StreamEnvelope,\n StreamingEndpointMetadata,\n StreamEventValidator,\n StreamTransportError,\n StreamWriter,\n StreamDirection,\n WpStream,\n getStreamingEndpoint,\n registerStreamingSchemas,\n} from './http/StreamingContract';\nexport type { RequestStream, ResponseStream, StreamEnvelopeKind } from './http/StreamingContract';\nexport type {\n EndpointResponseType,\n HttpMethod,\n HttpParameterSource,\n HttpParameterValueType,\n HttpQueryItemType,\n} from './http/HttpContract';\nexport {\n GET,\n POST,\n PUT,\n PATCH,\n DELETE,\n HTTP_METHODS,\n verbCarriesBody,\n isHttpMethod,\n} from './http/HttpContract';\nexport type {\n EndpointKind,\n EndpointOperation,\n EndpointOptions,\n ExternalEndpointOptions,\n NoResponseBodyOptionEndpointOptions,\n OperationEffectOptions,\n} from './http/decorators';\nexport {\n RPC,\n CLOUDTASKS,\n CRON,\n EXTERNAL_INBOUND,\n EXTERNAL_OUTBOUND,\n READ,\n WRITE_IDEMPOTENT,\n WRITE,\n NONE,\n} from './http/decorators';\nexport {\n ExternalContextKeys,\n getExternalContextKeys,\n declaresExternalContextKeys,\n} from './http/ExternalContextKeys';\nexport type { ResponseBodyKind } from './http/decorators';\nexport {\n InvalidEndpointForMcp,\n InvalidEndpointForMcpMetadata,\n WpMcpTool,\n WpMcpToolHints,\n WpMcpToolMetadata,\n getInvalidEndpointsForMcp,\n getWpMcpTools,\n mcpHintsForOperation,\n operationForMcpHints,\n UNKNOWN_OPERATION,\n} from './mcp/McpMetadata';\nexport type { McpOperationHints, McpToolOperation, WpMcpMethodDecorator } from './mcp/McpMetadata';\nexport { McpToolName } from './mcp/McpToolName';\nexport {\n ApiJsonSchema,\n ApiJsonSchemaDiscriminator,\n ApiJsonSchemaValidator,\n DtoValidationFailure,\n ObjectSchemaBuilder,\n} from './mcp/DtoSchema';\nexport type { ApiJsonSchemaType, DtoValue } from './mcp/DtoSchema';\nexport {\n McpToolCatalogFile,\n McpToolCatalogError,\n McpToolDefinition,\n} from './mcp/McpToolCatalogFile';\nexport {\n GeneratedApiDocsLayout,\n GenerateLayoutProblem,\n GenerateOutputLookup,\n GenerateOutputTarget,\n} from './mcp/GeneratedApiDocsLayout';\nexport type {\n LayoutDependsOn,\n LayoutDependsOnObject,\n LayoutTarget,\n LayoutTargets,\n} from './mcp/GeneratedApiDocsLayout';\n// The TYPE layer of the auth surface — likewise split out of decorators.ts for file size only.\nexport {\n AuthMeta,\n AuthDeclaration,\n jwt,\n oidcSameProject,\n oidcSvcs,\n sharedSecret,\n vendorAuth,\n apiKey,\n} from './http/auth-mode';\nexport type {\n AuthMode,\n ApiKeyCredential,\n ApiKeyCredentials,\n AuthMethod,\n AuthMethods,\n OidcAuthMethod,\n OidcAuthMethods,\n OidcCallers,\n} from './http/auth-mode';\n// API kind (RPC vs PubSub/Cloud Tasks) + queue naming. Split out of decorators.ts for file size only;\n// one-way dependency api-kind -> decorators, and the barrel keeps the surface identical.\nexport {\n Rpc,\n PubSub,\n Queue,\n ENDPOINT_KINDS_BY_API_KIND,\n getApiKind,\n assertApiKind,\n assertPubSubConventions,\n getQueueName,\n} from './http/api-kind';\nexport type { ApiKind } from './http/api-kind';\n// WHO calls an EXTERNAL_INBOUND endpoint — the caller declaration\n// @Endpoint(POST, ..., WRITE, EXTERNAL_INBOUND, { calledBy })\n// requires, and the reader for it.\nexport {\n EXTERNAL_SYSTEM_KINDS,\n DEFAULT_CALLER_KIND,\n ExternalCaller,\n isExternalSystemKind,\n getEndpointCaller,\n} from './http/external-caller';\nexport type { ExternalSystemKind } from './http/external-caller';\n// Client-side shared-secret store (the value THIS service sends per sharedSecret(...) key).\nexport { Secrets, SECRETS } from './http/Secrets';\n\n// Type validators\nexport { ValidateImplementation } from './http/validators';\n\n// Authentication subtype constants.\nexport {\n ENTITY_NOT_FOUND,\n WRONG_LOGIN_TYPE,\n WRONG_LOGIN,\n NOT_APPROVED,\n EMAIL_NOT_CONFIRMED,\n WRONG_DOMAIN,\n WRONG_COMPANY,\n NO_REG_CODE,\n} from './errors';\n\nexport { NetworkRejectClassifier } from './http/networkReject';\n\n// Date/Time DTOs and Utilities (inspired by Java Time / JSR-310)\nexport {\n InstantDto,\n DateDto,\n TimeDto,\n DateTimeDto,\n InstantUtil,\n DateUtil,\n TimeUtil,\n DateTimeUtil,\n} from './http/datetime';\n\n// Context keys + registry (the global magic-context header system)\nexport { HeaderRegistry } from './http/HeaderRegistry';\nexport { ClientRegistry } from './http/ClientRegistry';\n// What BOTH sides of a call read (error translator + classifier), scoped by CallScope.\nexport { ApiRegistry } from './http/ApiRegistry';\nexport { CallScope, CallScopeLadder } from './http/CallScope';\nexport { TransportDefault } from './http/TransportDefault';\nexport { RetryStrategy } from './http/RetryStrategy';\nexport { CallDeadline } from './http/CallDeadline';\nexport { CallContext } from './http/CallStrategy';\nexport type { Attempt, CallStrategy } from './http/CallStrategy';\nexport { ApiCallTimeoutError } from './http/ApiCallTimeoutError';\nexport type { ServiceUrlDeriver } from './http/ClientRegistry';\n\n// \"What service am I\" — set once at startup, read by the logging backends and by\n// RequestContextHeaders (to stamp requestIdSource on ids this service mints).\nexport { ServiceInfo } from './http/ServiceInfo';\n// \"Where am I running\" — declared once at startup (setupRuntime, from RuntimeSetupOptions.locality).\n// The ONE input to @WpLocalOnly enforcement. Undeclared reads as DEPLOYED (fail safe).\nexport { RuntimeLocality } from './http/RuntimeLocality';\nexport type { Locality } from './http/RuntimeLocality';\n// The ENTIRE HTTP response as pure data — the ONE form both transports (express, fetch) are\n// normalised into, so an ErrorTranslator implementation is written once and serves both.\nexport { HttpHeader, HttpResponseStatus, HttpResponseDto } from './http/HttpResponseDto';\n// Pluggable, bidirectional error translation (app exception <-> the WHOLE response). Set on\n// ApiRegistry at startup; consulted before the built-in webpieces mapping on BOTH sides.\nexport type { ErrorTranslator } from './http/ErrorTranslator';\n// THE webpieces default translator — always installed, and what an app's own translator delegates to\n// in order to decline an error. ONE class, both halves, node and browser alike.\nexport {\n WebpiecesDefaultErrorTranslator,\n WEBPIECES_DEFAULT_ERROR_TRANSLATOR,\n} from './http/WebpiecesDefaultErrorTranslator';\n// WHICH KIND OF CALLER drove this request (gui / llm / public-api), and the per-request end-user\n// status derived from it — the replacement for the deleted per-router EndUserStatus.\nexport { SurfaceEndUserStatus } from './http/Surface';\nexport type { Surface } from './http/Surface';\n// The ONE rule for an error RECEIVED from another process, shared verbatim by HTTP and IPC.\nexport { ReceivedApiErrorRule } from './errors/ReceivedApiErrorRule';\n// Pluggable per-client error classification: one CallOutcome (EXPECTED / TRANSIENT_FAILURE /\n// FAILURE) per thrown API-call error. Registered on ApiRegistry at startup; read by RetryStrategy,\n// ClientRegistry's per-attempt log line, LogApiCall and the MCP renderer's retry advice.\nexport type { ErrorClassifier } from './http/ErrorClassifier';\nexport { CallOutcome } from './http/ErrorClassifier';\nexport {\n WebpiecesDefaultErrorClassifier,\n WEBPIECES_DEFAULT_ERROR_CLASSIFIER,\n} from './http/WebpiecesDefaultErrorClassifier';\nexport { templateDeriver } from './http/templateDeriver';\nexport { WebpiecesCoreHeaders } from './http/WebpiecesCoreHeaders';\nexport { ContextReader } from './http/ContextReader';\nexport { ContextWriter, ContextStore } from './http/ContextWriter';\n\n// The OUTBOUND half of the trust model: whether a TRUSTED context key may ride to the endpoint being\n// called. Built ONLY from the destination endpoint's AuthMode — see the class doc.\nexport { DestinationTrust } from './http/DestinationTrust';\n\n// BROWSER-ONLY outbound-header propagation (app-held store + registry -> outbound HTTP headers).\n// Only @webpieces/http-client-browser may name it; the server reads RequestContext directly via\n// RequestContextHeaders in the Node-only @webpieces/core-context.\nexport { ContextMgr } from './http/ContextMgr';\n\n// API-call logging helper (uses LogManager above). NOT a singleton: construct one per environment\n// with that environment's ApiCallContext — `new LogApiCallImpl(new RequestContextApiCallContext())`\n// on node, `new LogApiCallImpl(new BrowserApiCallContext())` in a browser.\nexport { LogApiCallImpl } from './http/LogApiCall';\n// The logged-body cap (#1300): a per-runtime default (browser 2,000 / node 50,000 chars), overridable\n// once at startup with `LogApiCall.configure(new LogApiCallConfig(n))`.\nexport { LogApiCall, LogApiCallConfig } from './http/LogApiCall';\n\n// Opt-in field masking for the LogApiCall log path — declare per-api sensitive fields so secrets\n// (OAuth refresh tokens, id-token JWTs) are masked in the logs while the real value stays on the wire.\nexport { MaskSpec } from './http/LogFieldMask';\nexport type { MaskMode } from './http/LogFieldMask';\n\n// The structured `api` tag + the context-writer seam LogApiCall stamps through. The Node\n// RequestContext-backed impl lives in @webpieces/core-context, the browser one in\n// @webpieces/http-client-browser; each is CONSTRUCTED by its package, never installed globally.\nexport { ApiCallInfo, HttpCallFacts, HttpCallFactsHolder } from './http/ApiCallInfo';\nexport type { ApiCallDirection, ApiResult } from './http/ApiCallInfo';\n// Console-render bridge: turns LogApiCall's [LogApiCall] bracket into [API.{side}.{phase}] locally.\nexport {\n ApiCallLogName,\n ApiCallLogNameImpl,\n LOG_API_CALL_LOGGER_NAME,\n} from './http/ApiCallLogName';\nexport { ApiMethodInfo } from './http/ApiMethodInfo';\nexport type { ApiSide } from './http/ApiMethodInfo';\nexport type { ApiCallContext } from './http/ApiCallContext';\n\n// Test-case recording contract (impl lives in http-server; hooks in http-client)\nexport { TestCaseRecorder, RecorderKeys } from './http/recorder/TestCaseRecorder';\nexport {\n RecordedEndpoint,\n RecordedError,\n RecordedTestCase,\n} from './http/recorder/RecordedEndpoint';\nexport { DoNotRecord, getDoNotRecordFields } from './http/recorder/DoNotRecord';\nexport { RecordSerializer, SerializedMap, SerializedError } from './http/recorder/RecordSerializer';\n\n// ---------------------------------------------------------------------------------------------\n// Filter-chain primitives, shared by BOTH chains: the inbound server chain\n// (`Filter<MethodMeta, WpResponse<unknown>>`, @webpieces/http-routing) and the outbound client\n// chain (`Filter<ClientRequest, Response>`, @webpieces/http-client-core). Declared once, here, in\n// the package both depend on — see the class doc for why a second pair would be a shim.\nexport { Filter } from './filters/Filter';\nexport type { Service } from './filters/Filter';\nexport { FilterChain } from './filters/FilterChain';\n\nexport {\n ApiError,\n ApiNotFoundError,\n ApiDependencyError,\n ApiBadGatewayError,\n ApiUnavailableError,\n ApiDependencyTimeoutError,\n ApiImplementationError,\n ApiRateLimitedError,\n ApiForbiddenError,\n ApiRequestTimeoutError,\n ApiEndUserError,\n ApiBadRequestError,\n ApiUnauthorizedError,\n ApiDependencyBackoffError,\n ApiRetriesExhaustedError,\n ApiConnectionError,\n ApiEndpointNotFoundError,\n ApiConflictError,\n ApiUnprocessableError,\n ApiPreconditionFailedError,\n ApiUnsupportedMediaTypeError,\n ApiNotImplementedError,\n ApiCodedError,\n ApiClientTooOldError,\n ApiEndUserNotFoundError,\n ApiEndUserForbiddenError,\n ApiEndUserBadRequestError,\n EndUserErrorCode,\n EndUserErrorRegistry,\n ClientRole,\n ApiErrorCodec,\n ApiErrorPayload,\n ApiErrorBoundary,\n ApiCallSite,\n CallMode,\n CallModeMarker,\n ReportableApiFailure,\n RpcCallFailed,\n} from './errors';\nexport type {\n ApiErrorKind,\n ApiStatusCode,\n EdgeHttpStatus,\n EndUserErrorFactory,\n CallSiteBoundary,\n} from './errors';\nexport { ApiErrorHttpStatus } from './http/ApiErrorHttpStatus';\n\n// RFC 6749 / 6750 / 7591 OAuth refusals for app-hosted OAuth endpoints (#1176): the typed error,\n// its one renderer, the Bearer challenge builder and the authorization-endpoint error redirect.\nexport { OAuthErrorCode, OAuthErrorStatus, OAuthText } from './oauth/OAuthErrorCode';\nexport type {\n OAuthHttpStatus,\n InvalidClientStatus,\n OAuthFixedStatusErrorCode,\n BearerErrorCode,\n AuthorizationEndpointErrorCode,\n} from './oauth/OAuthErrorCode';\nexport { OAuthProtocolError, OAuthErrorExtras } from './oauth/OAuthProtocolError';\nexport { OAuthBearerChallenge } from './oauth/OAuthBearerChallenge';\nexport { OAuthErrorBody, OAuthErrorResponse } from './oauth/OAuthErrorResponse';\nexport { OAuthAuthorizationErrorRedirect } from './oauth/OAuthAuthorizationErrorRedirect';\nexport type { PublishedKind, PublishedApiError } from './http/ApiErrorHttpStatus';\n\nexport { Mcp, McpToolProfilesOptions } from './mcp/Mcp';\nexport type { McpToolProfiles } from './mcp/Mcp';\n\nexport { MCP_INVOCATION_CONTEXT, McpInvocationContext } from './mcp/McpInvocationContext';\nexport type { McpProgressReporter } from './mcp/McpInvocationContext';\n"]}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../../../../packages/core/core-util/src/index.ts"],"names":[],"mappings":";AAAA;;;;;;;GAOG;;;;;;;;AAEH,+CAA2C;AAAlC,qGAAA,OAAO,OAAA;AAChB,2CAA0C;AAAjC,wGAAA,UAAU,OAAA;AAOnB,+CAA8C;AAArC,4GAAA,YAAY,OAAA;AAErB,+EAA+E;AAC/E,kFAAkF;AAClF,yCAAyC;AACzC,mDAA0F;AAAjF,gHAAA,cAAc,OAAA;AAAE,kHAAA,gBAAgB,OAAA;AAAE,sHAAA,oBAAoB,OAAA;AAO/D,yDAAwD;AAA/C,8GAAA,aAAa,OAAA;AACtB,uEAAsE;AAA7D,4HAAA,oBAAoB,OAAA;AAC7B,mDAAkD;AAAzC,wGAAA,UAAU,OAAA;AACnB,mDAM8B;AAL1B,wGAAA,UAAU,OAAA;AACV,4GAAA,cAAc,OAAA;AACd,0GAAA,YAAY,OAAA;AACZ,+GAAA,iBAAiB,OAAA;AACjB,kHAAA,oBAA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B,OAAA;AAGxC,iCAAwD;AAA/C,0FAAA,GAAG,OAAA;AAAE,6GAAA,sBAAsB,OAAA;AAGpC,mEAA0F;AAAjF,8HAAA,sBAAsB,OAAA;AAAE,4HAAA,oBAAoB,OAAA","sourcesContent":["/**\n * @webpieces/core-util\n *\n * Utility functions for WebPieces applications.\n * This package works in both browser and Node.js environments.\n *\n * @packageDocumentation\n */\n\nexport { toError } from './lib/errorUtils';\nexport { ContextKey } from './ContextKey';\nexport type {\n AnyContextKey,\n AnyTrustedContextKey,\n AnyUntrustedContextKey,\n Trust,\n} from './ContextKey';\nexport { ContextTuple } from './ContextTuple';\n\n// @DocumentDesign — DI-design-root marker. Applies to ANY project kind (server\n// controllers AND library impl classes), so it lives here (browser + Node) rather\n// than in a server-only routing package.\nexport { DocumentDesign, isDocumentDesign, DESIGN_METADATA_KEYS } from './DocumentDesign';\n\n// Logging (merged from former @webpieces/wp-logging).\n// Pluggable logging interface + a browser-safe console default; apps plug in\n// bunyan/winston/pino/etc. via LogManager.setFactory(...). Browser + Node.\nexport type { Logger, LogLevel } from './logging/Logger';\nexport type { LoggerFactory } from './logging/LoggerFactory';\nexport { ConsoleLogger } from './logging/ConsoleLogger';\nexport { ConsoleLoggerFactory } from './logging/ConsoleLoggerFactory';\nexport { LogManager } from './logging/LogManager';\nexport {\n LogChunker,\n LogChunkerImpl,\n LogChunkInfo,\n MAX_GCP_LOG_BYTES,\n GCP_LOG_BUDGET_BYTES,\n} from './logging/LogChunker';\n\n// HTTP API contract (merged from former @webpieces/http-api).\n// Shared HTTP API definition consumed by both client and server: REST\n// decorators, the API error taxonomy, datetime DTOs, platform-header\n// registry/readers, ValidateImplementation, and the test-case recorder\n// contract. Pure definitions — express-free, browser + Node safe.\n\n// API definition decorators\nexport {\n ApiPath,\n Endpoint,\n // Auth mode decorators (clean service-to-service + user JWT model)\n WpAuthPublic,\n WpAuth,\n MISSING_AUTH_DECORATOR_FIX,\n WpLocalOnly,\n isLocalOnly,\n MaskLog,\n getApiPath,\n getEndpoints,\n getEndpointHttpMethod,\n getEndpointOptions,\n getEndpointOperation,\n getEndpointKind,\n getEndpointKinds,\n getMaskSpec,\n isFormPost,\n isRawBody,\n isApiPath,\n getAuthMeta,\n assertEveryEndpointHasAuthMode,\n assertExternalEndpointKinds,\n isExternalOutboundApi,\n assertEveryVendorAuthEndpointRetainsRawBody,\n validateNoConflictingDecorators,\n METADATA_KEYS,\n} from './http/decorators';\nexport {\n PathParam,\n QueryParam,\n QueryString,\n getHttpParameterDeclarations,\n} from './http/http-parameter-decorators';\nexport { QueryParams } from './http/QueryParams';\nexport type { QueryParamValue } from './http/QueryParams';\nexport { WpInt, WpMin, WpMax, NUMERIC_METADATA_KEYS } from './http/numeric-field-decorators';\nexport type { Integer } from './http/numeric-field-decorators';\nexport {\n ApiType,\n SVC_TO_SVC,\n EXTERNAL_CUSTOMER,\n MCP,\n API_TYPE_METADATA_KEY,\n DEFAULT_API_TYPES,\n getApiTypes,\n getApiTypeEndpointNames,\n assertApiTypeMatchesMcpTools,\n} from './http/api-type';\nexport type { ApiTypeKind } from './http/api-type';\nexport {\n WpInternal,\n WpIpcEndpoint,\n isInternalApi,\n getIpcApiId,\n getIpcEndpoints,\n getIpcEndpointKind,\n getIpcMaskSpec,\n assertInternalApi,\n assertNotInternalApi,\n IPC_METADATA_KEYS,\n} from './ipc/IpcDecorators';\nexport type { IpcApiType, IpcEndpointKind, IpcEndpointOptions } from './ipc/IpcDecorators';\n// The runtime representation of ONE route (split out of decorators.ts for file size only).\nexport { RouteMetadata } from './http/RouteMetadata';\nexport { RouteMetadataFactory } from './http/RouteMetadataFactory';\nexport {\n AuthorizationType,\n AuthorizationDeclaration,\n WpAuthorization,\n getAuthorization,\n} from './http/authorization';\nexport type { AuthorizationRequirement } from './http/authorization';\nexport { StreamingSchemaCatalog, registerStreamingCatalog } from './http/StreamingSchemaCatalog';\nexport {\n StreamErrorControl,\n StreamProtocolError,\n StreamDisconnectedError,\n} from './http/StreamErrorControl';\nexport {\n BoundHttpRequest,\n HttpContractMapper,\n HttpParameterBinding,\n HttpParameterDeclaration,\n} from './http/HttpContract';\nexport {\n StreamCorrelation,\n StreamEnvelope,\n StreamingEndpointMetadata,\n StreamEventValidator,\n StreamTransportError,\n StreamWriter,\n StreamDirection,\n WpStream,\n getStreamingEndpoint,\n registerStreamingSchemas,\n} from './http/StreamingContract';\nexport type { RequestStream, ResponseStream, StreamEnvelopeKind } from './http/StreamingContract';\nexport type {\n EndpointResponseType,\n HttpMethod,\n HttpParameterSource,\n HttpParameterValueType,\n HttpQueryItemType,\n} from './http/HttpContract';\nexport {\n GET,\n POST,\n PUT,\n PATCH,\n DELETE,\n HTTP_METHODS,\n verbCarriesBody,\n isHttpMethod,\n} from './http/HttpContract';\nexport type {\n EndpointKind,\n EndpointOperation,\n EndpointOptions,\n ExternalEndpointOptions,\n NoResponseBodyOptionEndpointOptions,\n OperationEffectOptions,\n} from './http/decorators';\nexport {\n RPC,\n CLOUDTASKS,\n CRON,\n EXTERNAL_INBOUND,\n EXTERNAL_OUTBOUND,\n READ,\n WRITE_IDEMPOTENT,\n WRITE,\n NONE,\n} from './http/decorators';\nexport {\n ExternalContextKeys,\n getExternalContextKeys,\n declaresExternalContextKeys,\n} from './http/ExternalContextKeys';\nexport type { ResponseBodyKind } from './http/decorators';\nexport {\n InvalidEndpointForMcp,\n InvalidEndpointForMcpMetadata,\n WpMcpTool,\n WpMcpToolHints,\n WpMcpToolMetadata,\n getInvalidEndpointsForMcp,\n getWpMcpTools,\n mcpHintsForOperation,\n operationForMcpHints,\n UNKNOWN_OPERATION,\n} from './mcp/McpMetadata';\nexport type { McpOperationHints, McpToolOperation, WpMcpMethodDecorator } from './mcp/McpMetadata';\nexport { McpToolName } from './mcp/McpToolName';\nexport {\n ApiJsonSchema,\n ApiJsonSchemaDiscriminator,\n ApiJsonSchemaValidator,\n DtoValidationFailure,\n ObjectSchemaBuilder,\n} from './mcp/DtoSchema';\nexport type { ApiJsonSchemaType, DtoValue } from './mcp/DtoSchema';\nexport {\n McpToolCatalogFile,\n McpToolCatalogError,\n McpToolDefinition,\n} from './mcp/McpToolCatalogFile';\nexport {\n GeneratedApiDocsLayout,\n GenerateLayoutProblem,\n GenerateOutputLookup,\n GenerateOutputTarget,\n} from './mcp/GeneratedApiDocsLayout';\nexport type {\n LayoutDependsOn,\n LayoutDependsOnObject,\n LayoutTarget,\n LayoutTargets,\n} from './mcp/GeneratedApiDocsLayout';\n// The TYPE layer of the auth surface — likewise split out of decorators.ts for file size only.\nexport {\n AuthMeta,\n AuthDeclaration,\n jwt,\n oidcSameProject,\n oidcSvcs,\n sharedSecret,\n vendorAuth,\n apiKey,\n} from './http/auth-mode';\nexport type {\n AuthMode,\n ApiKeyCredential,\n ApiKeyCredentials,\n AuthMethod,\n AuthMethods,\n OidcAuthMethod,\n OidcAuthMethods,\n OidcCallers,\n} from './http/auth-mode';\n// API kind (RPC vs PubSub/Cloud Tasks) + queue naming. Split out of decorators.ts for file size only;\n// one-way dependency api-kind -> decorators, and the barrel keeps the surface identical.\nexport {\n Rpc,\n PubSub,\n Queue,\n ENDPOINT_KINDS_BY_API_KIND,\n getApiKind,\n assertApiKind,\n assertPubSubConventions,\n getQueueName,\n} from './http/api-kind';\nexport type { ApiKind } from './http/api-kind';\n// WHO calls an EXTERNAL_INBOUND endpoint — the caller declaration\n// @Endpoint(POST, ..., WRITE, EXTERNAL_INBOUND, { calledBy })\n// requires, and the reader for it.\nexport {\n EXTERNAL_SYSTEM_KINDS,\n DEFAULT_CALLER_KIND,\n ExternalCaller,\n isExternalSystemKind,\n getEndpointCaller,\n} from './http/external-caller';\nexport type { ExternalSystemKind } from './http/external-caller';\n// Client-side shared-secret store (the value THIS service sends per sharedSecret(...) key).\nexport { Secrets, SECRETS } from './http/Secrets';\n\n// Type validators\nexport { ValidateImplementation } from './http/validators';\n\n// Authentication subtype constants.\nexport {\n ENTITY_NOT_FOUND,\n WRONG_LOGIN_TYPE,\n WRONG_LOGIN,\n NOT_APPROVED,\n EMAIL_NOT_CONFIRMED,\n WRONG_DOMAIN,\n WRONG_COMPANY,\n NO_REG_CODE,\n} from './errors';\n\nexport { NetworkRejectClassifier } from './http/networkReject';\n\n// Date/Time DTOs and Utilities (inspired by Java Time / JSR-310)\nexport {\n InstantDto,\n DateDto,\n TimeDto,\n DateTimeDto,\n InstantUtil,\n DateUtil,\n TimeUtil,\n DateTimeUtil,\n} from './http/datetime';\n\n// Context keys + registry (the global magic-context header system)\nexport { HeaderRegistry } from './http/HeaderRegistry';\nexport { ClientRegistry } from './http/ClientRegistry';\n// What BOTH sides of a call read (error translator + classifier), scoped by CallScope.\nexport { ApiRegistry } from './http/ApiRegistry';\nexport { CallScope, CallScopeLadder } from './http/CallScope';\nexport { TransportDefault } from './http/TransportDefault';\nexport { RetryStrategy } from './http/RetryStrategy';\nexport { CallDeadline } from './http/CallDeadline';\n// #1445: the injectable clock behind every call deadline and retry backoff.\nexport { TimerDeadlineScheduler } from './http/DeadlineScheduler';\nexport type { DeadlineScheduler, DeadlineTimer } from './http/DeadlineScheduler';\nexport { CallContext } from './http/CallStrategy';\nexport type { Attempt, CallStrategy } from './http/CallStrategy';\nexport { ApiCallTimeoutError } from './http/ApiCallTimeoutError';\nexport type { ServiceUrlDeriver } from './http/ClientRegistry';\n\n// \"What service am I\" — set once at startup, read by the logging backends and by\n// RequestContextHeaders (to stamp requestIdSource on ids this service mints).\nexport { ServiceInfo } from './http/ServiceInfo';\n// \"Where am I running\" — declared once at startup (setupRuntime, from RuntimeSetupOptions.locality).\n// The ONE input to @WpLocalOnly enforcement. Undeclared reads as DEPLOYED (fail safe).\nexport { RuntimeLocality } from './http/RuntimeLocality';\nexport type { Locality } from './http/RuntimeLocality';\n// The ENTIRE HTTP response as pure data — the ONE form both transports (express, fetch) are\n// normalised into, so an ErrorTranslator implementation is written once and serves both.\nexport { HttpHeader, HttpResponseStatus, HttpResponseDto } from './http/HttpResponseDto';\n// Pluggable, bidirectional error translation (app exception <-> the WHOLE response). Set on\n// ApiRegistry at startup; consulted before the built-in webpieces mapping on BOTH sides.\nexport type { ErrorTranslator } from './http/ErrorTranslator';\n// THE webpieces default translator — always installed, and what an app's own translator delegates to\n// in order to decline an error. ONE class, both halves, node and browser alike.\nexport {\n WebpiecesDefaultErrorTranslator,\n WEBPIECES_DEFAULT_ERROR_TRANSLATOR,\n} from './http/WebpiecesDefaultErrorTranslator';\n// WHICH KIND OF CALLER drove this request (gui / llm / public-api), and the per-request end-user\n// status derived from it — the replacement for the deleted per-router EndUserStatus.\nexport { SurfaceEndUserStatus } from './http/Surface';\nexport type { Surface } from './http/Surface';\n// The ONE rule for an error RECEIVED from another process, shared verbatim by HTTP and IPC.\nexport { ReceivedApiErrorRule } from './errors/ReceivedApiErrorRule';\n// Pluggable per-client error classification: one CallOutcome (EXPECTED / TRANSIENT_FAILURE /\n// FAILURE) per thrown API-call error. Registered on ApiRegistry at startup; read by RetryStrategy,\n// ClientRegistry's per-attempt log line, LogApiCall and the MCP renderer's retry advice.\nexport type { ErrorClassifier } from './http/ErrorClassifier';\nexport { CallOutcome } from './http/ErrorClassifier';\nexport {\n WebpiecesDefaultErrorClassifier,\n WEBPIECES_DEFAULT_ERROR_CLASSIFIER,\n} from './http/WebpiecesDefaultErrorClassifier';\nexport { templateDeriver } from './http/templateDeriver';\nexport { WebpiecesCoreHeaders } from './http/WebpiecesCoreHeaders';\nexport { ContextReader } from './http/ContextReader';\nexport { ContextWriter, ContextStore } from './http/ContextWriter';\n\n// The OUTBOUND half of the trust model: whether a TRUSTED context key may ride to the endpoint being\n// called. Built ONLY from the destination endpoint's AuthMode — see the class doc.\nexport { DestinationTrust } from './http/DestinationTrust';\n\n// BROWSER-ONLY outbound-header propagation (app-held store + registry -> outbound HTTP headers).\n// Only @webpieces/http-client-browser may name it; the server reads RequestContext directly via\n// RequestContextHeaders in the Node-only @webpieces/core-context.\nexport { ContextMgr } from './http/ContextMgr';\n\n// API-call logging helper (uses LogManager above). NOT a singleton: construct one per environment\n// with that environment's ApiCallContext — `new LogApiCallImpl(new RequestContextApiCallContext())`\n// on node, `new LogApiCallImpl(new BrowserApiCallContext())` in a browser.\nexport { LogApiCallImpl } from './http/LogApiCall';\n// The logged-body cap (#1300): a per-runtime default (browser 2,000 / node 50,000 chars), overridable\n// once at startup with `LogApiCall.configure(new LogApiCallConfig(n))`.\nexport { LogApiCall, LogApiCallConfig } from './http/LogApiCall';\n\n// Opt-in field masking for the LogApiCall log path — declare per-api sensitive fields so secrets\n// (OAuth refresh tokens, id-token JWTs) are masked in the logs while the real value stays on the wire.\nexport { MaskSpec } from './http/LogFieldMask';\nexport type { MaskMode } from './http/LogFieldMask';\n\n// The structured `api` tag + the context-writer seam LogApiCall stamps through. The Node\n// RequestContext-backed impl lives in @webpieces/core-context, the browser one in\n// @webpieces/http-client-browser; each is CONSTRUCTED by its package, never installed globally.\nexport { ApiCallInfo, HttpCallFacts, HttpCallFactsHolder } from './http/ApiCallInfo';\nexport type { ApiCallDirection, ApiResult } from './http/ApiCallInfo';\n// Console-render bridge: turns LogApiCall's [LogApiCall] bracket into [API.{side}.{phase}] locally.\nexport {\n ApiCallLogName,\n ApiCallLogNameImpl,\n LOG_API_CALL_LOGGER_NAME,\n} from './http/ApiCallLogName';\nexport { ApiMethodInfo } from './http/ApiMethodInfo';\nexport type { ApiSide } from './http/ApiMethodInfo';\nexport type { ApiCallContext } from './http/ApiCallContext';\n\n// Test-case recording contract (impl lives in http-server; hooks in http-client)\nexport { TestCaseRecorder, RecorderKeys } from './http/recorder/TestCaseRecorder';\nexport {\n RecordedEndpoint,\n RecordedError,\n RecordedTestCase,\n} from './http/recorder/RecordedEndpoint';\nexport { DoNotRecord, getDoNotRecordFields } from './http/recorder/DoNotRecord';\nexport { RecordSerializer, SerializedMap, SerializedError } from './http/recorder/RecordSerializer';\n\n// ---------------------------------------------------------------------------------------------\n// Filter-chain primitives, shared by BOTH chains: the inbound server chain\n// (`Filter<MethodMeta, WpResponse<unknown>>`, @webpieces/http-routing) and the outbound client\n// chain (`Filter<ClientRequest, Response>`, @webpieces/http-client-core). Declared once, here, in\n// the package both depend on — see the class doc for why a second pair would be a shim.\nexport { Filter } from './filters/Filter';\nexport type { Service } from './filters/Filter';\nexport { FilterChain } from './filters/FilterChain';\n\nexport {\n ApiError,\n ApiNotFoundError,\n ApiDependencyError,\n ApiBadGatewayError,\n ApiUnavailableError,\n ApiDependencyTimeoutError,\n ApiImplementationError,\n ApiRateLimitedError,\n ApiForbiddenError,\n ApiRequestTimeoutError,\n ApiEndUserError,\n ApiBadRequestError,\n ApiUnauthorizedError,\n ApiDependencyBackoffError,\n ApiRetriesExhaustedError,\n ApiConnectionError,\n ApiEndpointNotFoundError,\n ApiConflictError,\n ApiUnprocessableError,\n ApiPreconditionFailedError,\n ApiUnsupportedMediaTypeError,\n ApiNotImplementedError,\n ApiCodedError,\n ApiClientTooOldError,\n ApiEndUserNotFoundError,\n ApiEndUserForbiddenError,\n ApiEndUserBadRequestError,\n EndUserErrorCode,\n EndUserErrorRegistry,\n ClientRole,\n ApiErrorCodec,\n ApiErrorPayload,\n ApiErrorBoundary,\n ApiCallSite,\n CallMode,\n CallModeMarker,\n ReportableApiFailure,\n RpcCallFailed,\n} from './errors';\nexport type {\n ApiErrorKind,\n ApiStatusCode,\n EdgeHttpStatus,\n EndUserErrorFactory,\n CallSiteBoundary,\n} from './errors';\nexport { ApiErrorHttpStatus } from './http/ApiErrorHttpStatus';\n\n// RFC 6749 / 6750 / 7591 OAuth refusals for app-hosted OAuth endpoints (#1176): the typed error,\n// its one renderer, the Bearer challenge builder and the authorization-endpoint error redirect.\nexport { OAuthErrorCode, OAuthErrorStatus, OAuthText } from './oauth/OAuthErrorCode';\nexport type {\n OAuthHttpStatus,\n InvalidClientStatus,\n OAuthFixedStatusErrorCode,\n BearerErrorCode,\n AuthorizationEndpointErrorCode,\n} from './oauth/OAuthErrorCode';\nexport { OAuthProtocolError, OAuthErrorExtras } from './oauth/OAuthProtocolError';\nexport { OAuthBearerChallenge } from './oauth/OAuthBearerChallenge';\nexport { OAuthErrorBody, OAuthErrorResponse } from './oauth/OAuthErrorResponse';\nexport { OAuthAuthorizationErrorRedirect } from './oauth/OAuthAuthorizationErrorRedirect';\nexport type { PublishedKind, PublishedApiError } from './http/ApiErrorHttpStatus';\n\nexport { Mcp, McpToolProfilesOptions } from './mcp/Mcp';\nexport type { McpToolProfiles } from './mcp/Mcp';\n\nexport { MCP_INVOCATION_CONTEXT, McpInvocationContext } from './mcp/McpInvocationContext';\nexport type { McpProgressReporter } from './mcp/McpInvocationContext';\n"]}