@rexezuge/runtime 1.2.0 → 1.4.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.
Files changed (61) hide show
  1. package/dist/base/AbstractDurableObjectWorker.js +1 -38
  2. package/dist/base/AbstractDurableObjectWorker.js.map +7 -1
  3. package/dist/base/AbstractEntrypointWorker.js +1 -35
  4. package/dist/base/AbstractEntrypointWorker.js.map +7 -1
  5. package/dist/base/AbstractQueueWorker.d.ts +1 -1
  6. package/dist/base/AbstractQueueWorker.d.ts.map +1 -1
  7. package/dist/base/AbstractQueueWorker.js +1 -13
  8. package/dist/base/AbstractQueueWorker.js.map +7 -1
  9. package/dist/base/AbstractWorkflowWorker.js +1 -13
  10. package/dist/base/AbstractWorkflowWorker.js.map +7 -1
  11. package/dist/base/index.d.ts +7 -7
  12. package/dist/base/index.d.ts.map +1 -1
  13. package/dist/base/index.js +1 -5
  14. package/dist/base/index.js.map +7 -1
  15. package/dist/config/AppConfiguration.d.ts +6 -2
  16. package/dist/config/AppConfiguration.d.ts.map +1 -1
  17. package/dist/config/AppConfiguration.js +1 -63
  18. package/dist/config/AppConfiguration.js.map +7 -1
  19. package/dist/config/ConfigurationDefaults.d.ts +3 -1
  20. package/dist/config/ConfigurationDefaults.d.ts.map +1 -1
  21. package/dist/config/ConfigurationDefaults.js +1 -12
  22. package/dist/config/ConfigurationDefaults.js.map +7 -1
  23. package/dist/config/EnvParser.d.ts +3 -1
  24. package/dist/config/EnvParser.d.ts.map +1 -1
  25. package/dist/config/EnvParser.js +1 -59
  26. package/dist/config/EnvParser.js.map +7 -1
  27. package/dist/config/index.d.ts +3 -3
  28. package/dist/config/index.d.ts.map +1 -1
  29. package/dist/config/index.js +1 -4
  30. package/dist/config/index.js.map +7 -1
  31. package/dist/di/Container.js +1 -48
  32. package/dist/di/Container.js.map +7 -1
  33. package/dist/di/RequestScope.d.ts +1 -1
  34. package/dist/di/RequestScope.d.ts.map +1 -1
  35. package/dist/di/RequestScope.js +1 -22
  36. package/dist/di/RequestScope.js.map +7 -1
  37. package/dist/di/index.d.ts +4 -4
  38. package/dist/di/index.d.ts.map +1 -1
  39. package/dist/di/index.js +1 -3
  40. package/dist/di/index.js.map +7 -1
  41. package/dist/index.d.ts +20 -20
  42. package/dist/index.d.ts.map +1 -1
  43. package/dist/index.js +1 -18
  44. package/dist/index.js.map +7 -1
  45. package/dist/kv/KvCache.d.ts +1 -1
  46. package/dist/kv/KvCache.d.ts.map +1 -1
  47. package/dist/kv/KvCache.js +1 -197
  48. package/dist/kv/KvCache.js.map +7 -1
  49. package/dist/kv/KvDomains.js +1 -101
  50. package/dist/kv/KvDomains.js.map +7 -1
  51. package/dist/kv/index.d.ts +4 -4
  52. package/dist/kv/index.d.ts.map +1 -1
  53. package/dist/kv/index.js +1 -3
  54. package/dist/kv/index.js.map +7 -1
  55. package/dist/logger.js +1 -47
  56. package/dist/logger.js.map +7 -1
  57. package/dist/scheduled/index.d.ts +21 -7
  58. package/dist/scheduled/index.d.ts.map +1 -1
  59. package/dist/scheduled/index.js +1 -151
  60. package/dist/scheduled/index.js.map +7 -1
  61. package/package.json +2 -2
