@rexezuge/runtime 1.7.1 → 1.8.0

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/index.d.ts CHANGED
@@ -17,8 +17,8 @@ export { AbstractQueueWorker } from './base/AbstractQueueWorker.ts';
17
17
  export { AbstractWorkflowWorker } from './base/AbstractWorkflowWorker.ts';
18
18
  export { BASE_WORKER_MESSAGES } from './base/baseWorkerError.ts';
19
19
  export type { BaseWorkerOperation } from './base/baseWorkerError.ts';
20
- export { createLogger, isLogLevel, resetLogLevelForTests, resolveLogLevel, setLogLevel } from './logger.ts';
21
- export type { LogLevel, Logger } from './logger.ts';
20
+ export { consoleSink, createLogger, isLogLevel, resetLogLevelForTests, resolveLogLevel, setLogLevel } from './logger.ts';
21
+ export type { LogLevel, Logger, LogSink } from './logger.ts';
22
22
  export { COOLDOWN_MS, FAILURE_THRESHOLD, KV_DOMAINS, KV_KEY_VERSION, KV_MAX_KEY_LENGTH, KV_MIN_TTL_SECONDS, KvCache, PURGE_LIST_LIMIT, PURGE_MAX_PAGES, UNMETERED, buildKvKey, clampTtl, digest128, resetBreakerForTests, sanitizeSegment, utf8ByteLength, } from './kv/index.ts';
23
23
  export type { KvDomainDef, KvDomainName, KvDomains, KvNamespaceLike, KvPutOptions, SubrequestMeterLike } from './kv/index.ts';
