@rexezuge/runtime 1.8.0 → 1.8.2
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.
|
@@ -112,6 +112,26 @@ declare abstract class AbstractScheduledTask<TEnv extends ScheduledTaskEnv = Sch
|
|
|
112
112
|
Override to route this task's failures somewhere other than the console.
|
|
113
113
|
*/
|
|
114
114
|
protected logger(): TaskLogger;
|
|
115
|
+
/**
|
|
116
|
+
* How a caught error becomes the `errorMessage` written to the run record.
|
|
117
|
+
*
|
|
118
|
+
* The default is the error's own message, which is right for a console log and
|
|
119
|
+
* **wrong for a row a user reads back**. Run records are persisted and surfaced
|
|
120
|
+
* through an authenticated route, so a failure whose message carries a token, a
|
|
121
|
+
* bearer header or a signed URL writes credential material into the database and
|
|
122
|
+
* hands it to whoever loads the task-runs screen.
|
|
123
|
+
*
|
|
124
|
+
* A repo with that exposure overrides this and routes the value through its own
|
|
125
|
+
* redactor. The kit cannot do it here: `runtime` is the DI and platform layer
|
|
126
|
+
* with no dependency on the logging packages that carry those redaction rules,
|
|
127
|
+
* and taking one would invert the package graph.
|
|
128
|
+
*
|
|
129
|
+
* There was no seam for this before, so the only options were to accept the
|
|
130
|
+
* unredacted message or to keep a local copy of the whole Template Method — and
|
|
131
|
+
* five of the seven repos the file was converged from have exactly that
|
|
132
|
+
* redactor, so every one of them was carrying a duplicated base class.
|
|
133
|
+
*/
|
|
134
|
+
protected describeFailure(error: unknown): string;
|
|
115
135
|
/**
|
|
116
136
|
* Whether `handle` swallows a failure after recording it.
|
|
117
137
|
*
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/scheduled/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;GAwBG;AAEH;;EAEE;AACF,UAAU,cAAc;IACtB,cAAc,EAAE,MAAM,CAAC;IACvB,WAAW,EAAE,MAAM,CAAC;IACpB,OAAO,CAAC,EA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,EACT,GAAG,EAAE,oBAAoB,GACxB,OAAO,CAAC,cAAc,GAAG,IAAI,CAAC;CAClC;AAED;;;;;;;GAOG;AACH,cAAM,YAAY;IAChB,OAAO,CAAC,QAAQ,CAAC,OAAO,CAA8C;IAE/D,QAAQ,CAAC,KAAK,EAAE,MAAM,EAAE,IAAI,EAAE,qBAAqB,GAAG,IAAI;IAOjE;;MAEE;IACK,aAAa,CAAC,KAAK,EAAE,MAAM,GAAG,SAAS,qBAAqB,EAAE;IAIrE;;MAEE;IACK,MAAM,IAAI,SAAS,MAAM,EAAE;CAGnC;AAED,OAAO,EAAE,qBAAqB,EAAE,YAAY,EAAE,CAAC;AAC/C,YAAY,EAAE,oBAAoB,EAAE,gBAAgB,EAAE,UAAU,EAAE,eAAe,EAAE,cAAc,EAAE,CAAC"}
|
package/dist/scheduled/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
var
|
|
1
|
+
var l=Object.defineProperty;var a=(o,e)=>l(o,"name",{value:e,configurable:!0});const h=a((o,e)=>{o==="warn"?console.warn(e):console.error(e)},"consoleLogger");class d{static{a(this,"AbstractScheduledTask")}getTaskType(){return null}createRunRecorder(){return null}logger(){return h}describeFailure(e){return e instanceof Error?e.message:String(e)}swallowErrors(){return!1}async handle(e,n,r){const c=this.getTaskType(),s=c===null?null:this.createRunRecorder();let t=null;s&&c!==null&&(t=await s.startRun({taskType:c}).catch(()=>(this.logger()("warn",`[${this.constructor.name}] failed to start task run record`),null)));try{const i=await this.handleScheduledTask(e,n,r);s&&t&&await s.succeedRun(t,i??{itemsProcessed:0,itemsFailed:0}).catch(()=>{this.logger()("warn",`[${this.constructor.name}] failed to mark task run succeeded`)})}catch(i){if(this.logger()("error",`[${this.constructor.name}] uncaught error`),s&&t){const u=this.describeFailure(i);await s.failRun(t,u).catch(()=>{this.logger()("warn",`[${this.constructor.name}] failed to mark task run failed`)})}if(!this.swallowErrors())throw i}}async createApplicationRun(e,n){const r=this.createRunRecorder();if(!r)return null;const c=await r.startRun({taskType:e,applicationId:n}),s=a(t=>()=>{this.logger()("warn",`[${this.constructor.name}] failed to mark application run ${t}`)},"warn");return{succeed:a(t=>r.succeedRun(c,t).catch(s("succeeded")).then(()=>{}),"succeed"),fail:a((t,i)=>r.failRun(c,t,i).catch(s("failed")).then(()=>{}),"fail"),skip:a(t=>r.skipRun(c,t).catch(s("skipped")).then(()=>{}),"skip")}}}class g{static{a(this,"TaskRegistry")}byPhase=new Map;register(e,n){const r=this.byPhase.get(e)??[];return r.push(n),this.byPhase.set(e,r),this}tasksForPhase(e){return this.byPhase.get(e)??[]}phases(){return[...this.byPhase.keys()].sort((e,n)=>e-n)}}export{d as AbstractScheduledTask,g as TaskRegistry};
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../src/scheduled/index.ts"],
|
|
4
|
-
"sourcesContent": ["/**\n * The scheduled-task Template Method, and the run-record port it records through.\n *\n * Converged from `apps/background/src/scheduled/{IScheduledTask,TaskRegistry}.ts`\n * in seven repos, where the copies range from 13 lines (CalDAV-Bridge) to 103\n * (Mail-Otter). Mail-Otter's was the one that had solved the defects the others\n * carried, so this is that one.\n *\n * ## What the smaller copies were missing\n *\n * - **Run bookkeeping.** A task that fails silently leaves an operator with a\n * cron that appears to run and never does. `runId` here is the record that\n * says which.\n * - **A failure that is recorded as a failure.** The template's `catch` writes\n * `failRun`, so the task-runs table shows the reason rather than a row that\n * stopped at `running`.\n * - **A test seam.** `createRunRecorder` is a Factory Method so a suite\n * substitutes a double without a D1 binding.\n *\n * ## Why the recorder is a port and not a DAO\n *\n * `runtime` is the DI and platform layer and has no `d1` dependency — that\n * would invert the package graph. The port is four methods; the consumer binds\n * its `BackgroundTaskRunDAO` at the composition root.\n */\n\n/**\nThe summary a task reports when it finishes.\n*/\ninterface TaskRunSummary {\n itemsProcessed: number;\n itemsFailed: number;\n summary?: string;\n details?: unknown;\n}\n\n/**\n * Where run records go.\n *\n * Implemented by each repo's `BackgroundTaskRunDAO`; supplied as a factory so a\n * task can be constructed before the binding is known.\n */\ninterface TaskRunRecorder {\n startRun(fields: { taskType: string; applicationId?: string }): Promise<string>;\n succeedRun(runId: string, result: TaskRunSummary): Promise<void>;\n failRun(runId: string, errorMessage: string, partial?: Partial<TaskRunSummary>): Promise<void>;\n skipRun(runId: string, reason?: string): Promise<void>;\n}\n\n/**\n * A handle to one run's completion.\n *\n * Every method swallows its own recording failure and logs a warning. A task\n * whose work succeeded must not be reported as failed because the bookkeeping\n * write did not land — that is the same class of defect as a status read that\n * writes.\n */\ninterface ApplicationRunHandle {\n succeed(result: TaskRunSummary): Promise<void>;\n fail(errorMessage: string, partial?: Partial<TaskRunSummary>): Promise<void>;\n skip(reason?: string): Promise<void>;\n}\n\n/**\nThe minimum a task needs from `env`: a D1 binding, when the repo has one.\n*/\ninterface ScheduledTaskEnv {\n DB?: unknown;\n}\n\n/**\n * The cron event, structurally.\n *\n * Declared here rather than taken from `@cloudflare/workers-types`: this package\n * stays typecheckable with no platform types installed, the same trade\n * `AbstractEntrypointWorker` makes. A consumer's real `ScheduledController`\n * satisfies it.\n */\ninterface ScheduledControllerLike {\n cron: string;\n scheduledTime: number;\n noRetry(): void;\n}\n\n/**\nThe execution context, structurally. See {@link ScheduledControllerLike}.\n*/\ninterface ExecutionContextLike {\n waitUntil(promise: Promise<unknown>): void;\n passThroughOnException(): void;\n}\n\ntype TaskLogger = (level: 'warn' | 'error', message: string) => void;\n\nconst consoleLogger: TaskLogger = (level, message) => {\n if (level === 'warn') console.warn(message);\n else console.error(message);\n};\n\n/**\n * The base every scheduled task extends.\n *\n * Subclasses implement {@link handleScheduledTask} and, when they want their\n * runs recorded, override {@link getTaskType}.\n */\nabstract class AbstractScheduledTask<TEnv extends ScheduledTaskEnv = ScheduledTaskEnv> {\n /**\n * The task type recorded against each run, or `null` to opt out.\n *\n * Opting **in** rather than out is deliberate: a task that never reports is\n * invisible, and invisibility is the failure mode worth avoiding by default.\n * A per-application task should leave this `null` and use\n * {@link createApplicationRun} instead, so it does not produce a redundant\n * global record beside its per-application ones.\n */\n protected getTaskType(): string | null {\n return null;\n }\n\n /**\n Factory Method for the recorder. Override in tests.\n */\n protected createRunRecorder(): TaskRunRecorder | null {\n return null;\n }\n\n /**\n Override to route this task's failures somewhere other than the console.\n */\n protected logger(): TaskLogger {\n return consoleLogger;\n }\n\n /**\n * Whether `handle` swallows a failure after recording it.\n *\n * `false`, so a failed task **throws** at the platform once its run record\n * says why. The record is the durable evidence, but it is not the caller's\n * answer: a cron Durable Object that catches the rejection is the only party\n * that knows which invocation failed, and swallowing inside the task turned\n * that invocation into a *success* — an operator reading the schedule saw\n * \"completed\" for a task that had failed outright, with the evidence one\n * unrelated screen away.\n *\n * It exists because the opposite is a legitimate deployment choice, not\n * because it is the default: a repo whose platform retries a cron rejection\n * wants the whole batch re-run, and for that a per-task throw is the wrong\n * blast radius. Recording happens either way — the escape hatch changes who\n * learns about the failure, never whether it is remembered.\n */\n protected swallowErrors(): boolean {\n return false;\n }\n\n /**\n * The entry point the platform calls.\n *\n * Owns the try/catch so a task cannot forget it: a scheduled task that throws\n * uncaught is retried by the platform with no record of why. So the record is\n * written **before** the error is re-raised — that ordering is the point of\n * this method, and a subclass that overrides `handle` loses it.\n */\n public async handle(event: ScheduledControllerLike, env: TEnv, ctx: ExecutionContextLike): Promise<void> {\n const taskType = this.getTaskType();\n const recorder = taskType === null ? null : this.createRunRecorder();\n\n let runId: string | null = null;\n if (recorder && taskType !== null) {\n runId = await recorder.startRun({ taskType }).catch((): string | null => {\n // Losing the record must not lose the run: `null` is the absent run\n // id, which the `succeedRun` guard below already treats as \"unrecorded\".\n this.logger()('warn', `[${this.constructor.name}] failed to start task run record`);\n return null;\n });\n }\n\n try {\n const result = await this.handleScheduledTask(event, env, ctx);\n if (recorder && runId) {\n await recorder.succeedRun(runId, result ?? { itemsProcessed: 0, itemsFailed: 0 }).catch(() => {\n this.logger()('warn', `[${this.constructor.name}] failed to mark task run succeeded`);\n });\n }\n } catch (error: unknown) {\n this.logger()('error', `[${this.constructor.name}] uncaught error`);\n if (recorder && runId) {\n const message = error instanceof Error ? error.message : String(error);\n await recorder.failRun(runId, message).catch(() => {\n this.logger()('warn', `[${this.constructor.name}] failed to mark task run failed`);\n });\n }\n // After the record, never before: a rejection that escapes this method\n // must leave a `failed` row behind it, and `failRun` is what writes it.\n if (!this.swallowErrors()) throw error;\n }\n }\n\n /**\n * Open a per-application run record.\n *\n * Call inside a loop over applications, so the operator sees which one failed\n * rather than a single row for the whole cron.\n */\n protected async createApplicationRun(taskType: string, applicationId: string): Promise<ApplicationRunHandle | null> {\n const recorder = this.createRunRecorder();\n if (!recorder) return null;\n const runId = await recorder.startRun({ taskType, applicationId });\n\n const warn = (op: string) => (): void => {\n this.logger()('warn', `[${this.constructor.name}] failed to mark application run ${op}`);\n };\n\n return {\n succeed: (result: TaskRunSummary): Promise<void> =>\n recorder\n .succeedRun(runId, result)\n .catch(warn('succeeded'))\n .then(() => {}),\n fail: (errorMessage: string, partial?: Partial<TaskRunSummary>): Promise<void> =>\n recorder\n .failRun(runId, errorMessage, partial)\n .catch(warn('failed'))\n .then(() => {}),\n skip: (reason?: string): Promise<void> =>\n recorder\n .skipRun(runId, reason)\n .catch(warn('skipped'))\n .then(() => {}),\n };\n }\n\n /**\n * The task's work.\n *\n * Returns a summary to be recorded, or nothing for a task whose runs are not\n * tracked.\n */\n protected abstract handleScheduledTask(\n event: ScheduledControllerLike,\n env: TEnv,\n ctx: ExecutionContextLike,\n ): Promise<TaskRunSummary | void>;\n}\n\n/**\n * The phase registry.\n *\n * Two phases, run in order, each internally parallel. The split is what keeps\n * one slow task from delaying the pruning that has to run behind it — and it is\n * why this is a table rather than a list: adding a task at index 0 cannot\n * silently reclassify every task after it.\n */\nclass TaskRegistry {\n private readonly byPhase = new Map<number, AbstractScheduledTask[]>();\n\n public register(phase: number, task: AbstractScheduledTask): this {\n const existing = this.byPhase.get(phase) ?? [];\n existing.push(task);\n this.byPhase.set(phase, existing);\n return this;\n }\n\n /**\n Every task in a phase, in registration order.\n */\n public tasksForPhase(phase: number): readonly AbstractScheduledTask[] {\n return this.byPhase.get(phase) ?? [];\n }\n\n /**\n The phases that have at least one task, ascending.\n */\n public phases(): readonly number[] {\n return [...this.byPhase.keys()].sort((left, right) => left - right);\n }\n}\n\nexport { AbstractScheduledTask, TaskRegistry };\nexport type { ApplicationRunHandle, ScheduledTaskEnv, TaskLogger, TaskRunRecorder, TaskRunSummary };\n"],
|
|
5
|
-
"mappings": "+EA8FA,MAAMA,EAA4BC,EAAA,CAACC,EAAOC,IAAW,CAC/CD,IAAU,OAAQ,QAAQ,KAAKC,CAAO,EACrC,QAAQ,MAAMA,CAAO,CAC5B,EAHkC,iBAWlC,MAAeC,CAAqB,CAzGpC,MAyGoC,CAAAH,EAAA,8BAUxB,aAAW,CACnB,OAAO,IACT,CAKU,mBAAiB,CACzB,OAAO,IACT,CAKU,QAAM,CACd,OAAOD,CACT,CAmBU,eAAa,CACrB,MAAO,EACT,CAUO,MAAM,
|
|
6
|
-
"names": ["consoleLogger", "__name", "level", "message", "AbstractScheduledTask", "event", "env", "ctx", "taskType", "recorder", "runId", "result", "
|
|
4
|
+
"sourcesContent": ["/**\n * The scheduled-task Template Method, and the run-record port it records through.\n *\n * Converged from `apps/background/src/scheduled/{IScheduledTask,TaskRegistry}.ts`\n * in seven repos, where the copies range from 13 lines (CalDAV-Bridge) to 103\n * (Mail-Otter). Mail-Otter's was the one that had solved the defects the others\n * carried, so this is that one.\n *\n * ## What the smaller copies were missing\n *\n * - **Run bookkeeping.** A task that fails silently leaves an operator with a\n * cron that appears to run and never does. `runId` here is the record that\n * says which.\n * - **A failure that is recorded as a failure.** The template's `catch` writes\n * `failRun`, so the task-runs table shows the reason rather than a row that\n * stopped at `running`.\n * - **A test seam.** `createRunRecorder` is a Factory Method so a suite\n * substitutes a double without a D1 binding.\n *\n * ## Why the recorder is a port and not a DAO\n *\n * `runtime` is the DI and platform layer and has no `d1` dependency — that\n * would invert the package graph. The port is four methods; the consumer binds\n * its `BackgroundTaskRunDAO` at the composition root.\n */\n\n/**\nThe summary a task reports when it finishes.\n*/\ninterface TaskRunSummary {\n itemsProcessed: number;\n itemsFailed: number;\n summary?: string;\n details?: unknown;\n}\n\n/**\n * Where run records go.\n *\n * Implemented by each repo's `BackgroundTaskRunDAO`; supplied as a factory so a\n * task can be constructed before the binding is known.\n */\ninterface TaskRunRecorder {\n startRun(fields: { taskType: string; applicationId?: string }): Promise<string>;\n succeedRun(runId: string, result: TaskRunSummary): Promise<void>;\n failRun(runId: string, errorMessage: string, partial?: Partial<TaskRunSummary>): Promise<void>;\n skipRun(runId: string, reason?: string): Promise<void>;\n}\n\n/**\n * A handle to one run's completion.\n *\n * Every method swallows its own recording failure and logs a warning. A task\n * whose work succeeded must not be reported as failed because the bookkeeping\n * write did not land — that is the same class of defect as a status read that\n * writes.\n */\ninterface ApplicationRunHandle {\n succeed(result: TaskRunSummary): Promise<void>;\n fail(errorMessage: string, partial?: Partial<TaskRunSummary>): Promise<void>;\n skip(reason?: string): Promise<void>;\n}\n\n/**\nThe minimum a task needs from `env`: a D1 binding, when the repo has one.\n*/\ninterface ScheduledTaskEnv {\n DB?: unknown;\n}\n\n/**\n * The cron event, structurally.\n *\n * Declared here rather than taken from `@cloudflare/workers-types`: this package\n * stays typecheckable with no platform types installed, the same trade\n * `AbstractEntrypointWorker` makes. A consumer's real `ScheduledController`\n * satisfies it.\n */\ninterface ScheduledControllerLike {\n cron: string;\n scheduledTime: number;\n noRetry(): void;\n}\n\n/**\nThe execution context, structurally. See {@link ScheduledControllerLike}.\n*/\ninterface ExecutionContextLike {\n waitUntil(promise: Promise<unknown>): void;\n passThroughOnException(): void;\n}\n\ntype TaskLogger = (level: 'warn' | 'error', message: string) => void;\n\nconst consoleLogger: TaskLogger = (level, message) => {\n if (level === 'warn') console.warn(message);\n else console.error(message);\n};\n\n/**\n * The base every scheduled task extends.\n *\n * Subclasses implement {@link handleScheduledTask} and, when they want their\n * runs recorded, override {@link getTaskType}.\n */\nabstract class AbstractScheduledTask<TEnv extends ScheduledTaskEnv = ScheduledTaskEnv> {\n /**\n * The task type recorded against each run, or `null` to opt out.\n *\n * Opting **in** rather than out is deliberate: a task that never reports is\n * invisible, and invisibility is the failure mode worth avoiding by default.\n * A per-application task should leave this `null` and use\n * {@link createApplicationRun} instead, so it does not produce a redundant\n * global record beside its per-application ones.\n */\n protected getTaskType(): string | null {\n return null;\n }\n\n /**\n Factory Method for the recorder. Override in tests.\n */\n protected createRunRecorder(): TaskRunRecorder | null {\n return null;\n }\n\n /**\n Override to route this task's failures somewhere other than the console.\n */\n protected logger(): TaskLogger {\n return consoleLogger;\n }\n\n /**\n * How a caught error becomes the `errorMessage` written to the run record.\n *\n * The default is the error's own message, which is right for a console log and\n * **wrong for a row a user reads back**. Run records are persisted and surfaced\n * through an authenticated route, so a failure whose message carries a token, a\n * bearer header or a signed URL writes credential material into the database and\n * hands it to whoever loads the task-runs screen.\n *\n * A repo with that exposure overrides this and routes the value through its own\n * redactor. The kit cannot do it here: `runtime` is the DI and platform layer\n * with no dependency on the logging packages that carry those redaction rules,\n * and taking one would invert the package graph.\n *\n * There was no seam for this before, so the only options were to accept the\n * unredacted message or to keep a local copy of the whole Template Method — and\n * five of the seven repos the file was converged from have exactly that\n * redactor, so every one of them was carrying a duplicated base class.\n */\n protected describeFailure(error: unknown): string {\n return error instanceof Error ? error.message : String(error);\n }\n\n /**\n * Whether `handle` swallows a failure after recording it.\n *\n * `false`, so a failed task **throws** at the platform once its run record\n * says why. The record is the durable evidence, but it is not the caller's\n * answer: a cron Durable Object that catches the rejection is the only party\n * that knows which invocation failed, and swallowing inside the task turned\n * that invocation into a *success* — an operator reading the schedule saw\n * \"completed\" for a task that had failed outright, with the evidence one\n * unrelated screen away.\n *\n * It exists because the opposite is a legitimate deployment choice, not\n * because it is the default: a repo whose platform retries a cron rejection\n * wants the whole batch re-run, and for that a per-task throw is the wrong\n * blast radius. Recording happens either way — the escape hatch changes who\n * learns about the failure, never whether it is remembered.\n */\n protected swallowErrors(): boolean {\n return false;\n }\n\n /**\n * The entry point the platform calls.\n *\n * Owns the try/catch so a task cannot forget it: a scheduled task that throws\n * uncaught is retried by the platform with no record of why. So the record is\n * written **before** the error is re-raised — that ordering is the point of\n * this method, and a subclass that overrides `handle` loses it.\n */\n public async handle(event: ScheduledControllerLike, env: TEnv, ctx: ExecutionContextLike): Promise<void> {\n const taskType = this.getTaskType();\n const recorder = taskType === null ? null : this.createRunRecorder();\n\n let runId: string | null = null;\n if (recorder && taskType !== null) {\n runId = await recorder.startRun({ taskType }).catch((): string | null => {\n // Losing the record must not lose the run: `null` is the absent run\n // id, which the `succeedRun` guard below already treats as \"unrecorded\".\n this.logger()('warn', `[${this.constructor.name}] failed to start task run record`);\n return null;\n });\n }\n\n try {\n const result = await this.handleScheduledTask(event, env, ctx);\n if (recorder && runId) {\n await recorder.succeedRun(runId, result ?? { itemsProcessed: 0, itemsFailed: 0 }).catch(() => {\n this.logger()('warn', `[${this.constructor.name}] failed to mark task run succeeded`);\n });\n }\n } catch (error: unknown) {\n this.logger()('error', `[${this.constructor.name}] uncaught error`);\n if (recorder && runId) {\n const message = this.describeFailure(error);\n await recorder.failRun(runId, message).catch(() => {\n this.logger()('warn', `[${this.constructor.name}] failed to mark task run failed`);\n });\n }\n // After the record, never before: a rejection that escapes this method\n // must leave a `failed` row behind it, and `failRun` is what writes it.\n if (!this.swallowErrors()) throw error;\n }\n }\n\n /**\n * Open a per-application run record.\n *\n * Call inside a loop over applications, so the operator sees which one failed\n * rather than a single row for the whole cron.\n */\n protected async createApplicationRun(taskType: string, applicationId: string): Promise<ApplicationRunHandle | null> {\n const recorder = this.createRunRecorder();\n if (!recorder) return null;\n const runId = await recorder.startRun({ taskType, applicationId });\n\n const warn = (op: string) => (): void => {\n this.logger()('warn', `[${this.constructor.name}] failed to mark application run ${op}`);\n };\n\n return {\n succeed: (result: TaskRunSummary): Promise<void> =>\n recorder\n .succeedRun(runId, result)\n .catch(warn('succeeded'))\n .then(() => {}),\n fail: (errorMessage: string, partial?: Partial<TaskRunSummary>): Promise<void> =>\n recorder\n .failRun(runId, errorMessage, partial)\n .catch(warn('failed'))\n .then(() => {}),\n skip: (reason?: string): Promise<void> =>\n recorder\n .skipRun(runId, reason)\n .catch(warn('skipped'))\n .then(() => {}),\n };\n }\n\n /**\n * The task's work.\n *\n * Returns a summary to be recorded, or nothing for a task whose runs are not\n * tracked.\n */\n protected abstract handleScheduledTask(\n event: ScheduledControllerLike,\n env: TEnv,\n ctx: ExecutionContextLike,\n ): Promise<TaskRunSummary | void>;\n}\n\n/**\n * The phase registry.\n *\n * Two phases, run in order, each internally parallel. The split is what keeps\n * one slow task from delaying the pruning that has to run behind it — and it is\n * why this is a table rather than a list: adding a task at index 0 cannot\n * silently reclassify every task after it.\n */\nclass TaskRegistry {\n private readonly byPhase = new Map<number, AbstractScheduledTask[]>();\n\n public register(phase: number, task: AbstractScheduledTask): this {\n const existing = this.byPhase.get(phase) ?? [];\n existing.push(task);\n this.byPhase.set(phase, existing);\n return this;\n }\n\n /**\n Every task in a phase, in registration order.\n */\n public tasksForPhase(phase: number): readonly AbstractScheduledTask[] {\n return this.byPhase.get(phase) ?? [];\n }\n\n /**\n The phases that have at least one task, ascending.\n */\n public phases(): readonly number[] {\n return [...this.byPhase.keys()].sort((left, right) => left - right);\n }\n}\n\nexport { AbstractScheduledTask, TaskRegistry };\nexport type { ApplicationRunHandle, ScheduledTaskEnv, TaskLogger, TaskRunRecorder, TaskRunSummary };\n"],
|
|
5
|
+
"mappings": "+EA8FA,MAAMA,EAA4BC,EAAA,CAACC,EAAOC,IAAW,CAC/CD,IAAU,OAAQ,QAAQ,KAAKC,CAAO,EACrC,QAAQ,MAAMA,CAAO,CAC5B,EAHkC,iBAWlC,MAAeC,CAAqB,CAzGpC,MAyGoC,CAAAH,EAAA,8BAUxB,aAAW,CACnB,OAAO,IACT,CA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SAAAD,EAAU,cAAAI,CAAa,CAAE,EAE3DC,EAAOb,EAACc,GAAe,IAAW,CACtC,KAAK,OAAM,EAAG,OAAQ,IAAI,KAAK,YAAY,IAAI,oCAAoCA,CAAE,EAAE,CACzF,EAFa,QAIb,MAAO,CACL,QAASd,EAACW,GACRF,EACG,WAAWC,EAAOC,CAAM,EACxB,MAAME,EAAK,WAAW,CAAC,EACvB,KAAK,IAAK,CAAE,CAAC,EAJT,WAKT,KAAMb,EAAA,CAACe,EAAsBC,IAC3BP,EACG,QAAQC,EAAOK,EAAcC,CAAO,EACpC,MAAMH,EAAK,QAAQ,CAAC,EACpB,KAAK,IAAK,CAAE,CAAC,EAJZ,QAKN,KAAMb,EAACiB,GACLR,EACG,QAAQC,EAAOO,CAAM,EACrB,MAAMJ,EAAK,SAAS,CAAC,EACrB,KAAK,IAAK,CAAE,CAAC,EAJZ,QAMV,EAuBF,MAAMK,CAAY,CAnRlB,MAmRkB,CAAAlB,EAAA,qBACC,QAAU,IAAI,IAExB,SAASmB,EAAeC,EAA2B,CACxD,MAAMC,EAAW,KAAK,QAAQ,IAAIF,CAAK,GAAK,CAAA,EAC5C,OAAAE,EAAS,KAAKD,CAAI,EAClB,KAAK,QAAQ,IAAID,EAAOE,CAAQ,EACzB,IACT,CAKO,cAAcF,EAAa,CAChC,OAAO,KAAK,QAAQ,IAAIA,CAAK,GAAK,CAAA,CACpC,CAKO,QAAM,CACX,MAAO,CAAC,GAAG,KAAK,QAAQ,KAAI,CAAE,EAAE,KAAK,CAACG,EAAMC,IAAUD,EAAOC,CAAK,CACpE",
|
|
6
|
+
"names": ["consoleLogger", "__name", "level", "message", "AbstractScheduledTask", "error", "event", "env", "ctx", "taskType", "recorder", "runId", "result", "applicationId", "warn", "op", "errorMessage", "partial", "reason", "TaskRegistry", "phase", "task", "existing", "left", "right"]
|
|
7
7
|
}
|