@@ -1 +1,7 @@
1
- {"version":3,"file":"KvDomains.js","sourceRoot":"","sources":["../../src/kv/KvDomains.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;GAeG;AACH,MAAM,cAAc,GAAG,IAAI,CAAC;AAC5B,MAAM,iBAAiB,GAAG,GAAG,CAAC;AAC9B,MAAM,kBAAkB,GAAG,EAAE,CAAC;AAU9B,MAAM,UAAU,GAAsC;IACpD,OAAO,EAAE;QACP,UAAU,EAAE,GAAG;QACf,aAAa,EAAE,MAAM;QACrB,WAAW,EAAE,2EAA2E;KACzF;IACD,KAAK,EAAE;QACL,UAAU,EAAE,GAAG;QACf,aAAa,EAAE,UAAU;QACzB,WAAW,EAAE,qGAAqG;KACnH;IACD,QAAQ,EAAE;QACR,UAAU,EAAE,GAAG;QACf,aAAa,EAAE,SAA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AE,eAAe,EAAE,cAAc,EAAE,CAAC","sourcesContent":["/**\n * Single-KV keyspace: one `CACHE` binding, domains separated by key prefix.\n *\n * Converged from `backend-runtime/src/kv/KvDomains.ts` (Durable-DAV,\n * Durable-DAV-Router, Edge-Sonic, Mail-Otter — the same table under four sets\n * of names). The domains are generalized to the three the whole family shares;\n * a consumer with a different cache vocabulary renames its call sites (clients\n * adapt) rather than extending the registry, because an open registry is how\n * prefix collisions start.\n *\n * Rationale: D1 and the Durable Object stay the source of truth. KV is a\n * loss-tolerant, read-heavy cache only — a miss or eviction must always be\n * recoverable by recompute. Call sites never touch `env.CACHE` directly; they\n * go through `KvCache` with a closed `KvDomainName` registry so prefixes cannot\n * collide and TTL/size policy lives in one table.\n */\nconst KV_KEY_VERSION = 'v1';\nconst KV_MAX_KEY_LENGTH = 512;\nconst KV_MIN_TTL_SECONDS = 60;\n\ntype KvDomainName = 'session' | 'asset' | 'metadata';\n\ninterface KvDomainDef {\n ttlSeconds: number;\n maxValueBytes: number;\n description: string;\n}\n\nconst KV_DOMAINS: Record<KvDomainName, KvDomainDef> = {\n session: {\n ttlSeconds: 300,\n maxValueBytes: 65_536,\n description: 'Per-user session/profile snapshots; invalidated on any credential change.',\n },\n asset: {\n ttlSeconds: 300,\n maxValueBytes: 10_485_760,\n description: 'Binary payloads (file bodies, sealed secrets) with etag/contentType metadata; invalidated on write.',\n },\n metadata: {\n ttlSeconds: 120,\n maxValueBytes: 1_048_576,\n description: 'Listing/derived snapshots keyed by owner or collection; invalidated on mutation.',\n },\n};\n\n/**\n * 128-bit digest built from four independent FNV-1a lanes.\n *\n * Why not a single 32-bit FNV: `buildKvKey` falls back to a digest when a key\n * exceeds the platform's 512-character limit, and the longest keys embed a\n * user-controlled path or name. A 32-bit digest over a shared keyspace is\n * collision-searchable — someone who controls names in their own scope could\n * grind a colliding key and read another tenant's cached bytes. Four lanes over\n * the same bytes with different offsets/primes cost one extra pass and take a\n * birthday collision to ~2^64 work, which is not worth attacking.\n *\n * Synchronous on purpose: `buildKvKey` is called from sync cache-key builders.\n */\nfunction digest128(input: string): string {\n const LANES = 4;\n const offsets = [0x81_1c_9d_c5, 0xc2_b2_ae_35, 0x27_d4_eb_2f, 0x16_56_67_b1];\n let out = '';\n for (let lane = 0; lane < LANES; lane += 1) {\n let hash = offsets[lane] as number;\n const prime = 0x01_00_01_93 + lane * 0x9e_37_79_b9;\n for (let i = 0; i < input.length; i += 1) {\n hash ^= input.codePointAt(i) ?? 0;\n hash = Math.imul(hash, prime);\n }\n out += (hash >>> 0).toString(16).padStart(8, '0');\n }\n return out;\n}\n\nfunction sanitizeSegment(segment: string): string {\n const trimmed = segment.trim();\n if (!trimmed) throw new Error('KV key segment must not be empty.');\n return encodeURIComponent(trimmed);\n}\n\nfunction buildKvKey(domain: KvDomainName, parts: readonly string[]): string {\n const def = KV_DOMAINS[domain];\n if (!def) throw new Error(`Unknown KV domain: ${domain}.`);\n if (parts.length === 0) throw new Error(`KV domain ${domain} requires at least one key part.`);\n const prefix = `${domain}:${KV_KEY_VERSION}:`;\n const joined = parts.map((part) => sanitizeSegment(part)).join(':');\n const full = prefix + joined;\n if (full.length <= KV_MAX_KEY_LENGTH) return full;\n // Deterministic overflow form. Note the consequence for invalidation: an\n // overflowing key does not start with the plain prefix, so `purgePrefix` on\n // the parts will not match it. Callers must therefore bound the key material\n // they cache (path length, identifier length) — the digest is a crash guard,\n // not a caching strategy.\n return `${prefix}h:${digest128(joined)}`;\n}\n\nfunction utf8ByteLength(value: string): number {\n return new TextEncoder().encode(value).length;\n}\n\n/**\n * Resolve a TTL, defaulting to the domain's own. Every domain declares a\n * required `ttlSeconds`, so there is no \"no TTL\" case to represent.\n */\nfunction clampTtl(ttlSeconds: number | undefined, domain: KvDomainName): number {\n const effective = ttlSeconds ?? KV_DOMAINS[domain].ttlSeconds;\n return Number.isFinite(effective) ? Math.max(KV_MIN_TTL_SECONDS, Math.floor(effective)) : KV_DOMAINS[domain].ttlSeconds;\n}\n\nexport { KV_DOMAINS, KV_MAX_KEY_LENGTH, KV_MIN_TTL_SECONDS, buildKvKey, clampTtl, digest128, sanitizeSegment, utf8ByteLength };\nexport type { KvDomainDef, KvDomainName };\n"]}
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../src/kv/KvDomains.ts"],
4
+ "sourcesContent": ["/**\n * Single-KV keyspace: one `CACHE` binding, domains separated by key prefix.\n *\n * Converged from `backend-runtime/src/kv/KvDomains.ts` (Durable-DAV,\n * Durable-DAV-Router, Edge-Sonic, Mail-Otter — the same table under four sets\n * of names). The domains are generalized to the three the whole family shares;\n * a consumer with a different cache vocabulary renames its call sites (clients\n * adapt) rather than extending the registry, because an open registry is how\n * prefix collisions start.\n *\n * Rationale: D1 and the Durable Object stay the source of truth. KV is a\n * loss-tolerant, read-heavy cache only — a miss or eviction must always be\n * recoverable by recompute. Call sites never touch `env.CACHE` directly; they\n * go through `KvCache` with a closed `KvDomainName` registry so prefixes cannot\n * collide and TTL/size policy lives in one table.\n */\nconst KV_KEY_VERSION = 'v1';\nconst KV_MAX_KEY_LENGTH = 512;\nconst KV_MIN_TTL_SECONDS = 60;\n\ntype KvDomainName = 'session' | 'asset' | 'metadata';\n\ninterface KvDomainDef {\n ttlSeconds: number;\n maxValueBytes: number;\n description: string;\n}\n\nconst KV_DOMAINS: Record<KvDomainName, KvDomainDef> = {\n session: {\n ttlSeconds: 300,\n maxValueBytes: 65_536,\n description: 'Per-user session/profile snapshots; invalidated on any credential change.',\n },\n asset: {\n ttlSeconds: 300,\n maxValueBytes: 10_485_760,\n description: 'Binary payloads (file bodies, sealed secrets) with etag/contentType metadata; invalidated on write.',\n },\n metadata: {\n ttlSeconds: 120,\n maxValueBytes: 1_048_576,\n description: 'Listing/derived snapshots keyed by owner or collection; invalidated on mutation.',\n },\n};\n\n/**\n * 128-bit digest built from four independent FNV-1a lanes.\n *\n * Why not a single 32-bit FNV: `buildKvKey` falls back to a digest when a key\n * exceeds the platform's 512-character limit, and the longest keys embed a\n * user-controlled path or name. A 32-bit digest over a shared keyspace is\n * collision-searchable — someone who controls names in their own scope could\n * grind a colliding key and read another tenant's cached bytes. Four lanes over\n * the same bytes with different offsets/primes cost one extra pass and take a\n * birthday collision to ~2^64 work, which is not worth attacking.\n *\n * Synchronous on purpose: `buildKvKey` is called from sync cache-key builders.\n */\nfunction digest128(input: string): string {\n const LANES = 4;\n const offsets = [0x81_1c_9d_c5, 0xc2_b2_ae_35, 0x27_d4_eb_2f, 0x16_56_67_b1];\n let out = '';\n for (let lane = 0; lane < LANES; lane += 1) {\n let hash = offsets[lane];\n const prime = 0x01_00_01_93 + lane * 0x9e_37_79_b9;\n for (let i = 0; i < input.length; i += 1) {\n hash ^= input.codePointAt(i) ?? 0;\n hash = Math.imul(hash, prime);\n }\n out += (hash >>> 0).toString(16).padStart(8, '0');\n }\n return out;\n}\n\nfunction sanitizeSegment(segment: string): string {\n const trimmed = segment.trim();\n if (!trimmed) throw new Error('KV key segment must not be empty.');\n return encodeURIComponent(trimmed);\n}\n\nfunction buildKvKey(domain: KvDomainName, parts: readonly string[]): string {\n const def = KV_DOMAINS[domain];\n if (!def) throw new Error(`Unknown KV domain: ${domain}.`);\n if (parts.length === 0) throw new Error(`KV domain ${domain} requires at least one key part.`);\n const prefix = `${domain}:${KV_KEY_VERSION}:`;\n const joined = parts.map((part) => sanitizeSegment(part)).join(':');\n const full = prefix + joined;\n if (full.length <= KV_MAX_KEY_LENGTH) return full;\n // Deterministic overflow form. Note the consequence for invalidation: an\n // overflowing key does not start with the plain prefix, so `purgePrefix` on\n // the parts will not match it. Callers must therefore bound the key material\n // they cache (path length, identifier length) — the digest is a crash guard,\n // not a caching strategy.\n return `${prefix}h:${digest128(joined)}`;\n}\n\nfunction utf8ByteLength(value: string): number {\n return new TextEncoder().encode(value).length;\n}\n\n/**\n * Resolve a TTL, defaulting to the domain's own. Every domain declares a\n * required `ttlSeconds`, so there is no \"no TTL\" case to represent.\n */\nfunction clampTtl(ttlSeconds: number | undefined, domain: KvDomainName): number {\n const effective = ttlSeconds ?? KV_DOMAINS[domain].ttlSeconds;\n return Number.isFinite(effective) ? Math.max(KV_MIN_TTL_SECONDS, Math.floor(effective)) : KV_DOMAINS[domain].ttlSeconds;\n}\n\nexport { KV_DOMAINS, KV_MAX_KEY_LENGTH, KV_MIN_TTL_SECONDS, buildKvKey, clampTtl, digest128, sanitizeSegment, utf8ByteLength };\nexport type { KvDomainDef, KvDomainName };\n"],
5
+ "mappings": "AAgBA,MAAMA,EAAiB,KACjBC,EAAoB,IACpBC,EAAqB,GAUrBC,EAAgD,CACpD,QAAS,CACP,WAAY,IACZ,cAAe,MACf,YAAa,6EAEf,MAAO,CACL,WAAY,IACZ,cAAe,SACf,YAAa,uGAEf,SAAU,CACR,WAAY,IACZ,cAAe,QACf,YAAa,qFAiBjB,SAASC,EAAUC,EAAa,CAE9B,MAAMC,EAAU,CAAC,WAAe,WAAe,UAAe,SAAa,EAC3E,IAAIC,EAAM,GACV,QAASC,EAAO,EAAGA,EAAO,EAAOA,GAAQ,EAAG,CAC1C,IAAIC,EAAOH,EAAQE,CAAI,EACvB,MAAME,EAAQ,SAAgBF,EAAO,WACrC,QAASG,EAAI,EAAGA,EAAIN,EAAM,OAAQM,GAAK,EACrCF,GAAQJ,EAAM,YAAYM,CAAC,GAAK,EAChCF,EAAO,KAAK,KAAKA,EAAMC,CAAK,EAE9BH,IAAQE,IAAS,GAAG,SAAS,EAAE,EAAE,SAAS,EAAG,GAAG,CAClD,CACA,OAAOF,CACT,CAEA,SAASK,EAAgBC,EAAe,CACtC,MAAMC,EAAUD,EAAQ,KAAI,EAC5B,GAAI,CAACC,EAAS,MAAM,IAAI,MAAM,mCAAmC,EACjE,OAAO,mBAAmBA,CAAO,CACnC,CAEA,SAASC,EAAWC,EAAsBC,EAAwB,CAEhE,GAAI,CADQd,EAAWa,CAAM,EACnB,MAAM,IAAI,MAAM,sBAAsBA,CAAM,GAAG,EACzD,GAAIC,EAAM,SAAW,EAAG,MAAM,IAAI,MAAM,aAAaD,CAAM,kCAAkC,EAC7F,MAAME,EAAS,GAAGF,CAAM,OAClBG,EAASF,EAAM,IAAKG,GAASR,EAAgBQ,CAAI,CAAC,EAAE,KAAK,GAAG,EAC5DC,EAAOH,EAASC,EACtB,OAAIE,EAAK,QAAU,IAA0BA,EAMtC,GAAGH,CAAM,KAAKd,EAAUe,CAAM,CAAC,EACxC,CAEA,SAASG,EAAeC,EAAa,CACnC,OAAO,IAAI,YAAW,EAAG,OAAOA,CAAK,EAAE,MACzC,CAMA,SAASC,EAASC,EAAgCT,EAAoB,CACpE,MAAMU,EAAYD,GAActB,EAAWa,CAAM,EAAE,WACnD,OAAO,OAAO,SAASU,CAAS,EAAI,KAAK,IAAI,GAAoB,KAAK,MAAMA,CAAS,CAAC,EAAIvB,EAAWa,CAAM,EAAE,UAC/G",
6
+ "names": ["KV_KEY_VERSION", "KV_MAX_KEY_LENGTH", "KV_MIN_TTL_SECONDS", "KV_DOMAINS", "digest128", "input", "offsets", "out", "lane", "hash", "prime", "i", "sanitizeSegment", "segment", "trimmed", "buildKvKey", "domain", "parts", "prefix", "joined", "part", "full", "utf8ByteLength", "value", "clampTtl", "ttlSeconds", "effective"]
7
+ }
@@ -1,5 +1,5 @@
1
- export { KvCache, PURGE_LIST_LIMIT, PURGE_MAX_PAGES } from './KvCache';
2
- export type { KvBinaryEntry, KvFileMetadata, KvNamespaceLike, KvPutOptions } from './KvCache';
3
- export { KV_DOMAINS, KV_MAX_KEY_LENGTH, KV_MIN_TTL_SECONDS, buildKvKey, clampTtl, digest128, sanitizeSegment, utf8ByteLength, } from './KvDomains';
4
- export type { KvDomainDef, KvDomainName } from './KvDomains';
1
+ export { KvCache, PURGE_LIST_LIMIT, PURGE_MAX_PAGES } from './KvCache.ts';
2
+ export type { KvBinaryEntry, KvFileMetadata, KvNamespaceLike, KvPutOptions } from './KvCache.ts';
3
+ export { KV_DOMAINS, KV_MAX_KEY_LENGTH, KV_MIN_TTL_SECONDS, buildKvKey, clampTtl, digest128, sanitizeSegment, utf8ByteLength, } from './KvDomains.ts';
4
+ export type { KvDomainDef, KvDomainName } from './KvDomains.ts';
5
5
  //# sourceMappingURL=index.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/kv/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAE,gBAAgB,EAAE,eAAe,EAAE,MAAM,WAAW,CAAC;AACvE,YAAY,EAAE,aAAa,EAAE,cAAc,EAAE,eAAe,EAAE,YAAY,EAAE,MAAM,WAAW,CAAC;AAC9F,OAAO,EACL,UAAU,EACV,iBAAiB,EACjB,kBAAkB,EAClB,UAAU,EACV,QAAQ,EACR,SAAS,EACT,eAAe,EACf,cAAc,GACf,MAAM,aAAa,CAAC;AACrB,YAAY,EAAE,WAAW,EAAE,YAAY,EAAE,MAAM,aAAa,CAAC"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/kv/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAE,gBAAgB,EAAE,eAAe,EAAE,MAAM,cAAc,CAAC;AAC1E,YAAY,EAAE,aAAa,EAAE,cAAc,EAAE,eAAe,EAAE,YAAY,EAAE,MAAM,cAAc,CAAC;AACjG,OAAO,EACL,UAAU,EACV,iBAAiB,EACjB,kBAAkB,EAClB,UAAU,EACV,QAAQ,EACR,SAAS,EACT,eAAe,EACf,cAAc,GACf,MAAM,gBAAgB,CAAC;AACxB,YAAY,EAAE,WAAW,EAAE,YAAY,EAAE,MAAM,gBAAgB,CAAC"}