24
24
  export { AbstractScheduledTask, TaskRegistry } from './scheduled/index.ts';
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAEH,OAAO,EAAE,SAAS,EAAE,MAAM,mBAAmB,CAAC;AAC9C,YAAY,EAAE,OAAO,EAAE,KAAK,EAAE,MAAM,mBAAmB,CAAC;AACxD,OAAO,EAAE,eAAe,EAAE,eAAe,EAAE,kBAAkB,EAAE,eAAe,EAAE,qBAAqB,EAAE,MAAM,sBAAsB,CAAC;AACpI,YAAY,EAAE,aAAa,EAAE,MAA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V,QAAQ,EACR,SAAS,EACT,oBAAoB,EACpB,eAAe,EACf,cAAc,GACf,MAAM,eAAe,CAAC;AACvB,YAAY,EAAE,WAAW,EAAE,YAAY,EAAE,SAAS,EAAE,eAAe,EAAE,YAAY,EAAE,mBAAmB,EAAE,MAAM,eAAe,CAAC;AAC9H,OAAO,EAAE,qBAAqB,EAAE,YAAY,EAAE,MAAM,sBAAsB,CAAC;AAC3E,YAAY,EAAE,oBAAoB,EAAE,gBAAgB,EAAE,UAAU,EAAE,eAAe,EAAE,cAAc,EAAE,MAAM,sBAAsB,CAAC"}
package/dist/index.js CHANGED
@@ -1 +1 @@
1
- import{Container as t}from"./di/Container.js";import{asScopedContext as s,getRequestScope as E,tryGetRequestScope as S,setRequestScope as p,SCOPE_MISSING_MESSAGE as _}from"./di/RequestScope.js";import{AppConfiguration as a}from"./config/AppConfiguration.js";import{EnvParser as m}from"./config/EnvParser.js";import{DEFAULT_SITE_URL as c}from"./config/ConfigurationDefaults.js";import{AbstractEntrypointWorker as T}from"./base/AbstractEntrypointWorker.js";import{AbstractDurableObjectWorker as g}from"./base/AbstractDurableObjectWorker.js";import{AbstractQueueWorker as n}from"./base/AbstractQueueWorker.js";import{AbstractWorkflowWorker as u}from"./base/AbstractWorkflowWorker.js";import{BASE_WORKER_MESSAGES as K}from"./base/baseWorkerError.js";import{createLogger as O,isLogLevel as b,resetLogLevelForTests as k,resolveLogLevel as v,setLogLevel as G}from"./logger.js";import{COOLDOWN_MS as C,FAILURE_THRESHOLD as D,KV_DOMAINS as W,KV_KEY_VERSION as U,KV_MAX_KEY_LENGTH as d,KV_MIN_TTL_SECONDS as y,KvCache as P,PURGE_LIST_LIMIT as V,PURGE_MAX_PAGES as F,UNMETERED as h,buildKvKey as q,clampTtl as B,digest128 as H,resetBreakerForTests as X,sanitizeSegment as Y,utf8ByteLength as j}from"./kv/index.js";import{AbstractScheduledTask as z,TaskRegistry as Q}from"./scheduled/index.js";export{g as AbstractDurableObjectWorker,T as AbstractEntrypointWorker,n as AbstractQueueWorker,z as AbstractScheduledTask,u as AbstractWorkflowWorker,a as AppConfiguration,K as BASE_WORKER_MESSAGES,C as COOLDOWN_MS,t as Container,c as DEFAULT_SITE_URL,m as EnvParser,D as FAILURE_THRESHOLD,W as KV_DOMAINS,U as KV_KEY_VERSION,d as KV_MAX_KEY_LENGTH,y as KV_MIN_TTL_SECONDS,P as KvCache,V as PURGE_LIST_LIMIT,F as PURGE_MAX_PAGES,_ as SCOPE_MISSING_MESSAGE,Q as TaskRegistry,h as UNMETERED,s as asScopedContext,q as buildKvKey,B as clampTtl,O as createLogger,H as digest128,E as getRequestScope,b as isLogLevel,X as resetBreakerForTests,k as resetLogLevelForTests,v as resolveLogLevel,Y as sanitizeSegment,G as setLogLevel,p as setRequestScope,S as tryGetRequestScope,j as utf8ByteLength};
1
+ import{Container as o}from"./di/Container.js";import{asScopedContext as s,getRequestScope as S,tryGetRequestScope as E,setRequestScope as p,SCOPE_MISSING_MESSAGE as _}from"./di/RequestScope.js";import{AppConfiguration as a}from"./config/AppConfiguration.js";import{EnvParser as c}from"./config/EnvParser.js";import{DEFAULT_SITE_URL as A}from"./config/ConfigurationDefaults.js";import{AbstractEntrypointWorker as T}from"./base/AbstractEntrypointWorker.js";import{AbstractDurableObjectWorker as R}from"./base/AbstractDurableObjectWorker.js";import{AbstractQueueWorker as l}from"./base/AbstractQueueWorker.js";import{AbstractWorkflowWorker as u}from"./base/AbstractWorkflowWorker.js";import{BASE_WORKER_MESSAGES as K}from"./base/baseWorkerError.js";import{consoleSink as O,createLogger as k,isLogLevel as b,resetLogLevelForTests as v,resolveLogLevel as G,setLogLevel as N}from"./logger.js";import{COOLDOWN_MS as D,FAILURE_THRESHOLD as W,KV_DOMAINS as U,KV_KEY_VERSION as d,KV_MAX_KEY_LENGTH as y,KV_MIN_TTL_SECONDS as P,KvCache as V,PURGE_LIST_LIMIT as F,PURGE_MAX_PAGES as h,UNMETERED as q,buildKvKey as B,clampTtl as H,digest128 as X,resetBreakerForTests as Y,sanitizeSegment as j,utf8ByteLength as w}from"./kv/index.js";import{AbstractScheduledTask as Q,TaskRegistry as J}from"./scheduled/index.js";export{R as AbstractDurableObjectWorker,T as AbstractEntrypointWorker,l as AbstractQueueWorker,Q as AbstractScheduledTask,u as AbstractWorkflowWorker,a as AppConfiguration,K as BASE_WORKER_MESSAGES,D as COOLDOWN_MS,o as Container,A as DEFAULT_SITE_URL,c as EnvParser,W as FAILURE_THRESHOLD,U as KV_DOMAINS,d as KV_KEY_VERSION,y as KV_MAX_KEY_LENGTH,P as KV_MIN_TTL_SECONDS,V as KvCache,F as PURGE_LIST_LIMIT,h as PURGE_MAX_PAGES,_ as SCOPE_MISSING_MESSAGE,J as TaskRegistry,q as UNMETERED,s as asScopedContext,B as buildKvKey,H as clampTtl,O as consoleSink,k as createLogger,X as digest128,S as getRequestScope,b as isLogLevel,Y as resetBreakerForTests,v as resetLogLevelForTests,G as resolveLogLevel,j as sanitizeSegment,N as setLogLevel,p as setRequestScope,E as tryGetRequestScope,w as utf8ByteLength};
package/dist/index.js.map CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../src/index.ts"],
4
- "sourcesContent": ["/**\n * `@rexezuge/runtime` — the platform foundation layer: DI, configuration,\n * worker bases, logger, KV cache. Zero dependencies (the one platform import\n * is type-only, resolved through each consumer's generated wrangler types).\n */\n\nexport { Container } from './di/Container.ts';\nexport type { Factory, Token } from './di/Container.ts';\nexport { asScopedContext, getRequestScope, tryGetRequestScope, setRequestScope, SCOPE_MISSING_MESSAGE } from './di/RequestScope.ts';\nexport type { ScopedContext } from './di/RequestScope.ts';\nexport { AppConfiguration } from './config/AppConfiguration.ts';\nexport { EnvParser } from './config/EnvParser.ts';\nexport { DEFAULT_SITE_URL } from './config/ConfigurationDefaults.ts';\nexport { AbstractEntrypointWorker } from './base/AbstractEntrypointWorker.ts';\nexport type { WorkerExecutionContext, WorkerScheduledController } from './base/AbstractEntrypointWorker.ts';\nexport { AbstractDurableObjectWorker } from './base/AbstractDurableObjectWorker.ts';\nexport { AbstractQueueWorker } from './base/AbstractQueueWorker.ts';\nexport { AbstractWorkflowWorker } from './base/AbstractWorkflowWorker.ts';\nexport { BASE_WORKER_MESSAGES } from './base/baseWorkerError.ts';\nexport type { BaseWorkerOperation } from './base/baseWorkerError.ts';\nexport { createLogger, isLogLevel, resetLogLevelForTests, resolveLogLevel, setLogLevel } from './logger.ts';\nexport type { LogLevel, Logger } from './logger.ts';\nexport {\n COOLDOWN_MS,\n FAILURE_THRESHOLD,\n KV_DOMAINS,\n KV_KEY_VERSION,\n KV_MAX_KEY_LENGTH,\n KV_MIN_TTL_SECONDS,\n KvCache,\n PURGE_LIST_LIMIT,\n PURGE_MAX_PAGES,\n UNMETERED,\n buildKvKey,\n clampTtl,\n digest128,\n resetBreakerForTests,\n sanitizeSegment,\n utf8ByteLength,\n} from './kv/index.ts';\nexport type { KvDomainDef, KvDomainName, KvDomains, KvNamespaceLike, KvPutOptions, SubrequestMeterLike } from './kv/index.ts';\nexport { AbstractScheduledTask, TaskRegistry } from './scheduled/index.ts';\nexport type { ApplicationRunHandle, ScheduledTaskEnv, TaskLogger, TaskRunRecorder, TaskRunSummary } from './scheduled/index.ts';\n"],
5
- "mappings": "AAMA,OAAS,aAAAA,MAAiB,oBAE1B,OAAS,mBAAAC,EAAiB,mBAAAC,EAAiB,sBAAAC,EAAoB,mBAAAC,EAAiB,yBAAAC,MAA6B,uBAE7G,OAAS,oBAAAC,MAAwB,+BACjC,OAAS,aAAAC,MAAiB,wBAC1B,OAAS,oBAAAC,MAAwB,oCACjC,OAAS,4BAAAC,MAAgC,qCAEzC,OAAS,+BAAAC,MAAmC,wCAC5C,OAAS,uBAAAC,MAA2B,gCACpC,OAAS,0BAAAC,MAA8B,mCACvC,OAAS,wBAAAC,MAA4B,4BAErC,OAAS,gBAAAC,EAAc,cAAAC,EAAY,yBAAAC,EAAuB,mBAAAC,EAAiB,eAAAC,MAAmB,cAE9F,OACE,eAAAC,EACA,qBAAAC,EACA,cAAAC,EACA,kBAAAC,EACA,qBAAAC,EACA,sBAAAC,EACA,WAAAC,EACA,oBAAAC,EACA,mBAAAC,EACA,aAAAC,EACA,cAAAC,EACA,YAAAC,EACA,aAAAC,EACA,wBAAAC,EACA,mBAAAC,EACA,kBAAAC,MACK,gBAEP,OAAS,yBAAAC,EAAuB,gBAAAC,MAAoB",
6
- "names": ["Container", "asScopedContext", "getRequestScope", "tryGetRequestScope", "setRequestScope", "SCOPE_MISSING_MESSAGE", "AppConfiguration", "EnvParser", "DEFAULT_SITE_URL", "AbstractEntrypointWorker", "AbstractDurableObjectWorker", "AbstractQueueWorker", "AbstractWorkflowWorker", "BASE_WORKER_MESSAGES", "createLogger", "isLogLevel", "resetLogLevelForTests", "resolveLogLevel", "setLogLevel", "COOLDOWN_MS", "FAILURE_THRESHOLD", "KV_DOMAINS", "KV_KEY_VERSION", "KV_MAX_KEY_LENGTH", "KV_MIN_TTL_SECONDS", "KvCache", "PURGE_LIST_LIMIT", "PURGE_MAX_PAGES", "UNMETERED", "buildKvKey", "clampTtl", "digest128", "resetBreakerForTests", "sanitizeSegment", "utf8ByteLength", "AbstractScheduledTask", "TaskRegistry"]
4
+ "sourcesContent": ["/**\n * `@rexezuge/runtime` — the platform foundation layer: DI, configuration,\n * worker bases, logger, KV cache. Zero dependencies (the one platform import\n * is type-only, resolved through each consumer's generated wrangler types).\n */\n\nexport { Container } from './di/Container.ts';\nexport type { Factory, Token } from './di/Container.ts';\nexport { asScopedContext, getRequestScope, tryGetRequestScope, setRequestScope, SCOPE_MISSING_MESSAGE } from './di/RequestScope.ts';\nexport type { ScopedContext } from './di/RequestScope.ts';\nexport { AppConfiguration } from './config/AppConfiguration.ts';\nexport { EnvParser } from './config/EnvParser.ts';\nexport { DEFAULT_SITE_URL } from './config/ConfigurationDefaults.ts';\nexport { AbstractEntrypointWorker } from './base/AbstractEntrypointWorker.ts';\nexport type { WorkerExecutionContext, WorkerScheduledController } from './base/AbstractEntrypointWorker.ts';\nexport { AbstractDurableObjectWorker } from './base/AbstractDurableObjectWorker.ts';\nexport { AbstractQueueWorker } from './base/AbstractQueueWorker.ts';\nexport { AbstractWorkflowWorker } from './base/AbstractWorkflowWorker.ts';\nexport { BASE_WORKER_MESSAGES } from './base/baseWorkerError.ts';\nexport type { BaseWorkerOperation } from './base/baseWorkerError.ts';\nexport { consoleSink, createLogger, isLogLevel, resetLogLevelForTests, resolveLogLevel, setLogLevel } from './logger.ts';\nexport type { LogLevel, Logger, LogSink } from './logger.ts';\nexport {\n COOLDOWN_MS,\n FAILURE_THRESHOLD,\n KV_DOMAINS,\n KV_KEY_VERSION,\n KV_MAX_KEY_LENGTH,\n KV_MIN_TTL_SECONDS,\n KvCache,\n PURGE_LIST_LIMIT,\n PURGE_MAX_PAGES,\n UNMETERED,\n buildKvKey,\n clampTtl,\n digest128,\n resetBreakerForTests,\n sanitizeSegment,\n utf8ByteLength,\n} from './kv/index.ts';\nexport type { KvDomainDef, KvDomainName, KvDomains, KvNamespaceLike, KvPutOptions, SubrequestMeterLike } from './kv/index.ts';\nexport { AbstractScheduledTask, TaskRegistry } from './scheduled/index.ts';\nexport type { ApplicationRunHandle, ScheduledTaskEnv, TaskLogger, TaskRunRecorder, TaskRunSummary } from './scheduled/index.ts';\n"],
5
+ "mappings": "AAMA,OAAS,aAAAA,MAAiB,oBAE1B,OAAS,mBAAAC,EAAiB,mBAAAC,EAAiB,sBAAAC,EAAoB,mBAAAC,EAAiB,yBAAAC,MAA6B,uBAE7G,OAAS,oBAAAC,MAAwB,+BACjC,OAAS,aAAAC,MAAiB,wBAC1B,OAAS,oBAAAC,MAAwB,oCACjC,OAAS,4BAAAC,MAAgC,qCAEzC,OAAS,+BAAAC,MAAmC,wCAC5C,OAAS,uBAAAC,MAA2B,gCACpC,OAAS,0BAAAC,MAA8B,mCACvC,OAAS,wBAAAC,MAA4B,4BAErC,OAAS,eAAAC,EAAa,gBAAAC,EAAc,cAAAC,EAAY,yBAAAC,EAAuB,mBAAAC,EAAiB,eAAAC,MAAmB,cAE3G,OACE,eAAAC,EACA,qBAAAC,EACA,cAAAC,EACA,kBAAAC,EACA,qBAAAC,EACA,sBAAAC,EACA,WAAAC,EACA,oBAAAC,EACA,mBAAAC,EACA,aAAAC,EACA,cAAAC,EACA,YAAAC,EACA,aAAAC,EACA,wBAAAC,EACA,mBAAAC,EACA,kBAAAC,MACK,gBAEP,OAAS,yBAAAC,EAAuB,gBAAAC,MAAoB",
6
+ "names": ["Container", "asScopedContext", "getRequestScope", "tryGetRequestScope", "setRequestScope", "SCOPE_MISSING_MESSAGE", "AppConfiguration", "EnvParser", "DEFAULT_SITE_URL", "AbstractEntrypointWorker", "AbstractDurableObjectWorker", "AbstractQueueWorker", "AbstractWorkflowWorker", "BASE_WORKER_MESSAGES", "consoleSink", "createLogger", "isLogLevel", "resetLogLevelForTests", "resolveLogLevel", "setLogLevel", "COOLDOWN_MS", "FAILURE_THRESHOLD", "KV_DOMAINS", "KV_KEY_VERSION", "KV_MAX_KEY_LENGTH", "KV_MIN_TTL_SECONDS", "KvCache", "PURGE_LIST_LIMIT", "PURGE_MAX_PAGES", "UNMETERED", "buildKvKey", "clampTtl", "digest128", "resetBreakerForTests", "sanitizeSegment", "utf8ByteLength", "AbstractScheduledTask", "TaskRegistry"]
7
7
  }
