@geekmidas/constructs 10.0.0-alpha.83 → 10.0.0-alpha.85
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/dist/{Endpoint-ZJhv68qq.mjs → Endpoint-BG4UJ9oA.mjs} +8 -2
- package/dist/Endpoint-BG4UJ9oA.mjs.map +1 -0
- package/dist/{Endpoint-Ba1PiyuJ.cjs → Endpoint-BoUg8ocM.cjs} +8 -2
- package/dist/Endpoint-BoUg8ocM.cjs.map +1 -0
- package/dist/{Endpoint-DJZkADYh.d.cts → Endpoint-C4PZn_mD.d.cts} +11 -3
- package/dist/Endpoint-C4PZn_mD.d.cts.map +1 -0
- package/dist/{Endpoint-hcHSFhda.d.mts → Endpoint-ViSuXwMB.d.mts} +11 -3
- package/dist/Endpoint-ViSuXwMB.d.mts.map +1 -0
- package/dist/{EndpointFactory-C3QvXMk6.mjs → EndpointFactory-BDtsrEvJ.mjs} +18 -3
- package/dist/EndpointFactory-BDtsrEvJ.mjs.map +1 -0
- package/dist/{EndpointFactory-B5siFRcO.d.mts → EndpointFactory-CLmsBr1G.d.mts} +15 -2
- package/dist/EndpointFactory-CLmsBr1G.d.mts.map +1 -0
- package/dist/{EndpointFactory-BkYuVg8W.d.cts → EndpointFactory-CLnJ2GQ8.d.cts} +15 -2
- package/dist/EndpointFactory-CLnJ2GQ8.d.cts.map +1 -0
- package/dist/{EndpointFactory-B_x2fXWQ.cjs → EndpointFactory-DJ7gXLpR.cjs} +18 -3
- package/dist/EndpointFactory-DJ7gXLpR.cjs.map +1 -0
- package/dist/{HonoEndpointAdaptor-chgcjPmg.mjs → HonoEndpointAdaptor-PtPlbeKY.mjs} +2 -2
- package/dist/{HonoEndpointAdaptor-chgcjPmg.mjs.map → HonoEndpointAdaptor-PtPlbeKY.mjs.map} +1 -1
- package/dist/{HonoEndpointAdaptor-0yLvYunI.cjs → HonoEndpointAdaptor-zVzVLJEO.cjs} +2 -2
- package/dist/{HonoEndpointAdaptor-0yLvYunI.cjs.map → HonoEndpointAdaptor-zVzVLJEO.cjs.map} +1 -1
- package/dist/adaptors/aws.cjs +2 -2
- package/dist/adaptors/aws.cjs.map +1 -1
- package/dist/adaptors/aws.d.cts +2 -2
- package/dist/adaptors/aws.d.mts +2 -2
- package/dist/adaptors/aws.mjs +2 -2
- package/dist/adaptors/aws.mjs.map +1 -1
- package/dist/adaptors/hono.cjs +1 -1
- package/dist/adaptors/hono.d.cts +1 -1
- package/dist/adaptors/hono.d.mts +1 -1
- package/dist/adaptors/hono.mjs +1 -1
- package/dist/adaptors/testing.cjs +3 -3
- package/dist/adaptors/testing.d.cts +2 -2
- package/dist/adaptors/testing.d.mts +2 -2
- package/dist/adaptors/testing.mjs +3 -3
- package/dist/{auth-XtDcvQxV.d.mts → auth-CYFghDZw.d.mts} +23 -4
- package/dist/auth-CYFghDZw.d.mts.map +1 -0
- package/dist/{auth-CuCozjsh.d.cts → auth-CwYlcogd.d.cts} +23 -4
- package/dist/auth-CwYlcogd.d.cts.map +1 -0
- package/dist/auth.cjs +70 -10
- package/dist/auth.cjs.map +1 -1
- package/dist/auth.d.cts +2 -2
- package/dist/auth.d.mts +2 -2
- package/dist/auth.mjs +71 -12
- package/dist/auth.mjs.map +1 -1
- package/dist/database/kysely.cjs +1 -1
- package/dist/database/kysely.d.cts +1 -1
- package/dist/database/kysely.d.mts +1 -1
- package/dist/database/kysely.mjs +1 -1
- package/dist/endpoints/index.cjs +2 -2
- package/dist/endpoints/index.d.cts +2 -2
- package/dist/endpoints/index.d.mts +2 -2
- package/dist/endpoints/index.mjs +2 -2
- package/dist/external-api.cjs +1 -1
- package/dist/external-api.mjs +1 -1
- package/dist/index.d.cts +1 -1
- package/dist/index.d.mts +1 -1
- package/dist/{kysely-DN88k0gD.mjs → kysely-Bii4l6eP.mjs} +19 -7
- package/dist/kysely-Bii4l6eP.mjs.map +1 -0
- package/dist/{kysely-H7L1YDgE.cjs → kysely-CO_Dk43W.cjs} +18 -6
- package/dist/kysely-CO_Dk43W.cjs.map +1 -0
- package/dist/{kysely-BEm5sDlU.d.cts → kysely-D0bpzgPs.d.cts} +4 -2
- package/dist/kysely-D0bpzgPs.d.cts.map +1 -0
- package/dist/{kysely-CjuvdXEV.d.mts → kysely-DUqC3Ie0.d.mts} +4 -2
- package/dist/kysely-DUqC3Ie0.d.mts.map +1 -0
- package/dist/{telemetry-DGcFlVpB.d.cts → lambdaTelemetry-8vnmVZQ5.d.cts} +2 -2
- package/dist/lambdaTelemetry-8vnmVZQ5.d.cts.map +1 -0
- package/dist/{telemetry-DGcFlVpB.d.mts → lambdaTelemetry-8vnmVZQ5.d.mts} +2 -2
- package/dist/lambdaTelemetry-8vnmVZQ5.d.mts.map +1 -0
- package/dist/rest-api.cjs +5 -1
- package/dist/rest-api.cjs.map +1 -1
- package/dist/rest-api.d.cts +15 -2
- package/dist/rest-api.d.cts.map +1 -1
- package/dist/rest-api.d.mts +15 -2
- package/dist/rest-api.d.mts.map +1 -1
- package/dist/rest-api.mjs +5 -1
- package/dist/rest-api.mjs.map +1 -1
- package/dist/site.cjs +1 -0
- package/dist/site.cjs.map +1 -1
- package/dist/site.d.cts +8 -0
- package/dist/site.d.cts.map +1 -1
- package/dist/site.d.mts +8 -0
- package/dist/site.d.mts.map +1 -1
- package/dist/site.mjs +1 -0
- package/dist/site.mjs.map +1 -1
- package/dist/telemetry-B48RLjyk.d.cts +40 -0
- package/dist/telemetry-B48RLjyk.d.cts.map +1 -0
- package/dist/telemetry-DRtT1_0A.d.mts +40 -0
- package/dist/telemetry-DRtT1_0A.d.mts.map +1 -0
- package/dist/telemetry.cjs +56 -0
- package/dist/telemetry.cjs.map +1 -0
- package/dist/telemetry.d.cts +2 -0
- package/dist/telemetry.d.mts +2 -0
- package/dist/telemetry.mjs +55 -0
- package/dist/telemetry.mjs.map +1 -0
- package/dist/{tracing-DbcPuhEy.mjs → tracing-CxaZ98IB.mjs} +28 -5
- package/dist/tracing-CxaZ98IB.mjs.map +1 -0
- package/dist/{tracing-3PpqRX07.cjs → tracing-DPMidF_r.cjs} +32 -3
- package/dist/tracing-DPMidF_r.cjs.map +1 -0
- package/dist/worker.cjs +1 -0
- package/dist/worker.cjs.map +1 -1
- package/dist/worker.d.cts +7 -0
- package/dist/worker.d.cts.map +1 -1
- package/dist/worker.d.mts +7 -0
- package/dist/worker.d.mts.map +1 -1
- package/dist/worker.mjs +1 -0
- package/dist/worker.mjs.map +1 -1
- package/package.json +41 -31
- package/dist/Endpoint-Ba1PiyuJ.cjs.map +0 -1
- package/dist/Endpoint-DJZkADYh.d.cts.map +0 -1
- package/dist/Endpoint-ZJhv68qq.mjs.map +0 -1
- package/dist/Endpoint-hcHSFhda.d.mts.map +0 -1
- package/dist/EndpointFactory-B5siFRcO.d.mts.map +0 -1
- package/dist/EndpointFactory-B_x2fXWQ.cjs.map +0 -1
- package/dist/EndpointFactory-BkYuVg8W.d.cts.map +0 -1
- package/dist/EndpointFactory-C3QvXMk6.mjs.map +0 -1
- package/dist/auth-CuCozjsh.d.cts.map +0 -1
- package/dist/auth-XtDcvQxV.d.mts.map +0 -1
- package/dist/kysely-BEm5sDlU.d.cts.map +0 -1
- package/dist/kysely-CjuvdXEV.d.mts.map +0 -1
- package/dist/kysely-DN88k0gD.mjs.map +0 -1
- package/dist/kysely-H7L1YDgE.cjs.map +0 -1
- package/dist/telemetry-DGcFlVpB.d.cts.map +0 -1
- package/dist/telemetry-DGcFlVpB.d.mts.map +0 -1
- package/dist/tracing-3PpqRX07.cjs.map +0 -1
- package/dist/tracing-DbcPuhEy.mjs.map +0 -1
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
|
2
|
+
let _geekmidas_manifest = require("@geekmidas/manifest");
|
|
3
|
+
//#region src/telemetry.ts
|
|
4
|
+
/**
|
|
5
|
+
* `Telemetry` — what an application emits, declared.
|
|
6
|
+
*
|
|
7
|
+
* Traces and logs over OTLP, from every process that is given it. The
|
|
8
|
+
* construct says *what* is emitted — which requests are noise, which
|
|
9
|
+
* attributes every span carries — and never where it goes or how much of it:
|
|
10
|
+
* the provider and the sample rate are the deploy's, per stage
|
|
11
|
+
* (`deploy.telemetry` in `gkm.config.ts`), and locally `gkm dev` runs
|
|
12
|
+
* OpenObserve and sends everything there.
|
|
13
|
+
*
|
|
14
|
+
* ```ts
|
|
15
|
+
* export const telemetry = new Telemetry('Telemetry', {
|
|
16
|
+
* ignorePaths: ['/health', '/ready'],
|
|
17
|
+
* attributes: { 'service.namespace': 'shop' },
|
|
18
|
+
* });
|
|
19
|
+
*
|
|
20
|
+
* // passed like the logger: a fact about the process
|
|
21
|
+
* new RestApi('Api', { path: 'apps/api', defaultAuthorizer: 'none', telemetry });
|
|
22
|
+
* new Worker('Jobs', { logger, telemetry });
|
|
23
|
+
* ```
|
|
24
|
+
*
|
|
25
|
+
* Each process given it is an edge to this node, so the `OTEL_*` keys it
|
|
26
|
+
* provides reach exactly those processes, and the build of each one fails
|
|
27
|
+
* without the OpenTelemetry packages it needs.
|
|
28
|
+
*/
|
|
29
|
+
var Telemetry = class {
|
|
30
|
+
id;
|
|
31
|
+
ignorePaths;
|
|
32
|
+
attributes;
|
|
33
|
+
constructor(id, config = {}) {
|
|
34
|
+
this.id = (0, _geekmidas_manifest.canonicalId)(id);
|
|
35
|
+
this.ignorePaths = [...config.ignorePaths ?? []];
|
|
36
|
+
this.attributes = { ...config.attributes };
|
|
37
|
+
}
|
|
38
|
+
/**
|
|
39
|
+
* One node, providing OpenTelemetry's own variables. No address of its
|
|
40
|
+
* own: where the telemetry goes is the deploy's, so it is resolved by the
|
|
41
|
+
* target for each stage, never declared here.
|
|
42
|
+
*/
|
|
43
|
+
declare() {
|
|
44
|
+
return [{
|
|
45
|
+
kind: "telemetry",
|
|
46
|
+
id: this.id,
|
|
47
|
+
...this.ignorePaths.length ? { ignorePaths: this.ignorePaths } : {},
|
|
48
|
+
...Object.keys(this.attributes).length ? { attributes: this.attributes } : {},
|
|
49
|
+
provides: [..._geekmidas_manifest.TELEMETRY_KEYS]
|
|
50
|
+
}];
|
|
51
|
+
}
|
|
52
|
+
};
|
|
53
|
+
//#endregion
|
|
54
|
+
exports.Telemetry = Telemetry;
|
|
55
|
+
|
|
56
|
+
//# sourceMappingURL=telemetry.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"telemetry.cjs","names":["canonicalId","TELEMETRY_KEYS"],"sources":["../src/telemetry.ts"],"sourcesContent":["/**\n * `Telemetry` — what an application emits, declared.\n *\n * Traces and logs over OTLP, from every process that is given it. The\n * construct says *what* is emitted — which requests are noise, which\n * attributes every span carries — and never where it goes or how much of it:\n * the provider and the sample rate are the deploy's, per stage\n * (`deploy.telemetry` in `gkm.config.ts`), and locally `gkm dev` runs\n * OpenObserve and sends everything there.\n *\n * ```ts\n * export const telemetry = new Telemetry('Telemetry', {\n * ignorePaths: ['/health', '/ready'],\n * attributes: { 'service.namespace': 'shop' },\n * });\n *\n * // passed like the logger: a fact about the process\n * new RestApi('Api', { path: 'apps/api', defaultAuthorizer: 'none', telemetry });\n * new Worker('Jobs', { logger, telemetry });\n * ```\n *\n * Each process given it is an edge to this node, so the `OTEL_*` keys it\n * provides reach exactly those processes, and the build of each one fails\n * without the OpenTelemetry packages it needs.\n */\n\nimport {\n\ttype ConstructName,\n\tcanonicalId,\n\ttype Declaration,\n\tTELEMETRY_KEYS,\n} from '@geekmidas/manifest';\nimport type { Declarable } from './construct-interface';\n\nexport interface TelemetryConfig {\n\t/**\n\t * Request paths no span is recorded for, on every surface that uses this —\n\t * health checks, by default the only noise worth naming. A trailing `*`\n\t * matches a prefix. One route on one surface says so itself:\n\t * `.telemetry({ ignore: true })`.\n\t */\n\tignorePaths?: readonly string[];\n\t/**\n\t * Resource attributes every span and log record carries —\n\t * `{ 'service.namespace': 'shop' }`. The service's name is not one of\n\t * them: it is the app's, set per process.\n\t */\n\tattributes?: Readonly<Record<string, string>>;\n}\n\nexport class Telemetry<TName extends string = string>\n\timplements Declarable<TName>\n{\n\treadonly id: TName;\n\treadonly ignorePaths: readonly string[];\n\treadonly attributes: Readonly<Record<string, string>>;\n\n\tconstructor(id: ConstructName<TName>, config: TelemetryConfig = {}) {\n\t\tthis.id = canonicalId(id as string) as TName;\n\t\tthis.ignorePaths = [...(config.ignorePaths ?? [])];\n\t\tthis.attributes = { ...config.attributes };\n\t}\n\n\t/**\n\t * One node, providing OpenTelemetry's own variables. No address of its\n\t * own: where the telemetry goes is the deploy's, so it is resolved by the\n\t * target for each stage, never declared here.\n\t */\n\tdeclare(): Declaration[] {\n\t\treturn [\n\t\t\t{\n\t\t\t\tkind: 'telemetry',\n\t\t\t\tid: this.id,\n\t\t\t\t...(this.ignorePaths.length ? { ignorePaths: this.ignorePaths } : {}),\n\t\t\t\t...(Object.keys(this.attributes).length\n\t\t\t\t\t? { attributes: this.attributes }\n\t\t\t\t\t: {}),\n\t\t\t\tprovides: [...TELEMETRY_KEYS],\n\t\t\t},\n\t\t];\n\t}\n}\n\n/** Per-route telemetry, on the endpoint builder — `.telemetry({ ignore: true })`. */\nexport interface EndpointTelemetry {\n\t/** Record no span for this route. */\n\tignore?: boolean;\n\t/** Attributes this route's request span carries. */\n\tattributes?: Readonly<Record<string, string>>;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAkDA,IAAa,YAAb,MAEA;CACC;CACA;CACA;CAEA,YAAY,IAA0B,SAA0B,CAAC,GAAG;EACnE,KAAK,MAAA,GAAKA,oBAAAA,YAAAA,CAAY,EAAY;EAClC,KAAK,cAAc,CAAC,GAAI,OAAO,eAAe,CAAC,CAAE;EACjD,KAAK,aAAa,EAAE,GAAG,OAAO,WAAW;CAC1C;;;;;;CAOA,UAAyB;EACxB,OAAO,CACN;GACC,MAAM;GACN,IAAI,KAAK;GACT,GAAI,KAAK,YAAY,SAAS,EAAE,aAAa,KAAK,YAAY,IAAI,CAAC;GACnE,GAAI,OAAO,KAAK,KAAK,UAAU,CAAC,CAAC,SAC9B,EAAE,YAAY,KAAK,WAAW,IAC9B,CAAC;GACJ,UAAU,CAAC,GAAGC,oBAAAA,cAAc;EAC7B,CACD;CACD;AACD"}
|
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
import { TELEMETRY_KEYS, canonicalId } from "@geekmidas/manifest";
|
|
2
|
+
//#region src/telemetry.ts
|
|
3
|
+
/**
|
|
4
|
+
* `Telemetry` — what an application emits, declared.
|
|
5
|
+
*
|
|
6
|
+
* Traces and logs over OTLP, from every process that is given it. The
|
|
7
|
+
* construct says *what* is emitted — which requests are noise, which
|
|
8
|
+
* attributes every span carries — and never where it goes or how much of it:
|
|
9
|
+
* the provider and the sample rate are the deploy's, per stage
|
|
10
|
+
* (`deploy.telemetry` in `gkm.config.ts`), and locally `gkm dev` runs
|
|
11
|
+
* OpenObserve and sends everything there.
|
|
12
|
+
*
|
|
13
|
+
* ```ts
|
|
14
|
+
* export const telemetry = new Telemetry('Telemetry', {
|
|
15
|
+
* ignorePaths: ['/health', '/ready'],
|
|
16
|
+
* attributes: { 'service.namespace': 'shop' },
|
|
17
|
+
* });
|
|
18
|
+
*
|
|
19
|
+
* // passed like the logger: a fact about the process
|
|
20
|
+
* new RestApi('Api', { path: 'apps/api', defaultAuthorizer: 'none', telemetry });
|
|
21
|
+
* new Worker('Jobs', { logger, telemetry });
|
|
22
|
+
* ```
|
|
23
|
+
*
|
|
24
|
+
* Each process given it is an edge to this node, so the `OTEL_*` keys it
|
|
25
|
+
* provides reach exactly those processes, and the build of each one fails
|
|
26
|
+
* without the OpenTelemetry packages it needs.
|
|
27
|
+
*/
|
|
28
|
+
var Telemetry = class {
|
|
29
|
+
id;
|
|
30
|
+
ignorePaths;
|
|
31
|
+
attributes;
|
|
32
|
+
constructor(id, config = {}) {
|
|
33
|
+
this.id = canonicalId(id);
|
|
34
|
+
this.ignorePaths = [...config.ignorePaths ?? []];
|
|
35
|
+
this.attributes = { ...config.attributes };
|
|
36
|
+
}
|
|
37
|
+
/**
|
|
38
|
+
* One node, providing OpenTelemetry's own variables. No address of its
|
|
39
|
+
* own: where the telemetry goes is the deploy's, so it is resolved by the
|
|
40
|
+
* target for each stage, never declared here.
|
|
41
|
+
*/
|
|
42
|
+
declare() {
|
|
43
|
+
return [{
|
|
44
|
+
kind: "telemetry",
|
|
45
|
+
id: this.id,
|
|
46
|
+
...this.ignorePaths.length ? { ignorePaths: this.ignorePaths } : {},
|
|
47
|
+
...Object.keys(this.attributes).length ? { attributes: this.attributes } : {},
|
|
48
|
+
provides: [...TELEMETRY_KEYS]
|
|
49
|
+
}];
|
|
50
|
+
}
|
|
51
|
+
};
|
|
52
|
+
//#endregion
|
|
53
|
+
export { Telemetry };
|
|
54
|
+
|
|
55
|
+
//# sourceMappingURL=telemetry.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"telemetry.mjs","names":[],"sources":["../src/telemetry.ts"],"sourcesContent":["/**\n * `Telemetry` — what an application emits, declared.\n *\n * Traces and logs over OTLP, from every process that is given it. The\n * construct says *what* is emitted — which requests are noise, which\n * attributes every span carries — and never where it goes or how much of it:\n * the provider and the sample rate are the deploy's, per stage\n * (`deploy.telemetry` in `gkm.config.ts`), and locally `gkm dev` runs\n * OpenObserve and sends everything there.\n *\n * ```ts\n * export const telemetry = new Telemetry('Telemetry', {\n * ignorePaths: ['/health', '/ready'],\n * attributes: { 'service.namespace': 'shop' },\n * });\n *\n * // passed like the logger: a fact about the process\n * new RestApi('Api', { path: 'apps/api', defaultAuthorizer: 'none', telemetry });\n * new Worker('Jobs', { logger, telemetry });\n * ```\n *\n * Each process given it is an edge to this node, so the `OTEL_*` keys it\n * provides reach exactly those processes, and the build of each one fails\n * without the OpenTelemetry packages it needs.\n */\n\nimport {\n\ttype ConstructName,\n\tcanonicalId,\n\ttype Declaration,\n\tTELEMETRY_KEYS,\n} from '@geekmidas/manifest';\nimport type { Declarable } from './construct-interface';\n\nexport interface TelemetryConfig {\n\t/**\n\t * Request paths no span is recorded for, on every surface that uses this —\n\t * health checks, by default the only noise worth naming. A trailing `*`\n\t * matches a prefix. One route on one surface says so itself:\n\t * `.telemetry({ ignore: true })`.\n\t */\n\tignorePaths?: readonly string[];\n\t/**\n\t * Resource attributes every span and log record carries —\n\t * `{ 'service.namespace': 'shop' }`. The service's name is not one of\n\t * them: it is the app's, set per process.\n\t */\n\tattributes?: Readonly<Record<string, string>>;\n}\n\nexport class Telemetry<TName extends string = string>\n\timplements Declarable<TName>\n{\n\treadonly id: TName;\n\treadonly ignorePaths: readonly string[];\n\treadonly attributes: Readonly<Record<string, string>>;\n\n\tconstructor(id: ConstructName<TName>, config: TelemetryConfig = {}) {\n\t\tthis.id = canonicalId(id as string) as TName;\n\t\tthis.ignorePaths = [...(config.ignorePaths ?? [])];\n\t\tthis.attributes = { ...config.attributes };\n\t}\n\n\t/**\n\t * One node, providing OpenTelemetry's own variables. No address of its\n\t * own: where the telemetry goes is the deploy's, so it is resolved by the\n\t * target for each stage, never declared here.\n\t */\n\tdeclare(): Declaration[] {\n\t\treturn [\n\t\t\t{\n\t\t\t\tkind: 'telemetry',\n\t\t\t\tid: this.id,\n\t\t\t\t...(this.ignorePaths.length ? { ignorePaths: this.ignorePaths } : {}),\n\t\t\t\t...(Object.keys(this.attributes).length\n\t\t\t\t\t? { attributes: this.attributes }\n\t\t\t\t\t: {}),\n\t\t\t\tprovides: [...TELEMETRY_KEYS],\n\t\t\t},\n\t\t];\n\t}\n}\n\n/** Per-route telemetry, on the endpoint builder — `.telemetry({ ignore: true })`. */\nexport interface EndpointTelemetry {\n\t/** Record no span for this route. */\n\tignore?: boolean;\n\t/** Attributes this route's request span carries. */\n\tattributes?: Readonly<Record<string, string>>;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;AAkDA,IAAa,YAAb,MAEA;CACC;CACA;CACA;CAEA,YAAY,IAA0B,SAA0B,CAAC,GAAG;EACnE,KAAK,KAAK,YAAY,EAAY;EAClC,KAAK,cAAc,CAAC,GAAI,OAAO,eAAe,CAAC,CAAE;EACjD,KAAK,aAAa,EAAE,GAAG,OAAO,WAAW;CAC1C;;;;;;CAOA,UAAyB;EACxB,OAAO,CACN;GACC,MAAM;GACN,IAAI,KAAK;GACT,GAAI,KAAK,YAAY,SAAS,EAAE,aAAa,KAAK,YAAY,IAAI,CAAC;GACnE,GAAI,OAAO,KAAK,KAAK,UAAU,CAAC,CAAC,SAC9B,EAAE,YAAY,KAAK,WAAW,IAC9B,CAAC;GACJ,UAAU,CAAC,GAAG,cAAc;EAC7B,CACD;CACD;AACD"}
|
|
@@ -1,10 +1,12 @@
|
|
|
1
|
+
import { channel } from "node:diagnostics_channel";
|
|
1
2
|
import { carrierFromAttributes } from "@geekmidas/events";
|
|
2
|
-
import { SpanKind, SpanStatusCode, trace } from "@opentelemetry/api";
|
|
3
|
+
import { SpanKind, SpanStatusCode, context, propagation, trace } from "@opentelemetry/api";
|
|
3
4
|
//#region src/tracing.ts
|
|
4
5
|
/**
|
|
5
6
|
* Where the constructs meet OpenTelemetry, beyond the spans `@geekmidas/events`
|
|
6
|
-
* starts for the brokers: the trace context in a Lambda's records,
|
|
7
|
-
*
|
|
7
|
+
* starts for the brokers: the trace context in a Lambda's records, the spans
|
|
8
|
+
* around an `ExternalApi`'s client, and the context a call to a sibling
|
|
9
|
+
* service carries.
|
|
8
10
|
*
|
|
9
11
|
* Everything goes through the global API, so without a registered provider
|
|
10
12
|
* none of it records anything.
|
|
@@ -81,7 +83,28 @@ function callTraced(api, method, attributes, call) {
|
|
|
81
83
|
return result;
|
|
82
84
|
});
|
|
83
85
|
}
|
|
86
|
+
/**
|
|
87
|
+
* Where an instrumentation of `fetch` hears of each request — undici's own
|
|
88
|
+
* diagnostics channel, which OpenTelemetry's undici instrumentation (and every
|
|
89
|
+
* APM built on it) subscribes to.
|
|
90
|
+
*/
|
|
91
|
+
const FETCH_REQUESTS = channel("undici:request:create");
|
|
92
|
+
/**
|
|
93
|
+
* The active trace context, written into `headers` for a call this process
|
|
94
|
+
* makes to one of its own services — the auth server's session check — so the
|
|
95
|
+
* callee's span joins the caller's trace.
|
|
96
|
+
*
|
|
97
|
+
* Through the global propagator, so it is a no-op without one. And not at all
|
|
98
|
+
* when a `fetch` instrumentation is listening: that opens the request's own
|
|
99
|
+
* CLIENT span and writes its `traceparent` by appending a header, so a second
|
|
100
|
+
* one here would reach the callee as two values joined — `a, b` — which no
|
|
101
|
+
* propagator reads, and the trace would break instead of joining.
|
|
102
|
+
*/
|
|
103
|
+
function injectTraceContext(headers) {
|
|
104
|
+
if (FETCH_REQUESTS.hasSubscribers) return;
|
|
105
|
+
propagation.inject(context.active(), headers, { set: (carrier, key, value) => carrier.set(key, value) });
|
|
106
|
+
}
|
|
84
107
|
//#endregion
|
|
85
|
-
export {
|
|
108
|
+
export { recordCarrier as n, traceClient as r, injectTraceContext as t };
|
|
86
109
|
|
|
87
|
-
//# sourceMappingURL=tracing-
|
|
110
|
+
//# sourceMappingURL=tracing-CxaZ98IB.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"tracing-CxaZ98IB.mjs","names":[],"sources":["../src/tracing.ts"],"sourcesContent":["/**\n * Where the constructs meet OpenTelemetry, beyond the spans `@geekmidas/events`\n * starts for the brokers: the trace context in a Lambda's records, the spans\n * around an `ExternalApi`'s client, and the context a call to a sibling\n * service carries.\n *\n * Everything goes through the global API, so without a registered provider\n * none of it records anything.\n *\n * @module\n */\nimport { channel } from 'node:diagnostics_channel';\nimport { carrierFromAttributes, type TraceCarrier } from '@geekmidas/events';\nimport {\n\tcontext,\n\tpropagation,\n\tSpanKind,\n\tSpanStatusCode,\n\ttrace,\n} from '@opentelemetry/api';\n\n/**\n * The trace context a Lambda record carries: an SQS record's message\n * attributes, an SNS record's, or those of the SNS envelope an SQS\n * subscription delivers in its body.\n */\nexport function recordCarrier(record: unknown): TraceCarrier | undefined {\n\tconst r = record as {\n\t\tmessageAttributes?: Record<string, unknown>;\n\t\tbody?: string;\n\t\tSns?: { MessageAttributes?: Record<string, unknown> };\n\t};\n\tif (r?.Sns) return carrierFromAttributes(r.Sns.MessageAttributes);\n\n\tconst own = carrierFromAttributes(r?.messageAttributes);\n\tif (own || typeof r?.body !== 'string') return own;\n\ttry {\n\t\tconst body = JSON.parse(r.body);\n\t\treturn body?.Type === 'Notification'\n\t\t\t? carrierFromAttributes(body.MessageAttributes)\n\t\t\t: undefined;\n\t} catch {\n\t\treturn undefined;\n\t}\n}\n\n/**\n * `client`, with a span around each of its methods: `<api>.<method>`, carrying\n * the API's name. An outbound `fetch` the method makes is traced already, and\n * becomes this span's child, so the name is on the trace without anything\n * knowing which URL belongs to which API.\n *\n * Only the client's own methods: what they return is the client's business.\n * Methods are called on the client itself, never on the proxy, so private\n * fields keep working.\n */\nexport function traceClient<T>(\n\tapi: string,\n\tclient: T,\n\tattributes: Record<string, string> = {},\n): T {\n\tif (!client || (typeof client !== 'object' && typeof client !== 'function')) {\n\t\treturn client;\n\t}\n\tconst wrapped = new Map<PropertyKey, unknown>();\n\treturn new Proxy(client as object, {\n\t\tget(target, property, receiver) {\n\t\t\tconst value = Reflect.get(target, property, receiver);\n\t\t\tif (typeof value !== 'function' || typeof property === 'symbol') {\n\t\t\t\treturn value;\n\t\t\t}\n\t\t\tif (property === 'constructor' || property === 'then') return value;\n\n\t\t\tconst cached = wrapped.get(property);\n\t\t\tif (cached && (cached as { original?: unknown }).original === value) {\n\t\t\t\treturn cached;\n\t\t\t}\n\t\t\tconst traced = Object.assign(\n\t\t\t\t(...args: unknown[]) =>\n\t\t\t\t\tcallTraced(api, property, attributes, () =>\n\t\t\t\t\t\t(value as (...a: unknown[]) => unknown).apply(target, args),\n\t\t\t\t\t),\n\t\t\t\t{ original: value },\n\t\t\t);\n\t\t\twrapped.set(property, traced);\n\t\t\treturn traced;\n\t\t},\n\t}) as T;\n}\n\nfunction callTraced(\n\tapi: string,\n\tmethod: string,\n\tattributes: Record<string, string>,\n\tcall: () => unknown,\n): unknown {\n\treturn trace.getTracer('@geekmidas/constructs').startActiveSpan(\n\t\t`${api}.${method}`,\n\t\t{\n\t\t\tkind: SpanKind.INTERNAL,\n\t\t\tattributes: {\n\t\t\t\t'gkm.external_api.name': api,\n\t\t\t\t'gkm.external_api.method': method,\n\t\t\t\t...attributes,\n\t\t\t},\n\t\t},\n\t\t(span) => {\n\t\t\tconst fail = (error: unknown) => {\n\t\t\t\tif (error instanceof Error) span.recordException(error);\n\t\t\t\tspan.setStatus({ code: SpanStatusCode.ERROR });\n\t\t\t\tspan.end();\n\t\t\t};\n\t\t\tlet result: unknown;\n\t\t\ttry {\n\t\t\t\tresult = call();\n\t\t\t} catch (error) {\n\t\t\t\tfail(error);\n\t\t\t\tthrow error;\n\t\t\t}\n\t\t\t// Only a native promise is waited on, and the caller gets it back as\n\t\t\t// it was: a lazy thenable runs on `then`, and a promise subclass has\n\t\t\t// methods a chained promise would not.\n\t\t\tif (result instanceof Promise) {\n\t\t\t\tresult.then(\n\t\t\t\t\t() => span.end(),\n\t\t\t\t\t(error) => fail(error),\n\t\t\t\t);\n\t\t\t\treturn result;\n\t\t\t}\n\t\t\tspan.end();\n\t\t\treturn result;\n\t\t},\n\t);\n}\n\n/**\n * Where an instrumentation of `fetch` hears of each request — undici's own\n * diagnostics channel, which OpenTelemetry's undici instrumentation (and every\n * APM built on it) subscribes to.\n */\nconst FETCH_REQUESTS = channel('undici:request:create');\n\n/**\n * The active trace context, written into `headers` for a call this process\n * makes to one of its own services — the auth server's session check — so the\n * callee's span joins the caller's trace.\n *\n * Through the global propagator, so it is a no-op without one. And not at all\n * when a `fetch` instrumentation is listening: that opens the request's own\n * CLIENT span and writes its `traceparent` by appending a header, so a second\n * one here would reach the callee as two values joined — `a, b` — which no\n * propagator reads, and the trace would break instead of joining.\n */\nexport function injectTraceContext(headers: Headers): void {\n\tif (FETCH_REQUESTS.hasSubscribers) return;\n\tpropagation.inject(context.active(), headers, {\n\t\tset: (carrier, key, value) => carrier.set(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D,IACC,SAAS;EACT,MAAM,QAAQ,UAAmB;GAChC,IAAI,iBAAiB,OAAO,KAAK,gBAAgB,KAAK;GACtD,KAAK,UAAU,EAAE,MAAM,eAAe,MAAM,CAAC;GAC7C,KAAK,IAAI;EACV;EACA,IAAI;EACJ,IAAI;GACH,SAAS,KAAK;EACf,SAAS,OAAO;GACf,KAAK,KAAK;GACV,MAAM;EACP;EAIA,IAAI,kBAAkB,SAAS;GAC9B,OAAO,WACA,KAAK,IAAI,IACd,UAAU,KAAK,KAAK,CACtB;GACA,OAAO;EACR;EACA,KAAK,IAAI;EACT,OAAO;CACR,CACD;AACD;;;;;;AAOA,MAAM,iBAAiB,QAAQ,uBAAuB;;;;;;;;;;;;AAatD,SAAgB,mBAAmB,SAAwB;CAC1D,IAAI,eAAe,gBAAgB;CACnC,YAAY,OAAO,QAAQ,OAAO,GAAG,SAAS,EAC7C,MAAM,SAAS,KAAK,UAAU,QAAQ,IAAI,KAAK,KAAK,EACrD,CAAC;AACF"}
|
|
@@ -1,10 +1,12 @@
|
|
|
1
|
+
let node_diagnostics_channel = require("node:diagnostics_channel");
|
|
1
2
|
let _geekmidas_events = require("@geekmidas/events");
|
|
2
3
|
let _opentelemetry_api = require("@opentelemetry/api");
|
|
3
4
|
//#region src/tracing.ts
|
|
4
5
|
/**
|
|
5
6
|
* Where the constructs meet OpenTelemetry, beyond the spans `@geekmidas/events`
|
|
6
|
-
* starts for the brokers: the trace context in a Lambda's records,
|
|
7
|
-
*
|
|
7
|
+
* starts for the brokers: the trace context in a Lambda's records, the spans
|
|
8
|
+
* around an `ExternalApi`'s client, and the context a call to a sibling
|
|
9
|
+
* service carries.
|
|
8
10
|
*
|
|
9
11
|
* Everything goes through the global API, so without a registered provider
|
|
10
12
|
* none of it records anything.
|
|
@@ -81,7 +83,34 @@ function callTraced(api, method, attributes, call) {
|
|
|
81
83
|
return result;
|
|
82
84
|
});
|
|
83
85
|
}
|
|
86
|
+
/**
|
|
87
|
+
* Where an instrumentation of `fetch` hears of each request — undici's own
|
|
88
|
+
* diagnostics channel, which OpenTelemetry's undici instrumentation (and every
|
|
89
|
+
* APM built on it) subscribes to.
|
|
90
|
+
*/
|
|
91
|
+
const FETCH_REQUESTS = (0, node_diagnostics_channel.channel)("undici:request:create");
|
|
92
|
+
/**
|
|
93
|
+
* The active trace context, written into `headers` for a call this process
|
|
94
|
+
* makes to one of its own services — the auth server's session check — so the
|
|
95
|
+
* callee's span joins the caller's trace.
|
|
96
|
+
*
|
|
97
|
+
* Through the global propagator, so it is a no-op without one. And not at all
|
|
98
|
+
* when a `fetch` instrumentation is listening: that opens the request's own
|
|
99
|
+
* CLIENT span and writes its `traceparent` by appending a header, so a second
|
|
100
|
+
* one here would reach the callee as two values joined — `a, b` — which no
|
|
101
|
+
* propagator reads, and the trace would break instead of joining.
|
|
102
|
+
*/
|
|
103
|
+
function injectTraceContext(headers) {
|
|
104
|
+
if (FETCH_REQUESTS.hasSubscribers) return;
|
|
105
|
+
_opentelemetry_api.propagation.inject(_opentelemetry_api.context.active(), headers, { set: (carrier, key, value) => carrier.set(key, value) });
|
|
106
|
+
}
|
|
84
107
|
//#endregion
|
|
108
|
+
Object.defineProperty(exports, "injectTraceContext", {
|
|
109
|
+
enumerable: true,
|
|
110
|
+
get: function() {
|
|
111
|
+
return injectTraceContext;
|
|
112
|
+
}
|
|
113
|
+
});
|
|
85
114
|
Object.defineProperty(exports, "recordCarrier", {
|
|
86
115
|
enumerable: true,
|
|
87
116
|
get: function() {
|
|
@@ -95,4 +124,4 @@ Object.defineProperty(exports, "traceClient", {
|
|
|
95
124
|
}
|
|
96
125
|
});
|
|
97
126
|
|
|
98
|
-
//# sourceMappingURL=tracing-
|
|
127
|
+
//# sourceMappingURL=tracing-DPMidF_r.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"tracing-DPMidF_r.cjs","names":["carrierFromAttributes","trace","SpanKind","SpanStatusCode","channel","context"],"sources":["../src/tracing.ts"],"sourcesContent":["/**\n * Where the constructs meet OpenTelemetry, beyond the spans `@geekmidas/events`\n * starts for the brokers: the trace context in a Lambda's records, the spans\n * around an `ExternalApi`'s client, and the context a call to a sibling\n * service carries.\n *\n * Everything goes through the global API, so without a registered provider\n * none of it records anything.\n *\n * @module\n */\nimport { channel } from 'node:diagnostics_channel';\nimport { carrierFromAttributes, type TraceCarrier } from '@geekmidas/events';\nimport {\n\tcontext,\n\tpropagation,\n\tSpanKind,\n\tSpanStatusCode,\n\ttrace,\n} from '@opentelemetry/api';\n\n/**\n * The trace context a Lambda record carries: an SQS record's message\n * attributes, an SNS record's, or those of the SNS envelope an SQS\n * subscription delivers in its body.\n */\nexport function recordCarrier(record: unknown): TraceCarrier | undefined {\n\tconst r = record as {\n\t\tmessageAttributes?: Record<string, unknown>;\n\t\tbody?: string;\n\t\tSns?: { MessageAttributes?: Record<string, unknown> };\n\t};\n\tif (r?.Sns) return carrierFromAttributes(r.Sns.MessageAttributes);\n\n\tconst own = carrierFromAttributes(r?.messageAttributes);\n\tif (own || typeof r?.body !== 'string') return own;\n\ttry {\n\t\tconst body = JSON.parse(r.body);\n\t\treturn body?.Type === 'Notification'\n\t\t\t? carrierFromAttributes(body.MessageAttributes)\n\t\t\t: undefined;\n\t} catch {\n\t\treturn undefined;\n\t}\n}\n\n/**\n * `client`, with a span around each of its methods: `<api>.<method>`, carrying\n * the API's name. An outbound `fetch` the method makes is traced already, and\n * becomes this span's child, so the name is on the trace without anything\n * knowing which URL belongs to which API.\n *\n * Only the client's own methods: what they return is the client's business.\n * Methods are called on the client itself, never on the proxy, so private\n * fields keep working.\n */\nexport function traceClient<T>(\n\tapi: string,\n\tclient: T,\n\tattributes: Record<string, string> = {},\n): T {\n\tif (!client || (typeof client !== 'object' && typeof client !== 'function')) {\n\t\treturn client;\n\t}\n\tconst wrapped = new Map<PropertyKey, unknown>();\n\treturn new Proxy(client as object, {\n\t\tget(target, property, receiver) {\n\t\t\tconst value = Reflect.get(target, property, receiver);\n\t\t\tif (typeof value !== 'function' || typeof property === 'symbol') {\n\t\t\t\treturn value;\n\t\t\t}\n\t\t\tif (property === 'constructor' || property === 'then') return value;\n\n\t\t\tconst cached = wrapped.get(property);\n\t\t\tif (cached && (cached as { original?: unknown }).original === value) {\n\t\t\t\treturn cached;\n\t\t\t}\n\t\t\tconst traced = Object.assign(\n\t\t\t\t(...args: unknown[]) =>\n\t\t\t\t\tcallTraced(api, property, attributes, () =>\n\t\t\t\t\t\t(value as (...a: unknown[]) => unknown).apply(target, args),\n\t\t\t\t\t),\n\t\t\t\t{ original: value },\n\t\t\t);\n\t\t\twrapped.set(property, traced);\n\t\t\treturn traced;\n\t\t},\n\t}) as T;\n}\n\nfunction callTraced(\n\tapi: string,\n\tmethod: string,\n\tattributes: Record<string, string>,\n\tcall: () => unknown,\n): unknown {\n\treturn trace.getTracer('@geekmidas/constructs').startActiveSpan(\n\t\t`${api}.${method}`,\n\t\t{\n\t\t\tkind: SpanKind.INTERNAL,\n\t\t\tattributes: {\n\t\t\t\t'gkm.external_api.name': api,\n\t\t\t\t'gkm.external_api.method': method,\n\t\t\t\t...attributes,\n\t\t\t},\n\t\t},\n\t\t(span) => {\n\t\t\tconst fail = (error: unknown) => {\n\t\t\t\tif (error instanceof Error) span.recordException(error);\n\t\t\t\tspan.setStatus({ code: SpanStatusCode.ERROR });\n\t\t\t\tspan.end();\n\t\t\t};\n\t\t\tlet result: unknown;\n\t\t\ttry {\n\t\t\t\tresult = call();\n\t\t\t} catch (error) {\n\t\t\t\tfail(error);\n\t\t\t\tthrow error;\n\t\t\t}\n\t\t\t// Only a native promise is waited on, and the caller gets it back as\n\t\t\t// it was: a lazy thenable runs on `then`, and a promise subclass has\n\t\t\t// methods a chained promise would not.\n\t\t\tif (result instanceof Promise) {\n\t\t\t\tresult.then(\n\t\t\t\t\t() => span.end(),\n\t\t\t\t\t(error) => fail(error),\n\t\t\t\t);\n\t\t\t\treturn result;\n\t\t\t}\n\t\t\tspan.end();\n\t\t\treturn result;\n\t\t},\n\t);\n}\n\n/**\n * Where an instrumentation of `fetch` hears of each request — undici's own\n * diagnostics channel, which OpenTelemetry's undici instrumentation (and every\n * APM built on it) subscribes to.\n */\nconst FETCH_REQUESTS = channel('undici:request:create');\n\n/**\n * The active trace context, written into `headers` for a call this process\n * makes to one of its own services — the auth server's session check — so the\n * callee's span joins the caller's trace.\n *\n * Through the global propagator, so it is a no-op without one. And not at all\n * when a `fetch` instrumentation is listening: that opens the request's own\n * CLIENT span and writes its `traceparent` by appending a header, so a second\n * one here would reach the callee as two values joined — `a, b` — which no\n * propagator reads, and the trace would break instead of joining.\n */\nexport function injectTraceContext(headers: Headers): void {\n\tif (FETCH_REQUESTS.hasSubscribers) return;\n\tpropagation.inject(context.active(), headers, {\n\t\tset: (carrier, key, value) => carrier.set(key, value),\n\t});\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AA0BA,SAAgB,cAAc,QAA2C;CACxE,MAAM,IAAI;CAKV,IAAI,GAAG,KAAK,QAAA,GAAOA,kBAAAA,sBAAAA,CAAsB,EAAE,IAAI,iBAAiB;CAEhE,MAAM,OAAA,GAAMA,kBAAAA,sBAAAA,CAAsB,GAAG,iBAAiB;CACtD,IAAI,OAAO,OAAO,GAAG,SAAS,UAAU,OAAO;CAC/C,IAAI;EACH,MAAM,OAAO,KAAK,MAAM,EAAE,IAAI;EAC9B,OAAO,MAAM,SAAS,kBAAA,GACnBA,kBAAAA,sBAAAA,CAAsB,KAAK,iBAAiB,IAC5C,KAAA;CACJ,QAAQ;EACP;CACD;AACD;;;;;;;;;;;AAYA,SAAgB,YACf,KACA,QACA,aAAqC,CAAC,GAClC;CACJ,IAAI,CAAC,UAAW,OAAO,WAAW,YAAY,OAAO,WAAW,YAC/D,OAAO;CAER,MAAM,0BAAU,IAAI,IAA0B;CAC9C,OAAO,IAAI,MAAM,QAAkB,EAClC,IAAI,QAAQ,UAAU,UAAU;EAC/B,MAAM,QAAQ,QAAQ,IAAI,QAAQ,UAAU,QAA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AK,EACrD,CAAC;AACF"}
|
package/dist/worker.cjs
CHANGED
package/dist/worker.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"worker.cjs","names":["canonicalId","DEFAULT_LOGGER","envParserFor","edgeTo","CronBuilder","QueueBuilder","SubscriberBuilder","FunctionBuilder"],"sources":["../src/worker.ts"],"sourcesContent":["/**\n * A process with no port.\n *\n * `RestApi` is the process that answers HTTP. This is the one that does not —\n * the thing that runs a schedule, drains a queue, consumes a topic. Until it\n * existed, those had nowhere to say they belonged: a cron declared a schedule\n * and nothing else, and which container ran it was decided by the directory the\n * file sat in. A glob owned it.\n *\n * The cost of that shows up in the scaffolds. `gkm init --template worker` —\n * a project that is background jobs and nothing else — declared\n * `new RestApi('Api', { defaultAuthorizer: 'none', logger })`: an HTTP surface\n * with no HTTP on it, written because it was the only construct that made an\n * app exist and the only way to get a logger into the generated runtime.\n *\n * It takes no authorizer, and that is the tell that these are two constructs\n * rather than one with a flag: a `RestApi` needs one because an HTTP surface\n * can ship open by omission, and nothing reaches a worker from outside.\n *\n * ## Crons on a server target need a database\n *\n * A cron becomes an EventBridge rule on AWS and nothing here is consulted. A\n * server has nothing firing its crons but itself, and a process that schedules\n * in memory fires every job once per replica while reporting success — so the\n * schedule is kept in Postgres, and the worker says which one with\n * `.database(db)`.\n *\n * A worker with crons and no `.database(…)` schedules nothing on a server\n * target and says so at startup. That is a limitation of workers today rather\n * than a design: the store could be a cache, or something the target\n * provisions, and Postgres is what exists.\n *\n * ## The database is everything's default\n *\n * The same `.database(db)` is the database every cron, queue, subscriber and\n * function built from the worker receives as `db`. The work a worker groups is\n * usually work against one database, and naming it per handler was a line\n * repeated in every file that could drift in any one of them. A runnable that\n * works against another names its own with `.database(other)`, which replaces\n * the worker's — client and manifest edge both — rather than adding to it.\n *\n * It is not an app: it declares no path, and its code lives in an app's\n * directory. But it is a process of its own. On a server target each worker\n * with work to do is built — from the app that holds that work — into an image\n * that runs its crons, consumers and subscribers and answers only a health\n * check, so a slow queue never shares a process with the requests an API\n * serves. `gkm dev` still runs everything in one process. Declare as many as\n * the shape of the work wants: each is one container.\n *\n * @example\n * ```ts\n * // constructs/worker.ts\n * import { Worker } from '@geekmidas/constructs/worker';\n * import { logger } from './logger.js';\n *\n * export const worker = new Worker('Worker', { logger }).database(database);\n *\n * // crons/cleanup.ts\n * import { worker } from '@acme/constructs/worker.js';\n *\n * export const cleanup = worker\n * .cron('rate(1 day)')\n * .handle(async ({ db, logger }) => { … });\n *\n * // queues/reports.ts — against another database than the worker's\n * export const reports = worker\n * .queue('Reports')\n * .database(analytics)\n * .message(z.object({ id: z.uuid() }))\n * .handle(async ({ messages, db }) => { … });\n * ```\n */\n\nimport type { EnvironmentParser } from '@geekmidas/envkit';\nimport type { EventPublisher } from '@geekmidas/events';\nimport type { Logger } from '@geekmidas/logger';\nimport { DEFAULT_LOGGER } from '@geekmidas/logger/console';\nimport {\n\ttype ConstructName,\n\tcanonicalId,\n\ttype Declaration,\n\ttype Dependency,\n} from '@geekmidas/manifest';\nimport type { ComposableStandardSchema } from '@geekmidas/schema';\nimport type { Service } from '@geekmidas/services';\nimport type { StandardSchemaV1 } from '@standard-schema/spec';\nimport {\n\ttype Consumable,\n\ttype Declarable,\n\tedgeTo,\n} from './construct-interface';\nimport type { ScheduleExpression } from './crons/Cron';\nimport { CronBuilder } from './crons/CronBuilder';\nimport { envParserFor } from './endpoints/surfaceEnv';\nimport { FunctionBuilder } from './functions/FunctionBuilder';\nimport { QueueBuilder } from './queue/QueueBuilder';\nimport { SubscriberBuilder } from './subscribers/SubscriberBuilder';\nimport type { Topic, TopicEvents } from './topic/Topic';\n\nexport interface WorkerConfig {\n\t/**\n\t * The logger everything built from this worker runs with.\n\t *\n\t * The actual logger, not a path to one — the same reason `RestApi` takes\n\t * one. Every cron and subscriber in a scaffolded project used to open with\n\t * `import { logger } from '…/constructs/logger.js'`, which is the line this\n\t * removes.\n\t */\n\tlogger?: Logger;\n\t/**\n\t * The environment parser everything built from this worker runs with.\n\t *\n\t * Defaults to `process.env` merged with the credentials `gkm dev` injected,\n\t * which is what an application's own `config/env.ts` always was.\n\t */\n\tenvParser?: EnvironmentParser<{}>;\n}\n\nexport class Worker<\n\tTName extends string = string,\n\tTDatabase = undefined,\n\tTDatabaseServiceName extends string = string,\n> implements Declarable<TName>\n{\n\treadonly id: TName;\n\n\t/** Always defined — the worker's own, or the console logger. */\n\treadonly logger: Logger;\n\n\t/** Always defined, and normally the default. */\n\treadonly envParser: EnvironmentParser<{}>;\n\n\t/**\n\t * Where this worker's schedules live, when it has crons and a server runs\n\t * them — and the database everything built from it receives as `db`.\n\t * `undefined` until `.database(…)` says.\n\t */\n\treadonly scheduleStore?: Consumable<string, unknown>;\n\n\tconstructor(\n\t\tid: ConstructName<TName>,\n\t\tprivate readonly config: WorkerConfig = {},\n\t\t/** Internal: how `.calls()` carries edges into the copy it returns. */\n\t\tprivate readonly dependencies: readonly Dependency[] = [],\n\t\tscheduleStore?: Consumable<string, unknown>,\n\t) {\n\t\tconst canonical = canonicalId(id as string);\n\n\t\tthis.id = canonical as TName;\n\t\tthis.logger = config.logger ?? DEFAULT_LOGGER;\n\t\tthis.envParser = envParserFor(\n\t\t\tconfig.envParser\n\t\t\t\t? { id: canonical, envParser: config.envParser }\n\t\t\t\t: undefined,\n\t\t);\n\t\tthis.scheduleStore = scheduleStore;\n\t}\n\n\t/**\n\t * The database this worker keeps its schedules in, and the one everything\n\t * built from it — crons, queues, subscribers, functions — receives as `db`.\n\t * One of them that works against another database names it with its own\n\t * `.database(other)`, which replaces this one for that runnable alone.\n\t *\n\t * Only a server target uses it. On AWS a cron is an EventBridge rule\n\t * invoking a Lambda and nothing here is consulted — but a server has nothing\n\t * firing its crons except itself, and a process that schedules in memory\n\t * fires every job once per replica while reporting that all is well.\n\t *\n\t * So the store is declared rather than discovered. It could have been\n\t * inferred — from a database the app happens to declare, or from the events\n\t * backend when that backend is pg-boss — and both would work until an app\n\t * had two databases, or moved its events to SNS, at which point the\n\t * schedules would quietly move or stop. Naming it is one line and cannot\n\t * drift.\n\t *\n\t * @example\n\t * ```ts\n\t * export const jobs = new Worker('Jobs', { logger }).database(database);\n\t *\n\t * export const sweep = jobs\n\t * .cron('rate(1 hour)')\n\t * .handle(async ({ db }) => db.deleteFrom('sessions').execute());\n\t * ```\n\t */\n\tdatabase<T, TDbName extends string>(\n\t\tsource: Consumable<TDbName, T>,\n\t): Worker<TName, T, TDbName> {\n\t\treturn new Worker<TName, T, TDbName>(\n\t\t\tthis.id as ConstructName<TName>,\n\t\t\tthis.config,\n\t\t\t[...this.dependencies, edgeTo(source)],\n\t\t\tsource as unknown as Consumable<string, unknown>,\n\t\t);\n\t}\n\n\t/**\n\t * A scheduled runnable.\n\t *\n\t * @example `worker.cron('rate(1 day)').handle(async ({ logger }) => { … })`\n\t */\n\tcron(schedule: ScheduleExpression) {\n\t\treturn this.own(\n\t\t\tnew CronBuilder<\n\t\t\t\tComposableStandardSchema,\n\t\t\t\tService[],\n\t\t\t\tLogger,\n\t\t\t\tundefined,\n\t\t\t\tTDatabase,\n\t\t\t\tTDatabaseServiceName\n\t\t\t>().logger(this.logger),\n\t\t).schedule(schedule);\n\t}\n\n\t/**\n\t * A queue and its one consumer, run by this worker.\n\t *\n\t * One construct, because a queue has exactly one consumer: nothing else can\n\t * attach a second, or forget to attach the first. Producers send to it by\n\t * depending on it — `.dependsOn([emails])` makes `services.emails` the\n\t * publisher.\n\t *\n\t * @example\n\t * ```ts\n\t * export const emails = worker\n\t * .queue('Emails')\n\t * .message(z.object({ userId: z.uuid(), template: z.string() }))\n\t * .handle(async ({ messages, services }) => { … });\n\t * ```\n\t */\n\tqueue<TQueueName extends string>(name: TQueueName) {\n\t\treturn this.own(\n\t\t\tnew QueueBuilder<\n\t\t\t\tstring,\n\t\t\t\tundefined,\n\t\t\t\t[],\n\t\t\t\tLogger,\n\t\t\t\tTDatabase,\n\t\t\t\tTDatabaseServiceName\n\t\t\t>().logger(this.logger),\n\t\t).queue(name);\n\t}\n\n\t/**\n\t * A runnable that consumes a topic.\n\t *\n\t * Binding is not publishing: a consumer is handed the topic's event types\n\t * and no connection string it could publish with. A handler that emits\n\t * follow-up events depends on the topic it emits to —\n\t * `.dependsOn([orders])` — which is the only reason it would need one.\n\t *\n\t * @example `worker.topic(users).subscribe(['user.created']).handle(…)`\n\t */\n\ttopic<TTopicName extends string, TEvents extends TopicEvents>(\n\t\ttopic: Topic<TTopicName, TEvents>,\n\t) {\n\t\treturn this.own(\n\t\t\tnew SubscriberBuilder<\n\t\t\t\t[],\n\t\t\t\tLogger,\n\t\t\t\tundefined,\n\t\t\t\tundefined,\n\t\t\t\t[],\n\t\t\t\tTDatabase,\n\t\t\t\tTDatabaseServiceName\n\t\t\t>().logger(this.logger),\n\t\t).topic(topic);\n\t}\n\n\t/**\n\t * Everything below builds a function — the runnable with no schedule and no\n\t * topic, invoked by something else.\n\t *\n\t * These sit on the worker rather than behind a `functions` namespace because\n\t * the namespace was a hop that said nothing: `worker.functions.input(…)`\n\t * names a collection to reach one member of it. What kind of runnable is\n\t * being built is decided by which of these is called first — a schedule\n\t * makes a cron, a topic makes a subscriber, and anything else makes a\n\t * function.\n\t */\n\tinput<T extends ComposableStandardSchema>(schema: T) {\n\t\treturn this.functions.input(schema);\n\t}\n\n\toutput<T extends StandardSchemaV1>(schema: T) {\n\t\treturn this.functions.output(schema);\n\t}\n\n\ttimeout(ms: number) {\n\t\treturn this.functions.timeout(ms);\n\t}\n\n\tmemorySize(mb: number) {\n\t\treturn this.functions.memorySize(mb);\n\t}\n\n\tdependsOn<const T extends readonly Consumable[]>(constructs: T) {\n\t\treturn this.functions.dependsOn(constructs);\n\t}\n\n\tservices<T extends Service[]>(services: T) {\n\t\treturn this.functions.services(services);\n\t}\n\n\t/**\n\t * A function with no input schema — the shortest runnable there is.\n\t *\n\t * @example `worker.handle(async ({ logger }) => { … })`\n\t */\n\thandle(\n\t\t...args: Parameters<\n\t\t\tReturnType<\n\t\t\t\tWorker<TName, TDatabase, TDatabaseServiceName>['schemalessFunction']\n\t\t\t>['handle']\n\t\t>\n\t) {\n\t\treturn this.schemalessFunction().handle(...args);\n\t}\n\n\t/** The builder `handle` delegates to, named so its type can be referred to. */\n\tprivate schemalessFunction() {\n\t\treturn this.functions;\n\t}\n\n\t/** The function builder the delegating methods above are built on. */\n\tprivate get functions() {\n\t\treturn this.own(\n\t\t\tnew FunctionBuilder<\n\t\t\t\tany,\n\t\t\t\tundefined,\n\t\t\t\t[],\n\t\t\t\tLogger,\n\t\t\t\tundefined,\n\t\t\t\tstring,\n\t\t\t\tTDatabase,\n\t\t\t\tTDatabaseServiceName\n\t\t\t>().logger(this.logger),\n\t\t);\n\t}\n\n\t/**\n\t * Resources and surfaces this worker calls.\n\t *\n\t * Not `.dependsOn()`: this records the edge that derives the worker's\n\t * environment and its access, the same distinction `RestApi.calls()` draws.\n\t */\n\tcalls(\n\t\tconstructs: readonly Declarable[],\n\t): Worker<TName, TDatabase, TDatabaseServiceName> {\n\t\treturn new Worker<TName, TDatabase, TDatabaseServiceName>(\n\t\t\tthis.id as ConstructName<TName>,\n\t\t\tthis.config,\n\t\t\t[...this.dependencies, ...constructs.map(edgeTo)],\n\t\t\tthis.scheduleStore,\n\t\t);\n\t}\n\n\t/**\n\t * Stamps this worker's id onto a builder, so everything built from it says\n\t * which process runs it — and hands it the worker's database.\n\t *\n\t * The database goes through the builder's own `.database()` rather than\n\t * being written into its fields, so the default is recorded exactly as an\n\t * explicit one would be: the client the handler gets, and the edge the\n\t * manifest reads. That is also what lets a later `.database(other)` replace\n\t * it outright. The builder arrives already typed with this worker's\n\t * database; this is the runtime half of that.\n\t */\n\tprivate own<\n\t\tT extends {\n\t\t\t_owner?: string;\n\t\t\t_scheduleStore?: unknown;\n\t\t\tdatabase(source: Consumable<string, unknown>): unknown;\n\t\t},\n\t>(builder: T): T {\n\t\tconst owned = this.scheduleStore\n\t\t\t? (builder.database(this.scheduleStore) as T)\n\t\t\t: builder;\n\n\t\towned._owner = this.id;\n\t\towned._scheduleStore = this.scheduleStore;\n\n\t\treturn owned;\n\t}\n\n\tdeclare(): Declaration[] {\n\t\treturn [\n\t\t\t{\n\t\t\t\tkind: 'worker',\n\t\t\t\tid: this.id,\n\t\t\t\t...(this.dependencies.length\n\t\t\t\t\t? { dependencies: this.dependencies }\n\t\t\t\t\t: {}),\n\t\t\t\t// Nothing calls a worker, so it publishes no address.\n\t\t\t\tprovides: [],\n\t\t\t},\n\t\t];\n\t}\n}\n"],"mappings":";;;;;;;;;;AAsHA,IAAa,SAAb,MAAa,OAKb;CAkBmB;CAEA;CAnBlB;;CAGA;;CAGA;;;;;;CAOA;CAEA,YACC,IACA,SAAwC,CAAC,GAEzC,eAAuD,CAAC,GACxD,eACC;EAJgB,KAAA,SAAA;EAEA,KAAA,eAAA;EAGjB,MAAM,aAAA,GAAYA,oBAAAA,YAAAA,CAAY,EAAY;EAE1C,KAAK,KAAK;EACV,KAAK,SAAS,OAAO,UAAUC,0BAAAA;EAC/B,KAAK,YAAYC,mBAAAA,aAChB,OAAO,YACJ;GAAE,IAAI;GAAW,WAAW,OAAO;EAAU,IAC7C,KAAA,CACJ;EACA,KAAK,gBAAgB;CACtB;;;;;;;;;;;;;;;;;;;;;;;;;;;;CA6BA,SACC,QAC4B;EAC5B,OAAO,IAAI,OACV,KAAK,IACL,KAAK,QACL,CAAC,GAAG,KAAK,cAAcC,4BAAAA,OAAO,MAAM,CAAC,GACrC,MACD;CACD;;;;;;CAOA,KAAK,UAA8B;EAClC,OAAO,KAAK,IACX,IAAIC,oBAAAA,YAOF,CAAC,CAAC,OAAO,KAAK,MAAM,CACvB,CAAC,CAAC,SAAS,QAAQ;CACpB;;;;;;;;;;;;;;;;;CAkBA,MAAiC,MAAkB;EAClD,OAAO,KAAK,IACX,IAAIC,qBAAAA,aAOF,CAAC,CAAC,OAAO,KAAK,MAAM,CACvB,CAAC,CAAC,MAAM,IAAI;CACb;;;;;;;;;;;CAYA,MACC,OAC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3,"file":"worker.cjs","names":["canonicalId","DEFAULT_LOGGER","envParserFor","edgeTo","CronBuilder","QueueBuilder","SubscriberBuilder","FunctionBuilder"],"sources":["../src/worker.ts"],"sourcesContent":["/**\n * A process with no port.\n *\n * `RestApi` is the process that answers HTTP. This is the one that does not —\n * the thing that runs a schedule, drains a queue, consumes a topic. Until it\n * existed, those had nowhere to say they belonged: a cron declared a schedule\n * and nothing else, and which container ran it was decided by the directory the\n * file sat in. A glob owned it.\n *\n * The cost of that shows up in the scaffolds. `gkm init --template worker` —\n * a project that is background jobs and nothing else — declared\n * `new RestApi('Api', { defaultAuthorizer: 'none', logger })`: an HTTP surface\n * with no HTTP on it, written because it was the only construct that made an\n * app exist and the only way to get a logger into the generated runtime.\n *\n * It takes no authorizer, and that is the tell that these are two constructs\n * rather than one with a flag: a `RestApi` needs one because an HTTP surface\n * can ship open by omission, and nothing reaches a worker from outside.\n *\n * ## Crons on a server target need a database\n *\n * A cron becomes an EventBridge rule on AWS and nothing here is consulted. A\n * server has nothing firing its crons but itself, and a process that schedules\n * in memory fires every job once per replica while reporting success — so the\n * schedule is kept in Postgres, and the worker says which one with\n * `.database(db)`.\n *\n * A worker with crons and no `.database(…)` schedules nothing on a server\n * target and says so at startup. That is a limitation of workers today rather\n * than a design: the store could be a cache, or something the target\n * provisions, and Postgres is what exists.\n *\n * ## The database is everything's default\n *\n * The same `.database(db)` is the database every cron, queue, subscriber and\n * function built from the worker receives as `db`. The work a worker groups is\n * usually work against one database, and naming it per handler was a line\n * repeated in every file that could drift in any one of them. A runnable that\n * works against another names its own with `.database(other)`, which replaces\n * the worker's — client and manifest edge both — rather than adding to it.\n *\n * It is not an app: it declares no path, and its code lives in an app's\n * directory. But it is a process of its own. On a server target each worker\n * with work to do is built — from the app that holds that work — into an image\n * that runs its crons, consumers and subscribers and answers only a health\n * check, so a slow queue never shares a process with the requests an API\n * serves. `gkm dev` still runs everything in one process. Declare as many as\n * the shape of the work wants: each is one container.\n *\n * @example\n * ```ts\n * // constructs/worker.ts\n * import { Worker } from '@geekmidas/constructs/worker';\n * import { logger } from './logger.js';\n *\n * export const worker = new Worker('Worker', { logger }).database(database);\n *\n * // crons/cleanup.ts\n * import { worker } from '@acme/constructs/worker.js';\n *\n * export const cleanup = worker\n * .cron('rate(1 day)')\n * .handle(async ({ db, logger }) => { … });\n *\n * // queues/reports.ts — against another database than the worker's\n * export const reports = worker\n * .queue('Reports')\n * .database(analytics)\n * .message(z.object({ id: z.uuid() }))\n * .handle(async ({ messages, db }) => { … });\n * ```\n */\n\nimport type { EnvironmentParser } from '@geekmidas/envkit';\nimport type { EventPublisher } from '@geekmidas/events';\nimport type { Logger } from '@geekmidas/logger';\nimport { DEFAULT_LOGGER } from '@geekmidas/logger/console';\nimport {\n\ttype ConstructName,\n\tcanonicalId,\n\ttype Declaration,\n\ttype Dependency,\n} from '@geekmidas/manifest';\nimport type { ComposableStandardSchema } from '@geekmidas/schema';\nimport type { Service } from '@geekmidas/services';\nimport type { StandardSchemaV1 } from '@standard-schema/spec';\nimport {\n\ttype Consumable,\n\ttype Declarable,\n\tedgeTo,\n} from './construct-interface';\nimport type { ScheduleExpression } from './crons/Cron';\nimport { CronBuilder } from './crons/CronBuilder';\nimport { envParserFor } from './endpoints/surfaceEnv';\nimport { FunctionBuilder } from './functions/FunctionBuilder';\nimport { QueueBuilder } from './queue/QueueBuilder';\nimport { SubscriberBuilder } from './subscribers/SubscriberBuilder';\nimport type { Telemetry } from './telemetry';\nimport type { Topic, TopicEvents } from './topic/Topic';\n\nexport interface WorkerConfig {\n\t/**\n\t * The logger everything built from this worker runs with.\n\t *\n\t * The actual logger, not a path to one — the same reason `RestApi` takes\n\t * one. Every cron and subscriber in a scaffolded project used to open with\n\t * `import { logger } from '…/constructs/logger.js'`, which is the line this\n\t * removes.\n\t */\n\tlogger?: Logger;\n\t/**\n\t * The environment parser everything built from this worker runs with.\n\t *\n\t * Defaults to `process.env` merged with the credentials `gkm dev` injected,\n\t * which is what an application's own `config/env.ts` always was.\n\t */\n\tenvParser?: EnvironmentParser<{}>;\n\t/**\n\t * What the worker's process emits — the `Telemetry` construct, passed like\n\t * the logger. An edge to the node: the deploy hands the process the\n\t * `OTEL_*` keys its stage resolves.\n\t */\n\ttelemetry?: Telemetry;\n}\n\nexport class Worker<\n\tTName extends string = string,\n\tTDatabase = undefined,\n\tTDatabaseServiceName extends string = string,\n> implements Declarable<TName>\n{\n\treadonly id: TName;\n\n\t/** Always defined — the worker's own, or the console logger. */\n\treadonly logger: Logger;\n\n\t/** Always defined, and normally the default. */\n\treadonly envParser: EnvironmentParser<{}>;\n\n\t/**\n\t * Where this worker's schedules live, when it has crons and a server runs\n\t * them — and the database everything built from it receives as `db`.\n\t * `undefined` until `.database(…)` says.\n\t */\n\treadonly scheduleStore?: Consumable<string, unknown>;\n\n\tconstructor(\n\t\tid: ConstructName<TName>,\n\t\tprivate readonly config: WorkerConfig = {},\n\t\t/** Internal: how `.calls()` carries edges into the copy it returns. */\n\t\tprivate readonly dependencies: readonly Dependency[] = [],\n\t\tscheduleStore?: Consumable<string, unknown>,\n\t) {\n\t\tconst canonical = canonicalId(id as string);\n\n\t\tthis.id = canonical as TName;\n\t\tthis.logger = config.logger ?? DEFAULT_LOGGER;\n\t\tthis.envParser = envParserFor(\n\t\t\tconfig.envParser\n\t\t\t\t? { id: canonical, envParser: config.envParser }\n\t\t\t\t: undefined,\n\t\t);\n\t\tthis.scheduleStore = scheduleStore;\n\t}\n\n\t/**\n\t * The database this worker keeps its schedules in, and the one everything\n\t * built from it — crons, queues, subscribers, functions — receives as `db`.\n\t * One of them that works against another database names it with its own\n\t * `.database(other)`, which replaces this one for that runnable alone.\n\t *\n\t * Only a server target uses it. On AWS a cron is an EventBridge rule\n\t * invoking a Lambda and nothing here is consulted — but a server has nothing\n\t * firing its crons except itself, and a process that schedules in memory\n\t * fires every job once per replica while reporting that all is well.\n\t *\n\t * So the store is declared rather than discovered. It could have been\n\t * inferred — from a database the app happens to declare, or from the events\n\t * backend when that backend is pg-boss — and both would work until an app\n\t * had two databases, or moved its events to SNS, at which point the\n\t * schedules would quietly move or stop. Naming it is one line and cannot\n\t * drift.\n\t *\n\t * @example\n\t * ```ts\n\t * export const jobs = new Worker('Jobs', { logger }).database(database);\n\t *\n\t * export const sweep = jobs\n\t * .cron('rate(1 hour)')\n\t * .handle(async ({ db }) => db.deleteFrom('sessions').execute());\n\t * ```\n\t */\n\tdatabase<T, TDbName extends string>(\n\t\tsource: Consumable<TDbName, T>,\n\t): Worker<TName, T, TDbName> {\n\t\treturn new Worker<TName, T, TDbName>(\n\t\t\tthis.id as ConstructName<TName>,\n\t\t\tthis.config,\n\t\t\t[...this.dependencies, edgeTo(source)],\n\t\t\tsource as unknown as Consumable<string, unknown>,\n\t\t);\n\t}\n\n\t/**\n\t * A scheduled runnable.\n\t *\n\t * @example `worker.cron('rate(1 day)').handle(async ({ logger }) => { … })`\n\t */\n\tcron(schedule: ScheduleExpression) {\n\t\treturn this.own(\n\t\t\tnew CronBuilder<\n\t\t\t\tComposableStandardSchema,\n\t\t\t\tService[],\n\t\t\t\tLogger,\n\t\t\t\tundefined,\n\t\t\t\tTDatabase,\n\t\t\t\tTDatabaseServiceName\n\t\t\t>().logger(this.logger),\n\t\t).schedule(schedule);\n\t}\n\n\t/**\n\t * A queue and its one consumer, run by this worker.\n\t *\n\t * One construct, because a queue has exactly one consumer: nothing else can\n\t * attach a second, or forget to attach the first. Producers send to it by\n\t * depending on it — `.dependsOn([emails])` makes `services.emails` the\n\t * publisher.\n\t *\n\t * @example\n\t * ```ts\n\t * export const emails = worker\n\t * .queue('Emails')\n\t * .message(z.object({ userId: z.uuid(), template: z.string() }))\n\t * .handle(async ({ messages, services }) => { … });\n\t * ```\n\t */\n\tqueue<TQueueName extends string>(name: TQueueName) {\n\t\treturn this.own(\n\t\t\tnew QueueBuilder<\n\t\t\t\tstring,\n\t\t\t\tundefined,\n\t\t\t\t[],\n\t\t\t\tLogger,\n\t\t\t\tTDatabase,\n\t\t\t\tTDatabaseServiceName\n\t\t\t>().logger(this.logger),\n\t\t).queue(name);\n\t}\n\n\t/**\n\t * A runnable that consumes a topic.\n\t *\n\t * Binding is not publishing: a consumer is handed the topic's event types\n\t * and no connection string it could publish with. A handler that emits\n\t * follow-up events depends on the topic it emits to —\n\t * `.dependsOn([orders])` — which is the only reason it would need one.\n\t *\n\t * @example `worker.topic(users).subscribe(['user.created']).handle(…)`\n\t */\n\ttopic<TTopicName extends string, TEvents extends TopicEvents>(\n\t\ttopic: Topic<TTopicName, TEvents>,\n\t) {\n\t\treturn this.own(\n\t\t\tnew SubscriberBuilder<\n\t\t\t\t[],\n\t\t\t\tLogger,\n\t\t\t\tundefined,\n\t\t\t\tundefined,\n\t\t\t\t[],\n\t\t\t\tTDatabase,\n\t\t\t\tTDatabaseServiceName\n\t\t\t>().logger(this.logger),\n\t\t).topic(topic);\n\t}\n\n\t/**\n\t * Everything below builds a function — the runnable with no schedule and no\n\t * topic, invoked by something else.\n\t *\n\t * These sit on the worker rather than behind a `functions` namespace because\n\t * the namespace was a hop that said nothing: `worker.functions.input(…)`\n\t * names a collection to reach one member of it. What kind of runnable is\n\t * being built is decided by which of these is called first — a schedule\n\t * makes a cron, a topic makes a subscriber, and anything else makes a\n\t * function.\n\t */\n\tinput<T extends ComposableStandardSchema>(schema: T) {\n\t\treturn this.functions.input(schema);\n\t}\n\n\toutput<T extends StandardSchemaV1>(schema: T) {\n\t\treturn this.functions.output(schema);\n\t}\n\n\ttimeout(ms: number) {\n\t\treturn this.functions.timeout(ms);\n\t}\n\n\tmemorySize(mb: number) {\n\t\treturn this.functions.memorySize(mb);\n\t}\n\n\tdependsOn<const T extends readonly Consumable[]>(constructs: T) {\n\t\treturn this.functions.dependsOn(constructs);\n\t}\n\n\tservices<T extends Service[]>(services: T) {\n\t\treturn this.functions.services(services);\n\t}\n\n\t/**\n\t * A function with no input schema — the shortest runnable there is.\n\t *\n\t * @example `worker.handle(async ({ logger }) => { … })`\n\t */\n\thandle(\n\t\t...args: Parameters<\n\t\t\tReturnType<\n\t\t\t\tWorker<TName, TDatabase, TDatabaseServiceName>['schemalessFunction']\n\t\t\t>['handle']\n\t\t>\n\t) {\n\t\treturn this.schemalessFunction().handle(...args);\n\t}\n\n\t/** The builder `handle` delegates to, named so its type can be referred to. */\n\tprivate schemalessFunction() {\n\t\treturn this.functions;\n\t}\n\n\t/** The function builder the delegating methods above are built on. */\n\tprivate get functions() {\n\t\treturn this.own(\n\t\t\tnew FunctionBuilder<\n\t\t\t\tany,\n\t\t\t\tundefined,\n\t\t\t\t[],\n\t\t\t\tLogger,\n\t\t\t\tundefined,\n\t\t\t\tstring,\n\t\t\t\tTDatabase,\n\t\t\t\tTDatabaseServiceName\n\t\t\t>().logger(this.logger),\n\t\t);\n\t}\n\n\t/**\n\t * Resources and surfaces this worker calls.\n\t *\n\t * Not `.dependsOn()`: this records the edge that derives the worker's\n\t * environment and its access, the same distinction `RestApi.calls()` draws.\n\t */\n\tcalls(\n\t\tconstructs: readonly Declarable[],\n\t): Worker<TName, TDatabase, TDatabaseServiceName> {\n\t\treturn new Worker<TName, TDatabase, TDatabaseServiceName>(\n\t\t\tthis.id as ConstructName<TName>,\n\t\t\tthis.config,\n\t\t\t[...this.dependencies, ...constructs.map(edgeTo)],\n\t\t\tthis.scheduleStore,\n\t\t);\n\t}\n\n\t/**\n\t * Stamps this worker's id onto a builder, so everything built from it says\n\t * which process runs it — and hands it the worker's database.\n\t *\n\t * The database goes through the builder's own `.database()` rather than\n\t * being written into its fields, so the default is recorded exactly as an\n\t * explicit one would be: the client the handler gets, and the edge the\n\t * manifest reads. That is also what lets a later `.database(other)` replace\n\t * it outright. The builder arrives already typed with this worker's\n\t * database; this is the runtime half of that.\n\t */\n\tprivate own<\n\t\tT extends {\n\t\t\t_owner?: string;\n\t\t\t_scheduleStore?: unknown;\n\t\t\tdatabase(source: Consumable<string, unknown>): unknown;\n\t\t},\n\t>(builder: T): T {\n\t\tconst owned = this.scheduleStore\n\t\t\t? (builder.database(this.scheduleStore) as T)\n\t\t\t: builder;\n\n\t\towned._owner = this.id;\n\t\towned._scheduleStore = this.scheduleStore;\n\n\t\treturn owned;\n\t}\n\n\tdeclare(): Declaration[] {\n\t\treturn [\n\t\t\t{\n\t\t\t\tkind: 'worker',\n\t\t\t\tid: this.id,\n\t\t\t\t...(this.dependencies.length\n\t\t\t\t\t? { dependencies: this.dependencies }\n\t\t\t\t\t: {}),\n\t\t\t\t...(this.config.telemetry\n\t\t\t\t\t? { telemetry: this.config.telemetry.id }\n\t\t\t\t\t: {}),\n\t\t\t\t// Nothing calls a worker, so it publishes no address.\n\t\t\t\tprovides: [],\n\t\t\t},\n\t\t];\n\t}\n}\n"],"mappings":";;;;;;;;;;AA6HA,IAAa,SAAb,MAAa,OAKb;CAkBmB;CAEA;CAnBlB;;CAGA;;CAGA;;;;;;CAOA;CAEA,YACC,IACA,SAAwC,CAAC,GAEzC,eAAuD,CAAC,GACxD,eACC;EAJgB,KAAA,SAAA;EAEA,KAAA,eAAA;EAGjB,MAAM,aAAA,GAAYA,oBAAAA,YAAAA,CAAY,EAAY;EAE1C,KAAK,KAAK;EACV,KAAK,SAAS,OAAO,UAAUC,0BAAAA;EAC/B,KAAK,YAAYC,mBAAAA,aAChB,OAAO,YACJ;GAAE,IAAI;GAAW,WAAW,OAAO;EAAU,IAC7C,KAAA,CACJ;EACA,KAAK,gBAAgB;CACtB;;;;;;;;;;;;;;;;;;;;;;;;;;;;CA6BA,SACC,QAC4B;EAC5B,OAAO,IAAI,OACV,KAAK,IACL,KAAK,QACL,CAAC,GAAG,KAAK,cAAcC,4BAAAA,OAAO,MAAM,CAAC,GACrC,MACD;CACD;;;;;;CAOA,KAAK,UAA8B;EAClC,OAAO,KAAK,IACX,IAAIC,oBAAAA,YAOF,CAAC,CAAC,OAAO,KAAK,MAAM,CACvB,CAAC,CAAC,SAAS,QAAQ;CACpB;;;;;;;;;;;;;;;;;CAkBA,MAAiC,MAAkB;EAClD,OAAO,KAA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GAAI,KAAK,aAAa,SACnB,EAAE,cAAc,KAAK,aAAa,IAClC,CAAC;GACJ,GAAI,KAAK,OAAO,YACb,EAAE,WAAW,KAAK,OAAO,UAAU,GAAG,IACtC,CAAC;GAEJ,UAAU,CAAC;EACZ,CACD;CACD;AACD"}
|
package/dist/worker.d.cts
CHANGED
|
@@ -4,6 +4,7 @@ import { i as FunctionHandler, n as Function } from "./Function-Pu-1kKZz.cjs";
|
|
|
4
4
|
import { c as ServicesOf, i as Declarable, r as Consumable } from "./construct-interface-B1AfqRl4.cjs";
|
|
5
5
|
import { t as FunctionBuilder } from "./index-BuzRvKOQ.cjs";
|
|
6
6
|
import { i as ScheduleExpression } from "./Cron-DI3nKoic.cjs";
|
|
7
|
+
import { n as Telemetry } from "./telemetry-B48RLjyk.cjs";
|
|
7
8
|
import { t as CronBuilder } from "./CronBuilder-g1lZLWyG.cjs";
|
|
8
9
|
import { t as QueueBuilder } from "./QueueBuilder-OSi6LkV9.cjs";
|
|
9
10
|
import { t as SubscriberBuilder } from "./SubscriberBuilder-g3fAVWgs.cjs";
|
|
@@ -31,6 +32,12 @@ export interface WorkerConfig {
|
|
|
31
32
|
* which is what an application's own `config/env.ts` always was.
|
|
32
33
|
*/
|
|
33
34
|
envParser?: EnvironmentParser<{}>;
|
|
35
|
+
/**
|
|
36
|
+
* What the worker's process emits — the `Telemetry` construct, passed like
|
|
37
|
+
* the logger. An edge to the node: the deploy hands the process the
|
|
38
|
+
* `OTEL_*` keys its stage resolves.
|
|
39
|
+
*/
|
|
40
|
+
telemetry?: Telemetry;
|
|
34
41
|
}
|
|
35
42
|
export declare class Worker<TName extends string = string, TDatabase = undefined, TDatabaseServiceName extends string = string> implements Declarable<TName> {
|
|
36
43
|
private readonly config;
|
package/dist/worker.d.cts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"worker.d.cts","names":["_$__topic0.TopicMessage","_$__construct_interface0.ServicesOf","_$__functions0.FunctionHandler","_$__functions0.Function"],"sources":["../src/worker.ts"],"mappings":"
|
|
1
|
+
{"version":3,"file":"worker.d.cts","names":["_$__topic0.TopicMessage","_$__construct_interface0.ServicesOf","_$__functions0.FunctionHandler","_$__functions0.Function"],"sources":["../src/worker.ts"],"mappings":";;;;;;;;;;;;;;;;;iBAoGiB;;;;;;;;;EAShB,SAAS;;;;;;;EAOT,YAAY;;;;;;EAMZ,YAAY;;qBAGA,OACZ,+BACA,uBACA,yDACY,WAAW;mBAmBL;;mBAEA;WAnBT,IAAI;;WAGJ,QAAQ;;WAGR,WAAW;;;;;;WAOX,gBAAgB;EAEzB,YACC,IAAI,cAAc,QACD,SAAQ,cAER;;EAAA,wBAAuB,cACxC,gBAAgB;;;;;;;;;;;;;;;;;;;;;;;;;;;;EAyCjB,SAAS,GAAG,wBACX,QAAQ,WAAW,SAAS,KAC1B,OAAO,OAAO,GAAG;;;;;;EAcpB,KAAK,UAAU,qBAAkB,YAAA,0BAAA,WAAA,mBAAA,WAAA;;;;;;;;;;;;;;;;;EA6BjC,MAAM,2BAA2B,MAAM,aAAU,aAAA,2BAAA,QAAA,WAAA;;;;;;;;;;;EAuBjD,MAAM,2BAA2B,gBAAgB,aAChD,OAAO,MAAM,YAAY,WAAQ,sBAAA,mBAAA,eAAAA,aAAA,iBAAA,WAAA;;;;;;;;;;;;EA0BlC,MAAM,UAAU,0BAA0B,QAAQ,IAAC,gBAAA,kBAAA,2BAAA,WAAA,sBAAA;EAInD,OAAO,UAAU,kBAAkB,QAAQ,IAAC,qBAAA,OAAA,2BAAA,WAAA,sBAAA;EAI5C,QAAQ,aAAU,oCAAA,2BAAA,WAAA,sBAAA;EAIlB,WAAW,aAAU,oCAAA,2BAAA,WAAA,sBAAA;EAIrB,gBAAgB,mBAAmB,cAAc,YAAY,IAAC,oCAAAC,WAAA,KAAA,2BAAA,WAAA,sBAAA;EAI9D,SAAS,UAAU,WAAW,UAAU,IAAC,oCAAA,IAAA,2BAAA,WAAA,sBAAA;;;;;;EASzC,UACI,MAAM,WACR,WACC,OAAO,OAAO,WAAW,0DAE1BE,kBAAA,sCAAA,WAAA,sBAAA,kCAAAD,yBAAA,mBAAA,sBAAA;;UAMM;;cAKI;;;;;;;EAqBZ,MACC,qBAAqB,eACnB,OAAO,OAAO,WAAW;;;;;;;;;;;;UAoBpB;EAiBR,WAAW"}
|
package/dist/worker.d.mts
CHANGED
|
@@ -4,6 +4,7 @@ import { i as FunctionHandler, n as Function } from "./Function-DuqGcbOI.mjs";
|
|
|
4
4
|
import { c as ServicesOf, i as Declarable, r as Consumable } from "./construct-interface-DluK3_da.mjs";
|
|
5
5
|
import { t as FunctionBuilder } from "./index-CTkKOer4.mjs";
|
|
6
6
|
import { i as ScheduleExpression } from "./Cron-uYAHPnp7.mjs";
|
|
7
|
+
import { n as Telemetry } from "./telemetry-DRtT1_0A.mjs";
|
|
7
8
|
import { t as CronBuilder } from "./CronBuilder-DaSUm2Na.mjs";
|
|
8
9
|
import { t as QueueBuilder } from "./QueueBuilder-QHsnVt1P.mjs";
|
|
9
10
|
import { t as SubscriberBuilder } from "./SubscriberBuilder-CuCMFpYW.mjs";
|
|
@@ -31,6 +32,12 @@ export interface WorkerConfig {
|
|
|
31
32
|
* which is what an application's own `config/env.ts` always was.
|
|
32
33
|
*/
|
|
33
34
|
envParser?: EnvironmentParser<{}>;
|
|
35
|
+
/**
|
|
36
|
+
* What the worker's process emits — the `Telemetry` construct, passed like
|
|
37
|
+
* the logger. An edge to the node: the deploy hands the process the
|
|
38
|
+
* `OTEL_*` keys its stage resolves.
|
|
39
|
+
*/
|
|
40
|
+
telemetry?: Telemetry;
|
|
34
41
|
}
|
|
35
42
|
export declare class Worker<TName extends string = string, TDatabase = undefined, TDatabaseServiceName extends string = string> implements Declarable<TName> {
|
|
36
43
|
private readonly config;
|
package/dist/worker.d.mts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"worker.d.mts","names":["_$__topic0.TopicMessage","_$__construct_interface0.ServicesOf","_$__functions0.FunctionHandler","_$__functions0.Function"],"sources":["../src/worker.ts"],"mappings":"
|
|
1
|
+
{"version":3,"file":"worker.d.mts","names":["_$__topic0.TopicMessage","_$__construct_interface0.ServicesOf","_$__functions0.FunctionHandler","_$__functions0.Function"],"sources":["../src/worker.ts"],"mappings":";;;;;;;;;;;;;;;;;iBAoGiB;;;;;;;;;EAShB,SAAS;;;;;;;EAOT,YAAY;;;;;;EAMZ,YAAY;;qBAGA,OACZ,+BACA,uBACA,yDACY,WAAW;mBAmBL;;mBAEA;WAnBT,IAAI;;WAGJ,QAAQ;;WAGR,WAAW;;;;;;WAOX,gBAAgB;EAEzB,YACC,IAAI,cAAc,QACD,SAAQ,cAER;;EAAA,wBAAuB,cACxC,gBAAgB;;;;;;;;;;;;;;;;;;;;;;;;;;;;EAyCjB,SAAS,GAAG,wBACX,QAAQ,WAAW,SAAS,KAC1B,OAAO,OAAO,GAAG;;;;;;EAcpB,KAAK,UAAU,qBAAkB,YAAA,0BAAA,WAAA,mBAAA,WAAA;;;;;;;;;;;;;;;;;EA6BjC,MAAM,2BAA2B,MAAM,aAAU,aAAA,2BAAA,QAAA,WAAA;;;;;;;;;;;EAuBjD,MAAM,2BAA2B,gBAAgB,aAChD,OAAO,MAAM,YAAY,WAAQ,sBAAA,mBAAA,eAAAA,aAAA,iBAAA,WAAA;;;;;;;;;;;;EA0BlC,MAAM,UAAU,0BAA0B,QAAQ,IAAC,gBAAA,kBAAA,2BAAA,WAAA,sBAAA;EAInD,OAAO,UAAU,kBAAkB,QAAQ,IAAC,qBAAA,OAAA,2BAAA,WAAA,sBAAA;EAI5C,QAAQ,aAAU,oCAAA,2BAAA,WAAA,sBAAA;EAIlB,WAAW,aAAU,oCAAA,2BAAA,WAAA,sBAAA;EAIrB,gBAAgB,mBAAmB,cAAc,YAAY,IAAC,oCAAAC,WAAA,KAAA,2BAAA,WAAA,sBAAA;EAI9D,SAAS,UAAU,WAAW,UAAU,IAAC,oCAAA,IAAA,2BAAA,WAAA,sBAAA;;;;;;EASzC,UACI,MAAM,WACR,WACC,OAAO,OAAO,WAAW,0DAE1BE,kBAAA,sCAAA,WAAA,sBAAA,kCAAAD,yBAAA,mBAAA,sBAAA;;UAMM;;cAKI;;;;;;;EAqBZ,MACC,qBAAqB,eACnB,OAAO,OAAO,WAAW;;;;;;;;;;;;UAoBpB;EAiBR,WAAW"}
|
package/dist/worker.mjs
CHANGED
package/dist/worker.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"worker.mjs","names":[],"sources":["../src/worker.ts"],"sourcesContent":["/**\n * A process with no port.\n *\n * `RestApi` is the process that answers HTTP. This is the one that does not —\n * the thing that runs a schedule, drains a queue, consumes a topic. Until it\n * existed, those had nowhere to say they belonged: a cron declared a schedule\n * and nothing else, and which container ran it was decided by the directory the\n * file sat in. A glob owned it.\n *\n * The cost of that shows up in the scaffolds. `gkm init --template worker` —\n * a project that is background jobs and nothing else — declared\n * `new RestApi('Api', { defaultAuthorizer: 'none', logger })`: an HTTP surface\n * with no HTTP on it, written because it was the only construct that made an\n * app exist and the only way to get a logger into the generated runtime.\n *\n * It takes no authorizer, and that is the tell that these are two constructs\n * rather than one with a flag: a `RestApi` needs one because an HTTP surface\n * can ship open by omission, and nothing reaches a worker from outside.\n *\n * ## Crons on a server target need a database\n *\n * A cron becomes an EventBridge rule on AWS and nothing here is consulted. A\n * server has nothing firing its crons but itself, and a process that schedules\n * in memory fires every job once per replica while reporting success — so the\n * schedule is kept in Postgres, and the worker says which one with\n * `.database(db)`.\n *\n * A worker with crons and no `.database(…)` schedules nothing on a server\n * target and says so at startup. That is a limitation of workers today rather\n * than a design: the store could be a cache, or something the target\n * provisions, and Postgres is what exists.\n *\n * ## The database is everything's default\n *\n * The same `.database(db)` is the database every cron, queue, subscriber and\n * function built from the worker receives as `db`. The work a worker groups is\n * usually work against one database, and naming it per handler was a line\n * repeated in every file that could drift in any one of them. A runnable that\n * works against another names its own with `.database(other)`, which replaces\n * the worker's — client and manifest edge both — rather than adding to it.\n *\n * It is not an app: it declares no path, and its code lives in an app's\n * directory. But it is a process of its own. On a server target each worker\n * with work to do is built — from the app that holds that work — into an image\n * that runs its crons, consumers and subscribers and answers only a health\n * check, so a slow queue never shares a process with the requests an API\n * serves. `gkm dev` still runs everything in one process. Declare as many as\n * the shape of the work wants: each is one container.\n *\n * @example\n * ```ts\n * // constructs/worker.ts\n * import { Worker } from '@geekmidas/constructs/worker';\n * import { logger } from './logger.js';\n *\n * export const worker = new Worker('Worker', { logger }).database(database);\n *\n * // crons/cleanup.ts\n * import { worker } from '@acme/constructs/worker.js';\n *\n * export const cleanup = worker\n * .cron('rate(1 day)')\n * .handle(async ({ db, logger }) => { … });\n *\n * // queues/reports.ts — against another database than the worker's\n * export const reports = worker\n * .queue('Reports')\n * .database(analytics)\n * .message(z.object({ id: z.uuid() }))\n * .handle(async ({ messages, db }) => { … });\n * ```\n */\n\nimport type { EnvironmentParser } from '@geekmidas/envkit';\nimport type { EventPublisher } from '@geekmidas/events';\nimport type { Logger } from '@geekmidas/logger';\nimport { DEFAULT_LOGGER } from '@geekmidas/logger/console';\nimport {\n\ttype ConstructName,\n\tcanonicalId,\n\ttype Declaration,\n\ttype Dependency,\n} from '@geekmidas/manifest';\nimport type { ComposableStandardSchema } from '@geekmidas/schema';\nimport type { Service } from '@geekmidas/services';\nimport type { StandardSchemaV1 } from '@standard-schema/spec';\nimport {\n\ttype Consumable,\n\ttype Declarable,\n\tedgeTo,\n} from './construct-interface';\nimport type { ScheduleExpression } from './crons/Cron';\nimport { CronBuilder } from './crons/CronBuilder';\nimport { envParserFor } from './endpoints/surfaceEnv';\nimport { FunctionBuilder } from './functions/FunctionBuilder';\nimport { QueueBuilder } from './queue/QueueBuilder';\nimport { SubscriberBuilder } from './subscribers/SubscriberBuilder';\nimport type { Topic, TopicEvents } from './topic/Topic';\n\nexport interface WorkerConfig {\n\t/**\n\t * The logger everything built from this worker runs with.\n\t *\n\t * The actual logger, not a path to one — the same reason `RestApi` takes\n\t * one. Every cron and subscriber in a scaffolded project used to open with\n\t * `import { logger } from '…/constructs/logger.js'`, which is the line this\n\t * removes.\n\t */\n\tlogger?: Logger;\n\t/**\n\t * The environment parser everything built from this worker runs with.\n\t *\n\t * Defaults to `process.env` merged with the credentials `gkm dev` injected,\n\t * which is what an application's own `config/env.ts` always was.\n\t */\n\tenvParser?: EnvironmentParser<{}>;\n}\n\nexport class Worker<\n\tTName extends string = string,\n\tTDatabase = undefined,\n\tTDatabaseServiceName extends string = string,\n> implements Declarable<TName>\n{\n\treadonly id: TName;\n\n\t/** Always defined — the worker's own, or the console logger. */\n\treadonly logger: Logger;\n\n\t/** Always defined, and normally the default. */\n\treadonly envParser: EnvironmentParser<{}>;\n\n\t/**\n\t * Where this worker's schedules live, when it has crons and a server runs\n\t * them — and the database everything built from it receives as `db`.\n\t * `undefined` until `.database(…)` says.\n\t */\n\treadonly scheduleStore?: Consumable<string, unknown>;\n\n\tconstructor(\n\t\tid: ConstructName<TName>,\n\t\tprivate readonly config: WorkerConfig = {},\n\t\t/** Internal: how `.calls()` carries edges into the copy it returns. */\n\t\tprivate readonly dependencies: readonly Dependency[] = [],\n\t\tscheduleStore?: Consumable<string, unknown>,\n\t) {\n\t\tconst canonical = canonicalId(id as string);\n\n\t\tthis.id = canonical as TName;\n\t\tthis.logger = config.logger ?? DEFAULT_LOGGER;\n\t\tthis.envParser = envParserFor(\n\t\t\tconfig.envParser\n\t\t\t\t? { id: canonical, envParser: config.envParser }\n\t\t\t\t: undefined,\n\t\t);\n\t\tthis.scheduleStore = scheduleStore;\n\t}\n\n\t/**\n\t * The database this worker keeps its schedules in, and the one everything\n\t * built from it — crons, queues, subscribers, functions — receives as `db`.\n\t * One of them that works against another database names it with its own\n\t * `.database(other)`, which replaces this one for that runnable alone.\n\t *\n\t * Only a server target uses it. On AWS a cron is an EventBridge rule\n\t * invoking a Lambda and nothing here is consulted — but a server has nothing\n\t * firing its crons except itself, and a process that schedules in memory\n\t * fires every job once per replica while reporting that all is well.\n\t *\n\t * So the store is declared rather than discovered. It could have been\n\t * inferred — from a database the app happens to declare, or from the events\n\t * backend when that backend is pg-boss — and both would work until an app\n\t * had two databases, or moved its events to SNS, at which point the\n\t * schedules would quietly move or stop. Naming it is one line and cannot\n\t * drift.\n\t *\n\t * @example\n\t * ```ts\n\t * export const jobs = new Worker('Jobs', { logger }).database(database);\n\t *\n\t * export const sweep = jobs\n\t * .cron('rate(1 hour)')\n\t * .handle(async ({ db }) => db.deleteFrom('sessions').execute());\n\t * ```\n\t */\n\tdatabase<T, TDbName extends string>(\n\t\tsource: Consumable<TDbName, T>,\n\t): Worker<TName, T, TDbName> {\n\t\treturn new Worker<TName, T, TDbName>(\n\t\t\tthis.id as ConstructName<TName>,\n\t\t\tthis.config,\n\t\t\t[...this.dependencies, edgeTo(source)],\n\t\t\tsource as unknown as Consumable<string, unknown>,\n\t\t);\n\t}\n\n\t/**\n\t * A scheduled runnable.\n\t *\n\t * @example `worker.cron('rate(1 day)').handle(async ({ logger }) => { … })`\n\t */\n\tcron(schedule: ScheduleExpression) {\n\t\treturn this.own(\n\t\t\tnew CronBuilder<\n\t\t\t\tComposableStandardSchema,\n\t\t\t\tService[],\n\t\t\t\tLogger,\n\t\t\t\tundefined,\n\t\t\t\tTDatabase,\n\t\t\t\tTDatabaseServiceName\n\t\t\t>().logger(this.logger),\n\t\t).schedule(schedule);\n\t}\n\n\t/**\n\t * A queue and its one consumer, run by this worker.\n\t *\n\t * One construct, because a queue has exactly one consumer: nothing else can\n\t * attach a second, or forget to attach the first. Producers send to it by\n\t * depending on it — `.dependsOn([emails])` makes `services.emails` the\n\t * publisher.\n\t *\n\t * @example\n\t * ```ts\n\t * export const emails = worker\n\t * .queue('Emails')\n\t * .message(z.object({ userId: z.uuid(), template: z.string() }))\n\t * .handle(async ({ messages, services }) => { … });\n\t * ```\n\t */\n\tqueue<TQueueName extends string>(name: TQueueName) {\n\t\treturn this.own(\n\t\t\tnew QueueBuilder<\n\t\t\t\tstring,\n\t\t\t\tundefined,\n\t\t\t\t[],\n\t\t\t\tLogger,\n\t\t\t\tTDatabase,\n\t\t\t\tTDatabaseServiceName\n\t\t\t>().logger(this.logger),\n\t\t).queue(name);\n\t}\n\n\t/**\n\t * A runnable that consumes a topic.\n\t *\n\t * Binding is not publishing: a consumer is handed the topic's event types\n\t * and no connection string it could publish with. A handler that emits\n\t * follow-up events depends on the topic it emits to —\n\t * `.dependsOn([orders])` — which is the only reason it would need one.\n\t *\n\t * @example `worker.topic(users).subscribe(['user.created']).handle(…)`\n\t */\n\ttopic<TTopicName extends string, TEvents extends TopicEvents>(\n\t\ttopic: Topic<TTopicName, TEvents>,\n\t) {\n\t\treturn this.own(\n\t\t\tnew SubscriberBuilder<\n\t\t\t\t[],\n\t\t\t\tLogger,\n\t\t\t\tundefined,\n\t\t\t\tundefined,\n\t\t\t\t[],\n\t\t\t\tTDatabase,\n\t\t\t\tTDatabaseServiceName\n\t\t\t>().logger(this.logger),\n\t\t).topic(topic);\n\t}\n\n\t/**\n\t * Everything below builds a function — the runnable with no schedule and no\n\t * topic, invoked by something else.\n\t *\n\t * These sit on the worker rather than behind a `functions` namespace because\n\t * the namespace was a hop that said nothing: `worker.functions.input(…)`\n\t * names a collection to reach one member of it. What kind of runnable is\n\t * being built is decided by which of these is called first — a schedule\n\t * makes a cron, a topic makes a subscriber, and anything else makes a\n\t * function.\n\t */\n\tinput<T extends ComposableStandardSchema>(schema: T) {\n\t\treturn this.functions.input(schema);\n\t}\n\n\toutput<T extends StandardSchemaV1>(schema: T) {\n\t\treturn this.functions.output(schema);\n\t}\n\n\ttimeout(ms: number) {\n\t\treturn this.functions.timeout(ms);\n\t}\n\n\tmemorySize(mb: number) {\n\t\treturn this.functions.memorySize(mb);\n\t}\n\n\tdependsOn<const T extends readonly Consumable[]>(constructs: T) {\n\t\treturn this.functions.dependsOn(constructs);\n\t}\n\n\tservices<T extends Service[]>(services: T) {\n\t\treturn this.functions.services(services);\n\t}\n\n\t/**\n\t * A function with no input schema — the shortest runnable there is.\n\t *\n\t * @example `worker.handle(async ({ logger }) => { … })`\n\t */\n\thandle(\n\t\t...args: Parameters<\n\t\t\tReturnType<\n\t\t\t\tWorker<TName, TDatabase, TDatabaseServiceName>['schemalessFunction']\n\t\t\t>['handle']\n\t\t>\n\t) {\n\t\treturn this.schemalessFunction().handle(...args);\n\t}\n\n\t/** The builder `handle` delegates to, named so its type can be referred to. */\n\tprivate schemalessFunction() {\n\t\treturn this.functions;\n\t}\n\n\t/** The function builder the delegating methods above are built on. */\n\tprivate get functions() {\n\t\treturn this.own(\n\t\t\tnew FunctionBuilder<\n\t\t\t\tany,\n\t\t\t\tundefined,\n\t\t\t\t[],\n\t\t\t\tLogger,\n\t\t\t\tundefined,\n\t\t\t\tstring,\n\t\t\t\tTDatabase,\n\t\t\t\tTDatabaseServiceName\n\t\t\t>().logger(this.logger),\n\t\t);\n\t}\n\n\t/**\n\t * Resources and surfaces this worker calls.\n\t *\n\t * Not `.dependsOn()`: this records the edge that derives the worker's\n\t * environment and its access, the same distinction `RestApi.calls()` draws.\n\t */\n\tcalls(\n\t\tconstructs: readonly Declarable[],\n\t): Worker<TName, TDatabase, TDatabaseServiceName> {\n\t\treturn new Worker<TName, TDatabase, TDatabaseServiceName>(\n\t\t\tthis.id as ConstructName<TName>,\n\t\t\tthis.config,\n\t\t\t[...this.dependencies, ...constructs.map(edgeTo)],\n\t\t\tthis.scheduleStore,\n\t\t);\n\t}\n\n\t/**\n\t * Stamps this worker's id onto a builder, so everything built from it says\n\t * which process runs it — and hands it the worker's database.\n\t *\n\t * The database goes through the builder's own `.database()` rather than\n\t * being written into its fields, so the default is recorded exactly as an\n\t * explicit one would be: the client the handler gets, and the edge the\n\t * manifest reads. That is also what lets a later `.database(other)` replace\n\t * it outright. The builder arrives already typed with this worker's\n\t * database; this is the runtime half of that.\n\t */\n\tprivate own<\n\t\tT extends {\n\t\t\t_owner?: string;\n\t\t\t_scheduleStore?: unknown;\n\t\t\tdatabase(source: Consumable<string, unknown>): unknown;\n\t\t},\n\t>(builder: T): T {\n\t\tconst owned = this.scheduleStore\n\t\t\t? (builder.database(this.scheduleStore) as T)\n\t\t\t: builder;\n\n\t\towned._owner = this.id;\n\t\towned._scheduleStore = this.scheduleStore;\n\n\t\treturn owned;\n\t}\n\n\tdeclare(): Declaration[] {\n\t\treturn [\n\t\t\t{\n\t\t\t\tkind: 'worker',\n\t\t\t\tid: this.id,\n\t\t\t\t...(this.dependencies.length\n\t\t\t\t\t? { dependencies: this.dependencies }\n\t\t\t\t\t: {}),\n\t\t\t\t// Nothing calls a worker, so it publishes no address.\n\t\t\t\tprovides: [],\n\t\t\t},\n\t\t];\n\t}\n}\n"],"mappings":";;;;;;;;;AAsHA,IAAa,SAAb,MAAa,OAKb;CAkBmB;CAEA;CAnBlB;;CAGA;;CAGA;;;;;;CAOA;CAEA,YACC,IACA,SAAwC,CAAC,GAEzC,eAAuD,CAAC,GACxD,eACC;EAJgB,KAAA,SAAA;EAEA,KAAA,eAAA;EAGjB,MAAM,YAAY,YAAY,EAAY;EAE1C,KAAK,KAAK;EACV,KAAK,SAAS,OAAO,UAAU;EAC/B,KAAK,YAAY,aAChB,OAAO,YACJ;GAAE,IAAI;GAAW,WAAW,OAAO;EAAU,IAC7C,KAAA,CACJ;EACA,KAAK,gBAAgB;CACtB;;;;;;;;;;;;;;;;;;;;;;;;;;;;CA6BA,SACC,QAC4B;EAC5B,OAAO,IAAI,OACV,KAAK,IACL,KAAK,QACL,CAAC,GAAG,KAAK,cAAc,OAAO,MAAM,CAAC,GACrC,MACD;CACD;;;;;;CAOA,KAAK,UAA8B;EAClC,OAAO,KAAK,IACX,IAAI,YAOF,CAAC,CAAC,OAAO,KAAK,MAAM,CACvB,CAAC,CAAC,SAAS,QAAQ;CACpB;;;;;;;;;;;;;;;;;CAkBA,MAAiC,MAAkB;EAClD,OAAO,KAAK,IACX,IAAI,aAOF,CAAC,CAAC,OAAO,KAAK,MAAM,CAC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ACD;AACD"}
|
|
1
|
+
{"version":3,"file":"worker.mjs","names":[],"sources":["../src/worker.ts"],"sourcesContent":["/**\n * A process with no port.\n *\n * `RestApi` is the process that answers HTTP. This is the one that does not —\n * the thing that runs a schedule, drains a queue, consumes a topic. Until it\n * existed, those had nowhere to say they belonged: a cron declared a schedule\n * and nothing else, and which container ran it was decided by the directory the\n * file sat in. A glob owned it.\n *\n * The cost of that shows up in the scaffolds. `gkm init --template worker` —\n * a project that is background jobs and nothing else — declared\n * `new RestApi('Api', { defaultAuthorizer: 'none', logger })`: an HTTP surface\n * with no HTTP on it, written because it was the only construct that made an\n * app exist and the only way to get a logger into the generated runtime.\n *\n * It takes no authorizer, and that is the tell that these are two constructs\n * rather than one with a flag: a `RestApi` needs one because an HTTP surface\n * can ship open by omission, and nothing reaches a worker from outside.\n *\n * ## Crons on a server target need a database\n *\n * A cron becomes an EventBridge rule on AWS and nothing here is consulted. A\n * server has nothing firing its crons but itself, and a process that schedules\n * in memory fires every job once per replica while reporting success — so the\n * schedule is kept in Postgres, and the worker says which one with\n * `.database(db)`.\n *\n * A worker with crons and no `.database(…)` schedules nothing on a server\n * target and says so at startup. That is a limitation of workers today rather\n * than a design: the store could be a cache, or something the target\n * provisions, and Postgres is what exists.\n *\n * ## The database is everything's default\n *\n * The same `.database(db)` is the database every cron, queue, subscriber and\n * function built from the worker receives as `db`. The work a worker groups is\n * usually work against one database, and naming it per handler was a line\n * repeated in every file that could drift in any one of them. A runnable that\n * works against another names its own with `.database(other)`, which replaces\n * the worker's — client and manifest edge both — rather than adding to it.\n *\n * It is not an app: it declares no path, and its code lives in an app's\n * directory. But it is a process of its own. On a server target each worker\n * with work to do is built — from the app that holds that work — into an image\n * that runs its crons, consumers and subscribers and answers only a health\n * check, so a slow queue never shares a process with the requests an API\n * serves. `gkm dev` still runs everything in one process. Declare as many as\n * the shape of the work wants: each is one container.\n *\n * @example\n * ```ts\n * // constructs/worker.ts\n * import { Worker } from '@geekmidas/constructs/worker';\n * import { logger } from './logger.js';\n *\n * export const worker = new Worker('Worker', { logger }).database(database);\n *\n * // crons/cleanup.ts\n * import { worker } from '@acme/constructs/worker.js';\n *\n * export const cleanup = worker\n * .cron('rate(1 day)')\n * .handle(async ({ db, logger }) => { … });\n *\n * // queues/reports.ts — against another database than the worker's\n * export const reports = worker\n * .queue('Reports')\n * .database(analytics)\n * .message(z.object({ id: z.uuid() }))\n * .handle(async ({ messages, db }) => { … });\n * ```\n */\n\nimport type { EnvironmentParser } from '@geekmidas/envkit';\nimport type { EventPublisher } from '@geekmidas/events';\nimport type { Logger } from '@geekmidas/logger';\nimport { DEFAULT_LOGGER } from '@geekmidas/logger/console';\nimport {\n\ttype ConstructName,\n\tcanonicalId,\n\ttype Declaration,\n\ttype Dependency,\n} from '@geekmidas/manifest';\nimport type { ComposableStandardSchema } from '@geekmidas/schema';\nimport type { Service } from '@geekmidas/services';\nimport type { StandardSchemaV1 } from '@standard-schema/spec';\nimport {\n\ttype Consumable,\n\ttype Declarable,\n\tedgeTo,\n} from './construct-interface';\nimport type { ScheduleExpression } from './crons/Cron';\nimport { CronBuilder } from './crons/CronBuilder';\nimport { envParserFor } from './endpoints/surfaceEnv';\nimport { FunctionBuilder } from './functions/FunctionBuilder';\nimport { QueueBuilder } from './queue/QueueBuilder';\nimport { SubscriberBuilder } from './subscribers/SubscriberBuilder';\nimport type { Telemetry } from './telemetry';\nimport type { Topic, TopicEvents } from './topic/Topic';\n\nexport interface WorkerConfig {\n\t/**\n\t * The logger everything built from this worker runs with.\n\t *\n\t * The actual logger, not a path to one — the same reason `RestApi` takes\n\t * one. Every cron and subscriber in a scaffolded project used to open with\n\t * `import { logger } from '…/constructs/logger.js'`, which is the line this\n\t * removes.\n\t */\n\tlogger?: Logger;\n\t/**\n\t * The environment parser everything built from this worker runs with.\n\t *\n\t * Defaults to `process.env` merged with the credentials `gkm dev` injected,\n\t * which is what an application's own `config/env.ts` always was.\n\t */\n\tenvParser?: EnvironmentParser<{}>;\n\t/**\n\t * What the worker's process emits — the `Telemetry` construct, passed like\n\t * the logger. An edge to the node: the deploy hands the process the\n\t * `OTEL_*` keys its stage resolves.\n\t */\n\ttelemetry?: Telemetry;\n}\n\nexport class Worker<\n\tTName extends string = string,\n\tTDatabase = undefined,\n\tTDatabaseServiceName extends string = string,\n> implements Declarable<TName>\n{\n\treadonly id: TName;\n\n\t/** Always defined — the worker's own, or the console logger. */\n\treadonly logger: Logger;\n\n\t/** Always defined, and normally the default. */\n\treadonly envParser: EnvironmentParser<{}>;\n\n\t/**\n\t * Where this worker's schedules live, when it has crons and a server runs\n\t * them — and the database everything built from it receives as `db`.\n\t * `undefined` until `.database(…)` says.\n\t */\n\treadonly scheduleStore?: Consumable<string, unknown>;\n\n\tconstructor(\n\t\tid: ConstructName<TName>,\n\t\tprivate readonly config: WorkerConfig = {},\n\t\t/** Internal: how `.calls()` carries edges into the copy it returns. */\n\t\tprivate readonly dependencies: readonly Dependency[] = [],\n\t\tscheduleStore?: Consumable<string, unknown>,\n\t) {\n\t\tconst canonical = canonicalId(id as string);\n\n\t\tthis.id = canonical as TName;\n\t\tthis.logger = config.logger ?? DEFAULT_LOGGER;\n\t\tthis.envParser = envParserFor(\n\t\t\tconfig.envParser\n\t\t\t\t? { id: canonical, envParser: config.envParser }\n\t\t\t\t: undefined,\n\t\t);\n\t\tthis.scheduleStore = scheduleStore;\n\t}\n\n\t/**\n\t * The database this worker keeps its schedules in, and the one everything\n\t * built from it — crons, queues, subscribers, functions — receives as `db`.\n\t * One of them that works against another database names it with its own\n\t * `.database(other)`, which replaces this one for that runnable alone.\n\t *\n\t * Only a server target uses it. On AWS a cron is an EventBridge rule\n\t * invoking a Lambda and nothing here is consulted — but a server has nothing\n\t * firing its crons except itself, and a process that schedules in memory\n\t * fires every job once per replica while reporting that all is well.\n\t *\n\t * So the store is declared rather than discovered. It could have been\n\t * inferred — from a database the app happens to declare, or from the events\n\t * backend when that backend is pg-boss — and both would work until an app\n\t * had two databases, or moved its events to SNS, at which point the\n\t * schedules would quietly move or stop. Naming it is one line and cannot\n\t * drift.\n\t *\n\t * @example\n\t * ```ts\n\t * export const jobs = new Worker('Jobs', { logger }).database(database);\n\t *\n\t * export const sweep = jobs\n\t * .cron('rate(1 hour)')\n\t * .handle(async ({ db }) => db.deleteFrom('sessions').execute());\n\t * ```\n\t */\n\tdatabase<T, TDbName extends string>(\n\t\tsource: Consumable<TDbName, T>,\n\t): Worker<TName, T, TDbName> {\n\t\treturn new Worker<TName, T, TDbName>(\n\t\t\tthis.id as ConstructName<TName>,\n\t\t\tthis.config,\n\t\t\t[...this.dependencies, edgeTo(source)],\n\t\t\tsource as unknown as Consumable<string, unknown>,\n\t\t);\n\t}\n\n\t/**\n\t * A scheduled runnable.\n\t *\n\t * @example `worker.cron('rate(1 day)').handle(async ({ logger }) => { … })`\n\t */\n\tcron(schedule: ScheduleExpression) {\n\t\treturn this.own(\n\t\t\tnew CronBuilder<\n\t\t\t\tComposableStandardSchema,\n\t\t\t\tService[],\n\t\t\t\tLogger,\n\t\t\t\tundefined,\n\t\t\t\tTDatabase,\n\t\t\t\tTDatabaseServiceName\n\t\t\t>().logger(this.logger),\n\t\t).schedule(schedule);\n\t}\n\n\t/**\n\t * A queue and its one consumer, run by this worker.\n\t *\n\t * One construct, because a queue has exactly one consumer: nothing else can\n\t * attach a second, or forget to attach the first. Producers send to it by\n\t * depending on it — `.dependsOn([emails])` makes `services.emails` the\n\t * publisher.\n\t *\n\t * @example\n\t * ```ts\n\t * export const emails = worker\n\t * .queue('Emails')\n\t * .message(z.object({ userId: z.uuid(), template: z.string() }))\n\t * .handle(async ({ messages, services }) => { … });\n\t * ```\n\t */\n\tqueue<TQueueName extends string>(name: TQueueName) {\n\t\treturn this.own(\n\t\t\tnew QueueBuilder<\n\t\t\t\tstring,\n\t\t\t\tundefined,\n\t\t\t\t[],\n\t\t\t\tLogger,\n\t\t\t\tTDatabase,\n\t\t\t\tTDatabaseServiceName\n\t\t\t>().logger(this.logger),\n\t\t).queue(name);\n\t}\n\n\t/**\n\t * A runnable that consumes a topic.\n\t *\n\t * Binding is not publishing: a consumer is handed the topic's event types\n\t * and no connection string it could publish with. A handler that emits\n\t * follow-up events depends on the topic it emits to —\n\t * `.dependsOn([orders])` — which is the only reason it would need one.\n\t *\n\t * @example `worker.topic(users).subscribe(['user.created']).handle(…)`\n\t */\n\ttopic<TTopicName extends string, TEvents extends TopicEvents>(\n\t\ttopic: Topic<TTopicName, TEvents>,\n\t) {\n\t\treturn this.own(\n\t\t\tnew SubscriberBuilder<\n\t\t\t\t[],\n\t\t\t\tLogger,\n\t\t\t\tundefined,\n\t\t\t\tundefined,\n\t\t\t\t[],\n\t\t\t\tTDatabase,\n\t\t\t\tTDatabaseServiceName\n\t\t\t>().logger(this.logger),\n\t\t).topic(topic);\n\t}\n\n\t/**\n\t * Everything below builds a function — the runnable with no schedule and no\n\t * topic, invoked by something else.\n\t *\n\t * These sit on the worker rather than behind a `functions` namespace because\n\t * the namespace was a hop that said nothing: `worker.functions.input(…)`\n\t * names a collection to reach one member of it. What kind of runnable is\n\t * being built is decided by which of these is called first — a schedule\n\t * makes a cron, a topic makes a subscriber, and anything else makes a\n\t * function.\n\t */\n\tinput<T extends ComposableStandardSchema>(schema: T) {\n\t\treturn this.functions.input(schema);\n\t}\n\n\toutput<T extends StandardSchemaV1>(schema: T) {\n\t\treturn this.functions.output(schema);\n\t}\n\n\ttimeout(ms: number) {\n\t\treturn this.functions.timeout(ms);\n\t}\n\n\tmemorySize(mb: number) {\n\t\treturn this.functions.memorySize(mb);\n\t}\n\n\tdependsOn<const T extends readonly Consumable[]>(constructs: T) {\n\t\treturn this.functions.dependsOn(constructs);\n\t}\n\n\tservices<T extends Service[]>(services: T) {\n\t\treturn this.functions.services(services);\n\t}\n\n\t/**\n\t * A function with no input schema — the shortest runnable there is.\n\t *\n\t * @example `worker.handle(async ({ logger }) => { … })`\n\t */\n\thandle(\n\t\t...args: Parameters<\n\t\t\tReturnType<\n\t\t\t\tWorker<TName, TDatabase, TDatabaseServiceName>['schemalessFunction']\n\t\t\t>['handle']\n\t\t>\n\t) {\n\t\treturn this.schemalessFunction().handle(...args);\n\t}\n\n\t/** The builder `handle` delegates to, named so its type can be referred to. */\n\tprivate schemalessFunction() {\n\t\treturn this.functions;\n\t}\n\n\t/** The function builder the delegating methods above are built on. */\n\tprivate get functions() {\n\t\treturn this.own(\n\t\t\tnew FunctionBuilder<\n\t\t\t\tany,\n\t\t\t\tundefined,\n\t\t\t\t[],\n\t\t\t\tLogger,\n\t\t\t\tundefined,\n\t\t\t\tstring,\n\t\t\t\tTDatabase,\n\t\t\t\tTDatabaseServiceName\n\t\t\t>().logger(this.logger),\n\t\t);\n\t}\n\n\t/**\n\t * Resources and surfaces this worker calls.\n\t *\n\t * Not `.dependsOn()`: this records the edge that derives the worker's\n\t * environment and its access, the same distinction `RestApi.calls()` draws.\n\t */\n\tcalls(\n\t\tconstructs: readonly Declarable[],\n\t): Worker<TName, TDatabase, TDatabaseServiceName> {\n\t\treturn new Worker<TName, TDatabase, TDatabaseServiceName>(\n\t\t\tthis.id as ConstructName<TName>,\n\t\t\tthis.config,\n\t\t\t[...this.dependencies, ...constructs.map(edgeTo)],\n\t\t\tthis.scheduleStore,\n\t\t);\n\t}\n\n\t/**\n\t * Stamps this worker's id onto a builder, so everything built from it says\n\t * which process runs it — and hands it the worker's database.\n\t *\n\t * The database goes through the builder's own `.database()` rather than\n\t * being written into its fields, so the default is recorded exactly as an\n\t * explicit one would be: the client the handler gets, and the edge the\n\t * manifest reads. That is also what lets a later `.database(other)` replace\n\t * it outright. The builder arrives already typed with this worker's\n\t * database; this is the runtime half of that.\n\t */\n\tprivate own<\n\t\tT extends {\n\t\t\t_owner?: string;\n\t\t\t_scheduleStore?: unknown;\n\t\t\tdatabase(source: Consumable<string, unknown>): unknown;\n\t\t},\n\t>(builder: T): T {\n\t\tconst owned = this.scheduleStore\n\t\t\t? (builder.database(this.scheduleStore) as T)\n\t\t\t: builder;\n\n\t\towned._owner = this.id;\n\t\towned._scheduleStore = this.scheduleStore;\n\n\t\treturn owned;\n\t}\n\n\tdeclare(): Declaration[] {\n\t\treturn [\n\t\t\t{\n\t\t\t\tkind: 'worker',\n\t\t\t\tid: this.id,\n\t\t\t\t...(this.dependencies.length\n\t\t\t\t\t? { dependencies: this.dependencies }\n\t\t\t\t\t: {}),\n\t\t\t\t...(this.config.telemetry\n\t\t\t\t\t? { telemetry: this.config.telemetry.id }\n\t\t\t\t\t: {}),\n\t\t\t\t// Nothing calls a worker, so it publishes no address.\n\t\t\t\tprovides: [],\n\t\t\t},\n\t\t];\n\t}\n}\n"],"mappings":";;;;;;;;;AA6HA,IAAa,SAAb,MAAa,OAKb;CAkBmB;CAEA;CAnBlB;;CAGA;;CAGA;;;;;;CAOA;CAEA,YACC,IACA,SAAwC,CAAC,GAEzC,eAAuD,CAAC,GACxD,eACC;EAJgB,KAAA,SAAA;EAEA,KAAA,eAAA;EAGjB,MAAM,YAAY,YAAY,EAAY;EAE1C,KAAK,KAAK;EACV,KAAK,SAAS,OAAO,UAAU;EAC/B,KAAK,YAAY,aAChB,OAAO,YACJ;GAAE,IAAI;GAAW,WAAW,OAAO;EAAU,IAC7C,KAAA,CACJ;EACA,KAAK,gBAAgB;CACtB;;;;;;;;;;;;;;;;;;;;;;;;;;;;CA6BA,SACC,QAC4B;EAC5B,OAAO,IAAI,OACV,KAAK,IACL,KAAK,QACL,CAAC,GAAG,KAAK,cAAc,OAAO,MAAM,CAAC,GACrC,MACD;CACD;;;;;;CAOA,KAAK,UAA8B;EAClC,OAAO,KAAK,IACX,IAAI,YAOF,CAAC,CAAC,OAAO,KAAK,MAAM,CACvB,CAAC,CAAC,SAAS,QAAQ;CACpB;;;;;;;;;;;;;;;;;CAkBA,MAAiC,MAAkB;EAClD,OAAO,KAAK,IACX,IAAI,aAOF,CAAC,CAAC,OAAO,KAAK,MAAM,CACvB,CAAC,CAAC,MAAM,IAAI;CACb;;;;;;;;;;;CAYA,MACC,OACC;E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