package/dist/kv/index.js CHANGED
@@ -1,3 +1 @@
1
- export { KvCache, PURGE_LIST_LIMIT, PURGE_MAX_PAGES } from './KvCache';
2
- export { KV_DOMAINS, KV_MAX_KEY_LENGTH, KV_MIN_TTL_SECONDS, buildKvKey, clampTtl, digest128, sanitizeSegment, utf8ByteLength, } from './KvDomains';
3
- //# sourceMappingURL=index.js.map
1
+ import{KvCache as t,PURGE_LIST_LIMIT as K,PURGE_MAX_PAGES as E}from"./KvCache.js";import{KV_DOMAINS as T,KV_MAX_KEY_LENGTH as I,KV_MIN_TTL_SECONDS as L,buildKvKey as M,clampTtl as i,digest128 as m,sanitizeSegment as o,utf8ByteLength as r}from"./KvDomains.js";export{T as KV_DOMAINS,I as KV_MAX_KEY_LENGTH,L as KV_MIN_TTL_SECONDS,t as KvCache,K as PURGE_LIST_LIMIT,E as PURGE_MAX_PAGES,M as buildKvKey,i as clampTtl,m as digest128,o as sanitizeSegment,r as utf8ByteLength};
@@ -1 +1,7 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/kv/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAE,gBAAgB,EAAE,eAAe,EAAE,MAAM,WAAW,CAAC;AAEvE,OAAO,EACL,UAAU,EACV,iBAAiB,EACjB,kBAAkB,EAClB,UAAU,EACV,QAAQ,EACR,SAAS,EACT,eAAe,EACf,cAAc,GACf,MAAM,aAAa,CAAC","sourcesContent":["export { KvCache, PURGE_LIST_LIMIT, PURGE_MAX_PAGES } from './KvCache';\nexport type { KvBinaryEntry, KvFileMetadata, KvNamespaceLike, KvPutOptions } from './KvCache';\nexport {\n KV_DOMAINS,\n KV_MAX_KEY_LENGTH,\n KV_MIN_TTL_SECONDS,\n buildKvKey,\n clampTtl,\n digest128,\n sanitizeSegment,\n utf8ByteLength,\n} from './KvDomains';\nexport type { KvDomainDef, KvDomainName } from './KvDomains';\n"]}
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../src/kv/index.ts"],
4
+ "sourcesContent": ["export { KvCache, PURGE_LIST_LIMIT, PURGE_MAX_PAGES } from './KvCache.ts';\nexport type { KvBinaryEntry, KvFileMetadata, KvNamespaceLike, KvPutOptions } from './KvCache.ts';\nexport {\n KV_DOMAINS,\n KV_MAX_KEY_LENGTH,\n KV_MIN_TTL_SECONDS,\n buildKvKey,\n clampTtl,\n digest128,\n sanitizeSegment,\n utf8ByteLength,\n} from './KvDomains.ts';\nexport type { KvDomainDef, KvDomainName } from './KvDomains.ts';\n"],
5
+ "mappings": "AAAA,OAAS,WAAAA,EAAS,oBAAAC,EAAkB,mBAAAC,MAAuB,eAE3D,OACE,cAAAC,EACA,qBAAAC,EACA,sBAAAC,EACA,cAAAC,EACA,YAAAC,EACA,aAAAC,EACA,mBAAAC,EACA,kBAAAC,MACK",
6
+ "names": ["KvCache", "PURGE_LIST_LIMIT", "PURGE_MAX_PAGES", "KV_DOMAINS", "KV_MAX_KEY_LENGTH", "KV_MIN_TTL_SECONDS", "buildKvKey", "clampTtl", "digest128", "sanitizeSegment", "utf8ByteLength"]
7
+ }
package/dist/logger.js CHANGED
@@ -1,47 +1 @@
1
- const LOG_LEVELS = {
2
- debug: 0,
3
- info: 1,
4
- warn: 2,
5
- error: 3,
6
- };
7
- function isLogLevel(level) {
8
- return ['debug', 'info', 'warn', 'error'].includes(level);
9
- }
10
- function resolveLogLevel(env) {
11
- const fromInjected = env !== null && typeof env === 'object' ? env['LOG_LEVEL'] : undefined;
12
- const fromEnv = globalThis.process?.env?.LOG_LEVEL;
13
- const level = fromInjected ?? fromEnv ?? 'info';
14
- return isLogLevel(level) ? level : 'info';
15
- }
16
- function createLogger(namespace, fullRepoName, env) {
17
- const currentLevel = resolveLogLevel(env);
18
- const minLevel = LOG_LEVELS[currentLevel];
19
- const argsStr = [fullRepoName, namespace]
20
- .filter(Boolean)
21
- .map((s) => `[${s}]`)
22
- .join(' ');
23
- return {
24
- debug: (...args) => {
25
- if (LOG_LEVELS.debug >= minLevel) {
26
- console.debug(`[DEBUG] ${argsStr}`, ...args);
27
- }
28
- },
29
- info: (...args) => {
30
- if (LOG_LEVELS.info >= minLevel) {
31
- console.info(`[INFO] ${argsStr}`, ...args);
32
- }
33
- },
34
- warn: (...args) => {
35
- if (LOG_LEVELS.warn >= minLevel) {
36
- console.warn(`[WARN] ${argsStr}`, ...args);
37
- }
38
- },
39
- error: (...args) => {
40
- if (LOG_LEVELS.error >= minLevel) {
41
- console.error(`[ERROR] ${argsStr}`, ...args);
42
- }
43
- },
44
- };
45
- }
46
- export { createLogger, isLogLevel, resolveLogLevel };
47
- //# sourceMappingURL=logger.js.map
1
+ const n={debug:0,info:1,warn:2,error:3};function l(e){return["debug","info","warn","error"].includes(e)}function s(e){const c=e!==null&&typeof e=="object"?e.LOG_LEVEL:void 0,f=globalThis.process?.env?.LOG_LEVEL,r=c??f??"info";return l(r)?r:"info"}function L(e,c,f){const r=s(f),i=n[r],t=[c,e].filter(Boolean).map(o=>`[${o}]`).join(" ");return{debug:(...o)=>{n.debug>=i&&console.debug(`[DEBUG] ${t}`,...o)},info:(...o)=>{n.info>=i&&console.info(`[INFO] ${t}`,...o)},warn:(...o)=>{n.warn>=i&&console.warn(`[WARN] ${t}`,...o)},error:(...o)=>{n.error>=i&&console.error(`[ERROR] ${t}`,...o)}}}export{L as createLogger,l as isLogLevel,s as resolveLogLevel};
@@ -1 +1,7 @@
1
- {"version":3,"file":"logger.js","sourceRoot":"","sources":["../src/logger.ts"],"names":[],"mappings":"AAeA,MAAM,UAAU,GAA6B;IAC3C,KAAK,EAAE,CAAC;IACR,IAAI,EAAE,CAAC;IACP,IAAI,EAAE,CAAC;IACP,KAAK,EAAE,CAAC;CACA,CAAC;AAEX,SAAS,UAAU,CAAC,KAAa;IAC/B,OAAQ,CAAC,OAAO,EAAE,MAAM,EAAE,MAAM,EAAE,OAAO,CAAW,CAAC,QAAQ,CAAC,KAAiB,CAAC,CAAC;AACnF,CAAC;AAED,SAAS,eAAe,CAAC,GAAa;IACpC,MAAM,YAAY,GAAG,GAAG,KAAK,IAAI,IAAI,OAAO,GAAG,KAAK,QAAQ,CAAC,CAAC,CAAE,GAA0C,CAAC,WAAW,CAAC,CAAC,CAAC,CAAC,SAAS,CAAC;IACpI,MAAM,OAAO,GAAI,UAAyE,CAAC,OAAO,EAAE,GAAG,EAAE,SAAS,CAAC;IACnH,MAAM,KAAK,GAAG,YAAY,IAAI,OA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O,CAAC,KAAK,CAAC,WAAW,OAAO,EAAE,EAAE,GAAG,IAAI,CAAC,CAAC;YAC/C,CAAC;QACH,CAAC;KACF,CAAC;AACJ,CAAC;AAED,OAAO,EAAE,YAAY,EAAE,UAAU,EAAE,eAAe,EAAE,CAAC","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 * `info`: Workers have no `process.env` at runtime, so an injected object is\n * the configuration path, and `process.env` is a local-tooling affordance. An\n * unrecognized level floors at `info` rather than throwing — a typo in\n * `LOG_LEVEL` costing a worker a cold start is not a trade worth making.\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\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 ?? 'info';\n return isLogLevel(level) ? level : 'info';\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 currentLevel = resolveLogLevel(env);\n const minLevel = LOG_LEVELS[currentLevel];\n\n const argsStr = [fullRepoName, namespace]\n .filter(Boolean)\n .map((s) => `[${s}]`)\n .join(' ');\n\n return {\n debug: (...args: unknown[]): void => {\n if (LOG_LEVELS.debug >= minLevel) {\n console.debug(`[DEBUG] ${argsStr}`, ...args);\n }\n },\n info: (...args: unknown[]): void => {\n if (LOG_LEVELS.info >= minLevel) {\n console.info(`[INFO] ${argsStr}`, ...args);\n }\n },\n warn: (...args: unknown[]): void => {\n if (LOG_LEVELS.warn >= minLevel) {\n console.warn(`[WARN] ${argsStr}`, ...args);\n }\n },\n error: (...args: unknown[]): void => {\n if (LOG_LEVELS.error >= minLevel) {\n console.error(`[ERROR] ${argsStr}`, ...args);\n }\n },\n };\n}\n\nexport { createLogger, isLogLevel, resolveLogLevel };\nexport type { LogLevel, Logger };\n"]}
1
+ {
2
+ "version": 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 * `info`: Workers have no `process.env` at runtime, so an injected object is\n * the configuration path, and `process.env` is a local-tooling affordance. An\n * unrecognized level floors at `info` rather than throwing — a typo in\n * `LOG_LEVEL` costing a worker a cold start is not a trade worth making.\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\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 ?? 'info';\n return isLogLevel(level) ? level : 'info';\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 currentLevel = resolveLogLevel(env);\n const minLevel = LOG_LEVELS[currentLevel];\n\n const argsStr = [fullRepoName, namespace]\n .filter(Boolean)\n .map((s) => `[${s}]`)\n .join(' ');\n\n return {\n debug: (...args: unknown[]): void => {\n if (LOG_LEVELS.debug >= minLevel) {\n console.debug(`[DEBUG] ${argsStr}`, ...args);\n }\n },\n info: (...args: unknown[]): void => {\n if (LOG_LEVELS.info >= minLevel) {\n console.info(`[INFO] ${argsStr}`, ...args);\n }\n },\n warn: (...args: unknown[]): void => {\n if (LOG_LEVELS.warn >= minLevel) {\n console.warn(`[WARN] ${argsStr}`, ...args);\n }\n },\n error: (...args: unknown[]): void => {\n if (LOG_LEVELS.error >= minLevel) {\n console.error(`[ERROR] ${argsStr}`, ...args);\n }\n },\n };\n}\n\nexport { createLogger, isLogLevel, resolveLogLevel };\nexport type { LogLevel, Logger };\n"],
5
+ "mappings": "AAeA,MAAMA,EAAuC,CAC3C,MAAO,EACP,KAAM,EACN,KAAM,EACN,MAAO,GAGT,SAASC,EAAWC,EAAa,CAC/B,MAAQ,CAAC,QAAS,OAAQ,OAAQ,OAAO,EAAY,SAASA,CAAiB,CACjF,CAEA,SAASC,EAAgBC,EAAa,CACpC,MAAMC,EAAeD,IAAQ,MAAQ,OAAOA,GAAQ,SAAYA,EAA2C,UAAe,OACpHE,EAAW,WAA0E,SAAS,KAAK,UACnGJ,EAAQG,GAAgBC,GAAW,OACzC,OAAOL,EAAWC,CAAK,EAAIA,EAAQ,MACrC,CASA,SAASK,EAAaC,EAAoBC,EAAuBL,EAAa,CAC5E,MAAMM,EAAeP,EAAgBC,CAAG,EAClCO,EAAWX,EAAWU,CAAY,EAElCE,EAAU,CAACH,EAAcD,CAAS,EACrC,OAAO,OAAO,EACd,IAAKK,GAAM,IAAIA,CAAC,GAAG,EACnB,KAAK,GAAG,EAEX,MAAO,CACL,MAAO,IAAIC,IAAyB,CAC9Bd,EAAW,OAASW,GACtB,QAAQ,MAAM,WAAWC,CAAO,GAAI,GAAGE,CAAI,CAE/C,EACA,KAAM,IAAIA,IAAyB,CAC7Bd,EAAW,MAAQW,GACrB,QAAQ,KAAK,UAAUC,CAAO,GAAI,GAAGE,CAAI,CAE7C,EACA,KAAM,IAAIA,IAAyB,CAC7Bd,EAAW,MAAQW,GACrB,QAAQ,KAAK,UAAUC,CAAO,GAAI,GAAGE,CAAI,CAE7C,EACA,MAAO,IAAIA,IAAyB,CAC9Bd,EAAW,OAASW,GACtB,QAAQ,MAAM,WAAWC,CAAO,GAAI,GAAGE,CAAI,CAE/C,EAEJ",
6
+ "names": ["LOG_LEVELS", "isLogLevel", "level", "resolveLogLevel", "env", "fromInjected", "fromEnv", "createLogger", "namespace", "fullRepoName", "currentLevel", "minLevel", "argsStr", "s", "args"]
7
+ }
@@ -23,7 +23,9 @@
23
23
  * would invert the package graph. The port is four methods; the consumer binds