package/dist/logger.d.ts CHANGED
@@ -49,7 +49,41 @@ interface Logger {
49
49
  warn(...args: unknown[]): void;
50
50
  error(...args: unknown[]): void;
51
51
  }
52
- declare function createLogger(namespace?: string, fullRepoName?: string, env?: unknown): Logger;
53
- export { createLogger, isLogLevel, resetLogLevelForTests, resolveLogLevel, setLogLevel };
54
- export type { LogLevel, Logger };
52
+ /**
53
+ * Where a formatted emit goes.
54
+ *
55
+ * A **port, not a policy**: the kit owns the level decision, the namespace
56
+ * prefix and the argument list, and the consumer owns what happens to the bytes.
57
+ * The gap this fills is redaction. A consumer whose surfaces handle AWS
58
+ * `SecretAccessKey`s, session tokens and HMAC secrets cannot let an arbitrary
59
+ * object reach `console.*` — and the defence that actually holds is applied at
60
+ * the sink, because a check at each call site is a hundred chances to forget
61
+ * one. Without a seam, that consumer has to reimplement the logger itself
62
+ * (level resolution included) or ship its secrets to the log tail.
63
+ *
64
+ * A deny-list is consumer policy and deliberately not here: the key names that
65
+ * mean "secret" are a property of the consumer's data model, and the kit
66
+ * redaction-guessing across nine repos' vocabularies would redact diagnostic
67
+ * fields and train everyone to ignore the markers.
68
+ *
69
+ * The sink receives the level **and the namespace prefix already applied**, so a
70
+ * consumer that forwards to an aggregator does not have to reconstruct either.
71
+ */
72
+ interface LogSink {
73
+ (level: LogLevel, message: string, args: readonly unknown[]): void;
74
+ }
75
+ /**
76
+ * The default sink: today's behaviour, verbatim.
77
+ *
78
+ * Named rather than inlined so {@link createLogger}'s signature stays a plain
79
+ * optional argument and a consumer can wrap it — `createLogger(ns, repo, env,
80
+ * redactingSink(consoleSink))` — without reimplementing the level check.
81
+ */
82
+ declare function consoleSink(level: LogLevel, message: string, args: readonly unknown[]): void;
83
+ /**
84
+ * @param sink Where each accepted emit goes. Defaults to {@link consoleSink}.
85
+ */
86
+ declare function createLogger(namespace?: string, fullRepoName?: string, env?: unknown, sink?: LogSink): Logger;
87
+ export { consoleSink, createLogger, isLogLevel, resetLogLevelForTests, resolveLogLevel, setLogLevel };
88
+ export type { LogLevel, Logger, LogSink };
55
89
  //# sourceMappingURL=logger.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"logger.d.ts","sourceRoot":"","sources":["../src/logger.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;GAwBG;AACH,KAAK,QAAQ,GAAG,OAAO,GAAG,MAAM,GAAG,MAAM,GAAG,OAAO,CAAC;AASpD,iBAAS,UAAU,CAAC,KAAK,EAAE,MAAM,GAAG,KAAK,IAAI,QAAQ,CAEpD;AAWD,iBAAS,eAAe,CAAC,GAAG,CAAC,EAAE,OAAO,GAAG,QA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EAAE,OAAO,EAAE,GAAG,IAAI,CAAC;IAChC,IAAI,CAAC,GAAG,IAAI,EAAE,OAAO,EAAE,GAAG,IAAI,CAAC;IAC/B,IAAI,CAAC,GAAG,IAAI,EAAE,OAAO,EAAE,GAAG,IAAI,CAAC;IAC/B,KAAK,CAAC,GAAG,IAAI,EAAE,OAAO,EAAE,GAAG,IAAI,CAAC;CACjC;AAED;;;;;;;;;;;;;;;;;;;GAmBG;AACH,UAAU,OAAO;IACf,CAAC,KAAK,EAAE,QAAQ,EAAE,OAAO,EAAE,MAAM,EAAE,IAAI,EAAE,SAAS,OAAO,EAAE,GAAG,IAAI,CAAC;CACpE;AAED;;;;;;GAMG;AACH,iBAAS,WAAW,CAAC,KAAK,EAAE,QAAQ,EAAE,OAAO,EAAE,MAAM,EAAE,IAAI,EAAE,SAAS,OAAO,EAAE,GAAG,IAAI,CAmBrF;AAED;;GAEG;AACH,iBAAS,YAAY,CAAC,SAAS,CAAC,EAAE,MAAM,EAAE,YAAY,CAAC,EAAE,MAAM,EAAE,GAAG,CAAC,EAAE,OAAO,EAAE,IAAI,GAAE,OAAqB,GAAG,MAAM,CAyBnH;AAED,OAAO,EAAE,WAAW,EAAE,YAAY,EAAE,UAAU,EAAE,qBAAqB,EAAE,eAAe,EAAE,WAAW,EAAE,CAAC;AACtG,YAAY,EAAE,QAAQ,EAAE,MAAM,EAAE,OAAO,EAAE,CAAC"}
