@geekmidas/constructs 10.0.0-alpha.78 → 10.0.0-alpha.80
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/{Queue-umpX3683.cjs → Queue-A3wfD0it.cjs} +2 -2
- package/dist/{Queue-umpX3683.cjs.map → Queue-A3wfD0it.cjs.map} +1 -1
- package/dist/{Queue-CLRT_j5a.mjs → Queue-D6USGS4q.mjs} +2 -2
- package/dist/{Queue-CLRT_j5a.mjs.map → Queue-D6USGS4q.mjs.map} +1 -1
- package/dist/{QueueBuilder-B9ClmXjX.cjs → QueueBuilder-BjuF0UBl.cjs} +2 -2
- package/dist/{QueueBuilder-B9ClmXjX.cjs.map → QueueBuilder-BjuF0UBl.cjs.map} +1 -1
- package/dist/{QueueBuilder-B0mCqq74.mjs → QueueBuilder-Cue73M4t.mjs} +2 -2
- package/dist/{QueueBuilder-B0mCqq74.mjs.map → QueueBuilder-Cue73M4t.mjs.map} +1 -1
- package/dist/{Topic-DCxIstf9.mjs → Topic-D74b5cgs.mjs} +2 -2
- package/dist/{Topic-DCxIstf9.mjs.map → Topic-D74b5cgs.mjs.map} +1 -1
- package/dist/{Topic-BliAKi5r.cjs → Topic-GHxcU8AG.cjs} +2 -2
- package/dist/{Topic-BliAKi5r.cjs.map → Topic-GHxcU8AG.cjs.map} +1 -1
- package/dist/adaptors/aws.cjs +11 -2
- package/dist/adaptors/aws.cjs.map +1 -1
- package/dist/adaptors/aws.d.cts.map +1 -1
- package/dist/adaptors/aws.d.mts +1 -1
- package/dist/adaptors/aws.d.mts.map +1 -1
- package/dist/adaptors/aws.mjs +11 -2
- package/dist/adaptors/aws.mjs.map +1 -1
- package/dist/adaptors/testing.cjs +3 -3
- package/dist/adaptors/testing.mjs +3 -3
- package/dist/crons/index.cjs +25 -1
- package/dist/crons/index.cjs.map +1 -1
- package/dist/crons/index.d.cts +6 -1
- package/dist/crons/index.d.cts.map +1 -1
- package/dist/crons/index.d.mts +6 -1
- package/dist/crons/index.d.mts.map +1 -1
- package/dist/crons/index.mjs +25 -1
- package/dist/crons/index.mjs.map +1 -1
- package/dist/database/kysely.cjs +1 -1
- package/dist/database/kysely.mjs +1 -1
- package/dist/external-api-BEgXYeJD.d.mts.map +1 -1
- package/dist/external-api-BaIgJ6Ey.d.cts.map +1 -1
- package/dist/external-api.cjs +10 -1
- package/dist/external-api.cjs.map +1 -1
- package/dist/external-api.mjs +10 -1
- package/dist/external-api.mjs.map +1 -1
- package/dist/kysely-BEm5sDlU.d.cts.map +1 -1
- package/dist/kysely-CjuvdXEV.d.mts.map +1 -1
- package/dist/{kysely-BhJ3lLdE.mjs → kysely-DN88k0gD.mjs} +93 -23
- package/dist/kysely-DN88k0gD.mjs.map +1 -0
- package/dist/{kysely-B-xWOGmn.cjs → kysely-H7L1YDgE.cjs} +93 -23
- package/dist/kysely-H7L1YDgE.cjs.map +1 -0
- package/dist/queue/index.cjs +2 -2
- package/dist/queue/index.mjs +2 -2
- package/dist/subscribers/index.cjs +22 -15
- package/dist/subscribers/index.cjs.map +1 -1
- package/dist/subscribers/index.d.cts +1 -0
- package/dist/subscribers/index.d.cts.map +1 -1
- package/dist/subscribers/index.d.mts +1 -0
- package/dist/subscribers/index.d.mts.map +1 -1
- package/dist/subscribers/index.mjs +22 -15
- package/dist/subscribers/index.mjs.map +1 -1
- package/dist/topic/index.cjs +1 -1
- package/dist/topic/index.mjs +1 -1
- package/dist/tracing-3PpqRX07.cjs +98 -0
- package/dist/tracing-3PpqRX07.cjs.map +1 -0
- package/dist/tracing-DbcPuhEy.mjs +87 -0
- package/dist/tracing-DbcPuhEy.mjs.map +1 -0
- package/dist/worker.cjs +1 -1
- package/dist/worker.mjs +1 -1
- package/package.json +33 -31
- package/dist/kysely-B-xWOGmn.cjs.map +0 -1
- package/dist/kysely-BhJ3lLdE.mjs.map +0 -1
package/dist/crons/index.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.mjs","names":[],"sources":["../../src/crons/inProcess.ts","../../src/crons/runCron.ts","../../src/crons/schedule.ts"],"sourcesContent":["import { CronExpressionParser } from 'cron-parser';\n\n/**\n * The longest delay a timer takes. Node clamps anything longer to 1ms, so a\n * monthly cron would fire at once and then every millisecond.\n */\nconst MAX_DELAY = 2 ** 31 - 1;\n\n/** A schedule that is running, and the way to stop it. */\nexport interface InProcessSchedule {\n\tstop(): void;\n}\n\n/**\n * Run `fire` on a cron expression, in this process, by timer.\n *\n * For the one process that has no broker to keep a schedule: `gkm dev` on a\n * target whose crons are infrastructure once deployed — an EventBridge rule on\n * AWS. Deployed, a timer is the wrong tool: each replica would fire every job\n * once, and nothing would say so. That is why a server schedules through\n * pg-boss, and why this is never what a deployed process does.\n *\n * In UTC, as the deployed schedule is. The next firing is worked out from the\n * clock after each run rather than read off a sequence, so a run that outlasts\n * its interval skips what it overran instead of firing them back to back.\n */\nexport function scheduleInProcess(\n\texpression: string,\n\tfire: () => Promise<unknown> | unknown,\n): InProcessSchedule {\n\t// Parsed once up front, so a bad expression throws here — to the caller\n\t// scheduling it — rather than inside a timer.\n\tCronExpressionParser.parse(expression, { tz: 'UTC' });\n\n\tlet timer: ReturnType<typeof setTimeout> | undefined;\n\tlet stopped = false;\n\n\tconst arm = (at: number) => {\n\t\tif (stopped) return;\n\t\tconst delay = at - Date.now();\n\t\ttimer = setTimeout(\n\t\t\tasync () => {\n\t\t\t\tif (Date.now() < at) return arm(at);\n\t\t\t\tawait fire();\n\t\t\t\tarm(nextAfter(expression, new Date()));\n\t\t\t},\n\t\t\tMath.min(Math.max(delay, 0), MAX_DELAY),\n\t\t);\n\t\t// The server keeps the process alive; a schedule alone should not.\n\t\ttimer.unref?.();\n\t};\n\n\tarm(nextAfter(expression, new Date()));\n\n\treturn {\n\t\tstop() {\n\t\t\tstopped = true;\n\t\t\tclearTimeout(timer);\n\t\t},\n\t};\n}\n\nfunction nextAfter(expression: string, from: Date): number {\n\treturn CronExpressionParser.parse(expression, {\n\t\ttz: 'UTC',\n\t\tcurrentDate: from,\n\t})\n\t\t.next()\n\t\t.getTime();\n}\n","import type { AuditStorage } from '@geekmidas/audit';\nimport {\n\trunWithRequestContext,\n\ttype ServiceDiscovery,\n} from '@geekmidas/services';\nimport { publishEvents } from '../publisher';\nimport type { Cron } from './Cron';\n\n/**\n * Run a cron once, in this process: what an EventBridge rule's invocation does\n * on Lambda, for a server that schedules its own.\n *\n * The same steps as the Lambda adaptor — its services, its worker's database\n * as `db`, an auditor when it declared one, its output parsed, its events\n * published — because a cron that ran differently on a server than deployed\n * would pass locally and fail where it matters. Services come through the\n * discovery, which keeps one instance of each, so running every minute does not\n * reconnect a database every minute.\n */\nexport async function runCron(\n\tcron: Cron<any, any, any, any, any, any>,\n\tserviceDiscovery: ServiceDiscovery<any>,\n): Promise<unknown> {\n\tconst services =\n\t\tcron.services.length > 0\n\t\t\t? await serviceDiscovery.register(cron.services)\n\t\t\t: {};\n\n\tconst db = cron.databaseService\n\t\t? (await serviceDiscovery.register([cron.databaseService]))[\n\t\t\t\tcron.databaseService.serviceName\n\t\t\t]\n\t\t: undefined;\n\n\t// Only imported for a cron that audits: `@geekmidas/audit` is optional.\n\tlet auditor: { flush(): Promise<void> } | undefined;\n\tif (cron.auditorStorageService) {\n\t\tconst { DefaultAuditor } = await import('@geekmidas/audit');\n\t\tconst registered: Record<string, unknown> = await serviceDiscovery.register(\n\t\t\t[cron.auditorStorageService],\n\t\t);\n\t\tconst storage = registered[\n\t\t\tcron.auditorStorageService.serviceName\n\t\t] as AuditStorage;\n\t\tauditor = new DefaultAuditor({\n\t\t\tactor: { id: 'system', type: 'system' },\n\t\t\tstorage,\n\t\t\tmetadata: { function: cron.type },\n\t\t});\n\t}\n\n\tconst logger = cron.logger;\n\tconst requestId = `cron-${Date.now()}`;\n\n\treturn runWithRequestContext(\n\t\t{\n\t\t\tlogger,\n\t\t\trequestId,\n\t\t\tstartTime: Date.now(),\n\t\t\toperation: `cron ${cron.schedule ?? 'manual'}`,\n\t\t},\n\t\tasync () => {\n\t\t\tconst response = await cron.fn({\n\t\t\t\tinput: undefined,\n\t\t\t\tservices,\n\t\t\t\tlogger,\n\t\t\t\tdb,\n\t\t\t\tauditor,\n\t\t\t} as any);\n\t\t\tconst output = await cron.parseOutput(response);\n\n\t\t\tawait auditor?.flush();\n\t\t\t// The cron's output schema is erased by the `any` it is typed with here.\n\t\t\tawait publishEvents(\n\t\t\t\tlogger,\n\t\t\t\tserviceDiscovery,\n\t\t\t\tcron.events,\n\t\t\t\toutput as never,\n\t\t\t);\n\n\t\t\treturn output;\n\t\t},\n\t);\n}\n","import type { ScheduleExpression } from './Cron';\n\n/**\n * A schedule a cron runner can take, as standard five-field cron.\n *\n * `ScheduleExpression` has two spellings. `cron(m h dom mon dow)` is already\n * five-field cron and unwraps; `rate(n unit)` is an interval, and an interval\n * is not a schedule — it says how often, where cron says when.\n *\n * Most intervals still have an exact cron equivalent, because they divide their\n * unit evenly: `rate(5 minutes)` is every fifth minute of every hour, and that\n * is `*/5 * * * *` precisely. `rate(7 hours)` has none. There is no cron field\n * that means \"every seven hours\" — `*/7` in the hour field fires at 0, 7, 14\n * and 21 and then starts over at midnight, so the gap between the last firing\n * of one day and the first of the next is three hours rather than seven.\n *\n * Those are refused rather than rounded. A job that runs at the wrong hour is\n * far harder to notice than one that refused to build, and a schedule quietly\n * adjusted by the framework is a bug nobody goes looking for.\n */\nexport class UnrepresentableSchedule extends Error {\n\tconstructor(\n\t\treadonly schedule: string,\n\t\treason: string,\n\t) {\n\t\tsuper(\n\t\t\t`\\`${schedule}\\` has no exact cron equivalent: ${reason}.\\n\\n` +\n\t\t\t\t'Cron says *when*, not *how often*, so an interval is only exact when ' +\n\t\t\t\t'it divides its unit evenly.\\n' +\n\t\t\t\t'Write the schedule you mean instead — `cron(0 */6 * * *)` for every ' +\n\t\t\t\t'sixth hour, say — or pick an interval that divides: minutes into 60, ' +\n\t\t\t\t'hours into 24.',\n\t\t);\n\t\tthis.name = 'UnrepresentableSchedule';\n\t}\n}\n\n/** Units `rate(…)` accepts, singular or plural. */\nconst UNITS = ['minute', 'hour', 'day'] as const;\ntype Unit = (typeof UNITS)[number];\n\n/**\n * Standard five-field cron for a schedule expression.\n *\n * @throws {UnrepresentableSchedule} when a `rate(…)` has no exact equivalent.\n */\nexport function toCronExpression(schedule: ScheduleExpression): string {\n\tconst cron = /^cron\\((.+)\\)$/.exec(schedule);\n\tif (cron?.[1]) return cron[1].trim();\n\n\tconst rate = /^rate\\(\\s*(\\d+)\\s+(\\w+?)s?\\s*\\)$/.exec(schedule);\n\tif (!rate) {\n\t\tthrow new UnrepresentableSchedule(\n\t\t\tschedule,\n\t\t\t'it is neither `cron(…)` nor `rate(n unit)`',\n\t\t);\n\t}\n\n\tconst every = Number(rate[1]);\n\tconst unit = rate[2] as Unit;\n\t/* c8 ignore next */ if (!unit)\n\t\tthrow new UnrepresentableSchedule(schedule, 'no unit');\n\n\tif (!UNITS.includes(unit)) {\n\t\tthrow new UnrepresentableSchedule(\n\t\t\tschedule,\n\t\t\t`\\`${unit}\\` is not one of ${UNITS.join(', ')}`,\n\t\t);\n\t}\n\n\tif (every < 1) {\n\t\tthrow new UnrepresentableSchedule(\n\t\t\tschedule,\n\t\t\t'an interval must be at least 1',\n\t\t);\n\t}\n\n\tswitch (unit) {\n\t\tcase 'minute':\n\t\t\tif (every === 1) return '* * * * *';\n\t\t\tif (60 % every !== 0) {\n\t\t\t\tthrow new UnrepresentableSchedule(\n\t\t\t\t\tschedule,\n\t\t\t\t\t`${every} does not divide 60, so the interval would reset at the top of each hour`,\n\t\t\t\t);\n\t\t\t}\n\t\t\treturn `*/${every} * * * *`;\n\n\t\tcase 'hour':\n\t\t\tif (every === 1) return '0 * * * *';\n\t\t\tif (24 % every !== 0) {\n\t\t\t\tthrow new UnrepresentableSchedule(\n\t\t\t\t\tschedule,\n\t\t\t\t\t`${every} does not divide 24, so the interval would reset at midnight`,\n\t\t\t\t);\n\t\t\t}\n\t\t\treturn `0 */${every} * * *`;\n\n\t\tcase 'day':\n\t\t\tif (every === 1) return '0 0 * * *';\n\t\t\t// `*/n` in day-of-month restarts on the 1st, so a 2-day interval fires\n\t\t\t// on the 1st and 3rd of a 31-day month and then again on the 1st — one\n\t\t\t// day later, not two. No month length makes that come out even.\n\t\t\tthrow new UnrepresentableSchedule(\n\t\t\t\tschedule,\n\t\t\t\t'day-of-month restarts every month, so no multi-day interval is even',\n\t\t\t);\n\t}\n}\n"],"mappings":";;;;;;;;;AAMA,MAAM,YAAY,KAAK,KAAK;;;;;;;;;;;;;;AAoB5B,SAAgB,kBACf,YACA,MACoB;CAGpB,qBAAqB,MAAM,YAAY,EAAE,IAAI,MAAM,CAAC;CAEpD,IAAI;CACJ,IAAI,UAAU;CAEd,MAAM,OAAO,OAAe;EAC3B,IAAI,SAAS;EACb,MAAM,QAAQ,KAAK,KAAK,IAAI;EAC5B,QAAQ,WACP,YAAY;GACX,IAAI,KAAK,IAAI,IAAI,IAAI,OAAO,IAAI,EAAE;GAClC,MAAM,KAAK;GACX,IAAI,UAAU,4BAAY,IAAI,KAAK,CAAC,CAAC;EACtC,GACA,KAAK,IAAI,KAAK,IAAI,OAAO,CAAC,GAAG,SAAS,CACvC;EAEA,MAAM,QAAQ;CACf;CAEA,IAAI,UAAU,4BAAY,IAAI,KAAK,CAAC,CAAC;CAErC,OAAO,EACN,OAAO;EACN,UAAU;EACV,aAAa,KAAK;CACnB,EACD;AACD;AAEA,SAAS,UAAU,YAAoB,MAAoB;CAC1D,OAAO,qBAAqB,MAAM,YAAY;EAC7C,IAAI;EACJ,aAAa;CACd,CAAC,CAAC,CACA,KAAK,CAAC,CACN,QAAQ;AACX;;;;;;;;;;;;;;AClDA,eAAsB,QACrB,MACA,kBACmB;CACnB,MAAM,WACL,KAAK,SAAS,SAAS,IACpB,MAAM,iBAAiB,SAAS,KAAK,QAAQ,IAC7C,CAAC;CAEL,MAAM,KAAK,KAAK,mBACZ,MAAM,iBAAiB,SAAS,CA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,MAAM,OAAO,KAAK;sBACG,IAAI,CAAC,MACzB,MAAM,IAAI,wBAAwB,UAAU,SAAS;CAEtD,IAAI,CAAC,MAAM,SAAS,IAAI,GACvB,MAAM,IAAI,wBACT,UACA,KAAK,KAAK,mBAAmB,MAAM,KAAK,IAAI,GAC7C;CAGD,IAAI,QAAQ,GACX,MAAM,IAAI,wBACT,UACA,gCACD;CAGD,QAAQ,MAAR;EACC,KAAK;GACJ,IAAI,UAAU,GAAG,OAAO;GACxB,IAAI,KAAK,UAAU,GAClB,MAAM,IAAI,wBACT,UACA,GAAG,MAAM,yEACV;GAED,OAAO,KAAK,MAAM;EAEnB,KAAK;GACJ,IAAI,UAAU,GAAG,OAAO;GACxB,IAAI,KAAK,UAAU,GAClB,MAAM,IAAI,wBACT,UACA,GAAG,MAAM,6DACV;GAED,OAAO,OAAO,MAAM;EAErB,KAAK;GACJ,IAAI,UAAU,GAAG,OAAO;GAIxB,MAAM,IAAI,wBACT,UACA,qEACD;CACF;AACD"}
|
|
1
|
+
{"version":3,"file":"index.mjs","names":[],"sources":["../../src/crons/inProcess.ts","../../src/crons/runCron.ts","../../src/crons/schedule.ts"],"sourcesContent":["import { CronExpressionParser } from 'cron-parser';\n\n/**\n * The longest delay a timer takes. Node clamps anything longer to 1ms, so a\n * monthly cron would fire at once and then every millisecond.\n */\nconst MAX_DELAY = 2 ** 31 - 1;\n\n/** A schedule that is running, and the way to stop it. */\nexport interface InProcessSchedule {\n\tstop(): void;\n}\n\n/**\n * Run `fire` on a cron expression, in this process, by timer.\n *\n * For the one process that has no broker to keep a schedule: `gkm dev` on a\n * target whose crons are infrastructure once deployed — an EventBridge rule on\n * AWS. Deployed, a timer is the wrong tool: each replica would fire every job\n * once, and nothing would say so. That is why a server schedules through\n * pg-boss, and why this is never what a deployed process does.\n *\n * In UTC, as the deployed schedule is. The next firing is worked out from the\n * clock after each run rather than read off a sequence, so a run that outlasts\n * its interval skips what it overran instead of firing them back to back.\n */\nexport function scheduleInProcess(\n\texpression: string,\n\tfire: () => Promise<unknown> | unknown,\n): InProcessSchedule {\n\t// Parsed once up front, so a bad expression throws here — to the caller\n\t// scheduling it — rather than inside a timer.\n\tCronExpressionParser.parse(expression, { tz: 'UTC' });\n\n\tlet timer: ReturnType<typeof setTimeout> | undefined;\n\tlet stopped = false;\n\n\tconst arm = (at: number) => {\n\t\tif (stopped) return;\n\t\tconst delay = at - Date.now();\n\t\ttimer = setTimeout(\n\t\t\tasync () => {\n\t\t\t\tif (Date.now() < at) return arm(at);\n\t\t\t\tawait fire();\n\t\t\t\tarm(nextAfter(expression, new Date()));\n\t\t\t},\n\t\t\tMath.min(Math.max(delay, 0), MAX_DELAY),\n\t\t);\n\t\t// The server keeps the process alive; a schedule alone should not.\n\t\ttimer.unref?.();\n\t};\n\n\tarm(nextAfter(expression, new Date()));\n\n\treturn {\n\t\tstop() {\n\t\t\tstopped = true;\n\t\t\tclearTimeout(timer);\n\t\t},\n\t};\n}\n\nfunction nextAfter(expression: string, from: Date): number {\n\treturn CronExpressionParser.parse(expression, {\n\t\ttz: 'UTC',\n\t\tcurrentDate: from,\n\t})\n\t\t.next()\n\t\t.getTime();\n}\n","import type { AuditStorage } from '@geekmidas/audit';\nimport {\n\trunWithRequestContext,\n\ttype ServiceDiscovery,\n} from '@geekmidas/services';\nimport {\n\tcontext,\n\tROOT_CONTEXT,\n\tSpanKind,\n\tSpanStatusCode,\n\ttrace,\n} from '@opentelemetry/api';\nimport { publishEvents } from '../publisher';\nimport type { Cron } from './Cron';\n\n/**\n * Run a cron once, in this process: what an EventBridge rule's invocation does\n * on Lambda, for a server that schedules its own.\n *\n * The same steps as the Lambda adaptor — its services, its worker's database\n * as `db`, an auditor when it declared one, its output parsed, its events\n * published — because a cron that ran differently on a server than deployed\n * would pass locally and fail where it matters. Services come through the\n * discovery, which keeps one instance of each, so running every minute does not\n * reconnect a database every minute.\n *\n * Each run is a trace of its own: a root span, `cron <name>`, whatever was\n * active when the timer or the broker fired it.\n */\nexport async function runCron(\n\tcron: Cron<any, any, any, any, any, any>,\n\tserviceDiscovery: ServiceDiscovery<any>,\n\t/** The cron's export name, for its span. */\n\tname?: string,\n): Promise<unknown> {\n\tconst span = trace.getTracer('@geekmidas/constructs').startSpan(\n\t\t`cron ${name ?? cron.schedule ?? 'manual'}`,\n\t\t{\n\t\t\tkind: SpanKind.INTERNAL,\n\t\t\tattributes: {\n\t\t\t\t...(name && { 'gkm.cron.name': name }),\n\t\t\t\t...(cron.schedule && { 'gkm.cron.schedule': cron.schedule }),\n\t\t\t},\n\t\t},\n\t\tROOT_CONTEXT,\n\t);\n\n\treturn context.with(trace.setSpan(ROOT_CONTEXT, span), async () => {\n\t\ttry {\n\t\t\treturn await run(cron, serviceDiscovery);\n\t\t} catch (error) {\n\t\t\tif (error instanceof Error) span.recordException(error);\n\t\t\tspan.setStatus({ code: SpanStatusCode.ERROR });\n\t\t\tthrow error;\n\t\t} finally {\n\t\t\tspan.end();\n\t\t}\n\t});\n}\n\nasync function run(\n\tcron: Cron<any, any, any, any, any, any>,\n\tserviceDiscovery: ServiceDiscovery<any>,\n): Promise<unknown> {\n\tconst services =\n\t\tcron.services.length > 0\n\t\t\t? await serviceDiscovery.register(cron.services)\n\t\t\t: {};\n\n\tconst db = cron.databaseService\n\t\t? (await serviceDiscovery.register([cron.databaseService]))[\n\t\t\t\tcron.databaseService.serviceName\n\t\t\t]\n\t\t: undefined;\n\n\t// Only imported for a cron that audits: `@geekmidas/audit` is optional.\n\tlet auditor: { flush(): Promise<void> } | undefined;\n\tif (cron.auditorStorageService) {\n\t\tconst { DefaultAuditor } = await import('@geekmidas/audit');\n\t\tconst registered: Record<string, unknown> = await serviceDiscovery.register(\n\t\t\t[cron.auditorStorageService],\n\t\t);\n\t\tconst storage = registered[\n\t\t\tcron.auditorStorageService.serviceName\n\t\t] as AuditStorage;\n\t\tauditor = new DefaultAuditor({\n\t\t\tactor: { id: 'system', type: 'system' },\n\t\t\tstorage,\n\t\t\tmetadata: { function: cron.type },\n\t\t});\n\t}\n\n\tconst logger = cron.logger;\n\tconst requestId = `cron-${Date.now()}`;\n\n\treturn runWithRequestContext(\n\t\t{\n\t\t\tlogger,\n\t\t\trequestId,\n\t\t\tstartTime: Date.now(),\n\t\t\toperation: `cron ${cron.schedule ?? 'manual'}`,\n\t\t},\n\t\tasync () => {\n\t\t\tconst response = await cron.fn({\n\t\t\t\tinput: undefined,\n\t\t\t\tservices,\n\t\t\t\tlogger,\n\t\t\t\tdb,\n\t\t\t\tauditor,\n\t\t\t} as any);\n\t\t\tconst output = await cron.parseOutput(response);\n\n\t\t\tawait auditor?.flush();\n\t\t\t// The cron's output schema is erased by the `any` it is typed with here.\n\t\t\tawait publishEvents(\n\t\t\t\tlogger,\n\t\t\t\tserviceDiscovery,\n\t\t\t\tcron.events,\n\t\t\t\toutput as never,\n\t\t\t);\n\n\t\t\treturn output;\n\t\t},\n\t);\n}\n","import type { ScheduleExpression } from './Cron';\n\n/**\n * A schedule a cron runner can take, as standard five-field cron.\n *\n * `ScheduleExpression` has two spellings. `cron(m h dom mon dow)` is already\n * five-field cron and unwraps; `rate(n unit)` is an interval, and an interval\n * is not a schedule — it says how often, where cron says when.\n *\n * Most intervals still have an exact cron equivalent, because they divide their\n * unit evenly: `rate(5 minutes)` is every fifth minute of every hour, and that\n * is `*/5 * * * *` precisely. `rate(7 hours)` has none. There is no cron field\n * that means \"every seven hours\" — `*/7` in the hour field fires at 0, 7, 14\n * and 21 and then starts over at midnight, so the gap between the last firing\n * of one day and the first of the next is three hours rather than seven.\n *\n * Those are refused rather than rounded. A job that runs at the wrong hour is\n * far harder to notice than one that refused to build, and a schedule quietly\n * adjusted by the framework is a bug nobody goes looking for.\n */\nexport class UnrepresentableSchedule extends Error {\n\tconstructor(\n\t\treadonly schedule: string,\n\t\treason: string,\n\t) {\n\t\tsuper(\n\t\t\t`\\`${schedule}\\` has no exact cron equivalent: ${reason}.\\n\\n` +\n\t\t\t\t'Cron says *when*, not *how often*, so an interval is only exact when ' +\n\t\t\t\t'it divides its unit evenly.\\n' +\n\t\t\t\t'Write the schedule you mean instead — `cron(0 */6 * * *)` for every ' +\n\t\t\t\t'sixth hour, say — or pick an interval that divides: minutes into 60, ' +\n\t\t\t\t'hours into 24.',\n\t\t);\n\t\tthis.name = 'UnrepresentableSchedule';\n\t}\n}\n\n/** Units `rate(…)` accepts, singular or plural. */\nconst UNITS = ['minute', 'hour', 'day'] as const;\ntype Unit = (typeof UNITS)[number];\n\n/**\n * Standard five-field cron for a schedule expression.\n *\n * @throws {UnrepresentableSchedule} when a `rate(…)` has no exact equivalent.\n */\nexport function toCronExpression(schedule: ScheduleExpression): string {\n\tconst cron = /^cron\\((.+)\\)$/.exec(schedule);\n\tif (cron?.[1]) return cron[1].trim();\n\n\tconst rate = /^rate\\(\\s*(\\d+)\\s+(\\w+?)s?\\s*\\)$/.exec(schedule);\n\tif (!rate) {\n\t\tthrow new UnrepresentableSchedule(\n\t\t\tschedule,\n\t\t\t'it is neither `cron(…)` nor `rate(n unit)`',\n\t\t);\n\t}\n\n\tconst every = Number(rate[1]);\n\tconst unit = rate[2] as Unit;\n\t/* c8 ignore next */ if (!unit)\n\t\tthrow new UnrepresentableSchedule(schedule, 'no unit');\n\n\tif (!UNITS.includes(unit)) {\n\t\tthrow new UnrepresentableSchedule(\n\t\t\tschedule,\n\t\t\t`\\`${unit}\\` is not one of ${UNITS.join(', ')}`,\n\t\t);\n\t}\n\n\tif (every < 1) {\n\t\tthrow new UnrepresentableSchedule(\n\t\t\tschedule,\n\t\t\t'an interval must be at least 1',\n\t\t);\n\t}\n\n\tswitch (unit) {\n\t\tcase 'minute':\n\t\t\tif (every === 1) return '* * * * *';\n\t\t\tif (60 % every !== 0) {\n\t\t\t\tthrow new UnrepresentableSchedule(\n\t\t\t\t\tschedule,\n\t\t\t\t\t`${every} does not divide 60, so the interval would reset at the top of each hour`,\n\t\t\t\t);\n\t\t\t}\n\t\t\treturn `*/${every} * * * *`;\n\n\t\tcase 'hour':\n\t\t\tif (every === 1) return '0 * * * *';\n\t\t\tif (24 % every !== 0) {\n\t\t\t\tthrow new UnrepresentableSchedule(\n\t\t\t\t\tschedule,\n\t\t\t\t\t`${every} does not divide 24, so the interval would reset at midnight`,\n\t\t\t\t);\n\t\t\t}\n\t\t\treturn `0 */${every} * * *`;\n\n\t\tcase 'day':\n\t\t\tif (every === 1) return '0 0 * * *';\n\t\t\t// `*/n` in day-of-month restarts on the 1st, so a 2-day interval fires\n\t\t\t// on the 1st and 3rd of a 31-day month and then again on the 1st — one\n\t\t\t// day later, not two. No month length makes that come out even.\n\t\t\tthrow new UnrepresentableSchedule(\n\t\t\t\tschedule,\n\t\t\t\t'day-of-month restarts every month, so no multi-day interval is even',\n\t\t\t);\n\t}\n}\n"],"mappings":";;;;;;;;;;AAMA,MAAM,YAAY,KAAK,KAAK;;;;;;;;;;;;;;AAoB5B,SAAgB,kBACf,YACA,MACoB;CAGpB,qBAAqB,MAAM,YAAY,EAAE,IAAI,MAAM,CAAC;CAEpD,IAAI;CACJ,IAAI,UAAU;CAEd,MAAM,OAAO,OAAe;EAC3B,IAAI,SAAS;EACb,MAAM,QAAQ,KAAK,KAAK,IAAI;EAC5B,QAAQ,WACP,YAAY;GACX,IAAI,KAAK,IAAI,IAAI,IAAI,OAAO,IAAI,EAAE;GAClC,MAAM,KAAK;GACX,IAAI,UAAU,4BAAY,IAAI,KAAK,CAAC,CAAC;EACtC,GACA,KAAK,IAAI,KAAK,IAAI,OAAO,CAAC,GAAG,SAAS,CACvC;EAEA,MAAM,QAAQ;CACf;CAEA,IAAI,UAAU,4BAAY,IAAI,KAAK,CAAC,CAAC;CAErC,OAAO,EACN,OAAO;EACN,UAAU;EACV,aAAa,KAAK;CACnB,EACD;AACD;AAEA,SAAS,UAAU,YAAoB,MAAoB;CAC1D,OAAO,qBAAqB,MAAM,YAAY;EAC7C,IAAI;EACJ,aAAa;CACd,CAAC,CAAC,CACA,KAAK,CAAC,CACN,QAAQ;AACX;;;;;;;;;;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,6DACV;GAED,OAAO,OAAO,MAAM;EAErB,KAAK;GACJ,IAAI,UAAU,GAAG,OAAO;GAIxB,MAAM,IAAI,wBACT,UACA,qEACD;CACF;AACD"}
|
package/dist/database/kysely.cjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
1
|
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
|
2
|
-
const require_kysely = require("../kysely-
|
|
2
|
+
const require_kysely = require("../kysely-H7L1YDgE.cjs");
|
|
3
3
|
exports.KyselyDatabase = require_kysely.KyselyDatabase;
|
|
4
4
|
exports.closeDatabasePools = require_kysely.closeDatabasePools;
|
package/dist/database/kysely.mjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { n as closeDatabasePools, t as KyselyDatabase } from "../kysely-
|
|
1
|
+
import { n as closeDatabasePools, t as KyselyDatabase } from "../kysely-DN88k0gD.mjs";
|
|
2
2
|
export { KyselyDatabase, closeDatabasePools };
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"external-api-BEgXYeJD.d.mts","names":[],"sources":["../src/external-api.ts"],"mappings":";;;;;;
|
|
1
|
+
{"version":3,"file":"external-api-BEgXYeJD.d.mts","names":[],"sources":["../src/external-api.ts"],"mappings":";;;;;;KAoDK,MAAM,gBAAgB,oBAC1B,iBAAiB,YAAY;UAEb,mBAAmB,gBAAgB,kBAAkB;;;;;EAKrE,cAAc,SAAS;;EAEvB,aAAa;;EAEb,SAAS;IACR;IACA,aAAa,MAAM;QACd,UAAU,QAAQ;;cAGZ,YACZ,+BACA,gBAAgB,mBAAmB,kBACnC,8BACY,WAAW,OAAO;mBAeZ;WAXT,IAAI;WACJ,SAAS,QAAQ,aAAa,QAAQ;;mBAG9B;;UAGT;EAER,YACC,IAAI,cAAc,QACD,SAAS,mBAAmB,SAAS;;;;;;;MA0BnD,qBAAqB;EAIzB,WAAW;UAWG;;;UA6BE;EAChB,MAAM,SAAS,UAAU,WAAW,QAAQ;;;;;;cAOvC;;KAGD,cAAc,QAClB,aAAa,0BAA0B,oBACpC,iBAAiB,WAAW;;;;;;;KASpB;YACD;WACD;;WAGE;;WAEA,SAAS;;WAGT;;WAEA;;WAEA;;;;;;;;cAUC;;EAEZ,IAAI,gBAAc,SACR,cAAY;IACV,aAAa,cAAc;MACpC;;EAUH,MAAM,gBAAc,eACN;IACF;IAAc,aAAa,cAAc;MAClD;;;iBAYY,OAAO,iBAAiB,SAAS"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"external-api-BaIgJ6Ey.d.cts","names":[],"sources":["../src/external-api.ts"],"mappings":";;;;;;
|
|
1
|
+
{"version":3,"file":"external-api-BaIgJ6Ey.d.cts","names":[],"sources":["../src/external-api.ts"],"mappings":";;;;;;KAoDK,MAAM,gBAAgB,oBAC1B,iBAAiB,YAAY;UAEb,mBAAmB,gBAAgB,kBAAkB;;;;;EAKrE,cAAc,SAAS;;EAEvB,aAAa;;EAEb,SAAS;IACR;IACA,aAAa,MAAM;QACd,UAAU,QAAQ;;cAGZ,YACZ,+BACA,gBAAgB,mBAAmB,kBACnC,8BACY,WAAW,OAAO;mBAeZ;WAXT,IAAI;WACJ,SAAS,QAAQ,aAAa,QAAQ;;mBAG9B;;UAGT;EAER,YACC,IAAI,cAAc,QACD,SAAS,mBAAmB,SAAS;;;;;;;MA0BnD,qBAAqB;EAIzB,WAAW;UAWG;;;UA6BE;EAChB,MAAM,SAAS,UAAU,WAAW,QAAQ;;;;;;cAOvC;;KAGD,cAAc,QAClB,aAAa,0BAA0B,oBACpC,iBAAiB,WAAW;;;;;;;KASpB;YACD;WACD;;WAGE;;WAEA,SAAS;;WAGT;;WAEA;;WAEA;;;;;;;;cAUC;;EAEZ,IAAI,gBAAc,SACR,cAAY;IACV,aAAa,cAAc;MACpC;;EAUH,MAAM,gBAAc,eACN;IACF;IAAc,aAAa,cAAc;MAClD;;;iBAYY,OAAO,iBAAiB,SAAS"}
|
package/dist/external-api.cjs
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
|
2
2
|
const require_credential = require("./credential.cjs");
|
|
3
|
+
const require_tracing = require("./tracing-3PpqRX07.cjs");
|
|
3
4
|
let _geekmidas_manifest = require("@geekmidas/manifest");
|
|
4
5
|
//#region src/external-api.ts
|
|
5
6
|
/**
|
|
@@ -83,12 +84,20 @@ var ExternalApi = class {
|
|
|
83
84
|
async connect(options) {
|
|
84
85
|
const { url } = options.envParser.create((get) => ({ url: get(this.keys.url).string() })).parse();
|
|
85
86
|
const credentials = await require_credential.readCredentials(this.id, this.keys.credentials, this.options.credentials, options.envParser);
|
|
86
|
-
|
|
87
|
+
const client = await this.options.client({
|
|
87
88
|
url,
|
|
88
89
|
credentials
|
|
89
90
|
});
|
|
91
|
+
return require_tracing.traceClient(this.id, client, { "server.address": hostOf(url) });
|
|
90
92
|
}
|
|
91
93
|
};
|
|
94
|
+
function hostOf(url) {
|
|
95
|
+
try {
|
|
96
|
+
return new URL(url).host;
|
|
97
|
+
} catch {
|
|
98
|
+
return url;
|
|
99
|
+
}
|
|
100
|
+
}
|
|
92
101
|
/**
|
|
93
102
|
* Marks a fake. A registered symbol, so a fake built by a second copy of this
|
|
94
103
|
* package — a linked workspace, two versions in a lockfile — is still one.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"external-api.cjs","names":["canonicalId","provideKey","serviceKey","readCredentials"],"sources":["../src/external-api.ts"],"sourcesContent":["/**\n * `ExternalApi` — an HTTP API somebody else runs.\n *\n * Polar, Stripe, a payment gateway: nothing to provision, but an address that\n * changes by stage and credentials the provider issued for each one. Without a\n * construct every integration writes that switching by hand — an optional\n * `POLAR_URL`, a fake started somewhere, a client built in a service — and the\n * target cannot see any of it.\n *\n * ```ts\n * // constructs/polar.ts\n * export const polar = new ExternalApi('Polar', {\n * url: 'https://www.polaraccesslink.com',\n * credentials: z.object({ clientId: z.string(), clientSecret: z.string() }),\n * client: ({ url, credentials }) => new PolarClient(url, credentials),\n * });\n *\n * // test/fakes/polar.ts\n * export default fake.app(new Hono().post('/v3/oauth2/token', …), {\n * credentials: { clientId: 'fake', clientSecret: 'fake' },\n * });\n *\n * // in a handler — the real API deployed, the fake locally and in tests\n * .dependsOn([polar])\n * .handle(({ services }) => services.polar.exchangeCode(code))\n * ```\n *\n * Deployed, the URL is `url` — one for every stage, or one per stage name with\n * a `default` — and the credentials are the stage's `<ID>_CREDENTIALS`, one\n * JSON value read the way a `Credential`'s is. Locally and in tests both come\n * from the fake.\n *\n * **The construct never names its fake.** It is found by convention, at\n * `test/fakes/<id>.ts`, and read only by gkm and the generated test harness —\n * so a fake, and the recorded responses it answers from, cannot end up in a\n * deployed bundle however the bundler follows imports.\n */\n\nimport {\n\ttype ConstructName,\n\tcanonicalId,\n\ttype Declaration,\n\tprovideKey,\n\tserviceKey,\n} from '@geekmidas/manifest';\nimport type { Service, ServiceRegisterOptions } from '@geekmidas/services';\nimport type { StandardSchemaV1 } from '@standard-schema/spec';\nimport type { Consumable } from './construct-interface';\nimport { readCredentials } from './credential';\n\n/** What a credentials schema yields. */\ntype Value<TSchema extends StandardSchemaV1> =\n\tStandardSchemaV1.InferOutput<TSchema>;\n\nexport interface ExternalApiOptions<TSchema extends StandardSchemaV1, TClient> {\n\t/**\n\t * Where it answers deployed: one URL for every stage, or one per stage\n\t * name, with `default` for any stage not listed.\n\t */\n\turl: string | Readonly<Record<string, string>>;\n\t/** What the stage's `<ID>_CREDENTIALS` must look like. */\n\tcredentials: TSchema;\n\t/** What a handler is handed, built from where it answers and the credentials. */\n\tclient: (connection: {\n\t\turl: string;\n\t\tcredentials: Value<TSchema>;\n\t}) => TClient | Promise<TClient>;\n}\n\nexport class ExternalApi<\n\tTName extends string = string,\n\tTSchema extends StandardSchemaV1 = StandardSchemaV1,\n\tTClient = unknown,\n> implements Consumable<TName, TClient>\n{\n\t// `Consumable` for the reason `Credential` gives: a client generic in\n\t// `TClient` cannot satisfy `Construct`'s conditional service type.\n\treadonly id: TName;\n\treadonly service: Service<Uncapitalize<TName>, TClient>;\n\n\t/** Read by both `declare()` and `connect()`, so the two cannot drift. */\n\tprivate readonly keys: { url: string; credentials: string };\n\n\t/** The promise, so concurrent registrations share one client. */\n\tprivate connected?: Promise<TClient>;\n\n\tconstructor(\n\t\tid: ConstructName<TName>,\n\t\tprivate readonly options: ExternalApiOptions<TSchema, TClient>,\n\t) {\n\t\tconst canonical = canonicalId(id as string);\n\n\t\tthis.id = canonical as TName;\n\t\tthis.keys = {\n\t\t\turl: provideKey(canonical, 'url'),\n\t\t\tcredentials: provideKey(canonical, 'credentials'),\n\t\t};\n\n\t\t// A field, not a getter: consumers cache services by object identity.\n\t\tthis.service = {\n\t\t\tserviceName: serviceKey(canonical) as Uncapitalize<TName>,\n\t\t\tregister: (registerOptions) => {\n\t\t\t\tthis.connected ??= this.connect(registerOptions);\n\t\t\t\treturn this.connected;\n\t\t\t},\n\t\t};\n\t}\n\n\t/**\n\t * What the stage's `<ID>_CREDENTIALS` must look like — the schema the value\n\t * is validated against where it is read. Public so a tool setting the value\n\t * (`gkm secrets:add`) can check it, and describe its fields, before it is\n\t * stored rather than at the first request.\n\t */\n\tget credentialsSchema(): TSchema {\n\t\treturn this.options.credentials;\n\t}\n\n\tdeclare(): Declaration[] {\n\t\treturn [\n\t\t\t{\n\t\t\t\tkind: 'external-api',\n\t\t\t\tid: this.id,\n\t\t\t\turl: this.options.url,\n\t\t\t\tprovides: [this.keys.url, this.keys.credentials],\n\t\t\t},\n\t\t];\n\t}\n\n\tprivate async connect(options: ServiceRegisterOptions): Promise<TClient> {\n\t\tconst { url } = options.envParser\n\t\t\t.create((get) => ({ url: get(this.keys.url).string() }))\n\t\t\t.parse();\n\t\tconst credentials = await readCredentials(\n\t\t\tthis.id,\n\t\t\tthis.keys.credentials,\n\t\t\tthis.options.credentials,\n\t\t\toptions.envParser,\n\t\t);\n\n\t\
|
|
1
|
+
{"version":3,"file":"external-api.cjs","names":["canonicalId","provideKey","serviceKey","readCredentials","traceClient"],"sources":["../src/external-api.ts"],"sourcesContent":["/**\n * `ExternalApi` — an HTTP API somebody else runs.\n *\n * Polar, Stripe, a payment gateway: nothing to provision, but an address that\n * changes by stage and credentials the provider issued for each one. Without a\n * construct every integration writes that switching by hand — an optional\n * `POLAR_URL`, a fake started somewhere, a client built in a service — and the\n * target cannot see any of it.\n *\n * ```ts\n * // constructs/polar.ts\n * export const polar = new ExternalApi('Polar', {\n * url: 'https://www.polaraccesslink.com',\n * credentials: z.object({ clientId: z.string(), clientSecret: z.string() }),\n * client: ({ url, credentials }) => new PolarClient(url, credentials),\n * });\n *\n * // test/fakes/polar.ts\n * export default fake.app(new Hono().post('/v3/oauth2/token', …), {\n * credentials: { clientId: 'fake', clientSecret: 'fake' },\n * });\n *\n * // in a handler — the real API deployed, the fake locally and in tests\n * .dependsOn([polar])\n * .handle(({ services }) => services.polar.exchangeCode(code))\n * ```\n *\n * Deployed, the URL is `url` — one for every stage, or one per stage name with\n * a `default` — and the credentials are the stage's `<ID>_CREDENTIALS`, one\n * JSON value read the way a `Credential`'s is. Locally and in tests both come\n * from the fake.\n *\n * **The construct never names its fake.** It is found by convention, at\n * `test/fakes/<id>.ts`, and read only by gkm and the generated test harness —\n * so a fake, and the recorded responses it answers from, cannot end up in a\n * deployed bundle however the bundler follows imports.\n */\n\nimport {\n\ttype ConstructName,\n\tcanonicalId,\n\ttype Declaration,\n\tprovideKey,\n\tserviceKey,\n} from '@geekmidas/manifest';\nimport type { Service, ServiceRegisterOptions } from '@geekmidas/services';\nimport type { StandardSchemaV1 } from '@standard-schema/spec';\nimport type { Consumable } from './construct-interface';\nimport { readCredentials } from './credential';\nimport { traceClient } from './tracing';\n\n/** What a credentials schema yields. */\ntype Value<TSchema extends StandardSchemaV1> =\n\tStandardSchemaV1.InferOutput<TSchema>;\n\nexport interface ExternalApiOptions<TSchema extends StandardSchemaV1, TClient> {\n\t/**\n\t * Where it answers deployed: one URL for every stage, or one per stage\n\t * name, with `default` for any stage not listed.\n\t */\n\turl: string | Readonly<Record<string, string>>;\n\t/** What the stage's `<ID>_CREDENTIALS` must look like. */\n\tcredentials: TSchema;\n\t/** What a handler is handed, built from where it answers and the credentials. */\n\tclient: (connection: {\n\t\turl: string;\n\t\tcredentials: Value<TSchema>;\n\t}) => TClient | Promise<TClient>;\n}\n\nexport class ExternalApi<\n\tTName extends string = string,\n\tTSchema extends StandardSchemaV1 = StandardSchemaV1,\n\tTClient = unknown,\n> implements Consumable<TName, TClient>\n{\n\t// `Consumable` for the reason `Credential` gives: a client generic in\n\t// `TClient` cannot satisfy `Construct`'s conditional service type.\n\treadonly id: TName;\n\treadonly service: Service<Uncapitalize<TName>, TClient>;\n\n\t/** Read by both `declare()` and `connect()`, so the two cannot drift. */\n\tprivate readonly keys: { url: string; credentials: string };\n\n\t/** The promise, so concurrent registrations share one client. */\n\tprivate connected?: Promise<TClient>;\n\n\tconstructor(\n\t\tid: ConstructName<TName>,\n\t\tprivate readonly options: ExternalApiOptions<TSchema, TClient>,\n\t) {\n\t\tconst canonical = canonicalId(id as string);\n\n\t\tthis.id = canonical as TName;\n\t\tthis.keys = {\n\t\t\turl: provideKey(canonical, 'url'),\n\t\t\tcredentials: provideKey(canonical, 'credentials'),\n\t\t};\n\n\t\t// A field, not a getter: consumers cache services by object identity.\n\t\tthis.service = {\n\t\t\tserviceName: serviceKey(canonical) as Uncapitalize<TName>,\n\t\t\tregister: (registerOptions) => {\n\t\t\t\tthis.connected ??= this.connect(registerOptions);\n\t\t\t\treturn this.connected;\n\t\t\t},\n\t\t};\n\t}\n\n\t/**\n\t * What the stage's `<ID>_CREDENTIALS` must look like — the schema the value\n\t * is validated against where it is read. Public so a tool setting the value\n\t * (`gkm secrets:add`) can check it, and describe its fields, before it is\n\t * stored rather than at the first request.\n\t */\n\tget credentialsSchema(): TSchema {\n\t\treturn this.options.credentials;\n\t}\n\n\tdeclare(): Declaration[] {\n\t\treturn [\n\t\t\t{\n\t\t\t\tkind: 'external-api',\n\t\t\t\tid: this.id,\n\t\t\t\turl: this.options.url,\n\t\t\t\tprovides: [this.keys.url, this.keys.credentials],\n\t\t\t},\n\t\t];\n\t}\n\n\tprivate async connect(options: ServiceRegisterOptions): Promise<TClient> {\n\t\tconst { url } = options.envParser\n\t\t\t.create((get) => ({ url: get(this.keys.url).string() }))\n\t\t\t.parse();\n\t\tconst credentials = await readCredentials(\n\t\t\tthis.id,\n\t\t\tthis.keys.credentials,\n\t\t\tthis.options.credentials,\n\t\t\toptions.envParser,\n\t\t);\n\n\t\tconst client = await this.options.client({ url, credentials });\n\t\t// Each call a span carrying this API's name — the parent of the fetch\n\t\t// it makes, which is traced already.\n\t\treturn traceClient(this.id, client, {\n\t\t\t'server.address': hostOf(url),\n\t\t});\n\t}\n}\n\nfunction hostOf(url: string): string {\n\ttry {\n\t\treturn new URL(url).host;\n\t} catch {\n\t\treturn url;\n\t}\n}\n\n/** Anything that answers a request — a Hono app, or a bare `{ fetch }`. */\nexport interface FetchHandler {\n\tfetch(request: Request): Response | Promise<Response>;\n}\n\n/**\n * Marks a fake. A registered symbol, so a fake built by a second copy of this\n * package — a linked workspace, two versions in a lockfile — is still one.\n */\nconst FAKE = Symbol.for('@geekmidas/constructs/fake');\n\n/** What an external API's credentials look like going in, for a fake to supply. */\ntype CredentialsOf<TApi> =\n\tTApi extends ExternalApi<string, infer TSchema, unknown>\n\t\t? StandardSchemaV1.InferInput<TSchema>\n\t\t: unknown;\n\n/**\n * An external API's stand-in, as `test/fakes/<id>.ts` default-exports it.\n *\n * `credentials` are what the fake accepts, and what a local or test stage is\n * handed as `<ID>_CREDENTIALS` in place of the stage's own.\n */\nexport type Fake = {\n\treadonly [FAKE]: true;\n\treadonly credentials: unknown;\n} & (\n\t| {\n\t\t\treadonly kind: 'app';\n\t\t\t/** Served by gkm: in-process in a test, on its own port in `gkm dev`. */\n\t\t\treadonly handler: FetchHandler;\n\t }\n\t| {\n\t\t\treadonly kind: 'image';\n\t\t\t/** The provider's own local server, run as a container. */\n\t\t\treadonly image: string;\n\t\t\t/** The port it listens on inside the container. */\n\t\t\treadonly port: number;\n\t }\n);\n\n/**\n * Build the fake `test/fakes/<id>.ts` default-exports.\n *\n * Pass the API's type to have the credentials checked against its schema —\n * `fake.app<typeof polar>(…)`.\n */\nexport const fake = {\n\t/** A working implementation of the API, kept beside the tests that use it. */\n\tapp<TApi = unknown>(\n\t\thandler: FetchHandler,\n\t\toptions: { credentials: CredentialsOf<TApi> },\n\t): Fake {\n\t\treturn {\n\t\t\t[FAKE]: true,\n\t\t\tkind: 'app',\n\t\t\thandler,\n\t\t\tcredentials: options.credentials,\n\t\t};\n\t},\n\n\t/** A local server the provider publishes — `stripe/stripe-mock`. */\n\timage<TApi = unknown>(\n\t\timage: string,\n\t\toptions: { port: number; credentials: CredentialsOf<TApi> },\n\t): Fake {\n\t\treturn {\n\t\t\t[FAKE]: true,\n\t\t\tkind: 'image',\n\t\t\timage,\n\t\t\tport: options.port,\n\t\t\tcredentials: options.credentials,\n\t\t};\n\t},\n};\n\n/** Whether a value is a fake — what gkm asks of a `test/fakes` default export. */\nexport function isFake(value: unknown): value is Fake {\n\treturn (\n\t\ttypeof value === 'object' &&\n\t\tvalue !== null &&\n\t\t(value as { [FAKE]?: unknown })[FAKE] === true\n\t);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAsEA,IAAa,cAAb,MAKA;CAcmB;CAXlB;CACA;;CAGA;;CAGA;CAEA,YACC,IACA,SACC;EADgB,KAAA,UAAA;EAEjB,MAAM,aAAA,GAAYA,oBAAAA,YAAAA,CAAY,EAAY;EAE1C,KAAK,KAAK;EACV,KAAK,OAAO;GACX,MAAA,GAAKC,oBAAAA,WAAAA,CAAW,WAAW,KAAK;GAChC,cAAA,GAAaA,oBAAAA,WAAAA,CAAW,WAAW,aAAa;EACjD;EAGA,KAAK,UAAU;GACd,cAAA,GAAaC,oBAAAA,WAAAA,CAAW,SA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@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { readCredentials } from "./credential.mjs";
|
|
2
|
+
import { n as traceClient } from "./tracing-DbcPuhEy.mjs";
|
|
2
3
|
import { canonicalId, provideKey, serviceKey } from "@geekmidas/manifest";
|
|
3
4
|
//#region src/external-api.ts
|
|
4
5
|
/**
|
|
@@ -82,12 +83,20 @@ var ExternalApi = class {
|
|
|
82
83
|
async connect(options) {
|
|
83
84
|
const { url } = options.envParser.create((get) => ({ url: get(this.keys.url).string() })).parse();
|
|
84
85
|
const credentials = await readCredentials(this.id, this.keys.credentials, this.options.credentials, options.envParser);
|
|
85
|
-
|
|
86
|
+
const client = await this.options.client({
|
|
86
87
|
url,
|
|
87
88
|
credentials
|
|
88
89
|
});
|
|
90
|
+
return traceClient(this.id, client, { "server.address": hostOf(url) });
|
|
89
91
|
}
|
|
90
92
|
};
|
|
93
|
+
function hostOf(url) {
|
|
94
|
+
try {
|
|
95
|
+
return new URL(url).host;
|
|
96
|
+
} catch {
|
|
97
|
+
return url;
|
|
98
|
+
}
|
|
99
|
+
}
|
|
91
100
|
/**
|
|
92
101
|
* Marks a fake. A registered symbol, so a fake built by a second copy of this
|
|
93
102
|
* package — a linked workspace, two versions in a lockfile — is still one.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"external-api.mjs","names":[],"sources":["../src/external-api.ts"],"sourcesContent":["/**\n * `ExternalApi` — an HTTP API somebody else runs.\n *\n * Polar, Stripe, a payment gateway: nothing to provision, but an address that\n * changes by stage and credentials the provider issued for each one. Without a\n * construct every integration writes that switching by hand — an optional\n * `POLAR_URL`, a fake started somewhere, a client built in a service — and the\n * target cannot see any of it.\n *\n * ```ts\n * // constructs/polar.ts\n * export const polar = new ExternalApi('Polar', {\n * url: 'https://www.polaraccesslink.com',\n * credentials: z.object({ clientId: z.string(), clientSecret: z.string() }),\n * client: ({ url, credentials }) => new PolarClient(url, credentials),\n * });\n *\n * // test/fakes/polar.ts\n * export default fake.app(new Hono().post('/v3/oauth2/token', …), {\n * credentials: { clientId: 'fake', clientSecret: 'fake' },\n * });\n *\n * // in a handler — the real API deployed, the fake locally and in tests\n * .dependsOn([polar])\n * .handle(({ services }) => services.polar.exchangeCode(code))\n * ```\n *\n * Deployed, the URL is `url` — one for every stage, or one per stage name with\n * a `default` — and the credentials are the stage's `<ID>_CREDENTIALS`, one\n * JSON value read the way a `Credential`'s is. Locally and in tests both come\n * from the fake.\n *\n * **The construct never names its fake.** It is found by convention, at\n * `test/fakes/<id>.ts`, and read only by gkm and the generated test harness —\n * so a fake, and the recorded responses it answers from, cannot end up in a\n * deployed bundle however the bundler follows imports.\n */\n\nimport {\n\ttype ConstructName,\n\tcanonicalId,\n\ttype Declaration,\n\tprovideKey,\n\tserviceKey,\n} from '@geekmidas/manifest';\nimport type { Service, ServiceRegisterOptions } from '@geekmidas/services';\nimport type { StandardSchemaV1 } from '@standard-schema/spec';\nimport type { Consumable } from './construct-interface';\nimport { readCredentials } from './credential';\n\n/** What a credentials schema yields. */\ntype Value<TSchema extends StandardSchemaV1> =\n\tStandardSchemaV1.InferOutput<TSchema>;\n\nexport interface ExternalApiOptions<TSchema extends StandardSchemaV1, TClient> {\n\t/**\n\t * Where it answers deployed: one URL for every stage, or one per stage\n\t * name, with `default` for any stage not listed.\n\t */\n\turl: string | Readonly<Record<string, string>>;\n\t/** What the stage's `<ID>_CREDENTIALS` must look like. */\n\tcredentials: TSchema;\n\t/** What a handler is handed, built from where it answers and the credentials. */\n\tclient: (connection: {\n\t\turl: string;\n\t\tcredentials: Value<TSchema>;\n\t}) => TClient | Promise<TClient>;\n}\n\nexport class ExternalApi<\n\tTName extends string = string,\n\tTSchema extends StandardSchemaV1 = StandardSchemaV1,\n\tTClient = unknown,\n> implements Consumable<TName, TClient>\n{\n\t// `Consumable` for the reason `Credential` gives: a client generic in\n\t// `TClient` cannot satisfy `Construct`'s conditional service type.\n\treadonly id: TName;\n\treadonly service: Service<Uncapitalize<TName>, TClient>;\n\n\t/** Read by both `declare()` and `connect()`, so the two cannot drift. */\n\tprivate readonly keys: { url: string; credentials: string };\n\n\t/** The promise, so concurrent registrations share one client. */\n\tprivate connected?: Promise<TClient>;\n\n\tconstructor(\n\t\tid: ConstructName<TName>,\n\t\tprivate readonly options: ExternalApiOptions<TSchema, TClient>,\n\t) {\n\t\tconst canonical = canonicalId(id as string);\n\n\t\tthis.id = canonical as TName;\n\t\tthis.keys = {\n\t\t\turl: provideKey(canonical, 'url'),\n\t\t\tcredentials: provideKey(canonical, 'credentials'),\n\t\t};\n\n\t\t// A field, not a getter: consumers cache services by object identity.\n\t\tthis.service = {\n\t\t\tserviceName: serviceKey(canonical) as Uncapitalize<TName>,\n\t\t\tregister: (registerOptions) => {\n\t\t\t\tthis.connected ??= this.connect(registerOptions);\n\t\t\t\treturn this.connected;\n\t\t\t},\n\t\t};\n\t}\n\n\t/**\n\t * What the stage's `<ID>_CREDENTIALS` must look like — the schema the value\n\t * is validated against where it is read. Public so a tool setting the value\n\t * (`gkm secrets:add`) can check it, and describe its fields, before it is\n\t * stored rather than at the first request.\n\t */\n\tget credentialsSchema(): TSchema {\n\t\treturn this.options.credentials;\n\t}\n\n\tdeclare(): Declaration[] {\n\t\treturn [\n\t\t\t{\n\t\t\t\tkind: 'external-api',\n\t\t\t\tid: this.id,\n\t\t\t\turl: this.options.url,\n\t\t\t\tprovides: [this.keys.url, this.keys.credentials],\n\t\t\t},\n\t\t];\n\t}\n\n\tprivate async connect(options: ServiceRegisterOptions): Promise<TClient> {\n\t\tconst { url } = options.envParser\n\t\t\t.create((get) => ({ url: get(this.keys.url).string() }))\n\t\t\t.parse();\n\t\tconst credentials = await readCredentials(\n\t\t\tthis.id,\n\t\t\tthis.keys.credentials,\n\t\t\tthis.options.credentials,\n\t\t\toptions.envParser,\n\t\t);\n\n\t\
|
|
1
|
+
{"version":3,"file":"external-api.mjs","names":[],"sources":["../src/external-api.ts"],"sourcesContent":["/**\n * `ExternalApi` — an HTTP API somebody else runs.\n *\n * Polar, Stripe, a payment gateway: nothing to provision, but an address that\n * changes by stage and credentials the provider issued for each one. Without a\n * construct every integration writes that switching by hand — an optional\n * `POLAR_URL`, a fake started somewhere, a client built in a service — and the\n * target cannot see any of it.\n *\n * ```ts\n * // constructs/polar.ts\n * export const polar = new ExternalApi('Polar', {\n * url: 'https://www.polaraccesslink.com',\n * credentials: z.object({ clientId: z.string(), clientSecret: z.string() }),\n * client: ({ url, credentials }) => new PolarClient(url, credentials),\n * });\n *\n * // test/fakes/polar.ts\n * export default fake.app(new Hono().post('/v3/oauth2/token', …), {\n * credentials: { clientId: 'fake', clientSecret: 'fake' },\n * });\n *\n * // in a handler — the real API deployed, the fake locally and in tests\n * .dependsOn([polar])\n * .handle(({ services }) => services.polar.exchangeCode(code))\n * ```\n *\n * Deployed, the URL is `url` — one for every stage, or one per stage name with\n * a `default` — and the credentials are the stage's `<ID>_CREDENTIALS`, one\n * JSON value read the way a `Credential`'s is. Locally and in tests both come\n * from the fake.\n *\n * **The construct never names its fake.** It is found by convention, at\n * `test/fakes/<id>.ts`, and read only by gkm and the generated test harness —\n * so a fake, and the recorded responses it answers from, cannot end up in a\n * deployed bundle however the bundler follows imports.\n */\n\nimport {\n\ttype ConstructName,\n\tcanonicalId,\n\ttype Declaration,\n\tprovideKey,\n\tserviceKey,\n} from '@geekmidas/manifest';\nimport type { Service, ServiceRegisterOptions } from '@geekmidas/services';\nimport type { StandardSchemaV1 } from '@standard-schema/spec';\nimport type { Consumable } from './construct-interface';\nimport { readCredentials } from './credential';\nimport { traceClient } from './tracing';\n\n/** What a credentials schema yields. */\ntype Value<TSchema extends StandardSchemaV1> =\n\tStandardSchemaV1.InferOutput<TSchema>;\n\nexport interface ExternalApiOptions<TSchema extends StandardSchemaV1, TClient> {\n\t/**\n\t * Where it answers deployed: one URL for every stage, or one per stage\n\t * name, with `default` for any stage not listed.\n\t */\n\turl: string | Readonly<Record<string, string>>;\n\t/** What the stage's `<ID>_CREDENTIALS` must look like. */\n\tcredentials: TSchema;\n\t/** What a handler is handed, built from where it answers and the credentials. */\n\tclient: (connection: {\n\t\turl: string;\n\t\tcredentials: Value<TSchema>;\n\t}) => TClient | Promise<TClient>;\n}\n\nexport class ExternalApi<\n\tTName extends string = string,\n\tTSchema extends StandardSchemaV1 = StandardSchemaV1,\n\tTClient = unknown,\n> implements Consumable<TName, TClient>\n{\n\t// `Consumable` for the reason `Credential` gives: a client generic in\n\t// `TClient` cannot satisfy `Construct`'s conditional service type.\n\treadonly id: TName;\n\treadonly service: Service<Uncapitalize<TName>, TClient>;\n\n\t/** Read by both `declare()` and `connect()`, so the two cannot drift. */\n\tprivate readonly keys: { url: string; credentials: string };\n\n\t/** The promise, so concurrent registrations share one client. */\n\tprivate connected?: Promise<TClient>;\n\n\tconstructor(\n\t\tid: ConstructName<TName>,\n\t\tprivate readonly options: ExternalApiOptions<TSchema, TClient>,\n\t) {\n\t\tconst canonical = canonicalId(id as string);\n\n\t\tthis.id = canonical as TName;\n\t\tthis.keys = {\n\t\t\turl: provideKey(canonical, 'url'),\n\t\t\tcredentials: provideKey(canonical, 'credentials'),\n\t\t};\n\n\t\t// A field, not a getter: consumers cache services by object identity.\n\t\tthis.service = {\n\t\t\tserviceName: serviceKey(canonical) as Uncapitalize<TName>,\n\t\t\tregister: (registerOptions) => {\n\t\t\t\tthis.connected ??= this.connect(registerOptions);\n\t\t\t\treturn this.connected;\n\t\t\t},\n\t\t};\n\t}\n\n\t/**\n\t * What the stage's `<ID>_CREDENTIALS` must look like — the schema the value\n\t * is validated against where it is read. Public so a tool setting the value\n\t * (`gkm secrets:add`) can check it, and describe its fields, before it is\n\t * stored rather than at the first request.\n\t */\n\tget credentialsSchema(): TSchema {\n\t\treturn this.options.credentials;\n\t}\n\n\tdeclare(): Declaration[] {\n\t\treturn [\n\t\t\t{\n\t\t\t\tkind: 'external-api',\n\t\t\t\tid: this.id,\n\t\t\t\turl: this.options.url,\n\t\t\t\tprovides: [this.keys.url, this.keys.credentials],\n\t\t\t},\n\t\t];\n\t}\n\n\tprivate async connect(options: ServiceRegisterOptions): Promise<TClient> {\n\t\tconst { url } = options.envParser\n\t\t\t.create((get) => ({ url: get(this.keys.url).string() }))\n\t\t\t.parse();\n\t\tconst credentials = await readCredentials(\n\t\t\tthis.id,\n\t\t\tthis.keys.credentials,\n\t\t\tthis.options.credentials,\n\t\t\toptions.envParser,\n\t\t);\n\n\t\tconst client = await this.options.client({ url, credentials });\n\t\t// Each call a span carrying this API's name — the parent of the fetch\n\t\t// it makes, which is traced already.\n\t\treturn traceClient(this.id, client, {\n\t\t\t'server.address': hostOf(url),\n\t\t});\n\t}\n}\n\nfunction hostOf(url: string): string {\n\ttry {\n\t\treturn new URL(url).host;\n\t} catch {\n\t\treturn url;\n\t}\n}\n\n/** Anything that answers a request — a Hono app, or a bare `{ fetch }`. */\nexport interface FetchHandler {\n\tfetch(request: Request): Response | Promise<Response>;\n}\n\n/**\n * Marks a fake. A registered symbol, so a fake built by a second copy of this\n * package — a linked workspace, two versions in a lockfile — is still one.\n */\nconst FAKE = Symbol.for('@geekmidas/constructs/fake');\n\n/** What an external API's credentials look like going in, for a fake to supply. */\ntype CredentialsOf<TApi> =\n\tTApi extends ExternalApi<string, infer TSchema, unknown>\n\t\t? StandardSchemaV1.InferInput<TSchema>\n\t\t: unknown;\n\n/**\n * An external API's stand-in, as `test/fakes/<id>.ts` default-exports it.\n *\n * `credentials` are what the fake accepts, and what a local or test stage is\n * handed as `<ID>_CREDENTIALS` in place of the stage's own.\n */\nexport type Fake = {\n\treadonly [FAKE]: true;\n\treadonly credentials: unknown;\n} & (\n\t| {\n\t\t\treadonly kind: 'app';\n\t\t\t/** Served by gkm: in-process in a test, on its own port in `gkm dev`. */\n\t\t\treadonly handler: FetchHandler;\n\t }\n\t| {\n\t\t\treadonly kind: 'image';\n\t\t\t/** The provider's own local server, run as a container. */\n\t\t\treadonly image: string;\n\t\t\t/** The port it listens on inside the container. */\n\t\t\treadonly port: number;\n\t }\n);\n\n/**\n * Build the fake `test/fakes/<id>.ts` default-exports.\n *\n * Pass the API's type to have the credentials checked against its schema —\n * `fake.app<typeof polar>(…)`.\n */\nexport const fake = {\n\t/** A working implementation of the API, kept beside the tests that use it. */\n\tapp<TApi = unknown>(\n\t\thandler: FetchHandler,\n\t\toptions: { credentials: CredentialsOf<TApi> },\n\t): Fake {\n\t\treturn {\n\t\t\t[FAKE]: true,\n\t\t\tkind: 'app',\n\t\t\thandler,\n\t\t\tcredentials: options.credentials,\n\t\t};\n\t},\n\n\t/** A local server the provider publishes — `stripe/stripe-mock`. */\n\timage<TApi = unknown>(\n\t\timage: string,\n\t\toptions: { port: number; credentials: CredentialsOf<TApi> },\n\t): Fake {\n\t\treturn {\n\t\t\t[FAKE]: true,\n\t\t\tkind: 'image',\n\t\t\timage,\n\t\t\tport: options.port,\n\t\t\tcredentials: options.credentials,\n\t\t};\n\t},\n};\n\n/** Whether a value is a fake — what gkm asks of a `test/fakes` default export. */\nexport function isFake(value: unknown): value is Fake {\n\treturn (\n\t\ttypeof value === 'object' &&\n\t\tvalue !== null &&\n\t\t(value as { [FAKE]?: unknown })[FAKE] === true\n\t);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAsEA,IAAa,cAAb,MAKA;CAcmB;CAXlB;CACA;;CAGA;;CAGA;CAEA,YACC,IACA,SACC;EADgB,KAAA,UAAA;EAEjB,MAAM,YAAY,YAAY,EAAY;EAE1C,KAAK,KAAK;EACV,KAAK,OAAO;GACX,KAAK,WAAW,WAAW,KAAK;GAChC,aAAa,WAAW,WAAW,aAAa;EACjD;EAGA,KAAK,UAAU;GACd,aAAa,WAAW,SAAS;GACjC,WAAW,oBAAoB;IAC9B,KAAK,cAAc,KAAK,QAAQ,eAAe;IAC/C,OAAO,KAAK;GACb;EACD;CACD;;;;;;;CAQA,IAAI,oBAA6B;EAChC,OAAO,KAAK,QAAQ;CACrB;CAEA,UAAyB;EACxB,OAAO,CACN;GACC,MAAM;GACN,IAAI,KAAK;GACT,KAAK,KAAK,QAAQ;GAClB,UAAU,CAAC,KAAK,KAAK,KAAK,KAAK,KAAK,WAAW;EAChD,CACD;CACD;CAEA,MAAc,QAAQ,SAAmD;EACxE,MAAM,EAAE,QAAQ,QAAQ,UACtB,QAAQ,SAAS,EAAE,KAAK,IAAI,KAAK,KAAK,GAAG,CAAC,CAAC,OAAO,EAAE,EAAE,CAAC,CACvD,MAAM;EACR,MAAM,cAAc,MAAM,gBACzB,KAAK,IACL,KAAK,KAAK,aACV,KAAK,QAAQ,aACb,QAAQ,SACT;EAEA,MAAM,SAAS,MAAM,KAAK,QAAQ,OAAO;GAAE;GAAK;EAAY,CAAC;EAG7D,OAAO,YAAY,KAAK,IAAI,QAAQ,EACnC,kBAAkB,OAAO,GAAG,EAC7B,CAAC;CACF;AACD;AAEA,SAAS,OAAO,KAAqB;CACpC,IAAI;EACH,OAAO,IAAI,IAAI,GAAG,CAAC,CAAC;CACrB,QAAQ;EACP,OAAO;CACR;AACD;;;;;AAWA,MAAM,OAAO,OAAO,IAAI,4BAA4B;;;;;;;AAsCpD,MAAa,OAAO;;CAEnB,IACC,SACA,SACO;EACP,OAAO;IACL,OAAO;GACR,MAAM;GACN;GACA,aAAa,QAAQ;EACtB;CACD;;CAGA,MACC,OACA,SACO;EACP,OAAO;IACL,OAAO;GACR,MAAM;GACN;GACA,MAAM,QAAQ;GACd,aAAa,QAAQ;EACtB;CACD;AACD;;AAGA,SAAgB,OAAO,OAA+B;CACrD,OACC,OAAO,UAAU,YACjB,UAAU,QACT,MAA+B,UAAU;AAE5C"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"kysely-BEm5sDlU.d.cts","names":[],"sources":["../src/database/pool.ts","../src/database/kysely.ts"],"mappings":";;;;;;;;;;;
|
|
1
|
+
{"version":3,"file":"kysely-BEm5sDlU.d.cts","names":[],"sources":["../src/database/pool.ts","../src/database/kysely.ts"],"mappings":";;;;;;;;;;;iBAmGsB,sBAAsB;;;;;;;;;;;;UC3D3B,8BAA8B,KAAK;;;;;;;;EAQnD;;;;;;;;EAQA;;;;;;;;;;;EAWA,UAAU;;;;;;EAMV;;;UAIS;EACT;EACA;EACA;;;;;;;;;cAUY,eAAe,cAAc,0CAC9B,UAAU,OAAO,OAAO;mBAiBjB;WAfT,IAAI;WACJ,SAAS,QAAQ,aAAa,QAAQ,OAAO;;;;;mBAMrC;mBACA;mBACA;mBACA;mBACA;EAEjB,YACC,IAAI,cAAc,QACD,UAAS,uBAC1B,cAAc;EAyBf,WAAW;;;;;;;;;;;;;EAqDX,UAAU,iBAAiB,OAAO;;;;;;;;;;;;;;;;;;EAyBlC,MAAM,2BAA2B,cAChC,KAAI,cAAc,SAClB;IAAW;MACT,MAAM;;;;;;;;;EAeT,OAAO,UAAU,wBAChB,IAAI,cAAc,UAClB,UAAS,wBACP,eAAe,UAAU;;;;;;;;;;;;;MAoBxB,SAAS,WAAW,aAAa,eAAe,OAAO;;;;;;;;;MAgBvD,gBAAgB,KAAK;UAcX;;;;;;;;;;;;;;;;;;;KAuCH,iBAAiB,IAAI,wBAAwB,KACxD,eAAe,IAAI"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"kysely-CjuvdXEV.d.mts","names":[],"sources":["../src/database/pool.ts","../src/database/kysely.ts"],"mappings":";;;;;;;;;;;
|
|
1
|
+
{"version":3,"file":"kysely-CjuvdXEV.d.mts","names":[],"sources":["../src/database/pool.ts","../src/database/kysely.ts"],"mappings":";;;;;;;;;;;iBAmGsB,sBAAsB;;;;;;;;;;;;UC3D3B,8BAA8B,KAAK;;;;;;;;EAQnD;;;;;;;;EAQA;;;;;;;;;;;EAWA,UAAU;;;;;;EAMV;;;UAIS;EACT;EACA;EACA;;;;;;;;;cAUY,eAAe,cAAc,0CAC9B,UAAU,OAAO,OAAO;mBAiBjB;WAfT,IAAI;WACJ,SAAS,QAAQ,aAAa,QAAQ,OAAO;;;;;mBAMrC;mBACA;mBACA;mBACA;mBACA;EAEjB,YACC,IAAI,cAAc,QACD,UAAS,uBAC1B,cAAc;EAyBf,WAAW;;;;;;;;;;;;;EAqDX,UAAU,iBAAiB,OAAO;;;;;;;;;;;;;;;;;;EAyBlC,MAAM,2BAA2B,cAChC,KAAI,cAAc,SAClB;IAAW;MACT,MAAM;;;;;;;;;EAeT,OAAO,UAAU,wBAChB,IAAI,cAAc,UAClB,UAAS,wBACP,eAAe,UAAU;;;;;;;;;;;;;MAoBxB,SAAS,WAAW,aAAa,eAAe,OAAO;;;;;;;;;MAgBvD,gBAAgB,KAAK;UAcX;;;;;;;;;;;;;;;;;;;KAuCH,iBAAiB,IAAI,wBAAwB,KACxD,eAAe,IAAI"}
|
|
@@ -1,30 +1,10 @@
|
|
|
1
1
|
import { t as onShutdown } from "./shutdown-C7xa8x9S.mjs";
|
|
2
2
|
import { Cache } from "./cache.mjs";
|
|
3
3
|
import { DEFAULT_POSTGRES_VERSION, canonicalId, provideKey, serviceKey } from "@geekmidas/manifest";
|
|
4
|
+
import { SpanKind, SpanStatusCode, context, trace } from "@opentelemetry/api";
|
|
4
5
|
import { Kysely, PostgresDialect } from "kysely";
|
|
5
6
|
import { currentRequestContext } from "@geekmidas/services";
|
|
6
7
|
import pg from "pg";
|
|
7
|
-
//#region src/database/pool.ts
|
|
8
|
-
/**
|
|
9
|
-
* The `pg` pools a database construct opens, and what every one of them gets:
|
|
10
|
-
*
|
|
11
|
-
* - **A name.** `application_name` is what `pg_stat_activity` shows beside a
|
|
12
|
-
* connection. Without one, a database at `max_connections` cannot say who
|
|
13
|
-
* holds them. It is a *fallback*, so `PGAPPNAME` or `?application_name=` in
|
|
14
|
-
* the URL still win.
|
|
15
|
-
* - **Tagged queries.** Inside a request, each query ends in a comment naming
|
|
16
|
-
* what ran it — `/*operation='POST /orders',request_id='…'*\/` — in the
|
|
17
|
-
* sqlcommenter form. It shows in `pg_stat_activity.query`, in the server's
|
|
18
|
-
* slow-query and `auto_explain` logs, and costs no round trip;
|
|
19
|
-
* `pg_stat_statements` ignores comments, so its grouping is unchanged.
|
|
20
|
-
* - **A listener for idle-client errors.** When the server ends an idle
|
|
21
|
-
* connection (`idle_session_timeout`, a failover, an admin), the pool emits
|
|
22
|
-
* `'error'`. With no listener that is an uncaught exception that kills the
|
|
23
|
-
* process — for a client the pool has already discarded.
|
|
24
|
-
* - **A way to close.** {@link closeDatabasePools} ends every pool opened, so a
|
|
25
|
-
* server shutting down releases its connections instead of holding them
|
|
26
|
-
* until the process dies.
|
|
27
|
-
*/
|
|
28
8
|
/** Every pool opened and not yet closed, so a shutdown can end them all. */
|
|
29
9
|
const open = /* @__PURE__ */ new Set();
|
|
30
10
|
onShutdown(() => closeDatabasePools());
|
|
@@ -52,7 +32,11 @@ function openPool(url, options = {}) {
|
|
|
52
32
|
if (logger) logger.warn({ err: error }, "Idle database connection lost");
|
|
53
33
|
else console.warn("Idle database connection lost:", error.message);
|
|
54
34
|
});
|
|
55
|
-
|
|
35
|
+
const target = connectionAttributes(parsed);
|
|
36
|
+
pool.on("connect", (client) => {
|
|
37
|
+
if (options.queryTags !== false) tagQueries(client);
|
|
38
|
+
traceQueries(client, target);
|
|
39
|
+
});
|
|
56
40
|
open.add(pool);
|
|
57
41
|
const end = pool.end.bind(pool);
|
|
58
42
|
pool.end = (async () => {
|
|
@@ -106,6 +90,92 @@ function tagQueries(client) {
|
|
|
106
90
|
return query(first, ...rest);
|
|
107
91
|
});
|
|
108
92
|
}
|
|
93
|
+
/** What every span of one pool says about where it connects. */
|
|
94
|
+
function connectionAttributes(url) {
|
|
95
|
+
const name = decodeURIComponent(url.pathname.slice(1));
|
|
96
|
+
return {
|
|
97
|
+
"db.system": "postgresql",
|
|
98
|
+
...name && { "db.name": name },
|
|
99
|
+
"server.address": url.hostname,
|
|
100
|
+
"server.port": Number(url.port || 5432)
|
|
101
|
+
};
|
|
102
|
+
}
|
|
103
|
+
const TRACER = "@geekmidas/constructs";
|
|
104
|
+
/** `select`, `insert`, … — the first keyword, or `with`'s main statement. */
|
|
105
|
+
const OPERATION = /^\s*(?:\/\*.*?\*\/\s*)?(\w+)/s;
|
|
106
|
+
/** The table a statement is about, when it names one where it usually does. */
|
|
107
|
+
const TABLE = /\b(?:from|into|update|join)\s+((?:"[^"]+"|[\w$]+)(?:\.(?:"[^"]+"|[\w$]+))?)/i;
|
|
108
|
+
/**
|
|
109
|
+
* What a statement does and to which table, parsed cheaply from its first
|
|
110
|
+
* characters: `select "orders"`, `insert "public"."users"`. A statement the
|
|
111
|
+
* patterns cannot read leaves `table` unset.
|
|
112
|
+
*/
|
|
113
|
+
function describeStatement(text) {
|
|
114
|
+
const head = text.length > 512 ? text.slice(0, 512) : text;
|
|
115
|
+
const operation = OPERATION.exec(head)?.[1]?.toLowerCase();
|
|
116
|
+
const table = TABLE.exec(head)?.[1]?.replace(/"/g, "");
|
|
117
|
+
return {
|
|
118
|
+
...operation && { operation },
|
|
119
|
+
...table && { table }
|
|
120
|
+
};
|
|
121
|
+
}
|
|
122
|
+
/**
|
|
123
|
+
* A span around everything `client` runs — `<operation> <table>`, or
|
|
124
|
+
* `db.query` when the statement does not say.
|
|
125
|
+
*
|
|
126
|
+
* The statement text goes on the span only for a parameterized query — values
|
|
127
|
+
* passed separately, as Kysely always does — and truncated. Parameter values
|
|
128
|
+
* never do. A bare string with no values could hold anything a caller
|
|
129
|
+
* concatenated into it, so it gets no text at all.
|
|
130
|
+
*/
|
|
131
|
+
function traceQueries(client, connection) {
|
|
132
|
+
const query = client.query.bind(client);
|
|
133
|
+
client.query = ((first, ...rest) => {
|
|
134
|
+
const config = first && typeof first === "object" ? first : void 0;
|
|
135
|
+
const text = typeof first === "string" ? first : typeof config?.text === "string" ? config.text : void 0;
|
|
136
|
+
const values = typeof first === "string" ? rest[0] : config?.values;
|
|
137
|
+
const { operation, table } = text ? describeStatement(text) : {};
|
|
138
|
+
const span = trace.getTracer(TRACER).startSpan(operation && table ? `${operation} ${table}` : "db.query", {
|
|
139
|
+
kind: SpanKind.CLIENT,
|
|
140
|
+
attributes: {
|
|
141
|
+
...connection,
|
|
142
|
+
...operation && { "db.operation": operation },
|
|
143
|
+
...table && { "db.sql.table": table },
|
|
144
|
+
...text && Array.isArray(values) && { "db.statement": text.length > 2048 ? text.slice(0, 2048) : text }
|
|
145
|
+
}
|
|
146
|
+
});
|
|
147
|
+
const end = (error) => {
|
|
148
|
+
if (error) {
|
|
149
|
+
if (error instanceof Error) span.recordException(error);
|
|
150
|
+
span.setStatus({ code: SpanStatusCode.ERROR });
|
|
151
|
+
}
|
|
152
|
+
span.end();
|
|
153
|
+
};
|
|
154
|
+
const last = rest[rest.length - 1];
|
|
155
|
+
if (typeof last === "function") {
|
|
156
|
+
const args = [...rest];
|
|
157
|
+
args[args.length - 1] = (error, ...result) => {
|
|
158
|
+
end(error);
|
|
159
|
+
return last(error, ...result);
|
|
160
|
+
};
|
|
161
|
+
return context.with(trace.setSpan(context.active(), span), () => query(first, ...args));
|
|
162
|
+
}
|
|
163
|
+
let result;
|
|
164
|
+
try {
|
|
165
|
+
result = context.with(trace.setSpan(context.active(), span), () => query(first, ...rest));
|
|
166
|
+
} catch (error) {
|
|
167
|
+
end(error);
|
|
168
|
+
throw error;
|
|
169
|
+
}
|
|
170
|
+
if (result && typeof result.then === "function") result.then(() => end(), (error) => end(error));
|
|
171
|
+
else if (result && typeof result.once === "function") {
|
|
172
|
+
const emitter = result;
|
|
173
|
+
emitter.once("end", () => end());
|
|
174
|
+
emitter.once("error", (error) => end(error));
|
|
175
|
+
} else end();
|
|
176
|
+
return result;
|
|
177
|
+
});
|
|
178
|
+
}
|
|
109
179
|
//#endregion
|
|
110
180
|
//#region src/database/kysely.ts
|
|
111
181
|
/**
|
|
@@ -285,4 +355,4 @@ var KyselyDatabase = class KyselyDatabase {
|
|
|
285
355
|
//#endregion
|
|
286
356
|
export { closeDatabasePools as n, KyselyDatabase as t };
|
|
287
357
|
|
|
288
|
-
//# sourceMappingURL=kysely-
|
|
358
|
+
//# sourceMappingURL=kysely-DN88k0gD.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"kysely-DN88k0gD.mjs","names":[],"sources":["../src/database/pool.ts","../src/database/kysely.ts"],"sourcesContent":["/**\n * The `pg` pools a database construct opens, and what every one of them gets:\n *\n * - **A name.** `application_name` is what `pg_stat_activity` shows beside a\n * connection. Without one, a database at `max_connections` cannot say who\n * holds them. It is a *fallback*, so `PGAPPNAME` or `?application_name=` in\n * the URL still win.\n * - **Tagged queries.** Inside a request, each query ends in a comment naming\n * what ran it — `/*operation='POST /orders',request_id='…'*\\/` — in the\n * sqlcommenter form. It shows in `pg_stat_activity.query`, in the server's\n * slow-query and `auto_explain` logs, and costs no round trip;\n * `pg_stat_statements` ignores comments, so its grouping is unchanged.\n * - **A listener for idle-client errors.** When the server ends an idle\n * connection (`idle_session_timeout`, a failover, an admin), the pool emits\n * `'error'`. With no listener that is an uncaught exception that kills the\n * process — for a client the pool has already discarded.\n * - **A span per query.** Through the global OpenTelemetry tracer, so a no-op\n * without a provider. `pg` is bundled into a production entry, where no\n * instrumentation can hook its module load — so the client is wrapped here,\n * as the tags are. See {@link traceQueries}.\n * - **A way to close.** {@link closeDatabasePools} ends every pool opened, so a\n * server shutting down releases its connections instead of holding them\n * until the process dies.\n */\n\nimport { currentRequestContext } from '@geekmidas/services';\nimport {\n\ttype Attributes,\n\tcontext,\n\tSpanKind,\n\tSpanStatusCode,\n\ttrace,\n} from '@opentelemetry/api';\nimport pg from 'pg';\nimport { onShutdown } from '../shutdown';\n\nexport interface DatabasePoolOptions {\n\t/** Tag queries run inside a request with what ran them. Default true. */\n\tqueryTags?: boolean;\n}\n\n/** The longest statement text a query span carries. */\nexport const MAX_STATEMENT_LENGTH = 2048;\n\n/** Every pool opened and not yet closed, so a shutdown can end them all. */\nconst open = new Set<pg.Pool>();\nonShutdown(() => closeDatabasePools());\n\n/**\n * A pool for one URL, with its schema actually on the search path.\n *\n * `?search_path=` is not a libpq parameter — a URL carrying it connects\n * happily and then resolves every unqualified name against `public`, which is\n * how a schema tenant silently writes its tables into the database it was\n * separated from. Postgres takes it as a startup option instead, so the URL\n * keeps the readable form the target derives and this turns it into the thing\n * the server understands.\n */\nexport function openPool(\n\turl: string,\n\toptions: DatabasePoolOptions = {},\n): pg.Pool {\n\tconst parsed = new URL(url);\n\tconst searchPath = parsed.searchParams.get('search_path');\n\tparsed.searchParams.delete('search_path');\n\n\tconst pool = new pg.Pool({\n\t\tconnectionString: parsed.toString(),\n\t\t...(searchPath ? { options: `-c search_path=${searchPath}` } : {}),\n\t\tfallback_application_name: applicationName(),\n\t});\n\n\tpool.on('error', (error) => {\n\t\tconst logger = currentRequestContext()?.logger;\n\t\tif (logger) logger.warn({ err: error }, 'Idle database connection lost');\n\t\telse console.warn('Idle database connection lost:', error.message);\n\t});\n\tconst target = connectionAttributes(parsed);\n\tpool.on('connect', (client) => {\n\t\t// Tags first, so the span wraps them and records the statement as the\n\t\t// application wrote it rather than with the comment on the end.\n\t\tif (options.queryTags !== false) tagQueries(client);\n\t\ttraceQueries(client, target);\n\t});\n\n\topen.add(pool);\n\tconst end = pool.end.bind(pool);\n\tpool.end = (async () => {\n\t\topen.delete(pool);\n\t\tawait end();\n\t}) as typeof pool.end;\n\n\treturn pool;\n}\n\n/**\n * End every pool opened, waiting for checked-out connections to come back.\n * For a server's shutdown, after it has stopped taking requests.\n */\nexport async function closeDatabasePools(): Promise<void> {\n\tawait Promise.all([...open].map((pool) => pool.end()));\n}\n\n/**\n * Who this process is, as Postgres will show it: the Lambda function, else the\n * app — `GKM_APP_NAME` where an entry sets it, `gkm dev`'s app tag otherwise.\n * Postgres keeps 63 bytes of it.\n */\nexport function applicationName(\n\tenv: NodeJS.ProcessEnv = process.env,\n): string | undefined {\n\treturn (\n\t\tenv.AWS_LAMBDA_FUNCTION_NAME ||\n\t\tenv.GKM_APP_NAME ||\n\t\tenv.GKM_DEV_APP?.split('#').pop() ||\n\t\tundefined\n\t);\n}\n\n/**\n * The comment that says what ran a query, or '' outside a request.\n *\n * Values keep only characters that cannot end a comment or a quoted value —\n * `*` and `'` among those dropped — so a route cannot inject SQL through it.\n */\nexport function queryTag(): string {\n\tconst request = currentRequestContext();\n\tif (!request) return '';\n\n\tconst tags = [\n\t\t['operation', request.operation],\n\t\t['request_id', request.requestId],\n\t].filter((tag): tag is [string, string] => Boolean(tag[1]));\n\tif (tags.length === 0) return '';\n\n\tconst clean = (value: string) => value.replace(/[^\\w ./:{}@-]/g, '');\n\treturn ` /*${tags.map(([key, value]) => `${key}='${clean(value)}'`).join(',')}*/`;\n}\n\n/**\n * Append {@link queryTag} to everything `client` runs: a SQL string — what\n * Kysely sends — or a query object such as a cursor's.\n */\nfunction tagQueries(client: pg.PoolClient): void {\n\tconst query = client.query.bind(client) as (...args: unknown[]) => unknown;\n\tclient.query = ((first: unknown, ...rest: unknown[]) => {\n\t\tconst tag = queryTag();\n\t\tif (tag && typeof first === 'string') return query(first + tag, ...rest);\n\t\tif (\n\t\t\ttag &&\n\t\t\tfirst &&\n\t\t\ttypeof first === 'object' &&\n\t\t\ttypeof (first as { text?: unknown }).text === 'string'\n\t\t) {\n\t\t\tconst config = first as { text: string };\n\t\t\tconfig.text += tag;\n\t\t}\n\t\treturn query(first, ...rest);\n\t}) as typeof client.query;\n}\n\n/** What every span of one pool says about where it connects. */\nfunction connectionAttributes(url: URL): Attributes {\n\tconst name = decodeURIComponent(url.pathname.slice(1));\n\treturn {\n\t\t'db.system': 'postgresql',\n\t\t...(name && { 'db.name': name }),\n\t\t'server.address': url.hostname,\n\t\t'server.port': Number(url.port || 5432),\n\t};\n}\n\nconst TRACER = '@geekmidas/constructs';\n\n/** `select`, `insert`, … — the first keyword, or `with`'s main statement. */\nconst OPERATION = /^\\s*(?:\\/\\*.*?\\*\\/\\s*)?(\\w+)/s;\n/** The table a statement is about, when it names one where it usually does. */\nconst TABLE =\n\t/\\b(?:from|into|update|join)\\s+((?:\"[^\"]+\"|[\\w$]+)(?:\\.(?:\"[^\"]+\"|[\\w$]+))?)/i;\n\n/**\n * What a statement does and to which table, parsed cheaply from its first\n * characters: `select \"orders\"`, `insert \"public\".\"users\"`. A statement the\n * patterns cannot read leaves `table` unset.\n */\nexport function describeStatement(text: string): {\n\toperation?: string;\n\ttable?: string;\n} {\n\tconst head = text.length > 512 ? text.slice(0, 512) : text;\n\tconst operation = OPERATION.exec(head)?.[1]?.toLowerCase();\n\tconst table = TABLE.exec(head)?.[1]?.replace(/\"/g, '');\n\treturn {\n\t\t...(operation && { operation }),\n\t\t...(table && { table }),\n\t};\n}\n\n/**\n * A span around everything `client` runs — `<operation> <table>`, or\n * `db.query` when the statement does not say.\n *\n * The statement text goes on the span only for a parameterized query — values\n * passed separately, as Kysely always does — and truncated. Parameter values\n * never do. A bare string with no values could hold anything a caller\n * concatenated into it, so it gets no text at all.\n */\nfunction traceQueries(client: pg.PoolClient, connection: Attributes): void {\n\tconst query = client.query.bind(client) as (...args: unknown[]) => unknown;\n\tclient.query = ((first: unknown, ...rest: unknown[]) => {\n\t\tconst config =\n\t\t\tfirst && typeof first === 'object'\n\t\t\t\t? (first as { text?: unknown; values?: unknown })\n\t\t\t\t: undefined;\n\t\tconst text =\n\t\t\ttypeof first === 'string'\n\t\t\t\t? first\n\t\t\t\t: typeof config?.text === 'string'\n\t\t\t\t\t? config.text\n\t\t\t\t\t: undefined;\n\t\tconst values = typeof first === 'string' ? rest[0] : config?.values;\n\t\tconst { operation, table } = text ? describeStatement(text) : {};\n\n\t\tconst span = trace\n\t\t\t.getTracer(TRACER)\n\t\t\t.startSpan(operation && table ? `${operation} ${table}` : 'db.query', {\n\t\t\t\tkind: SpanKind.CLIENT,\n\t\t\t\tattributes: {\n\t\t\t\t\t...connection,\n\t\t\t\t\t...(operation && { 'db.operation': operation }),\n\t\t\t\t\t...(table && { 'db.sql.table': table }),\n\t\t\t\t\t...(text &&\n\t\t\t\t\t\tArray.isArray(values) && {\n\t\t\t\t\t\t\t'db.statement':\n\t\t\t\t\t\t\t\ttext.length > MAX_STATEMENT_LENGTH\n\t\t\t\t\t\t\t\t\t? text.slice(0, MAX_STATEMENT_LENGTH)\n\t\t\t\t\t\t\t\t\t: text,\n\t\t\t\t\t\t}),\n\t\t\t\t},\n\t\t\t});\n\t\tconst end = (error?: unknown) => {\n\t\t\tif (error) {\n\t\t\t\tif (error instanceof Error) span.recordException(error);\n\t\t\t\tspan.setStatus({ code: SpanStatusCode.ERROR });\n\t\t\t}\n\t\t\tspan.end();\n\t\t};\n\n\t\t// A callback, as `pg`'s own callback form takes it.\n\t\tconst last = rest[rest.length - 1];\n\t\tif (typeof last === 'function') {\n\t\t\tconst args = [...rest];\n\t\t\targs[args.length - 1] = (error: unknown, ...result: unknown[]) => {\n\t\t\t\tend(error);\n\t\t\t\treturn (last as (...a: unknown[]) => unknown)(error, ...result);\n\t\t\t};\n\t\t\treturn context.with(trace.setSpan(context.active(), span), () =>\n\t\t\t\tquery(first, ...args),\n\t\t\t);\n\t\t}\n\n\t\tlet result: unknown;\n\t\ttry {\n\t\t\tresult = context.with(trace.setSpan(context.active(), span), () =>\n\t\t\t\tquery(first, ...rest),\n\t\t\t);\n\t\t} catch (error) {\n\t\t\tend(error);\n\t\t\tthrow error;\n\t\t}\n\n\t\tif (result && typeof (result as Promise<unknown>).then === 'function') {\n\t\t\t(result as Promise<unknown>).then(\n\t\t\t\t() => end(),\n\t\t\t\t(error) => end(error),\n\t\t\t);\n\t\t} else if (\n\t\t\tresult &&\n\t\t\ttypeof (result as { once?: unknown }).once === 'function'\n\t\t) {\n\t\t\t// A submittable — a cursor or a stream — ends when it says so.\n\t\t\tconst emitter = result as {\n\t\t\t\tonce(event: string, fn: (e?: unknown) => void): void;\n\t\t\t};\n\t\t\temitter.once('end', () => end());\n\t\t\temitter.once('error', (error) => end(error));\n\t\t} else {\n\t\t\tend();\n\t\t}\n\t\treturn result;\n\t}) as typeof client.query;\n}\n","/**\n * `KyselyDatabase` — a declared Postgres database, typed by its schema.\n *\n * It declares a logical database, a schema, and the roles that reach it, and\n * hands back a Kysely client built from the one URL the adapter supplied. It\n * names no cloud: `--target=aws` fills that URL from RDS, local dev from the\n * Postgres container.\n *\n * Transactions and RLS context are the execution wrapper's job — it opens the\n * transaction and puts it in `ctx.db`. This construct does not resolve\n * connections per request.\n */\n\nimport {\n\ttype ConstructName,\n\tcanonicalId,\n\tDEFAULT_POSTGRES_VERSION,\n\ttype Declaration,\n\ttype PostgresVersion,\n\tprovideKey,\n\tserviceKey,\n} from '@geekmidas/manifest';\nimport type { Service, ServiceRegisterOptions } from '@geekmidas/services';\nimport { Kysely, type KyselyConfig, PostgresDialect } from 'kysely';\nimport { Cache } from '../cache';\nimport type { Construct } from '../construct-interface';\nimport { openPool } from './pool';\n\n/** The schema a database uses when it does not say otherwise. */\nconst DEFAULT_SCHEMA = 'app';\n\n/**\n * Everything Kysely takes, plus what this construct declares.\n *\n * `dialect` is omitted because the construct owns it — it is built from the one\n * URL the adapter supplied, which is the whole point of the construct. The rest\n * of `KyselyConfig` (`plugins`, `log`) is the app's business and passes\n * straight through, so anything Kysely adds later arrives without being\n * tracked here.\n */\nexport interface KyselyDatabaseOptions extends Omit<KyselyConfig, 'dialect'> {\n\t/**\n\t * The schema, pinned on both roles' `search_path`.\n\t *\n\t * Defaults to `app` — the role the schema plays, rather than a restatement\n\t * of the database's own name, which reads correctly beside `auth` and\n\t * `pgboss` and keeps the application off `public`.\n\t */\n\tschema?: string;\n\t/**\n\t * Provision the owner/runtime role split. Defaults to on.\n\t *\n\t * Off falls back to the cluster's master credential in both URLs, giving up\n\t * the DDL/DML split and putting credentials that can drop a table into the\n\t * function's environment. A deliberate downgrade, not a default.\n\t */\n\troles?: boolean;\n\t/**\n\t * The Postgres major version to provision.\n\t *\n\t * Declared here so one statement reaches both targets. It was previously\n\t * set in two unrelated places — a container tag locally, nothing at all on\n\t * AWS (so Aurora chose) — which is how local came to run 18 while deployed\n\t * ran 17.7 with nothing recording the difference.\n\t *\n\t * Defaults to {@link DEFAULT_POSTGRES_VERSION}.\n\t */\n\tversion?: PostgresVersion;\n\t/**\n\t * End each query run inside a request with a comment naming what ran it —\n\t * `/*operation='POST /orders',request_id='…'*\\/` — so `pg_stat_activity`\n\t * and the server's logs can tie a query to its endpoint. Defaults to on.\n\t */\n\tqueryTags?: boolean;\n}\n\n/** What makes a construct derived rather than a database in its own right. */\ninterface DerivedFrom {\n\tkind: 'database-reader' | 'database-schema';\n\tof: string;\n\tschema?: string;\n}\n\n/**\n * @typeParam DB - the database's schema.\n * @typeParam TName - the canonical id. TypeScript has no partial\n * type-argument inference, so `new KyselyDatabase<OrdersDB>('orders')` leaves\n * this at its default and the service key widens to `string`. `db` still types\n * through `.database()`, which infers from the service.\n */\nexport class KyselyDatabase<DB = unknown, TName extends string = string>\n\timplements Construct<TName, Kysely<DB>>\n{\n\treadonly id: TName;\n\treadonly service: Service<Uncapitalize<TName>, Kysely<DB>>;\n\n\t/**\n\t * Declared once and read by both `declare()` and `connect()`, so the key the\n\t * build publishes and the key the client reads cannot drift.\n\t */\n\tprivate readonly config: { url: string; ownerUrl: string };\n\tprivate readonly schemaName: string;\n\tprivate readonly roles: boolean;\n\tprivate readonly version: PostgresVersion;\n\tprivate readonly derivedFrom?: DerivedFrom;\n\n\tconstructor(\n\t\tid: ConstructName<TName>,\n\t\tprivate readonly options: KyselyDatabaseOptions = {},\n\t\tderivedFrom?: DerivedFrom,\n\t) {\n\t\t// Canonicalises, so `orders` and `Orders` are one construct rather than\n\t\t// two that collide. Throws on anything that cannot become a valid id.\n\t\tconst canonical = canonicalId(id as string);\n\n\t\tthis.id = canonical as TName;\n\t\tthis.config = {\n\t\t\turl: provideKey(canonical, 'url'),\n\t\t\townerUrl: provideKey(canonical, 'ownerUrl'),\n\t\t};\n\t\tthis.schemaName = options.schema ?? DEFAULT_SCHEMA;\n\t\tthis.roles = options.roles ?? true;\n\t\tthis.version = options.version ?? DEFAULT_POSTGRES_VERSION;\n\t\tthis.derivedFrom = derivedFrom;\n\n\t\t// A field, not a getter: service discovery caches by object identity.\n\t\tthis.service = {\n\t\t\tserviceName: serviceKey(canonical) as Uncapitalize<TName>,\n\t\t\t// Forwards the whole options object — cherry-picking `envParser` strips\n\t\t\t// `context` and with it the request-scoped logger.\n\t\t\tregister: (registerOptions) => this.connect(registerOptions),\n\t\t};\n\t}\n\n\tdeclare(): Declaration[] {\n\t\tif (this.derivedFrom) {\n\t\t\tconst { kind, of, schema } = this.derivedFrom;\n\n\t\t\treturn [\n\t\t\t\tkind === 'database-schema'\n\t\t\t\t\t? {\n\t\t\t\t\t\t\tkind,\n\t\t\t\t\t\t\tid: this.id,\n\t\t\t\t\t\t\tof,\n\t\t\t\t\t\t\tschema: schema ?? this.schemaName,\n\t\t\t\t\t\t\t// The runtime key alone — see the note below on the parent.\n\t\t\t\t\t\t\tprovides: [this.config.url],\n\t\t\t\t\t\t}\n\t\t\t\t\t: {\n\t\t\t\t\t\t\tkind,\n\t\t\t\t\t\t\tid: this.id,\n\t\t\t\t\t\t\tof,\n\t\t\t\t\t\t\t// A reader has no owner URL of its own — nothing migrates\n\t\t\t\t\t\t\t// through a read-only endpoint — so this is the one key.\n\t\t\t\t\t\t\tprovides: [this.config.url],\n\t\t\t\t\t\t},\n\t\t\t];\n\t\t}\n\n\t\treturn [\n\t\t\t{\n\t\t\t\tkind: 'database',\n\t\t\t\tid: this.id,\n\t\t\t\tengine: 'postgres',\n\t\t\t\tschema: this.schemaName,\n\t\t\t\tversion: this.version,\n\t\t\t\t// One key, the runtime role's. `config` also holds the owner key and\n\t\t\t\t// it is deliberately absent here: a key in `provides` is a key an\n\t\t\t\t// edge can name, and nothing should be able to depend on DDL rights.\n\t\t\t\tprovides: [this.config.url],\n\t\t\t\t...(this.roles ? {} : { roles: false }),\n\t\t\t},\n\t\t];\n\t}\n\n\t/**\n\t * A read-only endpoint on this database.\n\t *\n\t * Read-only is enforced by the reader role's grants rather than by which\n\t * endpoint it resolves to, so falling back to the writer where no replica\n\t * exists is safe rather than a silently writable connection behind a name\n\t * that says reader. There is no `writer()`: the database *is* the writer, so\n\t * a replica can never be reached by accident.\n\t *\n\t * The return type is narrower than this class on purpose — see\n\t * {@link ReadOnlyDatabase}.\n\t */\n\treader(): ReadOnlyDatabase<DB, `${TName}Reader`> {\n\t\treturn new KyselyDatabase<DB, `${TName}Reader`>(\n\t\t\t`${this.id}Reader` as ConstructName<`${TName}Reader`>,\n\t\t\tthis.options,\n\t\t\t{ kind: 'database-reader', of: this.id },\n\t\t);\n\t}\n\n\t/**\n\t * A cache that lives in this database.\n\t *\n\t * The same strengthening `schema()` is over a second database: `new\n\t * Cache('Sessions')` says the app caches and leaves where to the deployment,\n\t * while this says it caches *here* — which is a fact about the application\n\t * and so belongs in its code.\n\t *\n\t * What it buys beyond being explicit: the table's schema and the role that\n\t * reaches it come from this database rather than from a second convention,\n\t * and the backend no longer has to guess which database \"the database\" meant\n\t * when an app declares two.\n\t *\n\t * A cache is not a `KyselyDatabase`, so this returns a `Cache` — the client\n\t * is a key/value store, not a query builder, and typing it as the parent\n\t * would be a convenience that lies.\n\t */\n\tcache<TCache extends string = `${TName}Cache`>(\n\t\tid: ConstructName<TCache> = `${this.id}Cache` as ConstructName<TCache>,\n\t\toptions: { table?: string } = {},\n\t): Cache<TCache> {\n\t\treturn new Cache<TCache>(id, {\n\t\t\tof: this.id,\n\t\t\t...(options.table ? { table: options.table } : {}),\n\t\t});\n\t}\n\n\t/**\n\t * A second schema in this database, with its own role(s) and its own URL —\n\t * so this database's role holds no grant on those tables at all.\n\t *\n\t * Typed separately because a tenant has its own tables: the point is that\n\t * `auth.selectFrom('sessions')` type-checks and\n\t * `orders.selectFrom('sessions')` does not.\n\t */\n\tschema<TenantDB, TTenant extends string>(\n\t\tid: ConstructName<TTenant>,\n\t\toptions: KyselyDatabaseOptions = {},\n\t): KyselyDatabase<TenantDB, TTenant> {\n\t\treturn new KyselyDatabase<TenantDB, TTenant>(id, options, {\n\t\t\tkind: 'database-schema',\n\t\t\tof: this.id,\n\t\t\tschema: options.schema ?? (id as string).toLowerCase(),\n\t\t});\n\t}\n\n\t/**\n\t * A connection as the *owner* role — the one that may create, alter and drop.\n\t *\n\t * A `Service` rather than part of the construct, and deliberately so: a\n\t * construct is what `.dependsOn()` accepts, and nothing should be able to\n\t * depend on this. A migrator asks for it by name; a handler cannot ask at\n\t * all, which is the security property the role split exists for.\n\t *\n\t * Falls back to the runtime URL where no owner URL was published — the\n\t * `roles: false` downgrade, where there is only one credential and it is the\n\t * cluster master's.\n\t */\n\tget owner(): Service<`${Uncapitalize<TName>}Owner`, Kysely<DB>> {\n\t\treturn {\n\t\t\tserviceName:\n\t\t\t\t`${serviceKey(this.id)}Owner` as `${Uncapitalize<TName>}Owner`,\n\t\t\tregister: (options) => this.connect(options, { owner: true }),\n\t\t};\n\t}\n\n\t/**\n\t * What this database's clients are built with besides a dialect — the\n\t * plugins and logging it was declared with.\n\t *\n\t * Public so that whatever opens a connection to it outside \\`connect()\\` —\n\t * a test's transaction — builds the same client. A test that dropped the\n\t * plugins would write \\`createdAt\\` where production writes \\`created_at\\`.\n\t */\n\tget clientConfig(): Omit<KyselyConfig, 'dialect'> {\n\t\t// Split what the manifest declared from what Kysely takes, so neither\n\t\t// leaks into the other: \\`schema\\`, \\`roles\\` and \\`version\\` describe\n\t\t// infrastructure and mean nothing to a client.\n\t\tconst {\n\t\t\tschema: _schema,\n\t\t\troles: _roles,\n\t\t\tversion: _version,\n\t\t\tqueryTags: _queryTags,\n\t\t\t...kysely\n\t\t} = this.options;\n\t\treturn kysely;\n\t}\n\n\tprivate async connect(\n\t\toptions: ServiceRegisterOptions,\n\t\tas: { owner?: boolean } = {},\n\t): Promise<Kysely<DB>> {\n\t\tconst { url, ownerUrl } = options.envParser\n\t\t\t.create((get) => ({\n\t\t\t\turl: get(this.config.url).string(),\n\t\t\t\townerUrl: get(this.config.ownerUrl).string().optional(),\n\t\t\t}))\n\t\t\t.parse();\n\n\t\treturn new Kysely<DB>({\n\t\t\t...this.clientConfig,\n\t\t\tdialect: new PostgresDialect({\n\t\t\t\tpool: openPool(as.owner ? (ownerUrl ?? url) : url, {\n\t\t\t\t\tqueryTags: this.options.queryTags,\n\t\t\t\t}),\n\t\t\t}),\n\t\t});\n\t}\n}\n\n/**\n * A database you may read through, and derive nothing from.\n *\n * A reader is terminal in the graph, and this is that fact in the type system.\n * `DERIVES_FROM` gives `cache` and `database-schema` no `database-reader`\n * parent, and there is no reader of a reader — so `orders.reader().cache(…)`\n * has always been illegal, but it type-checked and failed later at\n * `assertDerivations`. That is a long way round to learn that a read-only\n * endpoint cannot own a table something writes to.\n *\n * Omitting the three deriving methods rather than making them throw keeps the\n * failure where it costs least: the editor, on the line that wrote it.\n *\n * The result is deliberately not assignable back to `KyselyDatabase` — a\n * reader is not one, and anything that genuinely needs the writer should say\n * so.\n */\nexport type ReadOnlyDatabase<DB, TName extends string> = Omit<\n\tKyselyDatabase<DB, TName>,\n\t'reader' | 'cache' | 'schema'\n>;\nexport { closeDatabasePools } from './pool';\n"],"mappings":";;;;;;;;AA6CA,MAAM,uBAAO,IAAI,IAAa;AAC9B,iBAAiB,mBAAmB,CAAC;;;;;;;;;;;AAYrC,SAAgB,SACf,KACA,UAA+B,CAAC,GACtB;CACV,MAAM,SAAS,IAAI,IAAI,GAAG;CAC1B,MAAM,aAAa,OAAO,aAAa,IAAI,aAAa;CACxD,OAAO,aAAa,OAAO,aAAa;CAExC,MAAM,OAAO,IAAI,GAAG,KAAK;EACxB,kBAAkB,OAAO,SAAS;EAClC,GAAI,aAAa,EAAE,SAAS,kBAAkB,aAAa,IAAI,CAAC;EAChE,2BAA2B,gBAAgB;CAC5C,CAAC;CAED,KAAK,GAAG,UAAU,UAAU;EAC3B,MAAM,SAAS,sBAAsB,CAAC,EAAE;EACxC,IAAI,QAAQ,OAAO,KAAK,EAAE,KAAK,MAAM,GAAG,+BAA+B;OAClE,QAAQ,KAAK,kCAAkC,MAAM,OAAO;CAClE,CAAC;CACD,MAAM,SAAS,qBAAqB,M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IAAI,CAAC;EACjD,CAAC;CACF;;;;;;;;;CAUA,OACC,IACA,UAAiC,CAAC,GACE;EACpC,OAAO,IAAI,eAAkC,IAAI,SAAS;GACzD,MAAM;GACN,IAAI,KAAK;GACT,QAAQ,QAAQ,UAAW,GAAc,YAAY;EACtD,CAAC;CACF;;;;;;;;;;;;;CAcA,IAAI,QAA4D;EAC/D,OAAO;GACN,aACC,GAAG,WAAW,KAAK,EAAE,EAAE;GACxB,WAAW,YAAY,KAAK,QAAQ,SAAS,EAAE,OAAO,KAAK,CAAC;EAC7D;CACD;;;;;;;;;CAUA,IAAI,eAA8C;EAIjD,MAAM,EACL,QAAQ,SACR,OAAO,QACP,SAAS,UACT,WAAW,YACX,GAAG,WACA,KAAK;EACT,OAAO;CACR;CAEA,MAAc,QACb,SACA,KAA0B,CAAC,GACL;EACtB,MAAM,EAAE,KAAK,aAAa,QAAQ,UAChC,QAAQ,SAAS;GACjB,KAAK,IAAI,KAAK,OAAO,GAAG,CAAC,CAAC,OAAO;GACjC,UAAU,IAAI,KAAK,OAAO,QAAQ,CAAC,CAAC,OAAO,CAAC,CAAC,SAAS;EACvD,EAAE,CAAC,CACF,MAAM;EAER,OAAO,IAAI,OAAW;GACrB,GAAG,KAAK;GACR,SAAS,IAAI,gBAAgB,EAC5B,MAAM,SAAS,GAAG,QAAS,YAAY,MAAO,KAAK,EAClD,WAAW,KAAK,QAAQ,UACzB,CAAC,EACF,CAAC;EACF,CAAC;CACF;AACD"}
|
|
@@ -2,31 +2,11 @@ const require_rolldown_runtime = require("./rolldown-runtime-y5ARvAq5.cjs");
|
|
|
2
2
|
const require_shutdown = require("./shutdown-BMJmAhSt.cjs");
|
|
3
3
|
const require_cache = require("./cache.cjs");
|
|
4
4
|
let _geekmidas_manifest = require("@geekmidas/manifest");
|
|
5
|
+
let _opentelemetry_api = require("@opentelemetry/api");
|
|
5
6
|
let kysely = require("kysely");
|
|
6
7
|
let _geekmidas_services = require("@geekmidas/services");
|
|
7
8
|
let pg = require("pg");
|
|
8
9
|
pg = require_rolldown_runtime.__toESM(pg, 1);
|
|
9
|
-
//#region src/database/pool.ts
|
|
10
|
-
/**
|
|
11
|
-
* The `pg` pools a database construct opens, and what every one of them gets:
|
|
12
|
-
*
|
|
13
|
-
* - **A name.** `application_name` is what `pg_stat_activity` shows beside a
|
|
14
|
-
* connection. Without one, a database at `max_connections` cannot say who
|
|
15
|
-
* holds them. It is a *fallback*, so `PGAPPNAME` or `?application_name=` in
|
|
16
|
-
* the URL still win.
|
|
17
|
-
* - **Tagged queries.** Inside a request, each query ends in a comment naming
|
|
18
|
-
* what ran it — `/*operation='POST /orders',request_id='…'*\/` — in the
|
|
19
|
-
* sqlcommenter form. It shows in `pg_stat_activity.query`, in the server's
|
|
20
|
-
* slow-query and `auto_explain` logs, and costs no round trip;
|
|
21
|
-
* `pg_stat_statements` ignores comments, so its grouping is unchanged.
|
|
22
|
-
* - **A listener for idle-client errors.** When the server ends an idle
|
|
23
|
-
* connection (`idle_session_timeout`, a failover, an admin), the pool emits
|
|
24
|
-
* `'error'`. With no listener that is an uncaught exception that kills the
|
|
25
|
-
* process — for a client the pool has already discarded.
|
|
26
|
-
* - **A way to close.** {@link closeDatabasePools} ends every pool opened, so a
|
|
27
|
-
* server shutting down releases its connections instead of holding them
|
|
28
|
-
* until the process dies.
|
|
29
|
-
*/
|
|
30
10
|
/** Every pool opened and not yet closed, so a shutdown can end them all. */
|
|
31
11
|
const open = /* @__PURE__ */ new Set();
|
|
32
12
|
require_shutdown.onShutdown(() => closeDatabasePools());
|
|
@@ -54,7 +34,11 @@ function openPool(url, options = {}) {
|
|
|
54
34
|
if (logger) logger.warn({ err: error }, "Idle database connection lost");
|
|
55
35
|
else console.warn("Idle database connection lost:", error.message);
|
|
56
36
|
});
|
|
57
|
-
|
|
37
|
+
const target = connectionAttributes(parsed);
|
|
38
|
+
pool.on("connect", (client) => {
|
|
39
|
+
if (options.queryTags !== false) tagQueries(client);
|
|
40
|
+
traceQueries(client, target);
|
|
41
|
+
});
|
|
58
42
|
open.add(pool);
|
|
59
43
|
const end = pool.end.bind(pool);
|
|
60
44
|
pool.end = (async () => {
|
|
@@ -108,6 +92,92 @@ function tagQueries(client) {
|
|
|
108
92
|
return query(first, ...rest);
|
|
109
93
|
});
|
|
110
94
|
}
|
|
95
|
+
/** What every span of one pool says about where it connects. */
|
|
96
|
+
function connectionAttributes(url) {
|
|
97
|
+
const name = decodeURIComponent(url.pathname.slice(1));
|
|
98
|
+
return {
|
|
99
|
+
"db.system": "postgresql",
|
|
100
|
+
...name && { "db.name": name },
|
|
101
|
+
"server.address": url.hostname,
|
|
102
|
+
"server.port": Number(url.port || 5432)
|
|
103
|
+
};
|
|
104
|
+
}
|
|
105
|
+
const TRACER = "@geekmidas/constructs";
|
|
106
|
+
/** `select`, `insert`, … — the first keyword, or `with`'s main statement. */
|
|
107
|
+
const OPERATION = /^\s*(?:\/\*.*?\*\/\s*)?(\w+)/s;
|
|
108
|
+
/** The table a statement is about, when it names one where it usually does. */
|
|
109
|
+
const TABLE = /\b(?:from|into|update|join)\s+((?:"[^"]+"|[\w$]+)(?:\.(?:"[^"]+"|[\w$]+))?)/i;
|
|
110
|
+
/**
|
|
111
|
+
* What a statement does and to which table, parsed cheaply from its first
|
|
112
|
+
* characters: `select "orders"`, `insert "public"."users"`. A statement the
|
|
113
|
+
* patterns cannot read leaves `table` unset.
|
|
114
|
+
*/
|
|
115
|
+
function describeStatement(text) {
|
|
116
|
+
const head = text.length > 512 ? text.slice(0, 512) : text;
|
|
117
|
+
const operation = OPERATION.exec(head)?.[1]?.toLowerCase();
|
|
118
|
+
const table = TABLE.exec(head)?.[1]?.replace(/"/g, "");
|
|
119
|
+
return {
|
|
120
|
+
...operation && { operation },
|
|
121
|
+
...table && { table }
|
|
122
|
+
};
|
|
123
|
+
}
|
|
124
|
+
/**
|
|
125
|
+
* A span around everything `client` runs — `<operation> <table>`, or
|
|
126
|
+
* `db.query` when the statement does not say.
|
|
127
|
+
*
|
|
128
|
+
* The statement text goes on the span only for a parameterized query — values
|
|
129
|
+
* passed separately, as Kysely always does — and truncated. Parameter values
|
|
130
|
+
* never do. A bare string with no values could hold anything a caller
|
|
131
|
+
* concatenated into it, so it gets no text at all.
|
|
132
|
+
*/
|
|
133
|
+
function traceQueries(client, connection) {
|
|
134
|
+
const query = client.query.bind(client);
|
|
135
|
+
client.query = ((first, ...rest) => {
|
|
136
|
+
const config = first && typeof first === "object" ? first : void 0;
|
|
137
|
+
const text = typeof first === "string" ? first : typeof config?.text === "string" ? config.text : void 0;
|
|
138
|
+
const values = typeof first === "string" ? rest[0] : config?.values;
|
|
139
|
+
const { operation, table } = text ? describeStatement(text) : {};
|
|
140
|
+
const span = _opentelemetry_api.trace.getTracer(TRACER).startSpan(operation && table ? `${operation} ${table}` : "db.query", {
|
|
141
|
+
kind: _opentelemetry_api.SpanKind.CLIENT,
|
|
142
|
+
attributes: {
|
|
143
|
+
...connection,
|
|
144
|
+
...operation && { "db.operation": operation },
|
|
145
|
+
...table && { "db.sql.table": table },
|
|
146
|
+
...text && Array.isArray(values) && { "db.statement": text.length > 2048 ? text.slice(0, 2048) : text }
|
|
147
|
+
}
|
|
148
|
+
});
|
|
149
|
+
const end = (error) => {
|
|
150
|
+
if (error) {
|
|
151
|
+
if (error instanceof Error) span.recordException(error);
|
|
152
|
+
span.setStatus({ code: _opentelemetry_api.SpanStatusCode.ERROR });
|
|
153
|
+
}
|
|
154
|
+
span.end();
|
|
155
|
+
};
|
|
156
|
+
const last = rest[rest.length - 1];
|
|
157
|
+
if (typeof last === "function") {
|
|
158
|
+
const args = [...rest];
|
|
159
|
+
args[args.length - 1] = (error, ...result) => {
|
|
160
|
+
end(error);
|
|
161
|
+
return last(error, ...result);
|
|
162
|
+
};
|
|
163
|
+
return _opentelemetry_api.context.with(_opentelemetry_api.trace.setSpan(_opentelemetry_api.context.active(), span), () => query(first, ...args));
|
|
164
|
+
}
|
|
165
|
+
let result;
|
|
166
|
+
try {
|
|
167
|
+
result = _opentelemetry_api.context.with(_opentelemetry_api.trace.setSpan(_opentelemetry_api.context.active(), span), () => query(first, ...rest));
|
|
168
|
+
} catch (error) {
|
|
169
|
+
end(error);
|
|
170
|
+
throw error;
|
|
171
|
+
}
|
|
172
|
+
if (result && typeof result.then === "function") result.then(() => end(), (error) => end(error));
|
|
173
|
+
else if (result && typeof result.once === "function") {
|
|
174
|
+
const emitter = result;
|
|
175
|
+
emitter.once("end", () => end());
|
|
176
|
+
emitter.once("error", (error) => end(error));
|
|
177
|
+
} else end();
|
|
178
|
+
return result;
|
|
179
|
+
});
|
|
180
|
+
}
|
|
111
181
|
//#endregion
|
|
112
182
|
//#region src/database/kysely.ts
|
|
113
183
|
/**
|
|
@@ -298,4 +368,4 @@ Object.defineProperty(exports, "closeDatabasePools", {
|
|
|
298
368
|
}
|
|
299
369
|
});
|
|
300
370
|
|
|
301
|
-
//# sourceMappingURL=kysely-
|
|
371
|
+
//# sourceMappingURL=kysely-H7L1YDgE.cjs.map
|