@webpieces/cloudtasks-client 0.4.390 → 0.4.391

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/cloudtasks-client",
3
- "version": "0.4.390",
3
+ "version": "0.4.391",
4
4
  "description": "Cloud Tasks enqueue client generated from a shared @PubSub API contract (twin of http-client)",
5
5
  "type": "commonjs",
6
6
  "main": "./src/index.js",
@@ -23,9 +23,9 @@
23
23
  "access": "public"
24
24
  },
25
25
  "dependencies": {
26
- "@webpieces/core-context": "0.4.390",
27
- "@webpieces/core-util": "0.4.390",
28
- "@webpieces/gcp-identity": "0.4.390",
26
+ "@webpieces/core-context": "0.4.391",
27
+ "@webpieces/core-util": "0.4.391",
28
+ "@webpieces/gcp-identity": "0.4.391",
29
29
  "@google-cloud/tasks": "5.5.2",
30
30
  "inversify": "7.10.4",
31
31
  "reflect-metadata": "0.2.2"
@@ -67,7 +67,6 @@ exports.ClientCloudTasksFactory = ClientCloudTasksFactory;
67
67
  exports.ClientCloudTasksFactory = ClientCloudTasksFactory = tslib_1.__decorate([
68
68
  (0, core_util_1.DocumentDesign)(),
69
69
  (0, core_context_1.provideFrameworkSingleton)(),
70
- (0, inversify_1.injectable)(),
71
70
  tslib_1.__param(0, (0, inversify_1.inject)(TaskProxyClient_1.TASK_PROXY_CLIENT_PROVIDER)),
72
71
  tslib_1.__metadata("design:paramtypes", [core_context_1.Provider])
73
72
  ], ClientCloudTasksFactory);
@@ -1 +1 @@
1
- {"version":3,"file":"ClientCloudTasksFactory.js","sourceRoot":"","sources":["../../../../../packages/cloud/cloudtasks-client/src/ClientCloudTasksFactory.ts"],"names":[],"mappings":";;;;AAAA,yCAA+C;AAC/C,oDAAsD;AACtD,0DAAqG;AACrG,uDAAgF;AAGhF,iGAAiG;AACjG,6EAA6E;AAC7E,IAAA,oCAAqB,EAAC,4CAA0B,EAAE,iCAA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AHnC,IAAA,0BAAc,GAAE;IAChB,IAAA,wCAAyB,GAAE;IAC3B,IAAA,sBAAU,GAAE;IAGJ,mBAAA,IAAA,kBAAM,EAAC,4CAA0B,CAAC,CAAA;6CAA2C,uBAAQ;GAFjF,uBAAuB,CA4BnC","sourcesContent":["import { inject, injectable } from 'inversify';\nimport { DocumentDesign } from '@webpieces/core-util';\nimport { Provider, bindFrameworkProvider, provideFrameworkSingleton } from '@webpieces/core-context';\nimport { TASK_PROXY_CLIENT_PROVIDER, TaskProxyClient } from './TaskProxyClient';\nimport { ApiPrototype, TaskClientConfig } from './TaskClientConfig';\n\n// Teach the container how to hand out fresh TaskProxyClients. TaskProxyClient is bound TRANSIENT\n// (@provideFrameworkTransient), so each provider.get() constructs a new one.\nbindFrameworkProvider(TASK_PROXY_CLIENT_PROVIDER, TaskProxyClient);\n\n/**\n * Properties DI frameworks / Promise checks / serializers probe on the proxy; return\n * undefined instead of treating them as endpoints. Mirrors http-client-core's buildClientProxy.\n */\nconst FRAMEWORK_INSPECTION_PROPERTIES = new Set<string>([\n 'constructor', 'prototype', '__proto__', 'name', 'then', 'catch', 'finally',\n 'toJSON', 'valueOf', 'toString', 'nodeType', 'tagName', '$$typeof',\n]);\n\n/**\n * ClientCloudTasksFactory - builds Cloud Tasks enqueue clients from a shared @PubSub API\n * contract. The fire-and-forget twin of http-client-node's ClientHttpFactory.\n *\n * Calling a method on the returned client ENQUEUES a task (it does not call remotely); the task\n * is later delivered to the same endpoint's controller through the full server filter chain.\n *\n * ```typescript\n * // same project + region as this container; the URL is derived, you maintain nothing\n * const emailTasks = factory.createPubSubClient(EmailApi, new TaskClientConfig('email-svc'));\n * await scheduler.addToQueue(() => emailTasks.sendEmail(req), { dedupName });\n * ```\n *\n * Every client it builds gets its OWN {@link TaskProxyClient} from the injected\n * `Provider<TaskProxyClient>` (bound transient), which `createPubSubClient` then `init`s for one\n * contract. Their collaborators (TaskInvoker, RequestContextHeaders) come from the container.\n *\n * Node-only, so the factory IS the inversify entry point. An enqueue outside\n * `RequestContext.run(...)` throws rather than silently dropping the caller's trace.\n */\n@DocumentDesign()\n@provideFrameworkSingleton()\n@injectable()\nexport class ClientCloudTasksFactory {\n constructor(\n @inject(TASK_PROXY_CLIENT_PROVIDER) private readonly taskProxyClientProvider: Provider<TaskProxyClient>,\n ) {}\n\n /** Typed enqueue client for a @PubSub contract, delivered to `config.svcName`. */\n createPubSubClient<T extends object>(apiClass: ApiPrototype<T>, config: TaskClientConfig): T {\n // Fresh instance per contract — TaskProxyClient is transient.\n const proxyClient = this.taskProxyClientProvider.get();\n proxyClient.init(apiClass, config);\n\n return new Proxy({} as T, {\n // webpieces-disable no-any-unknown -- proxy get trap returns either an endpoint method or undefined\n get(target: T, prop: string | symbol): unknown {\n if (typeof prop !== 'string' || FRAMEWORK_INSPECTION_PROPERTIES.has(prop)) {\n return undefined;\n }\n if (!proxyClient.hasEndpoint(prop)) {\n throw new Error(\n `No @PubSub endpoint '${prop}' on ${apiClass.name || 'Unknown'}. ` +\n `Check for typos or a missing @Endpoint() decorator.`,\n );\n }\n // webpieces-disable no-any-unknown -- request DTO type is erased at the proxy layer\n return (requestDto: unknown): Promise<void> => proxyClient.enqueue(prop, requestDto);\n },\n });\n }\n}\n"]}
1
+ {"version":3,"file":"ClientCloudTasksFactory.js","sourceRoot":"","sources":["../../../../../packages/cloud/cloudtasks-client/src/ClientCloudTasksFactory.ts"],"names":[],"mappings":";;;;AAAA,yCAAmC;AACnC,oDAAsD;AACtD,0DAAqG;AACrG,uDAAgF;AAGhF,iGAAiG;AACjG,6EAA6E;AAC7E,IAAA,oCAAqB,EAAC,4CAA0B,EAAE,iCAAe,CAAC,CAAC;AAEnE;;;GAGG;AACH,MAAM,+BAA+B,GAAG,IAAI,GAAG,CAAS;IACpD,aAAa,EAAE,WAAW,EAAE,WAAW,EAAE,MAAM,EAAE,MAAM,EAAE,OAAO,EAAE,SAAS;IAC3E,QAAQ,EAAE,SAAS,EAAE,UAAU,EAAE,UA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import { Provider, bindFrameworkProvider, provideFrameworkSingleton } from '@webpieces/core-context';\nimport { TASK_PROXY_CLIENT_PROVIDER, TaskProxyClient } from './TaskProxyClient';\nimport { ApiPrototype, TaskClientConfig } from './TaskClientConfig';\n\n// Teach the container how to hand out fresh TaskProxyClients. TaskProxyClient is bound TRANSIENT\n// (@provideFrameworkTransient), so each provider.get() constructs a new one.\nbindFrameworkProvider(TASK_PROXY_CLIENT_PROVIDER, TaskProxyClient);\n\n/**\n * Properties DI frameworks / Promise checks / serializers probe on the proxy; return\n * undefined instead of treating them as endpoints. Mirrors http-client-core's buildClientProxy.\n */\nconst FRAMEWORK_INSPECTION_PROPERTIES = new Set<string>([\n 'constructor', 'prototype', '__proto__', 'name', 'then', 'catch', 'finally',\n 'toJSON', 'valueOf', 'toString', 'nodeType', 'tagName', '$$typeof',\n]);\n\n/**\n * ClientCloudTasksFactory - builds Cloud Tasks enqueue clients from a shared @PubSub API\n * contract. The fire-and-forget twin of http-client-node's ClientHttpFactory.\n *\n * Calling a method on the returned client ENQUEUES a task (it does not call remotely); the task\n * is later delivered to the same endpoint's controller through the full server filter chain.\n *\n * ```typescript\n * // same project + region as this container; the URL is derived, you maintain nothing\n * const emailTasks = factory.createPubSubClient(EmailApi, new TaskClientConfig('email-svc'));\n * await scheduler.addToQueue(() => emailTasks.sendEmail(req), { dedupName });\n * ```\n *\n * Every client it builds gets its OWN {@link TaskProxyClient} from the injected\n * `Provider<TaskProxyClient>` (bound transient), which `createPubSubClient` then `init`s for one\n * contract. Their collaborators (TaskInvoker, RequestContextHeaders) come from the container.\n *\n * Node-only, so the factory IS the inversify entry point. An enqueue outside\n * `RequestContext.run(...)` throws rather than silently dropping the caller's trace.\n */\n@DocumentDesign()\n@provideFrameworkSingleton()\nexport class ClientCloudTasksFactory {\n constructor(\n @inject(TASK_PROXY_CLIENT_PROVIDER) private readonly taskProxyClientProvider: Provider<TaskProxyClient>,\n ) {}\n\n /** Typed enqueue client for a @PubSub contract, delivered to `config.svcName`. */\n createPubSubClient<T extends object>(apiClass: ApiPrototype<T>, config: TaskClientConfig): T {\n // Fresh instance per contract — TaskProxyClient is transient.\n const proxyClient = this.taskProxyClientProvider.get();\n proxyClient.init(apiClass, config);\n\n return new Proxy({} as T, {\n // webpieces-disable no-any-unknown -- proxy get trap returns either an endpoint method or undefined\n get(target: T, prop: string | symbol): unknown {\n if (typeof prop !== 'string' || FRAMEWORK_INSPECTION_PROPERTIES.has(prop)) {\n return undefined;\n }\n if (!proxyClient.hasEndpoint(prop)) {\n throw new Error(\n `No @PubSub endpoint '${prop}' on ${apiClass.name || 'Unknown'}. ` +\n `Check for typos or a missing @Endpoint() decorator.`,\n );\n }\n // webpieces-disable no-any-unknown -- request DTO type is erased at the proxy layer\n return (requestDto: unknown): Promise<void> => proxyClient.enqueue(prop, requestDto);\n },\n });\n }\n}\n"]}
@@ -102,7 +102,6 @@ let CloudTaskScheduler = class CloudTaskScheduler {
102
102
  exports.CloudTaskScheduler = CloudTaskScheduler;
103
103
  exports.CloudTaskScheduler = CloudTaskScheduler = tslib_1.__decorate([
104
104
  (0, core_context_1.provideFrameworkSingleton)(),
105
- (0, inversify_1.injectable)(),
106
105
  tslib_1.__param(0, (0, inversify_1.inject)(TaskTypes_1.TaskInvoker)),
107
106
  tslib_1.__metadata("design:paramtypes", [TaskTypes_1.TaskInvoker])
108
107
  ], CloudTaskScheduler);
@@ -1 +1 @@
1
- {"version":3,"file":"CloudTaskScheduler.js","sourceRoot":"","sources":["../../../../../packages/cloud/cloudtasks-client/src/CloudTaskScheduler.ts"],"names":[],"mappings":";;;;AAAA,yCAA+C;AAC/C,0DAAoE;AACpE,0DAAyD;AACzD,oDAAkD;AAClD,2CAAsE;AACtE,uDAAwF;AAExF,MAAM,GAAG,GAAG,sBAAU,CAAC,SAAS,CAAC,oBAAoB,CAAC,CAAC;AAEvD;;;;;GAKG;AACH,MAAa,eAAe;IACxB,qFAAqF;IACrF,SAAS,CAAU;IACnB,6CAA6C;IAC7C,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MAAM,QAAQ,EAAE,CAAC;QACrB,CAAC;gBAAS,CAAC;YACP,IAAA,oCAAkB,GAAE,CAAC;QACzB,CAAC;QACD,IAAI,CAAC,KAAK,CAAC,MAAM,EAAE,CAAC;YAChB,MAAM,IAAI,KAAK,CACX,4EAA4E;gBAC5E,oCAAoC,CACvC,CAAC;QACN,CAAC;QACD,GAAG,CAAC,KAAK,CAAC,kBAAkB,KAAK,CAAC,MAAM,CAAC,MAAM,EAAE,CAAC,CAAC;QACnD,OAAO,KAAK,CAAC,MAAM,CAAC;IACxB,CAAC;CACJ,CAAA;AAxDY,gDAAkB;6BAAlB,kBAAkB;IAF9B,IAAA,wCAAyB,GAAE;IAC3B,IAAA,sBAAU,GAAE;IAGJ,mBAAA,IAAA,kBAAM,EAAC,uBAAW,CAAC,CAAA;6CAA2B,uBAAW;GAFrD,kBAAkB,CAwD9B","sourcesContent":["import { inject, injectable } from 'inversify';\nimport { provideFrameworkSingleton } from '@webpieces/core-context';\nimport { RequestContext } from '@webpieces/core-context';\nimport { LogManager } from '@webpieces/core-util';\nimport { TaskInvoker, JobReference, ScheduleInfo } from './TaskTypes';\nimport { ScheduleFrame, setScheduleFrame, clearScheduleFrame } from './ScheduleContext';\n\nconst log = LogManager.getLogger('CloudTaskScheduler');\n\n/**\n * Options for a scheduled task. These are QUEUE/TRANSPORT knobs (dedup, deadline)\n * that belong on the enqueue CALL, never on the shared API method — the controller\n * implementing that method has no use for them. See CloudTaskScheduler's class doc\n * for the full rationale.\n */\nexport class ScheduleOptions {\n /** Deterministic Cloud Task name → idempotent dedup (duplicate = ALREADY_EXISTS). */\n dedupName?: string;\n /** Per-task dispatch deadline in seconds. */\n taskTimeoutSeconds?: number;\n\n constructor(dedupName?: string, taskTimeoutSeconds?: number) {\n this.dedupName = dedupName;\n this.taskTimeoutSeconds = taskTimeoutSeconds;\n }\n}\n\n/**\n * Schedules Cloud Tasks. You wrap an enqueue-client call in a lambda so the shared\n * contract's method signature stays `foo(req)` on both client and controller; the\n * scheduling options ride out-of-band in the schedule frame:\n *\n * await scheduler.addToQueue(() => taskClient.sendEmail(req), { dedupName: id });\n * await scheduler.schedule(() => taskClient.sendEmail(req), runAtEpochMs);\n *\n * Must be called inside an active RequestContext (a server request scope).\n *\n * WHY scheduling options are here and NOT parameters on the API method\n * ------------------------------------------------------------------------\n * The enqueue client and the controller implement the SAME abstract API method\n * (`sendEmail(req): Promise<void>`). Scheduling options — `dedupName`, \"run in the\n * future\", `taskTimeoutSeconds` — are QUEUE/TRANSPORT concerns, not part of the\n * business contract, so they must not appear on the method signature:\n *\n * - They are meaningless on the SERVER side. The controller's `sendEmail` just does\n * the work (send the email). It has no use for `dedupName` (a Cloud Tasks resource\n * name), a future run-time (Cloud Tasks already delivered it), or a dispatch\n * deadline. Putting them on the method would force the controller to accept and\n * ignore transport metadata it can't act on.\n * - They vary per CALL SITE, not per method. The same `sendEmail` might be enqueued\n * plain in one place, deduped in another, and scheduled for later in a third. That\n * is a property of THIS enqueue, not of the API — so it belongs on the enqueue\n * call (the scheduler), exactly like Cloud Tasks itself separates the task's\n * schedule/dedup/deadline from the HTTP body it delivers.\n * - Symmetry with RPC: an http-client RPC call is `foo(req)` with no transport knobs\n * in the contract; the async (queue) client keeps that same clean contract and\n * moves the queue knobs to the scheduler wrapper.\n *\n * So the rule is: the API method is `method(req)` on BOTH sides forever; anything\n * queue-shaped (dedup, delay, timeout, cancel) lives on CloudTaskScheduler /\n * ScheduleOptions here, never on the API.\n */\n@provideFrameworkSingleton()\n@injectable()\nexport class CloudTaskScheduler {\n constructor(\n @inject(TaskInvoker) private readonly invoker: TaskInvoker,\n ) {}\n\n /** Enqueue a task to run as soon as possible. Returns its JobReference. */\n async addToQueue(runnable: () => Promise<void>, opts?: ScheduleOptions): Promise<JobReference> {\n return this.runWithFrame(\n new ScheduleInfo(undefined, opts?.taskTimeoutSeconds, opts?.dedupName),\n runnable,\n );\n }\n\n /** Enqueue a task to run at an absolute epoch-millis time. Returns its JobReference. */\n async schedule(\n runnable: () => Promise<void>,\n epochMsToRunAt: number,\n opts?: ScheduleOptions,\n ): Promise<JobReference> {\n return this.runWithFrame(\n new ScheduleInfo(epochMsToRunAt, opts?.taskTimeoutSeconds, opts?.dedupName),\n runnable,\n );\n }\n\n /** Cancel a previously scheduled task. */\n async cancelJob(ref: JobReference): Promise<void> {\n await this.invoker.delete(ref);\n }\n\n private async runWithFrame(\n info: ScheduleInfo,\n runnable: () => Promise<void>,\n ): Promise<JobReference> {\n if (!RequestContext.isActive()) {\n throw new Error(\n 'CloudTaskScheduler must run inside a RequestContext (a server request scope).',\n );\n }\n const frame = new ScheduleFrame(info);\n setScheduleFrame(frame);\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions -- always clear the frame; the runnable's error propagates unchanged\n try {\n await runnable();\n } finally {\n clearScheduleFrame();\n }\n if (!frame.jobRef) {\n throw new Error(\n 'CloudTaskScheduler runnable did not enqueue a task — the lambda must call ' +\n 'a task-client method exactly once.',\n );\n }\n log.debug(`scheduled task ${frame.jobRef.taskId}`);\n return frame.jobRef;\n }\n}\n"]}
1
+ {"version":3,"file":"CloudTaskScheduler.js","sourceRoot":"","sources":["../../../../../packages/cloud/cloudtasks-client/src/CloudTaskScheduler.ts"],"names":[],"mappings":";;;;AAAA,yCAAmC;AACnC,0DAAoE;AACpE,0DAAyD;AACzD,oDAAkD;AAClD,2CAAsE;AACtE,uDAAwF;AAExF,MAAM,GAAG,GAAG,sBAAU,CAAC,SAAS,CAAC,oBAAoB,CAAC,CAAC;AAEvD;;;;;GAKG;AACH,MAAa,eAAe;IACxB,qFAAqF;IACrF,SAAS,CAAU;IACnB,6CAA6C;IAC7C,kBAAkB,CAAU;IAE5B,YAAY,SAAkB,EAAE,kBAA2B;QACvD,IAAI,CAAC,SAAS,GAAG,SAAS,CAAC;QAC3B,IAAI,CAAC,kBAAkB,GAAG,kBAAkB,CAAC;IACjD,CAAC;CACJ;AAVD,0CAUC;AAED;;;;;;;;;;;;;;;;;;;;;;;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AAC;QACN,CAAC;QACD,GAAG,CAAC,KAAK,CAAC,kBAAkB,KAAK,CAAC,MAAM,CAAC,MAAM,EAAE,CAAC,CAAC;QACnD,OAAO,KAAK,CAAC,MAAM,CAAC;IACxB,CAAC;CACJ,CAAA;AAxDY,gDAAkB;6BAAlB,kBAAkB;IAD9B,IAAA,wCAAyB,GAAE;IAGnB,mBAAA,IAAA,kBAAM,EAAC,uBAAW,CAAC,CAAA;6CAA2B,uBAAW;GAFrD,kBAAkB,CAwD9B","sourcesContent":["import { inject } from 'inversify';\nimport { provideFrameworkSingleton } from '@webpieces/core-context';\nimport { RequestContext } from '@webpieces/core-context';\nimport { LogManager } from '@webpieces/core-util';\nimport { TaskInvoker, JobReference, ScheduleInfo } from './TaskTypes';\nimport { ScheduleFrame, setScheduleFrame, clearScheduleFrame } from './ScheduleContext';\n\nconst log = LogManager.getLogger('CloudTaskScheduler');\n\n/**\n * Options for a scheduled task. These are QUEUE/TRANSPORT knobs (dedup, deadline)\n * that belong on the enqueue CALL, never on the shared API method — the controller\n * implementing that method has no use for them. See CloudTaskScheduler's class doc\n * for the full rationale.\n */\nexport class ScheduleOptions {\n /** Deterministic Cloud Task name → idempotent dedup (duplicate = ALREADY_EXISTS). */\n dedupName?: string;\n /** Per-task dispatch deadline in seconds. */\n taskTimeoutSeconds?: number;\n\n constructor(dedupName?: string, taskTimeoutSeconds?: number) {\n this.dedupName = dedupName;\n this.taskTimeoutSeconds = taskTimeoutSeconds;\n }\n}\n\n/**\n * Schedules Cloud Tasks. You wrap an enqueue-client call in a lambda so the shared\n * contract's method signature stays `foo(req)` on both client and controller; the\n * scheduling options ride out-of-band in the schedule frame:\n *\n * await scheduler.addToQueue(() => taskClient.sendEmail(req), { dedupName: id });\n * await scheduler.schedule(() => taskClient.sendEmail(req), runAtEpochMs);\n *\n * Must be called inside an active RequestContext (a server request scope).\n *\n * WHY scheduling options are here and NOT parameters on the API method\n * ------------------------------------------------------------------------\n * The enqueue client and the controller implement the SAME abstract API method\n * (`sendEmail(req): Promise<void>`). Scheduling options — `dedupName`, \"run in the\n * future\", `taskTimeoutSeconds` — are QUEUE/TRANSPORT concerns, not part of the\n * business contract, so they must not appear on the method signature:\n *\n * - They are meaningless on the SERVER side. The controller's `sendEmail` just does\n * the work (send the email). It has no use for `dedupName` (a Cloud Tasks resource\n * name), a future run-time (Cloud Tasks already delivered it), or a dispatch\n * deadline. Putting them on the method would force the controller to accept and\n * ignore transport metadata it can't act on.\n * - They vary per CALL SITE, not per method. The same `sendEmail` might be enqueued\n * plain in one place, deduped in another, and scheduled for later in a third. That\n * is a property of THIS enqueue, not of the API — so it belongs on the enqueue\n * call (the scheduler), exactly like Cloud Tasks itself separates the task's\n * schedule/dedup/deadline from the HTTP body it delivers.\n * - Symmetry with RPC: an http-client RPC call is `foo(req)` with no transport knobs\n * in the contract; the async (queue) client keeps that same clean contract and\n * moves the queue knobs to the scheduler wrapper.\n *\n * So the rule is: the API method is `method(req)` on BOTH sides forever; anything\n * queue-shaped (dedup, delay, timeout, cancel) lives on CloudTaskScheduler /\n * ScheduleOptions here, never on the API.\n */\n@provideFrameworkSingleton()\nexport class CloudTaskScheduler {\n constructor(\n @inject(TaskInvoker) private readonly invoker: TaskInvoker,\n ) {}\n\n /** Enqueue a task to run as soon as possible. Returns its JobReference. */\n async addToQueue(runnable: () => Promise<void>, opts?: ScheduleOptions): Promise<JobReference> {\n return this.runWithFrame(\n new ScheduleInfo(undefined, opts?.taskTimeoutSeconds, opts?.dedupName),\n runnable,\n );\n }\n\n /** Enqueue a task to run at an absolute epoch-millis time. Returns its JobReference. */\n async schedule(\n runnable: () => Promise<void>,\n epochMsToRunAt: number,\n opts?: ScheduleOptions,\n ): Promise<JobReference> {\n return this.runWithFrame(\n new ScheduleInfo(epochMsToRunAt, opts?.taskTimeoutSeconds, opts?.dedupName),\n runnable,\n );\n }\n\n /** Cancel a previously scheduled task. */\n async cancelJob(ref: JobReference): Promise<void> {\n await this.invoker.delete(ref);\n }\n\n private async runWithFrame(\n info: ScheduleInfo,\n runnable: () => Promise<void>,\n ): Promise<JobReference> {\n if (!RequestContext.isActive()) {\n throw new Error(\n 'CloudTaskScheduler must run inside a RequestContext (a server request scope).',\n );\n }\n const frame = new ScheduleFrame(info);\n setScheduleFrame(frame);\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions -- always clear the frame; the runnable's error propagates unchanged\n try {\n await runnable();\n } finally {\n clearScheduleFrame();\n }\n if (!frame.jobRef) {\n throw new Error(\n 'CloudTaskScheduler runnable did not enqueue a task — the lambda must call ' +\n 'a task-client method exactly once.',\n );\n }\n log.debug(`scheduled task ${frame.jobRef.taskId}`);\n return frame.jobRef;\n }\n}\n"]}
@@ -85,9 +85,8 @@ let GcpTaskInvoker = class GcpTaskInvoker extends TaskTypes_1.TaskInvoker {
85
85
  exports.GcpTaskInvoker = GcpTaskInvoker;
86
86
  exports.GcpTaskInvoker = GcpTaskInvoker = tslib_1.__decorate([
87
87
  (0, core_context_1.provideFrameworkSingletonDefaultForApi)(TaskTypes_1.TaskInvoker),
88
- (0, inversify_1.injectable)(),
89
88
  tslib_1.__param(0, (0, inversify_1.optional)()),
90
- tslib_1.__param(0, (0, inversify_1.inject)(core_util_1.Secrets)),
89
+ tslib_1.__param(0, (0, inversify_1.inject)(core_util_1.SECRETS)),
91
90
  tslib_1.__metadata("design:paramtypes", [core_util_1.Secrets])
92
91
  ], GcpTaskInvoker);
93
92
  //# sourceMappingURL=GcpTaskInvoker.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"GcpTaskInvoker.js","sourceRoot":"","sources":["../../../../../packages/cloud/cloudtasks-client/src/GcpTaskInvoker.ts"],"names":[],"mappings":";;;;AAAA,yCAAyD;AACzD,+CAA+D;AAC/D,0DAAiF;AACjF,0DAIiC;AACjC,oDAA2D;AAC3D,2CAAqE;AAErE,MAAM,GAAG,GAAG,sBAAU,CAAC,SAAS,CAAC,gBAAgB,CAAC,CAAC;AAInD;;;;;;GAMG;AACH,gGAAgG;A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,CAAC;QAC9B,IAAI,IAAI,CAAC,IAAI,KAAK,MAAM,EAAE,CAAC;YACvB,WAAW,CAAC,SAAS,GAAG;gBACpB,mBAAmB,EAAE,MAAM,IAAA,4CAA6B,GAAE;gBAC1D,QAAQ,EAAE,OAAO,CAAC,SAAS;aAC9B,CAAC;YACF,OAAO;QACX,CAAC;QACD,IAAI,IAAI,CAAC,IAAI,KAAK,eAAe,EAAE,CAAC;YAChC,MAAM,MAAM,GAAG,IAAI,CAAC,OAAO,EAAE,GAAG,CAAC,IAAI,CAAC,SAAS,CAAC,CAAC;YACjD,IAAI,MAAM,EAAE,CAAC;gBACT,2FAA2F;gBAC3F,OAAO,CAAC,GAAG,CAAC,eAAe,EAAE,aAAa,MAAM,EAAE,CAAC,CAAC;gBACpD,WAAW,CAAC,OAAO,GAAG,MAAM,CAAC,WAAW,CAAC,OAAO,CAAC,CAAC;YACtD,CAAC;QACL,CAAC;IACL,CAAC;CACJ,CAAA;AAxEY,wCAAc;yBAAd,cAAc;IAF1B,IAAA,qDAAsC,EAAC,uBAAW,CAAC;IACnD,IAAA,sBAAU,GAAE;IAKI,mBAAA,IAAA,oBAAQ,GAAE,CAAA;IAAE,mBAAA,IAAA,kBAAM,EAAC,mBAAO,CAAC,CAAA;6CAA4B,mBAAO;GAJlE,cAAc,CAwE1B","sourcesContent":["import { injectable, inject, optional } from 'inversify';\nimport { CloudTasksClient, protos } from '@google-cloud/tasks';\nimport { provideFrameworkSingletonDefaultForApi } from '@webpieces/core-context';\nimport {\n getProjectId,\n getRegion,\n getRuntimeServiceAccountEmail,\n} from '@webpieces/gcp-identity';\nimport { LogManager, Secrets } from '@webpieces/core-util';\nimport { TaskInvoker, TaskRequest, JobReference } from './TaskTypes';\n\nconst log = LogManager.getLogger('GcpTaskInvoker');\n\ntype ITask = protos.google.cloud.tasks.v2.ITask;\n\n/**\n * TaskInvoker that enqueues to Google Cloud Tasks (`@google-cloud/tasks`). Builds an\n * HTTP-target task delivered as POST to `targetUrl + path`, authenticated per the\n * endpoint's auth mode (OIDC token minted as this service's runtime SA, or a\n * shared-secret header). The task name is derived from the dedup name for idempotency\n * (a duplicate enqueue is rejected ALREADY_EXISTS = idempotent success upstream).\n */\n// Default (overridable) impl of the TaskInvoker contract: binds `TaskInvoker -> GcpTaskInvoker`\n// as a framework singleton. Tests/local dev override it via appOverrides:\n// `(await options.rebind(TaskInvoker)).to(InMemoryTaskInvoker)` — same idiom as AuthConfig.\n@provideFrameworkSingletonDefaultForApi(TaskInvoker)\n@injectable()\nexport class GcpTaskInvoker extends TaskInvoker {\n private readonly client = new CloudTasksClient();\n\n // @optional: only @AuthSharedSecret task endpoints need it; the client sends its bound value.\n constructor(@optional() @inject(Secrets) private readonly secrets?: Secrets) {\n super();\n }\n\n override async enqueue(request: TaskRequest): Promise<JobReference> {\n const projectId = await getProjectId();\n const region = await getRegion();\n const parent = this.client.queuePath(projectId, region, request.queueName);\n\n const task = await this.buildTask(request, parent);\n const result = await this.client.createTask({ parent: parent, task: task });\n const created = result[0];\n const name = created.name ?? request.scheduleInfo.dedupName ?? 'unknown';\n log.info(`enqueued cloud task ${name}`);\n return new JobReference(name);\n }\n\n override async delete(ref: JobReference): Promise<void> {\n await this.client.deleteTask({ name: ref.taskId });\n }\n\n private async buildTask(request: TaskRequest, parent: string): Promise<ITask> {\n const headers = new Map<string, string>(request.contextHeaders);\n headers.set('content-type', 'application/json');\n\n const httpRequest: protos.google.cloud.tasks.v2.IHttpRequest = {\n httpMethod: 'POST',\n url: request.targetUrl + request.path,\n headers: Object.fromEntries(headers),\n body: Buffer.from(JSON.stringify(request.body ?? {}), 'utf8').toString('base64'),\n };\n await this.applyAuth(request, httpRequest, headers);\n\n const task: ITask = { httpRequest: httpRequest };\n if (request.scheduleInfo.dedupName) {\n task.name = `${parent}/tasks/${request.scheduleInfo.dedupName}`;\n }\n if (request.scheduleInfo.epochMsToRunAt) {\n task.scheduleTime = { seconds: Math.floor(request.scheduleInfo.epochMsToRunAt / 1000) };\n }\n if (request.scheduleInfo.taskTimeoutSeconds) {\n task.dispatchDeadline = { seconds: request.scheduleInfo.taskTimeoutSeconds };\n }\n return task;\n }\n\n private async applyAuth(\n request: TaskRequest,\n httpRequest: protos.google.cloud.tasks.v2.IHttpRequest,\n headers: Map<string, string>,\n ): Promise<void> {\n const mode = request.authMode;\n if (mode.kind === 'oidc') {\n httpRequest.oidcToken = {\n serviceAccountEmail: await getRuntimeServiceAccountEmail(),\n audience: request.targetUrl,\n };\n return;\n }\n if (mode.kind === 'shared-secret') {\n const secret = this.secrets?.get(mode.secretKey);\n if (secret) {\n // One credential header; the 'Webpieces' scheme says a shared secret follows, not a token.\n headers.set('authorization', `Webpieces ${secret}`);\n httpRequest.headers = Object.fromEntries(headers);\n }\n }\n }\n}\n"]}
1
+ {"version":3,"file":"GcpTaskInvoker.js","sourceRoot":"","sources":["../../../../../packages/cloud/cloudtasks-client/src/GcpTaskInvoker.ts"],"names":[],"mappings":";;;;AAAA,yCAA6C;AAC7C,+CAA+D;AAC/D,0DAAiF;AACjF,0DAIiC;AACjC,oDAAoE;AACpE,2CAAqE;AAErE,MAAM,GAAG,GAAG,sBAAU,CAAC,SAAS,CAAC,gBAAgB,CAAC,CAAC;AAInD;;;;;;GAMG;AACH,gGAAgG;AAChG,0EAA0E;AAC1E,4FAA4F;AAErF,IAAM,cAAc,GAApB,MAAM,cAAe,SAAQ,uBAAW;IAIe;IAHzC,MAAM,GAAG,IAAI,wBAAgB,EAAE,CAAC;IAEjD,8FAA8F;IAC9F,YAA0D,OAAiB;QACvE,KAAK,EAAE,CAAC;QAD8C,YAAO,GAAP,OAAO,CAAU;IAE3E,CAAC;IAEQ,KAAK,CAAC,OAAO,CAAC,OAAoB;QACvC,MAAM,SAAS,GAAG,MAAM,IAAA,2BAAY,GAAE,CAAC;QACvC,MAAM,MAAM,GAAG,MAAM,IAAA,wBAAS,GAAE,CAAC;QACjC,MAAM,MAAM,GAAG,IAAI,CAAC,MAAM,CAAC,SAAS,CAAC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,aAAa,MAAM,EAAE,CAAC,CAAC;gBACpD,WAAW,CAAC,OAAO,GAAG,MAAM,CAAC,WAAW,CAAC,OAAO,CAAC,CAAC;YACtD,CAAC;QACL,CAAC;IACL,CAAC;CACJ,CAAA;AAxEY,wCAAc;yBAAd,cAAc;IAD1B,IAAA,qDAAsC,EAAC,uBAAW,CAAC;IAKnC,mBAAA,IAAA,oBAAQ,GAAE,CAAA;IAAE,mBAAA,IAAA,kBAAM,EAAC,mBAAO,CAAC,CAAA;6CAA4B,mBAAO;GAJlE,cAAc,CAwE1B","sourcesContent":["import { inject, optional } from 'inversify';\nimport { CloudTasksClient, protos } from '@google-cloud/tasks';\nimport { provideFrameworkSingletonDefaultForApi } from '@webpieces/core-context';\nimport {\n getProjectId,\n getRegion,\n getRuntimeServiceAccountEmail,\n} from '@webpieces/gcp-identity';\nimport { LogManager, Secrets, SECRETS } from '@webpieces/core-util';\nimport { TaskInvoker, TaskRequest, JobReference } from './TaskTypes';\n\nconst log = LogManager.getLogger('GcpTaskInvoker');\n\ntype ITask = protos.google.cloud.tasks.v2.ITask;\n\n/**\n * TaskInvoker that enqueues to Google Cloud Tasks (`@google-cloud/tasks`). Builds an\n * HTTP-target task delivered as POST to `targetUrl + path`, authenticated per the\n * endpoint's auth mode (OIDC token minted as this service's runtime SA, or a\n * shared-secret header). The task name is derived from the dedup name for idempotency\n * (a duplicate enqueue is rejected ALREADY_EXISTS = idempotent success upstream).\n */\n// Default (overridable) impl of the TaskInvoker contract: binds `TaskInvoker -> GcpTaskInvoker`\n// as a framework singleton. Tests/local dev override it via appOverrides:\n// `(await options.rebind(TaskInvoker)).to(InMemoryTaskInvoker)` — same idiom as AuthConfig.\n@provideFrameworkSingletonDefaultForApi(TaskInvoker)\nexport class GcpTaskInvoker extends TaskInvoker {\n private readonly client = new CloudTasksClient();\n\n // @optional: only @AuthSharedSecret task endpoints need it; the client sends its bound value.\n constructor(@optional() @inject(SECRETS) private readonly secrets?: Secrets) {\n super();\n }\n\n override async enqueue(request: TaskRequest): Promise<JobReference> {\n const projectId = await getProjectId();\n const region = await getRegion();\n const parent = this.client.queuePath(projectId, region, request.queueName);\n\n const task = await this.buildTask(request, parent);\n const result = await this.client.createTask({ parent: parent, task: task });\n const created = result[0];\n const name = created.name ?? request.scheduleInfo.dedupName ?? 'unknown';\n log.info(`enqueued cloud task ${name}`);\n return new JobReference(name);\n }\n\n override async delete(ref: JobReference): Promise<void> {\n await this.client.deleteTask({ name: ref.taskId });\n }\n\n private async buildTask(request: TaskRequest, parent: string): Promise<ITask> {\n const headers = new Map<string, string>(request.contextHeaders);\n headers.set('content-type', 'application/json');\n\n const httpRequest: protos.google.cloud.tasks.v2.IHttpRequest = {\n httpMethod: 'POST',\n url: request.targetUrl + request.path,\n headers: Object.fromEntries(headers),\n body: Buffer.from(JSON.stringify(request.body ?? {}), 'utf8').toString('base64'),\n };\n await this.applyAuth(request, httpRequest, headers);\n\n const task: ITask = { httpRequest: httpRequest };\n if (request.scheduleInfo.dedupName) {\n task.name = `${parent}/tasks/${request.scheduleInfo.dedupName}`;\n }\n if (request.scheduleInfo.epochMsToRunAt) {\n task.scheduleTime = { seconds: Math.floor(request.scheduleInfo.epochMsToRunAt / 1000) };\n }\n if (request.scheduleInfo.taskTimeoutSeconds) {\n task.dispatchDeadline = { seconds: request.scheduleInfo.taskTimeoutSeconds };\n }\n return task;\n }\n\n private async applyAuth(\n request: TaskRequest,\n httpRequest: protos.google.cloud.tasks.v2.IHttpRequest,\n headers: Map<string, string>,\n ): Promise<void> {\n const mode = request.authMode;\n if (mode.kind === 'oidc') {\n httpRequest.oidcToken = {\n serviceAccountEmail: await getRuntimeServiceAccountEmail(),\n audience: request.targetUrl,\n };\n return;\n }\n if (mode.kind === 'shared-secret') {\n const secret = this.secrets?.get(mode.secretKey);\n if (secret) {\n // One credential header; the 'Webpieces' scheme says a shared secret follows, not a token.\n headers.set('authorization', `Webpieces ${secret}`);\n httpRequest.headers = Object.fromEntries(headers);\n }\n }\n }\n}\n"]}
@@ -118,10 +118,9 @@ let InMemoryTaskInvoker = class InMemoryTaskInvoker extends TaskTypes_1.TaskInvo
118
118
  exports.InMemoryTaskInvoker = InMemoryTaskInvoker;
119
119
  exports.InMemoryTaskInvoker = InMemoryTaskInvoker = tslib_1.__decorate([
120
120
  (0, core_context_1.provideFrameworkSingleton)(),
121
- (0, inversify_1.injectable)(),
122
121
  tslib_1.__param(0, (0, inversify_1.inject)(gcp_identity_1.GcpOidc)),
123
122
  tslib_1.__param(1, (0, inversify_1.optional)()),
124
- tslib_1.__param(1, (0, inversify_1.inject)(core_util_1.Secrets)),
123
+ tslib_1.__param(1, (0, inversify_1.inject)(core_util_1.SECRETS)),
125
124
  tslib_1.__metadata("design:paramtypes", [gcp_identity_1.GcpOidc,
126
125
  core_util_1.Secrets])
127
126
  ], InMemoryTaskInvoker);
@@ -1 +1 @@
1
- {"version":3,"file":"InMemoryTaskInvoker.js","sourceRoot":"","sources":["../../../../../packages/cloud/cloudtasks-client/src/InMemoryTaskInvoker.ts"],"names":[],"mappings":";;;;AAAA,yCAAyD;AACzD,0DAAoE;AACpE,0DAAkD;AAClD,oDAAoE;AACpE,2CAAqE;AAErE,MAAM,GAAG,GAAG,sBAAU,CAAC,SAAS,CAAC,qBAAqB,CAAC,CAAC;AAExD;;;;;;;;;;;;;;;GAeG;AAGI,IAAM,mBAAmB,GAAzB,MAAM,mBAAoB,SAAQ,uBAAW;IAOV;IAGY;IAT1C,OAAO,GAAG,CAAC,CAAC;IACpB,uEAAuE;IACtD,OAAO,GAAG,IAAI,GAAG,EAAyC,CAAC;IAE5E,YAEsC,OAAgB,EAGJ,OAAiB;QAE/D,KAAK,EAAE,CAAC;QAL0B,YAAO,GAAP,OAAO,CAAS;QAGJ,YAAO,GAAP,OAAO,CAAU;IAGnE,CAAC;IAEQ,KAAK,CAAC,OAAO,CAAC,OAAoB;QACvC,IAAI,CAAC,OAAO,IAAI,CAAC,CAAC;QAClB,MAAM,MAAM,GAAG,OAAO,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context';\nimport { GcpOidc } from '@webpieces/gcp-identity';\nimport { LogManager, toError, Secrets } from '@webpieces/core-util';\nimport { TaskInvoker, TaskRequest, JobReference } from './TaskTypes';\n\nconst log = LogManager.getLogger('InMemoryTaskInvoker');\n\n/**\n * TaskInvoker for tests + local dev — the in-memory-queue twin of GcpTaskInvoker\n * (a TypeScript port of webpieces-java's LocalRemoteInvoker).\n *\n * Instead of enqueuing to Google Cloud Tasks, it drops the delivery onto an in-process\n * timer queue and returns IMMEDIATELY (breaking from the caller, exactly like handing a\n * task to Cloud Tasks). The queued job then delivers the task the SAME way real Cloud\n * Tasks does: a plain HTTP POST to `targetUrl + path` with the JSON body and the\n * synthesized delivery auth (OIDC bearer / shared-secret). It does NOT invoke the server\n * in-process — the target may be a different process entirely — so the request travels\n * over real HTTP (e.g. http://localhost:{port}/queue/path) and is served by the target's\n * real routing + filter chain, giving production parity without GCP.\n *\n * Bind it (via appOverrides) in place of GcpTaskInvoker:\n * bind(TaskInvoker).to(InMemoryTaskInvoker)\n */\n@provideFrameworkSingleton()\n@injectable()\nexport class InMemoryTaskInvoker extends TaskInvoker {\n private counter = 0;\n /** Scheduled (not-yet-delivered) jobs, so delete() can cancel them. */\n private readonly pending = new Map<string, ReturnType<typeof setTimeout>>();\n\n constructor(\n // webpieces-disable inject-annotation-not-needed-for-concrete-class -- DI-resolved param; the esbuild/vitest path elides type-only imports (no design:paramtypes), so the explicit token is required\n @inject(GcpOidc) private readonly gcpOidc: GcpOidc,\n // @optional: only @AuthSharedSecret task endpoints need it; the client sends its bound value.\n // webpieces-disable inject-annotation-not-needed-for-concrete-class -- DI-resolved param; the esbuild/vitest path elides type-only imports (no design:paramtypes), so the explicit token is required\n @optional() @inject(Secrets) private readonly secrets?: Secrets,\n ) {\n super();\n }\n\n override async enqueue(request: TaskRequest): Promise<JobReference> {\n this.counter += 1;\n const taskId = request.scheduleInfo.dedupName ?? `inmem-${request.queueName}-${this.counter}`;\n const delayMs = this.computeDelayMs(request.scheduleInfo.epochMsToRunAt);\n\n // Break from the caller: queue the HTTP delivery and return the reference NOW.\n const timer = setTimeout(() => {\n this.pending.delete(taskId);\n void this.deliver(request, taskId);\n }, delayMs);\n // A queued task must not keep the process alive on its own.\n timer.unref?.();\n this.pending.set(taskId, timer);\n\n log.debug(`queued local task ${taskId} -> ${request.targetUrl}${request.path} (delay ${delayMs}ms)`);\n return new JobReference(taskId);\n }\n\n override async delete(ref: JobReference): Promise<void> {\n const timer = this.pending.get(ref.taskId);\n if (timer) {\n clearTimeout(timer);\n this.pending.delete(ref.taskId);\n }\n }\n\n /** ms until the scheduled run time (0 = as soon as possible / already due). */\n private computeDelayMs(epochMsToRunAt?: number): number {\n if (epochMsToRunAt === undefined) {\n return 0;\n }\n const delay = epochMsToRunAt - Date.now();\n return delay > 0 ? delay : 0;\n }\n\n /** Deliver the queued task over real HTTP, mirroring Cloud Tasks' HTTP callback. */\n private async deliver(request: TaskRequest, taskId: string): Promise<void> {\n const url = `${request.targetUrl}${request.path}`;\n const headers = await this.buildHeaders(request);\n log.info(`delivering local task ${taskId}: POST ${url}`);\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions -- detached queue job: log delivery failure, never crash the queue\n try {\n // webpieces-disable no-fetch -- in-memory queue delivers over real HTTP like Cloud Tasks (no server to invoke in-process)\n const response = await fetch(url, {\n method: 'POST',\n headers: headers,\n body: JSON.stringify(request.body ?? {}),\n });\n if (!response.ok) {\n log.error(`local task ${taskId} delivery to ${url} failed: HTTP ${response.status}`);\n return;\n }\n log.debug(`local task ${taskId} delivered: HTTP ${response.status}`);\n } catch (err: unknown) {\n const error = toError(err);\n log.error(`local task ${taskId} delivery to ${url} threw: ${error.message}`);\n }\n }\n\n /** content-type + propagated context headers + synthesized delivery credential. */\n private async buildHeaders(request: TaskRequest): Promise<Record<string, string>> {\n const headers: Record<string, string> = { 'content-type': 'application/json' };\n for (const entry of request.contextHeaders.entries()) {\n headers[entry[0]] = entry[1];\n }\n await this.attachAuth(request, headers);\n return headers;\n }\n\n /** Synthesize the delivery credential Cloud Tasks would attach, per the auth mode. */\n private async attachAuth(request: TaskRequest, headers: Record<string, string>): Promise<void> {\n const mode = request.authMode;\n if (mode.kind === 'oidc') {\n headers['authorization'] = `Bearer ${await this.gcpOidc.mintIdToken(request.targetUrl)}`;\n return;\n }\n if (mode.kind === 'shared-secret') {\n const secret = this.secrets?.get(mode.secretKey);\n if (secret) {\n // One credential header; the 'Webpieces' scheme says a shared secret follows, not a token.\n headers['authorization'] = `Webpieces ${secret}`;\n }\n }\n // public / jwt → no service credential is synthesized.\n }\n}\n"]}
1
+ {"version":3,"file":"InMemoryTaskInvoker.js","sourceRoot":"","sources":["../../../../../packages/cloud/cloudtasks-client/src/InMemoryTaskInvoker.ts"],"names":[],"mappings":";;;;AAAA,yCAA6C;AAC7C,0DAAoE;AACpE,0DAAkD;AAClD,oDAA6E;AAC7E,2CAAqE;AAErE,MAAM,GAAG,GAAG,sBAAU,CAAC,SAAS,CAAC,qBAAqB,CAAC,CAAC;AAExD;;;;;;;;;;;;;;;GAeG;AAEI,IAAM,mBAAmB,GAAzB,MAAM,mBAAoB,SAAQ,uBAAW;IAOV;IAGY;IAT1C,OAAO,GAAG,CAAC,CAAC;IACpB,uEAAuE;IACtD,OAAO,GAAG,IAAI,GAAG,EAAyC,CAAC;IAE5E,YAEsC,OAAgB,EAGJ,OAAiB;QAE/D,KAAK,EAAE,CAAC;QAL0B,YAAO,GAAP,OAAO,CAAS;QAGJ,YAAO,GAAP,OAAO,CAAU;IAGnE,CAAC;IAEQ,KAAK,CAAC,OAAO,CAAC,OAAoB;QACvC,IAAI,CAAC,OAAO,IAAI,CAAC,CAAC;QAClB,MAAM,MAAM,GAAG,OAAO,CAAC,YAAY,CAAC,SAAS,IAAI,SAAS,OAAO,CAAC,SAAS,IAAI,IAAI,CAAC,OAAO,EAAE,CAAC;QAC9F,MAAM,OAAO,GAAG,IAAI,CAAC,cAAc,CAAC,OAAO,CAAC,YAAY,CAAC,cAAc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,IAAI,CAAC,UAAU,CAAC,OAAO,EAAE,OAAO,CAAC,CAAC;QACxC,OAAO,OAAO,CAAC;IACnB,CAAC;IAED,sFAAsF;IAC9E,KAAK,CAAC,UAAU,CAAC,OAAoB,EAAE,OAA+B;QAC1E,MAAM,IAAI,GAAG,OAAO,CAAC,QAAQ,CAAC;QAC9B,IAAI,IAAI,CAAC,IAAI,KAAK,MAAM,EAAE,CAAC;YACvB,OAAO,CAAC,eAAe,CAAC,GAAG,UAAU,MAAM,IAAI,CAAC,OAAO,CAAC,WAAW,CAAC,OAAO,CAAC,SAAS,CAAC,EAAE,CAAC;YACzF,OAAO;QACX,CAAC;QACD,IAAI,IAAI,CAAC,IAAI,KAAK,eAAe,EAAE,CAAC;YAChC,MAAM,MAAM,GAAG,IAAI,CAAC,OAAO,EAAE,GAAG,CAAC,IAAI,CAAC,SAAS,CAAC,CAAC;YACjD,IAAI,MAAM,EAAE,CAAC;gBACT,2FAA2F;gBAC3F,OAAO,CAAC,eAAe,CAAC,GAAG,aAAa,MAAM,EAAE,CAAC;YACrD,CAAC;QACL,CAAC;QACD,uDAAuD;IAC3D,CAAC;CACJ,CAAA;AApGY,kDAAmB;8BAAnB,mBAAmB;IAD/B,IAAA,wCAAyB,GAAE;IAQnB,mBAAA,IAAA,kBAAM,EAAC,sBAAO,CAAC,CAAA;IAGf,mBAAA,IAAA,oBAAQ,GAAE,CAAA;IAAE,mBAAA,IAAA,kBAAM,EAAC,mBAAO,CAAC,CAAA;6CAHe,sBAAO;QAGM,mBAAO;GAV1D,mBAAmB,CAoG/B","sourcesContent":["import { inject, optional } from 'inversify';\nimport { provideFrameworkSingleton } from '@webpieces/core-context';\nimport { GcpOidc } from '@webpieces/gcp-identity';\nimport { LogManager, toError, Secrets, SECRETS } from '@webpieces/core-util';\nimport { TaskInvoker, TaskRequest, JobReference } from './TaskTypes';\n\nconst log = LogManager.getLogger('InMemoryTaskInvoker');\n\n/**\n * TaskInvoker for tests + local dev — the in-memory-queue twin of GcpTaskInvoker\n * (a TypeScript port of webpieces-java's LocalRemoteInvoker).\n *\n * Instead of enqueuing to Google Cloud Tasks, it drops the delivery onto an in-process\n * timer queue and returns IMMEDIATELY (breaking from the caller, exactly like handing a\n * task to Cloud Tasks). The queued job then delivers the task the SAME way real Cloud\n * Tasks does: a plain HTTP POST to `targetUrl + path` with the JSON body and the\n * synthesized delivery auth (OIDC bearer / shared-secret). It does NOT invoke the server\n * in-process — the target may be a different process entirely — so the request travels\n * over real HTTP (e.g. http://localhost:{port}/queue/path) and is served by the target's\n * real routing + filter chain, giving production parity without GCP.\n *\n * Bind it (via appOverrides) in place of GcpTaskInvoker:\n * bind(TaskInvoker).to(InMemoryTaskInvoker)\n */\n@provideFrameworkSingleton()\nexport class InMemoryTaskInvoker extends TaskInvoker {\n private counter = 0;\n /** Scheduled (not-yet-delivered) jobs, so delete() can cancel them. */\n private readonly pending = new Map<string, ReturnType<typeof setTimeout>>();\n\n constructor(\n // webpieces-disable inject-annotation-not-needed-for-concrete-class -- DI-resolved param; the esbuild/vitest path elides type-only imports (no design:paramtypes), so the explicit token is required\n @inject(GcpOidc) private readonly gcpOidc: GcpOidc,\n // @optional: only @AuthSharedSecret task endpoints need it; the client sends its bound value.\n // webpieces-disable inject-annotation-not-needed-for-concrete-class -- DI-resolved param; the esbuild/vitest path elides type-only imports (no design:paramtypes), so the explicit token is required\n @optional() @inject(SECRETS) private readonly secrets?: Secrets,\n ) {\n super();\n }\n\n override async enqueue(request: TaskRequest): Promise<JobReference> {\n this.counter += 1;\n const taskId = request.scheduleInfo.dedupName ?? `inmem-${request.queueName}-${this.counter}`;\n const delayMs = this.computeDelayMs(request.scheduleInfo.epochMsToRunAt);\n\n // Break from the caller: queue the HTTP delivery and return the reference NOW.\n const timer = setTimeout(() => {\n this.pending.delete(taskId);\n void this.deliver(request, taskId);\n }, delayMs);\n // A queued task must not keep the process alive on its own.\n timer.unref?.();\n this.pending.set(taskId, timer);\n\n log.debug(`queued local task ${taskId} -> ${request.targetUrl}${request.path} (delay ${delayMs}ms)`);\n return new JobReference(taskId);\n }\n\n override async delete(ref: JobReference): Promise<void> {\n const timer = this.pending.get(ref.taskId);\n if (timer) {\n clearTimeout(timer);\n this.pending.delete(ref.taskId);\n }\n }\n\n /** ms until the scheduled run time (0 = as soon as possible / already due). */\n private computeDelayMs(epochMsToRunAt?: number): number {\n if (epochMsToRunAt === undefined) {\n return 0;\n }\n const delay = epochMsToRunAt - Date.now();\n return delay > 0 ? delay : 0;\n }\n\n /** Deliver the queued task over real HTTP, mirroring Cloud Tasks' HTTP callback. */\n private async deliver(request: TaskRequest, taskId: string): Promise<void> {\n const url = `${request.targetUrl}${request.path}`;\n const headers = await this.buildHeaders(request);\n log.info(`delivering local task ${taskId}: POST ${url}`);\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions -- detached queue job: log delivery failure, never crash the queue\n try {\n // webpieces-disable no-fetch -- in-memory queue delivers over real HTTP like Cloud Tasks (no server to invoke in-process)\n const response = await fetch(url, {\n method: 'POST',\n headers: headers,\n body: JSON.stringify(request.body ?? {}),\n });\n if (!response.ok) {\n log.error(`local task ${taskId} delivery to ${url} failed: HTTP ${response.status}`);\n return;\n }\n log.debug(`local task ${taskId} delivered: HTTP ${response.status}`);\n } catch (err: unknown) {\n const error = toError(err);\n log.error(`local task ${taskId} delivery to ${url} threw: ${error.message}`);\n }\n }\n\n /** content-type + propagated context headers + synthesized delivery credential. */\n private async buildHeaders(request: TaskRequest): Promise<Record<string, string>> {\n const headers: Record<string, string> = { 'content-type': 'application/json' };\n for (const entry of request.contextHeaders.entries()) {\n headers[entry[0]] = entry[1];\n }\n await this.attachAuth(request, headers);\n return headers;\n }\n\n /** Synthesize the delivery credential Cloud Tasks would attach, per the auth mode. */\n private async attachAuth(request: TaskRequest, headers: Record<string, string>): Promise<void> {\n const mode = request.authMode;\n if (mode.kind === 'oidc') {\n headers['authorization'] = `Bearer ${await this.gcpOidc.mintIdToken(request.targetUrl)}`;\n return;\n }\n if (mode.kind === 'shared-secret') {\n const secret = this.secrets?.get(mode.secretKey);\n if (secret) {\n // One credential header; the 'Webpieces' scheme says a shared secret follows, not a token.\n headers['authorization'] = `Webpieces ${secret}`;\n }\n }\n // public / jwt → no service credential is synthesized.\n }\n}\n"]}
@@ -130,7 +130,6 @@ let TaskProxyClient = class TaskProxyClient {
130
130
  exports.TaskProxyClient = TaskProxyClient;
131
131
  exports.TaskProxyClient = TaskProxyClient = tslib_1.__decorate([
132
132
  (0, core_context_1.provideFrameworkTransient)(),
133
- (0, inversify_1.injectable)(),
134
133
  tslib_1.__param(0, (0, inversify_1.inject)(TaskTypes_1.TaskInvoker)),
135
134
  tslib_1.__param(1, (0, inversify_1.inject)(core_context_1.RequestContextHeaders)),
136
135
  tslib_1.__metadata("design:paramtypes", [TaskTypes_1.TaskInvoker,
@@ -1 +1 @@
1
- {"version":3,"file":"TaskProxyClient.js","sourceRoot":"","sources":["../../../../../packages/cloud/cloudtasks-client/src/TaskProxyClient.ts"],"names":[],"mappings":";;;;AAAA,yCAA+C;AAC/C,oDAY8B;AAC9B,0DAGiC;AACjC,2CAAqE;AACrE,uDAAyD;AAGzD,MAAM,GAAG,GAAG,sBAAU,CAAC,SAAS,CAAC,iBAAiB,CAAC,CAAC;AAEpD,8EAA8E;AAC9E,MAAM,YAAY;IACd,IAAI,CAAS;IACb,SAAS,CAAS;IAClB,QAAQ,CAAW;IAEnB,YAAY,IAAY,EAAE,SAAiB,EAAE,QAAkB;QAC3D,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC;QACjB,IAAI,CAAC,SAAS,GAAG,SAAS,CAAC;QAC3B,IAAI,CAAC,QAAQ,GAAG,QAAQ,CAAC;IAC7B,CAAC;CACJ;AAED;;;;;;;;;;;;;;;;;GAiBG;AAGI,IAAM,eAAe,GAArB,MAAM,eAAe;IAOkB;IACU;IAPpD,8EAA8E;IACtE,KAAK,CAA6B;IAClC,OAAO,CAAU;IACjB,MAAM,CAAoB;IAElC,YAC0C,OAA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,EAAE,CAAC;YAC9C,MAAM,QAAQ,GAAG,IAAA,uBAAW,EAAC,QAAQ,EAAE,UAAU,CAAC,CAAC;YACnD,IAAI,CAAC,QAAQ,EAAE,CAAC;gBACZ,MAAM,IAAI,KAAK,CAAC,aAAa,UAAU,QAAQ,IAAI,CAAC,OAAO,mBAAmB,CAAC,CAAC;YACpF,CAAC;YACD,MAAM,IAAI,GAAG,IAAI,YAAY,CACzB,QAAQ,GAAG,SAAS,CAAC,UAAU,CAAC,EAChC,IAAA,wBAAY,EAAC,QAAQ,EAAE,UAAU,CAAC,EAClC,QAAQ,CACX,CAAC;YACF,KAAK,CAAC,GAAG,CAAC,UAAU,EAAE,IAAI,CAAC,CAAC;QAChC,CAAC;QACD,OAAO,KAAK,CAAC;IACjB,CAAC;IAED;;;;;;;OAOG;IACK,mBAAmB;QACvB,OAAO,IAAI,CAAC,OAAO,CAAC,oBAAoB,EAAE,CAAC;IAC/C,CAAC;CACJ,CAAA;AAlHY,0CAAe;0BAAf,eAAe;IAF3B,IAAA,wCAAyB,GAAE;IAC3B,IAAA,sBAAU,GAAE;IAQJ,mBAAA,IAAA,kBAAM,EAAC,uBAAW,CAAC,CAAA;IACnB,mBAAA,IAAA,kBAAM,EAAC,oCAAqB,CAAC,CAAA;6CADiB,uBAAW;QACD,oCAAqB;GARzE,eAAe,CAkH3B;AAED;;;;;;;GAOG;AACH,gGAAgG;AACnF,QAAA,0BAA0B,GAAG,MAAM,CAAC,GAAG,CAAC,2BAA2B,CAAC,CAAC","sourcesContent":["import { inject, injectable } from 'inversify';\nimport {\n isApiPath,\n getApiPath,\n getEndpoints,\n getAuthMode,\n getQueueName,\n assertPubSubConventions,\n assertEveryEndpointHasAuthMode,\n AuthMode,\n LogManager,\n LogApiCall,\n ApiMethodInfo,\n} from '@webpieces/core-util';\nimport {\n RequestContextHeaders,\n provideFrameworkTransient,\n} from '@webpieces/core-context';\nimport { TaskInvoker, TaskRequest, ScheduleInfo } from './TaskTypes';\nimport { currentScheduleFrame } from './ScheduleContext';\nimport { ApiPrototype, TaskClientConfig } from './TaskClientConfig';\n\nconst log = LogManager.getLogger('TaskProxyClient');\n\n/** Per-endpoint routing plan resolved once from the contract's decorators. */\nclass EndpointPlan {\n path: string;\n queueName: string;\n authMode: AuthMode;\n\n constructor(path: string, queueName: string, authMode: AuthMode) {\n this.path = path;\n this.queueName = queueName;\n this.authMode = authMode;\n }\n}\n\n/**\n * TaskProxyClient - the enqueue engine behind one @PubSub API contract's client proxy.\n *\n * The fire-and-forget twin of http-client-core's ProxyClient, and TWO-PHASE for the same reason:\n * its COLLABORATORS (invoker, headers) come from the container, while the PER-CLIENT state (which\n * contract, which target) arrives on {@link init}. That is what lets {@link ClientCloudTasksFactory}\n * hold a `Provider<TaskProxyClient>` and hand out a fresh, independently-configured client per\n * contract.\n *\n * Calling an endpoint ENQUEUES a task (it does not call remotely); the task is later delivered to\n * the same endpoint's controller through the full server filter chain.\n *\n * It owns:\n * - @ApiPath / @PubSub convention validation + the endpoint plans from the contract's decorators\n * - Resolving the callee's base URL from svcName (ClientRegistry override, else GCP derivation)\n * - Context propagation onto the task headers (a credential is never a context key, so none can ride along)\n * - Handing a fully-built TaskRequest to the bound {@link TaskInvoker}\n */\n@provideFrameworkTransient()\n@injectable()\nexport class TaskProxyClient {\n // Assigned by init(), which the factory calls immediately after construction.\n private plans!: Map<string, EndpointPlan>;\n private apiName!: string;\n private config!: TaskClientConfig;\n\n constructor(\n @inject(TaskInvoker) private readonly invoker: TaskInvoker,\n @inject(RequestContextHeaders) private readonly headers: RequestContextHeaders,\n ) {}\n\n /** Bind this client to one @PubSub contract + target. */\n init(apiClass: ApiPrototype<object>, config: TaskClientConfig): void {\n if (!isApiPath(apiClass)) {\n throw new Error(`Class ${apiClass.name || 'Unknown'} must be decorated with @ApiPath()`);\n }\n assertPubSubConventions(apiClass);\n assertEveryEndpointHasAuthMode(apiClass);\n\n this.config = config;\n this.apiName = apiClass.name || 'UnknownApi';\n this.plans = this.buildPlans(apiClass);\n }\n\n /** Check whether the contract declares a @PubSub endpoint with this method name. */\n hasEndpoint(methodName: string): boolean {\n return this.plans.has(methodName);\n }\n\n /**\n * Enqueue one task for the named endpoint. Must run inside a CloudTaskScheduler lambda\n * (which supplies the ScheduleInfo) within an active RequestContext, e.g.:\n * scheduler.addToQueue(() => taskClient.foo(req), { dedupName });\n */\n // webpieces-disable no-any-unknown -- the request DTO's type is erased at the proxy boundary\n async enqueue(methodName: string, requestDto: unknown): Promise<void> {\n const plan = this.plans.get(methodName);\n if (!plan) {\n throw new Error(`No @PubSub endpoint '${methodName}' on ${this.apiName}`);\n }\n\n const frame = currentScheduleFrame();\n if (!frame) {\n throw new Error(\n 'Cloud task enqueue must run inside a CloudTaskScheduler lambda, e.g. ' +\n 'scheduler.addToQueue(() => taskClient.method(req), { dedupName }).',\n );\n }\n\n // Route through LogApiCall exactly like ProxyClient does for http. TaskProxyClient.enqueue is\n // the ONE seam above BOTH GcpTaskInvoker (prod) and InMemoryTaskInvoker (localhost) — whichever\n // TaskInvoker is bound, this method sits above it — so the enqueue edge gets structured\n // `jsonPayload.api.*` logging (and, once recording is unified at LogApiCall, is recorded)\n // uniformly, without touching either invoker impl.\n const info = new ApiMethodInfo('client', this.apiName, methodName);\n await LogApiCall.execute(info, requestDto, async () => {\n // Resolved lazily (not at client construction) so building a client stays synchronous.\n // Every metadata read beneath resolveUrl is memoized process-wide, so only the first\n // enqueue in the process pays a lookup.\n const targetUrl = await this.config.resolveUrl();\n\n const request = new TaskRequest(\n targetUrl,\n plan.path,\n plan.queueName,\n requestDto,\n this.buildContextHeaders(),\n plan.authMode,\n frame.info ?? new ScheduleInfo(),\n );\n\n // svcName, not the URL, is the stable name across demo/qa/prod.\n log.debug(`enqueue task ${plan.queueName} -> ${this.config.svcName}${plan.path}`);\n frame.jobRef = await this.invoker.enqueue(request);\n\n // Fire-and-forget: the enqueue ack is not a meaningful response. Return a non-null value so\n // LogApiCall's null-response guard passes; a recorded test asserts the enqueued REQUEST\n // (payload), never this ack.\n return frame.jobRef ?? { enqueued: true };\n });\n }\n\n /** Endpoint name -> its resolved path / queue / auth mode, read once from the decorators. */\n private buildPlans(apiClass: ApiPrototype<object>): Map<string, EndpointPlan> {\n const basePath = getApiPath(apiClass) ?? '';\n const endpoints = getEndpoints(apiClass) ?? {};\n const plans = new Map<string, EndpointPlan>();\n\n for (const methodName of Object.keys(endpoints)) {\n const authMode = getAuthMode(apiClass, methodName);\n if (!authMode) {\n throw new Error(`Endpoint '${methodName}' on ${this.apiName} has no auth mode`);\n }\n const plan = new EndpointPlan(\n basePath + endpoints[methodName],\n getQueueName(apiClass, methodName),\n authMode,\n );\n plans.set(methodName, plan);\n }\n return plans;\n }\n\n /**\n * Every transferred context key (txId/requestId/tenant…), request-id chained.\n * Throws if there is no active RequestContext — an enqueue with no trace is a bug.\n *\n * No credential can appear here: `authorization` is read off the inbound HttpRequest and is not\n * a ContextKey, so it never enters the RequestContext to be transferred. The invoker mints the\n * task's own delivery auth per the endpoint's @AuthOidc / @AuthSharedSecret mode.\n */\n private buildContextHeaders(): Map<string, string> {\n return this.headers.buildOutboundHeaders();\n }\n}\n\n/**\n * DI token for the `Provider<TaskProxyClient>` that hands out enqueue clients — one per @PubSub\n * contract. `Provider<T>` is erased at runtime, so it cannot be its own token; this Symbol names T.\n *\n * Because TaskProxyClient is bound TRANSIENT, every `get()` constructs a new one. (Were it bound\n * `@provideFrameworkSingleton`, the very same Provider would hand back one lazily-created instance\n * instead — the provider caches nothing, so the target's scope decides.)\n */\n// webpieces-disable no-symbol-di-tokens -- Provider<T> is erased at runtime; the Symbol names T\nexport const TASK_PROXY_CLIENT_PROVIDER = Symbol.for('Provider<TaskProxyClient>');\n"]}
1
+ {"version":3,"file":"TaskProxyClient.js","sourceRoot":"","sources":["../../../../../packages/cloud/cloudtasks-client/src/TaskProxyClient.ts"],"names":[],"mappings":";;;;AAAA,yCAAmC;AACnC,oDAY8B;AAC9B,0DAGiC;AACjC,2CAAqE;AACr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AAC,CAAA;IACnB,mBAAA,IAAA,kBAAM,EAAC,oCAAqB,CAAC,CAAA;6CADiB,uBAAW;QACD,oCAAqB;GARzE,eAAe,CAkH3B;AAED;;;;;;;GAOG;AACH,gGAAgG;AACnF,QAAA,0BAA0B,GAAG,MAAM,CAAC,GAAG,CAAC,2BAA2B,CAAC,CAAC","sourcesContent":["import { inject } from 'inversify';\nimport {\n isApiPath,\n getApiPath,\n getEndpoints,\n getAuthMode,\n getQueueName,\n assertPubSubConventions,\n assertEveryEndpointHasAuthMode,\n AuthMode,\n LogManager,\n LogApiCall,\n ApiMethodInfo,\n} from '@webpieces/core-util';\nimport {\n RequestContextHeaders,\n provideFrameworkTransient,\n} from '@webpieces/core-context';\nimport { TaskInvoker, TaskRequest, ScheduleInfo } from './TaskTypes';\nimport { currentScheduleFrame } from './ScheduleContext';\nimport { ApiPrototype, TaskClientConfig } from './TaskClientConfig';\n\nconst log = LogManager.getLogger('TaskProxyClient');\n\n/** Per-endpoint routing plan resolved once from the contract's decorators. */\nclass EndpointPlan {\n path: string;\n queueName: string;\n authMode: AuthMode;\n\n constructor(path: string, queueName: string, authMode: AuthMode) {\n this.path = path;\n this.queueName = queueName;\n this.authMode = authMode;\n }\n}\n\n/**\n * TaskProxyClient - the enqueue engine behind one @PubSub API contract's client proxy.\n *\n * The fire-and-forget twin of http-client-core's ProxyClient, and TWO-PHASE for the same reason:\n * its COLLABORATORS (invoker, headers) come from the container, while the PER-CLIENT state (which\n * contract, which target) arrives on {@link init}. That is what lets {@link ClientCloudTasksFactory}\n * hold a `Provider<TaskProxyClient>` and hand out a fresh, independently-configured client per\n * contract.\n *\n * Calling an endpoint ENQUEUES a task (it does not call remotely); the task is later delivered to\n * the same endpoint's controller through the full server filter chain.\n *\n * It owns:\n * - @ApiPath / @PubSub convention validation + the endpoint plans from the contract's decorators\n * - Resolving the callee's base URL from svcName (ClientRegistry override, else GCP derivation)\n * - Context propagation onto the task headers (a credential is never a context key, so none can ride along)\n * - Handing a fully-built TaskRequest to the bound {@link TaskInvoker}\n */\n@provideFrameworkTransient()\nexport class TaskProxyClient {\n // Assigned by init(), which the factory calls immediately after construction.\n private plans!: Map<string, EndpointPlan>;\n private apiName!: string;\n private config!: TaskClientConfig;\n\n constructor(\n @inject(TaskInvoker) private readonly invoker: TaskInvoker,\n @inject(RequestContextHeaders) private readonly headers: RequestContextHeaders,\n ) {}\n\n /** Bind this client to one @PubSub contract + target. */\n init(apiClass: ApiPrototype<object>, config: TaskClientConfig): void {\n if (!isApiPath(apiClass)) {\n throw new Error(`Class ${apiClass.name || 'Unknown'} must be decorated with @ApiPath()`);\n }\n assertPubSubConventions(apiClass);\n assertEveryEndpointHasAuthMode(apiClass);\n\n this.config = config;\n this.apiName = apiClass.name || 'UnknownApi';\n this.plans = this.buildPlans(apiClass);\n }\n\n /** Check whether the contract declares a @PubSub endpoint with this method name. */\n hasEndpoint(methodName: string): boolean {\n return this.plans.has(methodName);\n }\n\n /**\n * Enqueue one task for the named endpoint. Must run inside a CloudTaskScheduler lambda\n * (which supplies the ScheduleInfo) within an active RequestContext, e.g.:\n * scheduler.addToQueue(() => taskClient.foo(req), { dedupName });\n */\n // webpieces-disable no-any-unknown -- the request DTO's type is erased at the proxy boundary\n async enqueue(methodName: string, requestDto: unknown): Promise<void> {\n const plan = this.plans.get(methodName);\n if (!plan) {\n throw new Error(`No @PubSub endpoint '${methodName}' on ${this.apiName}`);\n }\n\n const frame = currentScheduleFrame();\n if (!frame) {\n throw new Error(\n 'Cloud task enqueue must run inside a CloudTaskScheduler lambda, e.g. ' +\n 'scheduler.addToQueue(() => taskClient.method(req), { dedupName }).',\n );\n }\n\n // Route through LogApiCall exactly like ProxyClient does for http. TaskProxyClient.enqueue is\n // the ONE seam above BOTH GcpTaskInvoker (prod) and InMemoryTaskInvoker (localhost) — whichever\n // TaskInvoker is bound, this method sits above it — so the enqueue edge gets structured\n // `jsonPayload.api.*` logging (and, once recording is unified at LogApiCall, is recorded)\n // uniformly, without touching either invoker impl.\n const info = new ApiMethodInfo('client', this.apiName, methodName);\n await LogApiCall.execute(info, requestDto, async () => {\n // Resolved lazily (not at client construction) so building a client stays synchronous.\n // Every metadata read beneath resolveUrl is memoized process-wide, so only the first\n // enqueue in the process pays a lookup.\n const targetUrl = await this.config.resolveUrl();\n\n const request = new TaskRequest(\n targetUrl,\n plan.path,\n plan.queueName,\n requestDto,\n this.buildContextHeaders(),\n plan.authMode,\n frame.info ?? new ScheduleInfo(),\n );\n\n // svcName, not the URL, is the stable name across demo/qa/prod.\n log.debug(`enqueue task ${plan.queueName} -> ${this.config.svcName}${plan.path}`);\n frame.jobRef = await this.invoker.enqueue(request);\n\n // Fire-and-forget: the enqueue ack is not a meaningful response. Return a non-null value so\n // LogApiCall's null-response guard passes; a recorded test asserts the enqueued REQUEST\n // (payload), never this ack.\n return frame.jobRef ?? { enqueued: true };\n });\n }\n\n /** Endpoint name -> its resolved path / queue / auth mode, read once from the decorators. */\n private buildPlans(apiClass: ApiPrototype<object>): Map<string, EndpointPlan> {\n const basePath = getApiPath(apiClass) ?? '';\n const endpoints = getEndpoints(apiClass) ?? {};\n const plans = new Map<string, EndpointPlan>();\n\n for (const methodName of Object.keys(endpoints)) {\n const authMode = getAuthMode(apiClass, methodName);\n if (!authMode) {\n throw new Error(`Endpoint '${methodName}' on ${this.apiName} has no auth mode`);\n }\n const plan = new EndpointPlan(\n basePath + endpoints[methodName],\n getQueueName(apiClass, methodName),\n authMode,\n );\n plans.set(methodName, plan);\n }\n return plans;\n }\n\n /**\n * Every transferred context key (txId/requestId/tenant…), request-id chained.\n * Throws if there is no active RequestContext — an enqueue with no trace is a bug.\n *\n * No credential can appear here: `authorization` is read off the inbound HttpRequest and is not\n * a ContextKey, so it never enters the RequestContext to be transferred. The invoker mints the\n * task's own delivery auth per the endpoint's @AuthOidc / @AuthSharedSecret mode.\n */\n private buildContextHeaders(): Map<string, string> {\n return this.headers.buildOutboundHeaders();\n }\n}\n\n/**\n * DI token for the `Provider<TaskProxyClient>` that hands out enqueue clients — one per @PubSub\n * contract. `Provider<T>` is erased at runtime, so it cannot be its own token; this Symbol names T.\n *\n * Because TaskProxyClient is bound TRANSIENT, every `get()` constructs a new one. (Were it bound\n * `@provideFrameworkSingleton`, the very same Provider would hand back one lazily-created instance\n * instead — the provider caches nothing, so the target's scope decides.)\n */\n// webpieces-disable no-symbol-di-tokens -- Provider<T> is erased at runtime; the Symbol names T\nexport const TASK_PROXY_CLIENT_PROVIDER = Symbol.for('Provider<TaskProxyClient>');\n"]}