package/dist/logger.js CHANGED
@@ -1 +1 @@
1
- var u=Object.defineProperty;var n=(e,t)=>u(e,"name",{value:t,configurable:!0});const L={debug:0,info:1,warn:2,error:3};function s(e){return["debug","info","warn","error"].includes(e)}n(s,"isLogLevel");let c;function l(e){const t=e!==null&&typeof e=="object"?e.LOG_LEVEL:void 0,f=globalThis.process?.env?.LOG_LEVEL,r=t??f??c??"info";return s(r)?r:"info"}n(l,"resolveLogLevel");function d(e){c=typeof e=="string"&&s(e)?e:void 0}n(d,"setLogLevel");function g(){c=void 0}n(g,"resetLogLevelForTests");function a(e,t,f){const r=[t,e].filter(Boolean).map(o=>`[${o}]`).join(" "),i=n(o=>L[o]>=L[l(f)],"enabled");return{debug:n((...o)=>{i("debug")&&console.debug(`[DEBUG] ${r}`,...o)},"debug"),info:n((...o)=>{i("info")&&console.info(`[INFO] ${r}`,...o)},"info"),warn:n((...o)=>{i("warn")&&console.warn(`[WARN] ${r}`,...o)},"warn"),error:n((...o)=>{i("error")&&console.error(`[ERROR] ${r}`,...o)},"error")}}n(a,"createLogger");export{a as createLogger,s as isLogLevel,g as resetLogLevelForTests,l as resolveLogLevel,d as setLogLevel};
1
+ var d=Object.defineProperty;var n=(e,i)=>d(e,"name",{value:i,configurable:!0});const l={debug:0,info:1,warn:2,error:3};function s(e){return["debug","info","warn","error"].includes(e)}n(s,"isLogLevel");let u;function L(e){const i=e!==null&&typeof e=="object"?e.LOG_LEVEL:void 0,t=globalThis.process?.env?.LOG_LEVEL,o=i??t??u??"info";return s(o)?o:"info"}n(L,"resolveLogLevel");function g(e){u=typeof e=="string"&&s(e)?e:void 0}n(g,"setLogLevel");function b(){u=void 0}n(b,"resetLogLevelForTests");function a(e,i,t){const o=`[${e.toUpperCase()}] ${i}`;switch(e){case"debug":{console.debug(o,...t);break}case"error":{console.error(o,...t);break}case"warn":{console.warn(o,...t);break}default:console.info(o,...t)}}n(a,"consoleSink");function w(e,i,t,o=a){const c=[i,e].filter(Boolean).map(r=>`[${r}]`).join(" "),f=n(r=>l[r]>=l[L(t)],"enabled");return{debug:n((...r)=>{f("debug")&&o("debug",c,r)},"debug"),info:n((...r)=>{f("info")&&o("info",c,r)},"info"),warn:n((...r)=>{f("warn")&&o("warn",c,r)},"warn"),error:n((...r)=>{f("error")&&o("error",c,r)},"error")}}n(w,"createLogger");export{a as consoleSink,w as createLogger,s as isLogLevel,b as resetLogLevelForTests,L as resolveLogLevel,g as setLogLevel};
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../src/logger.ts"],
4
- "sourcesContent": ["/**\n * `KvLogger` — the family's console logger with a level floor.\n *\n * Converged from `backend-runtime/src/logger.ts`, which is identical in\n * Durable-DAV, Durable-DAV-Router, Edge-Sonic, Mail-Otter and Mail-Meow (the\n * copies in AWS/ChordDHT's `shared` are the same shape without the env floor).\n *\n * The level resolves from an injected `env` first, then `process.env`, then\n * anything {@link setLogLevel} installed, then `info`: Workers have no\n * `process.env` at runtime, so an injected object is the configuration path,\n * and `process.env` is a local-tooling affordance. An unrecognized level floors\n * at `info` rather than throwing — a typo in `LOG_LEVEL` costing a worker a\n * cold start is not a trade worth making.\n *\n * ### The level is read per emit, not per construction\n *\n * Both loggers a repo holds at module scope — one in this file's `KvCache`, one\n * in its KV facade — are constructed when the isolate starts, long before any\n * request scope exists to hand them an `env`. Resolving the level in the\n * constructor therefore meant a module-scope logger could *only ever* read\n * `process.env`, which workerd does not have: `LOG_LEVEL=debug` shipped,\n * validated by nothing, and was inert. `setLogLevel` is the seam that closes\n * that, and every emit re-reads so an already-constructed logger picks the level\n * up without being rebuilt.\n */\ntype LogLevel = 'debug' | 'info' | 'warn' | 'error';\n\nconst LOG_LEVELS: Record<LogLevel, number> = {\n debug: 0,\n info: 1,\n warn: 2,\n error: 3,\n} as const;\n\nfunction isLogLevel(level: string): level is LogLevel {\n return (['debug', 'info', 'warn', 'error'] as const).includes(level as LogLevel);\n}\n\n/**\n * What {@link setLogLevel} installed, or `undefined` when nothing has.\n *\n * Module-level rather than per-logger because the emit path must not depend on\n * which logger asks: a logger built before the scope existed and a logger built\n * after it have to answer the same question identically.\n */\nlet installedLogLevel: LogLevel | undefined;\n\nfunction resolveLogLevel(env?: unknown): LogLevel {\n const fromInjected = env !== null && typeof env === 'object' ? (env as Record<string, string | undefined>)['LOG_LEVEL'] : undefined;\n const fromEnv = (globalThis as { process?: { env?: Record<string, string | undefined> } }).process?.env?.LOG_LEVEL;\n const level = fromInjected ?? fromEnv ?? installedLogLevel ?? 'info';\n return isLogLevel(level) ? level : 'info';\n}\n\n/**\n * Install the level every logger falls back to, for the rest of the isolate.\n *\n * The third source in {@link resolveLogLevel}'s chain, and below both an\n * injected `env` and `process.env` on purpose: an explicit request scope\n * outranks a process-wide default, and a developer's local shell outranks both.\n * Only what neither can answer falls through to this.\n *\n * A composition root calls it once, with the level its config resolved to.\n * Unrecognized input clears the installation rather than throwing — the same\n * \"a typo costs a cold start\" trade as everywhere else in this file.\n */\nfunction setLogLevel(level: string | undefined): void {\n installedLogLevel = typeof level === 'string' && isLogLevel(level) ? level : undefined;\n}\n\n/**\n * Test seam: forget whatever {@link setLogLevel} installed.\n */\nfunction resetLogLevelForTests(): void {\n installedLogLevel = undefined;\n}\n\ninterface Logger {\n debug(...args: unknown[]): void;\n info(...args: unknown[]): void;\n warn(...args: unknown[]): void;\n error(...args: unknown[]): void;\n}\n\nfunction createLogger(namespace?: string, fullRepoName?: string, env?: unknown): Logger {\n const argsStr = [fullRepoName, namespace]\n .filter(Boolean)\n .map((s) => `[${s}]`)\n .join(' ');\n\n // `enabled` is called per emit rather than compared against a level captured\n // at construction, for the reason in the header: these loggers are built at\n // module scope and the level that answers is not known until a scope runs.\n const enabled = (level: LogLevel): boolean => LOG_LEVELS[level] >= LOG_LEVELS[resolveLogLevel(env)];\n\n return {\n debug: (...args: unknown[]): void => {\n if (enabled('debug')) {\n console.debug(`[DEBUG] ${argsStr}`, ...args);\n }\n },\n info: (...args: unknown[]): void => {\n if (enabled('info')) {\n console.info(`[INFO] ${argsStr}`, ...args);\n }\n },\n warn: (...args: unknown[]): void => {\n if (enabled('warn')) {\n console.warn(`[WARN] ${argsStr}`, ...args);\n }\n },\n error: (...args: unknown[]): void => {\n if (enabled('error')) {\n console.error(`[ERROR] ${argsStr}`, ...args);\n }\n },\n };\n}\n\nexport { createLogger, isLogLevel, resetLogLevelForTests, resolveLogLevel, setLogLevel };\nexport type { LogLevel, Logger };\n"],
5
- "mappings": "+EA2BA,MAAMA,EAAuC,CAC3C,MAAO,EACP,KAAM,EACN,KAAM,EACN,M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AQ,MAAM,WAAWF,CAAO,GAAI,GAAGG,CAAI,CAE/C,EAJO,SAMX,CAjCSd,EAAAQ,EAAA",
6
- "names": ["LOG_LEVELS", "isLogLevel", "level", "__name", "installedLogLevel", "resolveLogLevel", "env", "fromInjected", "fromEnv", "setLogLevel", "resetLogLevelForTests", "createLogger", "namespace", "fullRepoName", "argsStr", "s", "enabled", "args"]
4
+ "sourcesContent": ["/**\n * `KvLogger` — the family's console logger with a level floor.\n *\n * Converged from `backend-runtime/src/logger.ts`, which is identical in\n * Durable-DAV, Durable-DAV-Router, Edge-Sonic, Mail-Otter and Mail-Meow (the\n * copies in AWS/ChordDHT's `shared` are the same shape without the env floor).\n *\n * The level resolves from an injected `env` first, then `process.env`, then\n * anything {@link setLogLevel} installed, then `info`: Workers have no\n * `process.env` at runtime, so an injected object is the configuration path,\n * and `process.env` is a local-tooling affordance. An unrecognized level floors\n * at `info` rather than throwing — a typo in `LOG_LEVEL` costing a worker a\n * cold start is not a trade worth making.\n *\n * ### The level is read per emit, not per construction\n *\n * Both loggers a repo holds at module scope — one in this file's `KvCache`, one\n * in its KV facade — are constructed when the isolate starts, long before any\n * request scope exists to hand them an `env`. Resolving the level in the\n * constructor therefore meant a module-scope logger could *only ever* read\n * `process.env`, which workerd does not have: `LOG_LEVEL=debug` shipped,\n * validated by nothing, and was inert. `setLogLevel` is the seam that closes\n * that, and every emit re-reads so an already-constructed logger picks the level\n * up without being rebuilt.\n */\ntype LogLevel = 'debug' | 'info' | 'warn' | 'error';\n\nconst LOG_LEVELS: Record<LogLevel, number> = {\n debug: 0,\n info: 1,\n warn: 2,\n error: 3,\n} as const;\n\nfunction isLogLevel(level: string): level is LogLevel {\n return (['debug', 'info', 'warn', 'error'] as const).includes(level as LogLevel);\n}\n\n/**\n * What {@link setLogLevel} installed, or `undefined` when nothing has.\n *\n * Module-level rather than per-logger because the emit path must not depend on\n * which logger asks: a logger built before the scope existed and a logger built\n * after it have to answer the same question identically.\n */\nlet installedLogLevel: LogLevel | undefined;\n\nfunction resolveLogLevel(env?: unknown): LogLevel {\n const fromInjected = env !== null && typeof env === 'object' ? (env as Record<string, string | undefined>)['LOG_LEVEL'] : undefined;\n const fromEnv = (globalThis as { process?: { env?: Record<string, string | undefined> } }).process?.env?.LOG_LEVEL;\n const level = fromInjected ?? fromEnv ?? installedLogLevel ?? 'info';\n return isLogLevel(level) ? level : 'info';\n}\n\n/**\n * Install the level every logger falls back to, for the rest of the isolate.\n *\n * The third source in {@link resolveLogLevel}'s chain, and below both an\n * injected `env` and `process.env` on purpose: an explicit request scope\n * outranks a process-wide default, and a developer's local shell outranks both.\n * Only what neither can answer falls through to this.\n *\n * A composition root calls it once, with the level its config resolved to.\n * Unrecognized input clears the installation rather than throwing — the same\n * \"a typo costs a cold start\" trade as everywhere else in this file.\n */\nfunction setLogLevel(level: string | undefined): void {\n installedLogLevel = typeof level === 'string' && isLogLevel(level) ? level : undefined;\n}\n\n/**\n * Test seam: forget whatever {@link setLogLevel} installed.\n */\nfunction resetLogLevelForTests(): void {\n installedLogLevel = undefined;\n}\n\ninterface Logger {\n debug(...args: unknown[]): void;\n info(...args: unknown[]): void;\n warn(...args: unknown[]): void;\n error(...args: unknown[]): void;\n}\n\n/**\n * Where a formatted emit goes.\n *\n * A **port, not a policy**: the kit owns the level decision, the namespace\n * prefix and the argument list, and the consumer owns what happens to the bytes.\n * The gap this fills is redaction. A consumer whose surfaces handle AWS\n * `SecretAccessKey`s, session tokens and HMAC secrets cannot let an arbitrary\n * object reach `console.*` — and the defence that actually holds is applied at\n * the sink, because a check at each call site is a hundred chances to forget\n * one. Without a seam, that consumer has to reimplement the logger itself\n * (level resolution included) or ship its secrets to the log tail.\n *\n * A deny-list is consumer policy and deliberately not here: the key names that\n * mean \"secret\" are a property of the consumer's data model, and the kit\n * redaction-guessing across nine repos' vocabularies would redact diagnostic\n * fields and train everyone to ignore the markers.\n *\n * The sink receives the level **and the namespace prefix already applied**, so a\n * consumer that forwards to an aggregator does not have to reconstruct either.\n */\ninterface LogSink {\n (level: LogLevel, message: string, args: readonly unknown[]): void;\n}\n\n/**\n * The default sink: today's behaviour, verbatim.\n *\n * Named rather than inlined so {@link createLogger}'s signature stays a plain\n * optional argument and a consumer can wrap it — `createLogger(ns, repo, env,\n * redactingSink(consoleSink))` — without reimplementing the level check.\n */\nfunction consoleSink(level: LogLevel, message: string, args: readonly unknown[]): void {\n const line = `[${level.toUpperCase()}] ${message}`;\n switch (level) {\n case 'debug': {\n console.debug(line, ...args);\n break;\n }\n case 'error': {\n console.error(line, ...args);\n break;\n }\n case 'warn': {\n console.warn(line, ...args);\n break;\n }\n default: {\n console.info(line, ...args);\n }\n }\n}\n\n/**\n * @param sink Where each accepted emit goes. Defaults to {@link consoleSink}.\n */\nfunction createLogger(namespace?: string, fullRepoName?: string, env?: unknown, sink: LogSink = consoleSink): Logger {\n const argsStr = [fullRepoName, namespace]\n .filter(Boolean)\n .map((s) => `[${s}]`)\n .join(' ');\n\n // `enabled` is called per emit rather than compared against a level captured\n // at construction, for the reason in the header: these loggers are built at\n // module scope and the level that answers is not known until a scope runs.\n const enabled = (level: LogLevel): boolean => LOG_LEVELS[level] >= LOG_LEVELS[resolveLogLevel(env)];\n\n return {\n debug: (...args: unknown[]): void => {\n if (enabled('debug')) sink('debug', argsStr, args);\n },\n info: (...args: unknown[]): void => {\n if (enabled('info')) sink('info', argsStr, args);\n },\n warn: (...args: unknown[]): void => {\n if (enabled('warn')) sink('warn', argsStr, args);\n },\n error: (...args: unknown[]): void => {\n if (enabled('error')) sink('error', argsStr, args);\n },\n };\n}\n\nexport { consoleSink, createLogger, isLogLevel, resetLogLevelForTests, resolveLogLevel, setLogLevel };\nexport type { LogLevel, Logger, LogSink };\n"],
5
+ "mappings": "+EA2BA,MAAMA,EAAuC,CAC3C,MAAO,EACP,KAAM,EACN,KAAM,EACN,MAAO,GAGT,SAASC,EAAWC,EAAa,CAC/B,MAAQ,CAAC,QAAS,OAAQ,OAAQ,OAAO,EAAY,SAASA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CACnD,EAFO,SAGP,KAAMV,EAAA,IAAIU,IAAyB,CAC7BQ,EAAQ,MAAM,GAAGH,EAAK,OAAQC,EAASN,CAAI,CACjD,EAFM,QAGN,KAAMV,EAAA,IAAIU,IAAyB,CAC7BQ,EAAQ,MAAM,GAAGH,EAAK,OAAQC,EAASN,CAAI,CACjD,EAFM,QAGN,MAAOV,EAAA,IAAIU,IAAyB,CAC9BQ,EAAQ,OAAO,GAAGH,EAAK,QAASC,EAASN,CAAI,CACnD,EAFO,SAIX,CAzBSV,EAAAY,EAAA",
6
+ "names": ["LOG_LEVELS", "isLogLevel", "level", "__name", "installedLogLevel", "resolveLogLevel", "env", "fromInjected", "fromEnv", "setLogLevel", "resetLogLevelForTests", "consoleSink", "message", "args", "line", "createLogger", "namespace", "fullRepoName", "sink", "argsStr", "s", "enabled"]
7
7
  }