24
24
  * its `BackgroundTaskRunDAO` at the composition root.
25
25
  */
26
- /** The summary a task reports when it finishes. */
26
+ /**
27
+ The summary a task reports when it finishes.
28
+ */
27
29
  interface TaskRunSummary {
28
30
  itemsProcessed: number;
29
31
  itemsFailed: number;
@@ -58,7 +60,9 @@ interface ApplicationRunHandle {
58
60
  fail(errorMessage: string, partial?: Partial<TaskRunSummary>): Promise<void>;
59
61
  skip(reason?: string): Promise<void>;
60
62
  }
61
- /** The minimum a task needs from `env`: a D1 binding, when the repo has one. */
63
+ /**
64
+ The minimum a task needs from `env`: a D1 binding, when the repo has one.
65
+ */
62
66
  interface ScheduledTaskEnv {
63
67
  DB?: unknown;
64
68
  }
@@ -75,7 +79,9 @@ interface ScheduledControllerLike {
75
79
  scheduledTime: number;
76
80
  noRetry(): void;
77
81
  }
78
- /** The execution context, structurally. See {@link ScheduledControllerLike}. */
82
+ /**
83
+ The execution context, structurally. See {@link ScheduledControllerLike}.
84
+ */
79
85
  interface ExecutionContextLike {
80
86
  waitUntil(promise: Promise<unknown>): void;
81
87
  passThroughOnException(): void;
@@ -98,9 +104,13 @@ declare abstract class AbstractScheduledTask<TEnv extends ScheduledTaskEnv = Sch
98
104
  * global record beside its per-application ones.
99
105
  */
100
106
  protected getTaskType(): string | null;
101
- /** Factory Method for the recorder. Override in tests. */
107
+ /**
108
+ Factory Method for the recorder. Override in tests.
109
+ */
102
110
  protected createRunRecorder(): TaskRunRecorder | null;
103
- /** Override to route this task's failures somewhere other than the console. */
111
+ /**
112
+ Override to route this task's failures somewhere other than the console.
113
+ */
104
114
  protected logger(): TaskLogger;
105
115
  /**
106
116
  * The entry point the platform calls.
@@ -135,9 +145,13 @@ declare abstract class AbstractScheduledTask<TEnv extends ScheduledTaskEnv = Sch
135
145
  declare class TaskRegistry {
136
146
  private readonly byPhase;
137
147
  register(phase: number, task: AbstractScheduledTask): this;
138
- /** Every task in a phase, in registration order. */
148
+ /**
149
+ Every task in a phase, in registration order.
150
+ */
139
151
  tasksForPhase(phase: number): readonly AbstractScheduledTask[];
140
- /** The phases that have at least one task, ascending. */
152
+ /**
153
+ The phases that have at least one task, ascending.
154
+ */
141
155
  phases(): readonly number[];
142
156
  }
143
157
  export { AbstractScheduledTask, TaskRegistry };
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/scheduled/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;GAwBG;AAEH,mDAAmD;AACnD,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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Y,EAAE,CAAC;AAC/C,YAAY,EAAE,oBAAoB,EAAE,gBAAgB,EAAE,UAAU,EAAE,eAAe,EAAE,cAAc,EAAE,CAAC"}
@@ -1,151 +1 @@
1
- /**
2
- * The scheduled-task Template Method, and the run-record port it records through.
3
- *
4
- * Converged from `apps/background/src/scheduled/{IScheduledTask,TaskRegistry}.ts`
5
- * in seven repos, where the copies range from 13 lines (CalDAV-Bridge) to 103
6
- * (Mail-Otter). Mail-Otter's was the one that had solved the defects the others
7
- * carried, so this is that one.
8
- *
9
- * ## What the smaller copies were missing
10
- *
11
- * - **Run bookkeeping.** A task that fails silently leaves an operator with a
12
- * cron that appears to run and never does. `runId` here is the record that
13
- * says which.
14
- * - **A failure that is recorded as a failure.** The template's `catch` writes
15
- * `failRun`, so the task-runs table shows the reason rather than a row that
16
- * stopped at `running`.
17
- * - **A test seam.** `createRunRecorder` is a Factory Method so a suite
18
- * substitutes a double without a D1 binding.
19
- *
20
- * ## Why the recorder is a port and not a DAO
21
- *
22
- * `runtime` is the DI and platform layer and has no `d1` dependency — that
23
- * would invert the package graph. The port is four methods; the consumer binds
24
- * its `BackgroundTaskRunDAO` at the composition root.
25
- */
26
- const consoleLogger = (level, message) => {
27
- if (level === 'warn')
28
- console.warn(message);
29
- else
30
- console.error(message);
31
- };
32
- /**
33
- * The base every scheduled task extends.
34
- *
35
- * Subclasses implement {@link handleScheduledTask} and, when they want their
36
- * runs recorded, override {@link getTaskType}.
37
- */
38
- class AbstractScheduledTask {
39
- /**
40
- * The task type recorded against each run, or `null` to opt out.
41
- *
42
- * Opting **in** rather than out is deliberate: a task that never reports is
43
- * invisible, and invisibility is the failure mode worth avoiding by default.
44
- * A per-application task should leave this `null` and use
45
- * {@link createApplicationRun} instead, so it does not produce a redundant
46
- * global record beside its per-application ones.
47
- */
48
- getTaskType() {
49
- return null;
50
- }
51
- /** Factory Method for the recorder. Override in tests. */
52
- createRunRecorder() {
53
- return null;
54
- }
55
- /** Override to route this task's failures somewhere other than the console. */
56
- logger() {
57
- return consoleLogger;
58
- }
59
- /**
60
- * The entry point the platform calls.
61
- *
62
- * Owns the try/catch so a task cannot forget it: a scheduled task that throws
63
- * uncaught is retried by the platform with no record of why.
64
- */
65
- async handle(event, env, ctx) {
66
- const taskType = this.getTaskType();
67
- const recorder = taskType === null ? null : this.createRunRecorder();
68
- let runId;
69
- if (recorder && taskType !== null) {
70
- runId = await recorder.startRun({ taskType }).catch((error) => {
71
- // Losing the record must not lose the run.
72
- this.logger()('warn', `[${this.constructor.name}] failed to start task run record`);
73
- void error;
74
- return undefined;
75
- });
76
- }
77
- try {
78
- const result = await this.handleScheduledTask(event, env, ctx);
79
- if (recorder && runId) {
80
- await recorder.succeedRun(runId, result ?? { itemsProcessed: 0, itemsFailed: 0 }).catch(() => {
81
- this.logger()('warn', `[${this.constructor.name}] failed to mark task run succeeded`);
82
- });
83
- }
84
- }
85
- catch (error) {
86
- this.logger()('error', `[${this.constructor.name}] uncaught error`);
87
- if (recorder && runId) {
88
- const message = error instanceof Error ? error.message : String(error);
89
- await recorder.failRun(runId, message).catch(() => {
90
- this.logger()('warn', `[${this.constructor.name}] failed to mark task run failed`);
91
- });
92
- }
93
- }
94
- }
95
- /**
96
- * Open a per-application run record.
97
- *
98
- * Call inside a loop over applications, so the operator sees which one failed
99
- * rather than a single row for the whole cron.
100
- */
101
- async createApplicationRun(taskType, applicationId) {
102
- const recorder = this.createRunRecorder();
103
- if (!recorder)
104
- return null;
105
- const runId = await recorder.startRun({ taskType, applicationId });
106
- const warn = (op) => () => {
107
- this.logger()('warn', `[${this.constructor.name}] failed to mark application run ${op}`);
108
- };
109
- return {
110
- succeed: (result) => recorder
111
- .succeedRun(runId, result)
112
- .catch(warn('succeeded'))
113
- .then(() => undefined),
114
- fail: (errorMessage, partial) => recorder
115
- .failRun(runId, errorMessage, partial)
116
- .catch(warn('failed'))
117
- .then(() => undefined),
118
- skip: (reason) => recorder
119
- .skipRun(runId, reason)
120
- .catch(warn('skipped'))
121
- .then(() => undefined),
122
- };
123
- }
124
- }
125
- /**
126
- * The phase registry.
127
- *
128
- * Two phases, run in order, each internally parallel. The split is what keeps
129
- * one slow task from delaying the pruning that has to run behind it — and it is
130
- * why this is a table rather than a list: adding a task at index 0 cannot
131
- * silently reclassify every task after it.
132
- */
133
- class TaskRegistry {
134
- byPhase = new Map();
135
- register(phase, task) {
136
- const existing = this.byPhase.get(phase) ?? [];
137
- existing.push(task);
138
- this.byPhase.set(phase, existing);
139
- return this;
140
- }
141
- /** Every task in a phase, in registration order. */
142
- tasksForPhase(phase) {
143
- return this.byPhase.get(phase) ?? [];
144
- }
145
- /** The phases that have at least one task, ascending. */
146
- phases() {
147
- return [...this.byPhase.keys()].sort((left, right) => left - right);
148
- }
149
- }
150
- export { AbstractScheduledTask, TaskRegistry };
151
- //# sourceMappingURL=index.js.map
1
+ const u=(i,e)=>{i==="warn"?console.warn(e):console.error(e)};class l{getTaskType(){return null}createRunRecorder(){return null}logger(){return u}async handle(e,a,r){const n=this.getTaskType(),s=n===null?null:this.createRunRecorder();let t=null;s&&n!==null&&(t=await s.startRun({taskType:n}).catch(()=>(this.logger()("warn",`[${this.constructor.name}] failed to start task run record`),null)));try{const c=await this.handleScheduledTask(e,a,r);s&&t&&await s.succeedRun(t,c??{itemsProcessed:0,itemsFailed:0}).catch(()=>{this.logger()("warn",`[${this.constructor.name}] failed to mark task run succeeded`)})}catch(c){if(this.logger()("error",`[${this.constructor.name}] uncaught error`),s&&t){const o=c instanceof Error?c.message:String(c);await s.failRun(t,o).catch(()=>{this.logger()("warn",`[${this.constructor.name}] failed to mark task run failed`)})}}}async createApplicationRun(e,a){const r=this.createRunRecorder();if(!r)return null;const n=await r.startRun({taskType:e,applicationId:a}),s=t=>()=>{this.logger()("warn",`[${this.constructor.name}] failed to mark application run ${t}`)};return{succeed:t=>r.succeedRun(n,t).catch(s("succeeded")).then(()=>{}),fail:(t,c)=>r.failRun(n,t,c).catch(s("failed")).then(()=>{}),skip:t=>r.skipRun(n,t).catch(s("skipped")).then(()=>{})}}}class h{byPhase=new Map;register(e,a){const r=this.byPhase.get(e)??[];return r.push(a),this.byPhase.set(e,r),this}tasksForPhase(e){return this.byPhase.get(e)??[]}phases(){return[...this.byPhase.keys()].sort((e,a)=>e-a)}}export{l as AbstractScheduledTask,h as TaskRegistry};
@@ -1 +1,7 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/scheduled/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;GAwBG;AAgEH,MAAM,aAAa,GAAe,CAAC,KAAK,EAAE,OAAO,EAAE,EAAE;IACnD,IAAI,KAAK,KAAK,MAAM;QAAE,OAAO,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC;;QACvC,OAAO,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC;AAC9B,CAAC,CAAC;AAEF;;;;;GAKG;AACH,MAAe,qBAAqB;IAClC;;;;;;;;OAQG;IACO,WAAW;QACnB,OAAO,IAAI,CAAC;IACd,CAAC;IAED,0DAA0D;IAChD,iBAAiB;QACzB,OAAO,IAAI,CAAC;IACd,CAAC;IAED,+EAA+E;IACrE,MAAM;QACd,OAAO,aAAa,CAAC;IACvB,CAAC;IAED;;;;;OAKG;IACI,KAAK,CAAC,MAAM,CAAC,KAA8B,EAAE,GAAS,EAAE,GAAyB;QACtF,MAAM,QAAQ,GAAG,IAAI,CAAC,WAAW,EAAE,CAAC;QACpC,MAAM,QAAQ,GAAG,QAAQ,KAAK,IAAI,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,IAAI,CAAC,iBAAiB,EAAE,CAAC;QAErE,IAAI,KAAyB,CAAC;QAC9B,IAAI,QAAQ,IAAI,QAAQ,KAAK,IAAI,EAAE,CAAC;YAClC,KAAK,GAAG,MAAM,QAAQ,CAAC,QAAQ,CAAC,EAAE,QAAQ,EAAE,CAAC,CAAC,KAAK,CAAC,CAAC,KAAc,EAAE,EAAE;gBACrE,2CAA2C;gBAC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,EAAE,IAA2B;QACxD,MAAM,QAAQ,GAAG,IAAI,CAAC,OAAO,CAAC,GAAG,CAAC,KAAK,CAAC,IAAI,EAAE,CAAC;QAC/C,QAAQ,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;QACpB,IAAI,CAAC,OAAO,CAAC,GAAG,CAAC,KAAK,EAAE,QAAQ,CAAC,CAAC;QAClC,OAAO,IAAI,CAAC;IACd,CAAC;IAED,oDAAoD;IAC7C,aAAa,CAAC,KAAa;QAChC,OAAO,IAAI,CAAC,OAAO,CAAC,GAAG,CAAC,KAAK,CAAC,IAAI,EAAE,CAAC;IACvC,CAAC;IAED,yDAAyD;IAClD,MAAM;QACX,OAAO,CAAC,GAAG,IAAI,CAAC,OAAO,CAAC,IAAI,EAAE,CAAC,CAAC,IAAI,CAAC,CAAC,IAAI,EAAE,KAAK,EAAE,EAAE,CAAC,IAAI,GAAG,KAAK,CAAC,CAAC;IACtE,CAAC;CACF;AAED,OAAO,EAAE,qBAAqB,EAAE,YAAY,EAAE,CAAC","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/** The summary a task reports when it finishes. */\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/** The minimum a task needs from `env`: a D1 binding, when the repo has one. */\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/** The execution context, structurally. See {@link ScheduledControllerLike}. */\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 /** Factory Method for the recorder. Override in tests. */\n protected createRunRecorder(): TaskRunRecorder | null {\n return null;\n }\n\n /** Override to route this task's failures somewhere other than the console. */\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 | undefined;\n if (recorder && taskType !== null) {\n runId = await recorder.startRun({ taskType }).catch((error: unknown) => {\n // Losing the record must not lose the run.\n this.logger()('warn', `[${this.constructor.name}] failed to start task run record`);\n void error;\n return undefined;\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(() => undefined),\n fail: (errorMessage: string, partial?: Partial<TaskRunSummary>): Promise<void> =>\n recorder\n .failRun(runId, errorMessage, partial)\n .catch(warn('failed'))\n .then(() => undefined),\n skip: (reason?: string): Promise<void> =>\n recorder\n .skipRun(runId, reason)\n .catch(warn('skipped'))\n .then(() => undefined),\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 /** Every task in a phase, in registration order. */\n public tasksForPhase(phase: number): readonly AbstractScheduledTask[] {\n return this.byPhase.get(phase) ?? [];\n }\n\n /** The phases that have at least one task, ascending. */\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"]}
1
+ {
2
+ "version": 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": "AA8FA,MAAMA,EAA4B,CAACC,EAAOC,IAAW,CAC/CD,IAAU,OAAQ,QAAQ,KAAKC,CAAO,EACrC,QAAQ,MAAMA,CAAO,CAC5B,EAQA,MAAeC,CAAqB,CAUxB,aAAW,CACnB,OAAO,IACT,CAKU,mBAAiB,CACzB,OAAO,IACT,CAKU,QAAM,CACd,OAAOH,CACT,CAQO,MAAM,OAAOI,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,oBAAoBN,EAAOC,EAAKC,CAAG,EACzDE,GAAYC,GACd,MAAMD,EAAS,WAAWC,EAAOC,GAAU,CAAE,eAAgB,EAAG,YAAa,CAAC,CAAE,EAAE,MAAM,IAAK,CAC3F,KAAK,OAAM,EAAG,OAAQ,IAAI,KAAK,YAAY,IAAI,qCAAqC,CACtF,CAAC,CAEL,OAASC,EAAgB,CAEvB,GADA,KAAK,OAAM,EAAG,QAAS,IAAI,KAAK,YAAY,IAAI,kBAAkB,EAC9DH,GAAYC,EAAO,CACrB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,EAAOC,CAAK,CACpE",
6
+ "names": ["consoleLogger", "level", "message", "AbstractScheduledTask", "event", "env", "ctx", "taskType", "recorder", "runId", "result", "error", "applicationId", "warn", "op", "errorMessage", "partial", "reason", "TaskRegistry", "phase", "task", "existing", "left", "right"]
7
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@rexezuge/runtime",
3
- "version": "1.2.0",
3
+ "version": "1.4.0",
4
4
  "private": false,
5
5
  "license": "MIT",
6
6
  "repository": {
@@ -31,7 +31,7 @@
31
31
  },
32
32
  "description": "DI container, configuration, worker bases, logger, and KV cache for Cloudflare Workers.",
33
33
  "scripts": {
34
- "build": "tsc -p tsconfig.json",
34
+ "build": "tsc -p tsconfig.json && node ../../scripts/minify-dist.mjs",
35
35
  "typecheck": "tsc -p tsconfig.test.json --noEmit",
36
36
  "test": "vitest run"
37
37
  }