@@ -112,11 +112,31 @@ 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
+ * Whether `handle` swallows a failure after recording it.
117
+ *
118
+ * `false`, so a failed task **throws** at the platform once its run record
119
+ * says why. The record is the durable evidence, but it is not the caller's
120
+ * answer: a cron Durable Object that catches the rejection is the only party
121
+ * that knows which invocation failed, and swallowing inside the task turned
122
+ * that invocation into a *success* — an operator reading the schedule saw
123
+ * "completed" for a task that had failed outright, with the evidence one
124
+ * unrelated screen away.
125
+ *
126
+ * It exists because the opposite is a legitimate deployment choice, not
127
+ * because it is the default: a repo whose platform retries a cron rejection
128
+ * wants the whole batch re-run, and for that a per-task throw is the wrong
129
+ * blast radius. Recording happens either way — the escape hatch changes who
130
+ * learns about the failure, never whether it is remembered.
131
+ */
132
+ protected swallowErrors(): boolean;
115
133
  /**
116
134
  * The entry point the platform calls.
117
135
  *
118
136
  * Owns the try/catch so a task cannot forget it: a scheduled task that throws
119
- * uncaught is retried by the platform with no record of why.
137
+ * uncaught is retried by the platform with no record of why. So the record is
138
+ * written **before** the error is re-raised — that ordering is the point of
139
+ * this method, and a subclass that overrides `handle` loses it.
120
140
  */
121
141
  handle(event: ScheduledControllerLike, env: TEnv, ctx: ExecutionContextLike): Promise<void>;
122
142
  /**
@@ -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,EAAE,MAAM,CAAC;IACjB,OAAO,CAAC,EAAE,OAAO,CAAC;CACnB;AAED;;;;;GAKG;AACH,UAAU,eAAe;IACvB,QAAQ,CAAC,MAAM,EAAE;QAAE,QAAQ,EAAE,MAAM,CAAC;QAAC,aAAa,CAAC,EAAE,MAAM,CAAA;KAAE,GAAG,OAAO,CAAC,MAAM,CAAC,CAAC;IAChF,UAAU,CAAC,KAAK,EAAE,MAAM,EAAE,MAAM,EAAE,cAAc,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;IACjE,OAAO,CAAC,KAAK,EAAE,MAAM,EAAE,YAAY,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,OAAO,CAAC,cAAc,CAAC,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;IAC/F,OAAO,CAAC,KAAK,EAAE,MAAM,EAAE,MAAM,CAAC,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;CACxD;AAED;;;;;;;GAOG;AACH,UAAU,oBAAoB;IAC5B,OAAO,CAAC,MAAM,EAAE,cAAc,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;IAC/C,IAAI,CAAC,YAAY,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,OAAO,CAAC,cAAc,CAAC,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;IAC7E,IAAI,CAAC,MAAM,C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OAKG;cACa,oBAAoB,CAAC,QAAQ,EAAE,MAAM,EAAE,aAAa,EAAE,MAAM,GAAG,OAAO,CAAC,oBAAoB,GAAG,IAAI,CAAC;IA4BnH;;;;;OAKG;IACH,SAAS,CAAC,QAAQ,CAAC,mBAAmB,CACpC,KAAK,EAAE,uBAAuB,EAC9B,GAAG,EAAE,IAAI,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"}
@@ -1 +1 @@
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}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=i instanceof Error?i.message:String(i);await s.failRun(t,u).catch(()=>{this.logger()("warn",`[${this.constructor.name}] failed to mark task run failed`)})}}}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
+ var u=Object.defineProperty;var n=(i,e)=>u(i,"name",{value:e,configurable:!0});const h=n((i,e)=>{i==="warn"?console.warn(e):console.error(e)},"consoleLogger");class d{static{n(this,"AbstractScheduledTask")}getTaskType(){return null}createRunRecorder(){return null}logger(){return h}swallowErrors(){return!1}async handle(e,c,t){const o=this.getTaskType(),s=o===null?null:this.createRunRecorder();let r=null;s&&o!==null&&(r=await s.startRun({taskType:o}).catch(()=>(this.logger()("warn",`[${this.constructor.name}] failed to start task run record`),null)));try{const a=await this.handleScheduledTask(e,c,t);s&&r&&await s.succeedRun(r,a??{itemsProcessed:0,itemsFailed:0}).catch(()=>{this.logger()("warn",`[${this.constructor.name}] failed to mark task run succeeded`)})}catch(a){if(this.logger()("error",`[${this.constructor.name}] uncaught error`),s&&r){const l=a instanceof Error?a.message:String(a);await s.failRun(r,l).catch(()=>{this.logger()("warn",`[${this.constructor.name}] failed to mark task run failed`)})}if(!this.swallowErrors())throw a}}async createApplicationRun(e,c){const t=this.createRunRecorder();if(!t)return null;const o=await t.startRun({taskType:e,applicationId:c}),s=n(r=>()=>{this.logger()("warn",`[${this.constructor.name}] failed to mark application run ${r}`)},"warn");return{succeed:n(r=>t.succeedRun(o,r).catch(s("succeeded")).then(()=>{}),"succeed"),fail:n((r,a)=>t.failRun(o,r,a).catch(s("failed")).then(()=>{}),"fail"),skip:n(r=>t.skipRun(o,r).catch(s("skipped")).then(()=>{}),"skip")}}}class g{static{n(this,"TaskRegistry")}byPhase=new Map;register(e,c){const t=this.byPhase.get(e)??[];return t.push(c),this.byPhase.set(e,t),this}tasksForPhase(e){return this.byPhase.get(e)??[]}phases(){return[...this.byPhase.keys()].sort((e,c)=>e-c)}}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 * 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.\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 }\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,CAQO,MA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AAOC,CAAM,EACxB,MAAMG,EAAK,WAAW,CAAC,EACvB,KAAK,IAAK,CAAE,CAAC,EAJT,WAKT,KAAMb,EAAA,CAACe,EAAsBC,IAC3BR,EACG,QAAQC,EAAOM,EAAcC,CAAO,EACpC,MAAMH,EAAK,QAAQ,CAAC,EACpB,KAAK,IAAK,CAAE,CAAC,EAJZ,QAKN,KAAMb,EAACiB,GACLT,EACG,QAAQC,EAAOQ,CAAM,EACrB,MAAMJ,EAAK,SAAS,CAAC,EACrB,KAAK,IAAK,CAAE,CAAC,EAJZ,QAMV,EAuBF,MAAMK,CAAY,CAlOlB,MAkOkB,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",
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,OAAOK,EAAgCC,EAAWC,EAAyB,CACtF,MAAMC,EAAW,KAAK,YAAW,EAC3BC,EAAWD,IAAa,KAAO,KAAO,KAAK,kBAAiB,EAElE,IAAIE,EAAuB,KACvBD,GAAYD,IAAa,OAC3BE,EAAQ,MAAMD,EAAS,SAAS,CAAE,SAAAD,CAAQ,CAAE,EAAE,MAAM,KAGlD,KAAK,OAAM,EAAG,OAAQ,IAAI,KAAK,YAAY,IAAI,mCAAmC,EAC3E,KACR,GAGH,GAAI,CACF,MAAMG,EAAS,MAAM,KAAK,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S,CAAC,EACrB,KAAK,IAAK,CAAE,CAAC,EAJZ,QAMV,EAuBF,MAAMK,CAAY,CA5PlB,MA4PkB,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
6
  "names": ["consoleLogger", "__name", "level", "message", "AbstractScheduledTask", "event", "env", "ctx", "taskType", "recorder", "runId", "result", "error", "applicationId", "warn", "op", "errorMessage", "partial", "reason", "TaskRegistry", "phase", "task", "existing", "left", "right"]
7
7
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@rexezuge/runtime",
3
- "version": "1.7.1",
3
+ "version": "1.8.0",
4
4
  "private": false,
5
5
  "license": "MIT",
6
6
  "repository": {