@milaboratories/pl-middle-layer 2.10.0 → 2.10.1
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.cjs +1 -1
- package/dist/index.d.ts +2 -2
- package/dist/index.js +1 -1
- package/dist/middle_layer/build_stamp.cjs +1 -1
- package/dist/middle_layer/build_stamp.js +1 -1
- package/dist/middle_layer/middle_layer.cjs +4 -3
- package/dist/middle_layer/middle_layer.cjs.map +1 -1
- package/dist/middle_layer/middle_layer.d.ts.map +1 -1
- package/dist/middle_layer/middle_layer.js +3 -2
- package/dist/middle_layer/middle_layer.js.map +1 -1
- package/dist/middle_layer/project.cjs +6 -21
- package/dist/middle_layer/project.cjs.map +1 -1
- package/dist/middle_layer/project.d.ts +1 -1
- package/dist/middle_layer/project.d.ts.map +1 -1
- package/dist/middle_layer/project.js +5 -19
- package/dist/middle_layer/project.js.map +1 -1
- package/dist/model/block_pack_spec.cjs.map +1 -1
- package/dist/model/block_pack_spec.d.ts +3 -3
- package/dist/model/block_pack_spec.d.ts.map +1 -1
- package/dist/model/block_pack_spec.js.map +1 -1
- package/dist/model/template_spec.d.ts +18 -0
- package/dist/model/template_spec.d.ts.map +1 -1
- package/dist/mutator/block-pack/block_pack.cjs +89 -2
- package/dist/mutator/block-pack/block_pack.cjs.map +1 -1
- package/dist/mutator/block-pack/block_pack.d.ts +16 -0
- package/dist/mutator/block-pack/block_pack.d.ts.map +1 -1
- package/dist/mutator/block-pack/block_pack.js +90 -4
- package/dist/mutator/block-pack/block_pack.js.map +1 -1
- package/dist/mutator/block-pack/required_capabilities.cjs +16 -0
- package/dist/mutator/block-pack/required_capabilities.cjs.map +1 -1
- package/dist/mutator/block-pack/required_capabilities.js +16 -1
- package/dist/mutator/block-pack/required_capabilities.js.map +1 -1
- package/dist/mutator/template/template_cache.cjs +8 -1
- package/dist/mutator/template/template_cache.cjs.map +1 -1
- package/dist/mutator/template/template_cache.d.ts +7 -3
- package/dist/mutator/template/template_cache.d.ts.map +1 -1
- package/dist/mutator/template/template_cache.js +8 -1
- package/dist/mutator/template/template_cache.js.map +1 -1
- package/package.json +2 -2
- package/src/middle_layer/middle_layer.ts +4 -2
- package/src/middle_layer/project.ts +7 -27
- package/src/model/block_pack_spec.ts +3 -2
- package/src/model/template_spec.ts +21 -0
- package/src/mutator/block-pack/block_pack.test.ts +10 -1
- package/src/mutator/block-pack/block_pack.ts +102 -2
- package/src/mutator/block-pack/block_pack_load.test.ts +52 -0
- package/src/mutator/block-pack/required_capabilities.ts +25 -0
- package/src/mutator/project-v3.test.ts +27 -16
- package/src/mutator/template/template_cache.ts +26 -3
- package/src/test/block_packs.ts +12 -0
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"template_cache.cjs","names":["resourceType","notEmpty","createHash","PlTemplateLibV1","PlTemplateSoftwareV1","PlWasmV1","PlTemplateV1","field","PlTemplateOverrideV1","ensureSignedResourceIdNotNull","toGlobalResourceId","parseTemplate","_","getDebugFlags"],"sources":["../../../src/mutator/template/template_cache.ts"],"sourcesContent":["import { createHash } from \"node:crypto\";\nimport type {\n AnyResourceRef,\n PlClient,\n PlTransaction,\n SignedResourceId,\n ResourceRef,\n} from \"@milaboratories/pl-client\";\nimport {\n ensureSignedResourceIdNotNull,\n field,\n resourceType,\n toGlobalResourceId,\n} from \"@milaboratories/pl-client\";\nimport {\n parseTemplate,\n PlTemplateLibV1,\n PlTemplateOverrideV1,\n PlTemplateSoftwareV1,\n PlTemplateV1,\n PlWasmV1,\n} from \"@milaboratories/pl-model-backend\";\nimport type {\n CompiledTemplateV3,\n TemplateData,\n TemplateDataV3,\n TemplateLibData,\n TemplateLibDataV3,\n TemplateSoftwareData,\n TemplateSoftwareDataV3,\n TemplateWasmDataV3,\n} from \"@milaboratories/pl-model-backend\";\nimport { notEmpty } from \"@milaboratories/ts-helpers\";\nimport type { BlockPackSpecPrepared } from \"../../model\";\nimport type { TemplateSpecPrepared } from \"../../model/template_spec\";\nimport { getDebugFlags } from \"../../debug\";\n\nexport const TemplateCacheType = resourceType(\"TemplateCache\", \"1\");\n\nexport const TemplateCacheFieldName = \"__templateCache\";\nconst BATCH_SIZE = 50;\n/** @internal exported for testing */\nexport const GC_ACCESS_THRESHOLD = 30;\n/** @internal exported for testing */\nexport const GC_MAX_ENTRIES = 3000;\n/** @internal exported for testing */\nexport const ACCESS_COUNT_KEY = \"_accessCount\";\n/** @internal exported for testing */\nexport const ACCESS_KEY_PREFIX = \"access_\";\n\nexport type TemplateCacheStat = {\n totalMs: number;\n flattenMs: number;\n cacheInitMs: number;\n materializeMs: number;\n totalNodes: number;\n cacheHits: number;\n cacheMisses: number;\n batchCount: number;\n happyPath: boolean;\n gcTriggered: boolean;\n retries: number;\n templateFormat: string;\n};\n\nfunction initialStat(): TemplateCacheStat {\n return {\n totalMs: 0,\n flattenMs: 0,\n cacheInitMs: 0,\n materializeMs: 0,\n totalNodes: 0,\n cacheHits: 0,\n cacheMisses: 0,\n batchCount: 0,\n happyPath: false,\n gcTriggered: false,\n retries: 0,\n templateFormat: \"\",\n };\n}\n\ninterface CacheableNode {\n /** SHA-256 content hash (includes all descendant content) */\n hash: string;\n /** Creates this node's resource in a transaction.\n * childRefs maps child hash → already-resolved ResourceRef or SignedResourceId */\n create: (tx: PlTransaction, childRefs: ReadonlyMap<string, AnyResourceRef>) => ResourceRef;\n /** Hashes of direct child nodes this node depends on */\n childHashes: string[];\n}\n\nfunction getSourceCode(name: string, sources: Record<string, string>, sourceHash: string): string {\n return notEmpty(\n sources[sourceHash],\n `trying to get \"${name}\" source: sources map doesn't contain source hash ${sourceHash}`,\n );\n}\n\n/**\n * Bottom-up hash composition: each node hashes its OWN content + child hash STRINGS.\n * This means each unique node is hashed exactly once → O(n) instead of O(n * depth).\n */\n\n// V2 leaf hashes (libs, software — no children)\n\nfunction hashLibV2(lib: TemplateLibData): string {\n return createHash(\"sha256\")\n .update(PlTemplateLibV1.type.name)\n .update(PlTemplateLibV1.type.version)\n .update(lib.name)\n .update(lib.version)\n .update(lib.src)\n .digest(\"hex\");\n}\n\nfunction hashSoftwareV2(sw: TemplateSoftwareData): string {\n return createHash(\"sha256\")\n .update(PlTemplateSoftwareV1.type.name)\n .update(PlTemplateSoftwareV1.type.version)\n .update(sw.name)\n .update(sw.version)\n .update(sw.src)\n .digest(\"hex\");\n}\n\n// V3 leaf hashes — use sourceHash directly instead of resolving source content\n\nfunction hashLibV3(lib: TemplateLibDataV3): string {\n return createHash(\"sha256\")\n .update(PlTemplateLibV1.type.name)\n .update(PlTemplateLibV1.type.version)\n .update(lib.name)\n .update(lib.version)\n .update(lib.sourceHash)\n .digest(\"hex\");\n}\n\nfunction hashSoftwareV3(sw: TemplateSoftwareDataV3): string {\n return createHash(\"sha256\")\n .update(PlTemplateSoftwareV1.type.name)\n .update(PlTemplateSoftwareV1.type.version)\n .update(sw.name)\n .update(sw.version)\n .update(sw.sourceHash)\n .digest(\"hex\");\n}\n\nfunction hashWasmV3(wasm: TemplateWasmDataV3): string {\n return createHash(\"sha256\")\n .update(PlWasmV1.type.name)\n .update(PlWasmV1.type.version)\n .update(wasm.name)\n .update(wasm.version)\n .update(wasm.sourceHash)\n .digest(\"hex\");\n}\n\n// ─── Tree flattening ─────────────────────────────────────────────────────────\n\nfunction flattenV2Tree(data: TemplateData): CacheableNode[] {\n const nodes: CacheableNode[] = [];\n const seen = new Set<string>();\n\n function processLib(lib: TemplateLibData): string {\n const hash = hashLibV2(lib);\n if (!seen.has(hash)) {\n seen.add(hash);\n nodes.push({\n hash,\n create: (tx) =>\n tx.createValue(\n PlTemplateLibV1.type,\n JSON.stringify(PlTemplateLibV1.fromV2Data(lib).data),\n ),\n childHashes: [],\n });\n }\n return hash;\n }\n\n function processSoftware(sw: TemplateSoftwareData): string {\n const hash = hashSoftwareV2(sw);\n if (!seen.has(hash)) {\n seen.add(hash);\n nodes.push({\n hash,\n create: (tx) => {\n const swData = PlTemplateSoftwareV1.fromV2Data(sw);\n const ref = tx.createStruct(PlTemplateSoftwareV1.type, swData.data);\n tx.setKValue(ref, PlTemplateSoftwareV1.metaNameKey, JSON.stringify(swData.name));\n tx.lock(ref);\n return ref;\n },\n childHashes: [],\n });\n }\n return hash;\n }\n\n function processTemplate(tpl: TemplateData): string {\n // Process children first (bottom-up) — their hashes are computed before ours\n const childHashes: string[] = [];\n const children: { fieldName: string; hash: string }[] = [];\n\n for (const [libId, lib] of Object.entries(tpl.libs ?? {})) {\n const h = processLib(lib);\n childHashes.push(h);\n children.push({ fieldName: `${PlTemplateV1.libPrefix}/${libId}`, hash: h });\n }\n for (const [swId, sw] of Object.entries(tpl.software ?? {})) {\n const h = processSoftware(sw);\n childHashes.push(h);\n children.push({ fieldName: `${PlTemplateV1.softPrefix}/${swId}`, hash: h });\n }\n for (const [swId, sw] of Object.entries(tpl.assets ?? {})) {\n const h = processSoftware(sw);\n childHashes.push(h);\n children.push({ fieldName: `${PlTemplateV1.softPrefix}/${swId}`, hash: h });\n }\n for (const [tplId, sub] of Object.entries(tpl.templates ?? {})) {\n const h = processTemplate(sub);\n childHashes.push(h);\n children.push({ fieldName: `${PlTemplateV1.tplPrefix}/${tplId}`, hash: h });\n }\n\n // Compose hash from own content + child hash strings (NOT child content)\n const h = createHash(\"sha256\")\n .update(PlTemplateV1.type.name)\n .update(PlTemplateV1.type.version)\n .update(tpl.hashOverride ?? \"no-override\")\n .update(tpl.name)\n .update(tpl.version)\n .update(tpl.src);\n for (const child of children) {\n h.update(\"child:\" + child.fieldName + \":\" + child.hash);\n }\n const hash = h.digest(\"hex\");\n\n if (seen.has(hash)) return hash;\n seen.add(hash);\n nodes.push({\n hash,\n create: (tx, childRefs) => {\n const tplRef = tx.createStruct(\n PlTemplateV1.type,\n JSON.stringify(PlTemplateV1.fromV2Data(tpl).data),\n );\n for (const child of children) {\n const fld = field(tplRef, child.fieldName);\n tx.createField(fld, \"Input\");\n tx.setField(fld, notEmpty(childRefs.get(child.hash), `missing child ref ${child.hash}`));\n }\n tx.lock(tplRef);\n\n if (!tpl.hashOverride) return tplRef;\n\n const overrideRef = tx.createStruct(\n PlTemplateOverrideV1.type,\n JSON.stringify(PlTemplateOverrideV1.fromV2Data(tpl)),\n );\n const overrideFld = PlTemplateOverrideV1.tplField(overrideRef);\n tx.createField(overrideFld, \"Service\");\n tx.setField(overrideFld, tplRef);\n tx.lock(overrideRef);\n return overrideRef;\n },\n childHashes,\n });\n\n return hash;\n }\n\n processTemplate(data);\n return nodes;\n}\n\nfunction flattenV3Tree(data: CompiledTemplateV3): CacheableNode[] {\n const nodes: CacheableNode[] = [];\n const seen = new Set<string>();\n const sources = data.hashToSource;\n\n function processLib(lib: TemplateLibDataV3): string {\n const hash = hashLibV3(lib);\n if (!seen.has(hash)) {\n seen.add(hash);\n nodes.push({\n hash,\n create: (tx) =>\n tx.createValue(\n PlTemplateLibV1.type,\n JSON.stringify(\n PlTemplateLibV1.fromV3Data(lib, getSourceCode(lib.name, sources, lib.sourceHash))\n .data,\n ),\n ),\n childHashes: [],\n });\n }\n return hash;\n }\n\n function processSoftware(sw: TemplateSoftwareDataV3): string {\n const hash = hashSoftwareV3(sw);\n if (!seen.has(hash)) {\n seen.add(hash);\n nodes.push({\n hash,\n create: (tx) => {\n const swData = PlTemplateSoftwareV1.fromV3Data(\n sw,\n getSourceCode(sw.name, sources, sw.sourceHash),\n );\n const ref = tx.createStruct(PlTemplateSoftwareV1.type, swData.data);\n tx.setKValue(ref, PlTemplateSoftwareV1.metaNameKey, JSON.stringify(swData.name));\n tx.lock(ref);\n return ref;\n },\n childHashes: [],\n });\n }\n return hash;\n }\n\n function processWasm(wasm: TemplateWasmDataV3): string {\n const hash = hashWasmV3(wasm);\n if (!seen.has(hash)) {\n seen.add(hash);\n nodes.push({\n hash,\n create: (tx) =>\n tx.createValue(\n PlWasmV1.type,\n JSON.stringify(\n PlWasmV1.fromV3Data(wasm, getSourceCode(wasm.name, sources, wasm.sourceHash)).data,\n ),\n ),\n childHashes: [],\n });\n }\n return hash;\n }\n\n function processTemplate(tpl: TemplateDataV3): string {\n // Defensive: a template can carry no embedded version at runtime even\n // though the type says `string` — the compiler writes `packageJson.version`\n // unchecked, so a template built from a package with no `version` field\n // yields undefined. Identity is fully covered by name + sourceHash, so the\n // placeholder is safe for both the cache key and the backend resource's\n // required Version field.\n const version = tpl.version ?? \"0.0.0\";\n\n // Process children first (bottom-up)\n const childHashes: string[] = [];\n const children: { fieldName: string; hash: string }[] = [];\n\n for (const [libId, lib] of Object.entries(tpl.libs ?? {})) {\n const h = processLib(lib);\n childHashes.push(h);\n children.push({ fieldName: `${PlTemplateV1.libPrefix}/${libId}`, hash: h });\n }\n for (const [swId, sw] of Object.entries(tpl.software ?? {})) {\n const h = processSoftware(sw);\n childHashes.push(h);\n children.push({ fieldName: `${PlTemplateV1.softPrefix}/${swId}`, hash: h });\n }\n for (const [swId, sw] of Object.entries(tpl.assets ?? {})) {\n const h = processSoftware(sw);\n childHashes.push(h);\n children.push({ fieldName: `${PlTemplateV1.softPrefix}/${swId}`, hash: h });\n }\n for (const [tplId, sub] of Object.entries(tpl.templates ?? {})) {\n const h = processTemplate(sub);\n childHashes.push(h);\n children.push({ fieldName: `${PlTemplateV1.tplPrefix}/${tplId}`, hash: h });\n }\n for (const [wasmId, wasm] of Object.entries(tpl.wasm ?? {})) {\n const h = processWasm(wasm);\n childHashes.push(h);\n children.push({ fieldName: `${PlTemplateV1.wasmPrefix}/${wasmId}`, hash: h });\n }\n\n // Compose hash from own content + child hash strings (NOT child content).\n // Uses sourceHash directly — it already uniquely identifies the source.\n const h = createHash(\"sha256\")\n .update(PlTemplateV1.type.name)\n .update(PlTemplateV1.type.version)\n .update(tpl.hashOverride ?? \"no-override\")\n .update(tpl.name)\n .update(version)\n .update(tpl.sourceHash);\n for (const child of children) {\n h.update(\"child:\" + child.fieldName + \":\" + child.hash);\n }\n const hash = h.digest(\"hex\");\n\n if (seen.has(hash)) return hash;\n seen.add(hash);\n nodes.push({\n hash,\n create: (tx, childRefs) => {\n const sourceCode = getSourceCode(tpl.name, sources, tpl.sourceHash);\n const tplRef = tx.createStruct(\n PlTemplateV1.type,\n JSON.stringify(PlTemplateV1.fromV3Data({ ...tpl, version }, sourceCode).data),\n );\n for (const child of children) {\n const fld = field(tplRef, child.fieldName);\n tx.createField(fld, \"Input\");\n tx.setField(fld, notEmpty(childRefs.get(child.hash), `missing child ref ${child.hash}`));\n }\n tx.lock(tplRef);\n\n if (!tpl.hashOverride) return tplRef;\n\n const overrideRef = tx.createStruct(\n PlTemplateOverrideV1.type,\n JSON.stringify(PlTemplateOverrideV1.fromV3Data(tpl)),\n );\n const overrideFld = PlTemplateOverrideV1.tplField(overrideRef);\n tx.createField(overrideFld, \"Service\");\n tx.setField(overrideFld, tplRef);\n tx.lock(overrideRef);\n return overrideRef;\n },\n childHashes,\n });\n\n return hash;\n }\n\n processTemplate(data.template);\n return nodes;\n}\n\n/** Flatten template tree into a topologically ordered list of cacheable nodes (leaves first). */\nexport function flattenTemplateTree(data: TemplateData | CompiledTemplateV3): CacheableNode[] {\n if (data.type === \"pl.tengo-template.v2\") {\n return flattenV2Tree(data);\n } else {\n return flattenV3Tree(data);\n }\n}\n\n/** In-memory cache for the TemplateCache SignedResourceId per PlClient instance. */\nconst cacheRidMap = new WeakMap<PlClient, SignedResourceId>();\n\n/** Clear the in-memory cacheRid entry (call on errors referencing the cache resource). */\nexport function invalidateTemplateCacheId(pl: PlClient): void {\n cacheRidMap.delete(pl);\n}\n\n/** Find or create the TemplateCache/1 resource on user root. */\nexport async function getOrCreateTemplateCache(pl: PlClient): Promise<SignedResourceId> {\n // Check in-memory cache first (0ms after first call)\n const cached = cacheRidMap.get(pl);\n if (cached !== undefined) return cached;\n\n // Try read-only check\n const existing = await pl.withReadTx(\"templateCache:check\", async (tx) => {\n const fd = await tx.getFieldIfExists(field(pl.clientRoot, TemplateCacheFieldName));\n return fd ? ensureSignedResourceIdNotNull(fd.value) : undefined;\n });\n if (existing) {\n cacheRidMap.set(pl, existing);\n return existing;\n }\n\n const result = await pl.withWriteTx(\"templateCache:init\", async (tx) => {\n // Double-check inside write tx (another instance may have created it)\n const fd = await tx.getFieldIfExists(field(pl.clientRoot, TemplateCacheFieldName));\n if (fd) return ensureSignedResourceIdNotNull(fd.value);\n\n const cache = tx.createStruct(TemplateCacheType);\n tx.createField(field(pl.clientRoot, TemplateCacheFieldName), \"Dynamic\", cache);\n tx.lock(cache);\n await tx.commit();\n return await cache.globalId;\n });\n cacheRidMap.set(pl, result);\n return result;\n}\n\n/** Remove the template cache from user root. */\nexport async function dropTemplateCache(pl: PlClient): Promise<void> {\n await pl.withWriteTx(\"templateCache:drop\", async (tx) => {\n const cacheField = field(pl.clientRoot, TemplateCacheFieldName);\n const fd = await tx.getFieldIfExists(cacheField);\n if (fd) {\n tx.removeField(cacheField);\n await tx.commit();\n }\n });\n invalidateTemplateCacheId(pl);\n}\n\n/**\n * Run count-based garbage collection on the template cache.\n * Evicts least-recently-used entries when the cache exceeds maxEntries.\n * Always resets the access counter to 0.\n *\n * @internal exported for testing (maxEntries parameter allows low thresholds in tests)\n * @returns true if entries were evicted\n */\nexport async function runGc(\n pl: PlClient,\n cacheRid: SignedResourceId,\n maxEntries: number = GC_MAX_ENTRIES,\n): Promise<boolean> {\n return await pl.withWriteTx(\"templateCache:gc\", async (tx) => {\n const kvs = await tx.listKeyValuesString(cacheRid);\n const entries: { hash: string; timestamp: number }[] = [];\n for (const { key, value } of kvs) {\n if (!key.startsWith(ACCESS_KEY_PREFIX)) continue;\n entries.push({\n hash: key.slice(ACCESS_KEY_PREFIX.length),\n timestamp: parseInt(value, 10),\n });\n }\n\n // Always reset counter\n tx.setKValue(cacheRid, ACCESS_COUNT_KEY, \"0\");\n\n if (entries.length <= maxEntries) {\n await tx.commit();\n return false;\n }\n\n // Sort oldest first, evict until under limit\n entries.sort((a, b) => a.timestamp - b.timestamp);\n const toEvict = entries.length - maxEntries;\n for (let i = 0; i < toEvict; i++) {\n tx.removeField(field(cacheRid, entries[i].hash));\n tx.deleteKValue(cacheRid, ACCESS_KEY_PREFIX + entries[i].hash);\n }\n\n await tx.commit();\n return true;\n });\n}\n\n/** Create a batch of cache nodes in the current transaction. */\nfunction createBatchNodes(\n tx: PlTransaction,\n cacheRid: SignedResourceId,\n batch: CacheableNode[],\n resolvedIds: ReadonlyMap<string, SignedResourceId>,\n newRefs: Map<string, ResourceRef>,\n now: string,\n): void {\n for (const node of batch) {\n const childRefs = new Map<string, AnyResourceRef>();\n for (const ch of node.childHashes) {\n const resolved = resolvedIds.get(ch) ?? newRefs.get(ch);\n if (resolved === undefined) {\n throw new Error(`BUG: child ${ch} not resolved`);\n }\n childRefs.set(ch, resolved);\n }\n const ref = node.create(tx, childRefs);\n newRefs.set(node.hash, ref);\n tx.createField(field(cacheRid, node.hash), \"Dynamic\", ref);\n tx.setKValue(cacheRid, ACCESS_KEY_PREFIX + node.hash, now);\n }\n}\n\n/**\n * Materialize a template tree via the cache using \"probe all + batched creation\".\n *\n * Phase 1 (single write tx):\n * - Check existence of ALL hashes in one roundtrip\n * - Happy path: if root cached, update access tracking and return\n * - Otherwise: fetch ResourceIds for all cache hits, create first batch of missing nodes\n *\n * Phase 2..N (one write tx per batch):\n * - Create remaining missing nodes in BATCH_SIZE chunks\n *\n * @returns root SignedResourceId and current access count (for GC decision)\n */\nasync function materialize(\n pl: PlClient,\n cacheRid: SignedResourceId,\n rootHash: string,\n nodes: CacheableNode[],\n stat: TemplateCacheStat,\n): Promise<{ rootId: SignedResourceId; accessCount: number }> {\n const allHashes = nodes.map((n) => n.hash);\n const resolvedIds = new Map<string, SignedResourceId>();\n\n // Phase 1: probe all + first batch\n const phase1 = await pl.withWriteTx(\"templateCache:materialize\", async (tx) => {\n // 1 roundtrip: check all hashes + read access count\n const [exists, countStr] = await Promise.all([\n Promise.all(allHashes.map((h) => tx.fieldExists(field(cacheRid, h)))),\n tx.getKValueStringIfExists(cacheRid, ACCESS_COUNT_KEY),\n ]);\n\n const prevCount = countStr ? parseInt(countStr, 10) : 0;\n const newCount = prevCount + 1;\n const now = Date.now().toString();\n const rootIdx = allHashes.length - 1;\n\n // Happy path: root already cached\n if (exists[rootIdx]) {\n const rootFd = await tx.getField(field(cacheRid, rootHash));\n const rootRid = ensureSignedResourceIdNotNull(rootFd.value);\n tx.setKValue(cacheRid, ACCESS_KEY_PREFIX + rootHash, now);\n tx.setKValue(cacheRid, ACCESS_COUNT_KEY, newCount.toString());\n await tx.commit();\n stat.happyPath = true;\n stat.cacheHits = stat.totalNodes;\n stat.batchCount = 1;\n return { done: true as const, rootId: rootRid, accessCount: newCount };\n }\n\n // Fetch ResourceIds for all cache hits (1 roundtrip)\n const hitIndices: number[] = [];\n for (let i = 0; i < allHashes.length; i++) {\n if (exists[i]) hitIndices.push(i);\n }\n\n if (hitIndices.length > 0) {\n const hitFields = await Promise.all(\n hitIndices.map((i) => tx.getField(field(cacheRid, allHashes[i]))),\n );\n for (let j = 0; j < hitIndices.length; j++) {\n resolvedIds.set(\n allHashes[hitIndices[j]],\n ensureSignedResourceIdNotNull(hitFields[j].value),\n );\n }\n }\n stat.cacheHits = hitIndices.length;\n\n // Missing nodes (topo order preserved from flatten)\n const missing = nodes.filter((n) => !resolvedIds.has(n.hash));\n stat.cacheMisses = missing.length;\n\n // Create first batch of missing nodes\n const firstBatch = missing.slice(0, BATCH_SIZE);\n const newRefs = new Map<string, ResourceRef>();\n createBatchNodes(tx, cacheRid, firstBatch, resolvedIds, newRefs, now);\n\n // Update access tracking for cache hits\n for (const i of hitIndices) {\n tx.setKValue(cacheRid, ACCESS_KEY_PREFIX + allHashes[i], now);\n }\n tx.setKValue(cacheRid, ACCESS_COUNT_KEY, newCount.toString());\n\n await tx.commit();\n\n // Resolve new refs to global IDs (after commit)\n for (const [hash, ref] of newRefs) {\n resolvedIds.set(hash, await toGlobalResourceId(ref));\n }\n\n return {\n done: false as const,\n remaining: missing.slice(BATCH_SIZE),\n accessCount: newCount,\n };\n });\n\n if (phase1.done) {\n return { rootId: phase1.rootId, accessCount: phase1.accessCount };\n }\n\n stat.batchCount = 1;\n\n // Phase 2+: remaining batches\n const { remaining } = phase1;\n for (let i = 0; i < remaining.length; i += BATCH_SIZE) {\n const batch = remaining.slice(i, i + BATCH_SIZE);\n stat.batchCount++;\n\n await pl.withWriteTx(\"templateCache:create\", async (tx) => {\n const newRefs = new Map<string, ResourceRef>();\n const now = Date.now().toString();\n createBatchNodes(tx, cacheRid, batch, resolvedIds, newRefs, now);\n await tx.commit();\n\n for (const [hash, ref] of newRefs) {\n resolvedIds.set(hash, await toGlobalResourceId(ref));\n }\n });\n }\n\n const rootId = resolvedIds.get(rootHash);\n if (!rootId) throw new Error(\"BUG: root hash not resolved after all batches\");\n return { rootId, accessCount: phase1.accessCount };\n}\n\n/**\n * Materialize a template tree via the cache.\n * Manages its own transactions internally — do NOT call inside an existing tx.\n *\n * @returns concrete SignedResourceId of the root template\n */\nexport async function loadTemplateCached(\n pl: PlClient,\n spec: TemplateSpecPrepared,\n options?: { cacheResourceId?: SignedResourceId },\n): Promise<SignedResourceId> {\n const stat = initialStat();\n const t0 = performance.now();\n\n try {\n // Parse to data if needed\n let tplData: TemplateData | CompiledTemplateV3;\n switch (spec.type) {\n case \"explicit\":\n tplData = parseTemplate(spec.content);\n break;\n case \"prepared\":\n tplData = spec.data;\n break;\n case \"cached\":\n return spec.resourceId;\n case \"from-registry\":\n throw new Error(\n \"loadTemplateCached does not support from-registry specs; use loadTemplate instead\",\n );\n default: {\n const _: never = spec;\n throw new Error(`unexpected spec type: ${(_ as any).type}`);\n }\n }\n\n stat.templateFormat = tplData.type;\n\n // Flatten to ordered nodes\n const tFlatten = performance.now();\n const nodes = flattenTemplateTree(tplData);\n stat.flattenMs = performance.now() - tFlatten;\n if (nodes.length === 0) throw new Error(\"template tree produced no nodes\");\n\n stat.totalNodes = nodes.length;\n const rootHash = nodes[nodes.length - 1].hash;\n\n // Resolve or create cache resource\n const tCacheInit = performance.now();\n const cacheRid = options?.cacheResourceId ?? (await getOrCreateTemplateCache(pl));\n stat.cacheInitMs = performance.now() - tCacheInit;\n\n // Retry loop: if a write tx fails (e.g. concurrent GC invalidated a cached resource),\n // restart materialization from scratch.\n const MAX_RETRIES = 3;\n for (let attempt = 0; attempt < MAX_RETRIES; attempt++) {\n try {\n const tMat = performance.now();\n const result = await materialize(pl, cacheRid, rootHash, nodes, stat);\n stat.materializeMs = performance.now() - tMat;\n stat.retries = attempt;\n\n // GC in separate tx if access count exceeded threshold\n if (result.accessCount >= GC_ACCESS_THRESHOLD) {\n await runGc(pl, cacheRid);\n stat.gcTriggered = true;\n }\n\n return result.rootId;\n } catch (e) {\n if (attempt === MAX_RETRIES - 1) throw e;\n // Retry from scratch — previous batch results may reference GC'd resources\n stat.cacheHits = 0;\n stat.cacheMisses = 0;\n }\n }\n\n throw new Error(\"BUG: unreachable\");\n } finally {\n stat.totalMs = performance.now() - t0;\n if (getDebugFlags().logTemplateCacheStat) {\n console.log(`[templateCache] ${JSON.stringify(stat)}`);\n }\n }\n}\n\n/**\n * Pre-materialize a block pack's template via cache.\n * Returns a copy of the spec with the template replaced by a cached reference.\n * If the template is already cached, returns the spec unchanged.\n */\nexport async function cacheBlockPackTemplate(\n pl: PlClient,\n spec: BlockPackSpecPrepared,\n options?: { cacheResourceId?: SignedResourceId },\n): Promise<BlockPackSpecPrepared> {\n if (spec.template.type === \"cached\") return spec;\n\n const resourceId = await loadTemplateCached(pl, spec.template, options);\n return {\n ...spec,\n template: { type: \"cached\", resourceId },\n };\n}\n"],"mappings":";;;;;;AAqCA,MAAa,qBAAA,GAAoBA,0BAAAA,aAAAA,CAAa,iBAAiB,GAAG;AAElE,MAAa,yBAAyB;AACtC,MAAM,aAAa;;AAEnB,MAAa,sBAAsB;;AAEnC,MAAa,iBAAiB;;AAE9B,MAAa,mBAAmB;;AAEhC,MAAa,oBAAoB;AAiBjC,SAAS,cAAiC;CACxC,OAAO;EACL,SAAS;EACT,WAAW;EACX,aAAa;EACb,eAAe;EACf,YAAY;EACZ,W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Y,IAAI,IAAI;EAIvC,MAAM,cAAc;EACpB,KAAK,IAAI,UAAU,GAAG,UAAU,aAAa,WAC3C,IAAI;GACF,MAAM,OAAO,YAAY,IAAI;GAC7B,MAAM,SAAS,MAAM,YAAY,IAAI,UAAU,UAAU,OAAO,IAAI;GACpE,KAAK,gBAAgB,YAAY,IAAI,IAAI;GACzC,KAAK,UAAU;GAGf,IAAI,OAAO,eAAA,IAAoC;IAC7C,MAAM,MAAM,IAAI,QAAQ;IACxB,KAAK,cAAc;GACrB;GAEA,OAAO,OAAO;EAChB,SAAS,GAAG;GACV,IAAI,YAAY,GAAiB,MAAM;GAEvC,KAAK,YAAY;GACjB,KAAK,cAAc;EACrB;EAGF,MAAM,IAAI,MAAM,kBAAkB;CACpC,UAAU;EACR,KAAK,UAAU,YAAY,IAAI,IAAI;EACnC,IAAIC,cAAAA,cAAc,CAAC,CAAC,sBAClB,QAAQ,IAAI,mBAAmB,KAAK,UAAU,IAAI,GAAG;CAEzD;AACF;;;;;;AAOA,eAAsB,uBACpB,IACA,MACA,SACgC;CAChC,IAAI,KAAK,SAAS,SAAS,UAAU,OAAO;CAE5C,MAAM,aAAa,MAAM,mBAAmB,IAAI,KAAK,UAAU,OAAO;CACtE,OAAO;EACL,GAAG;EACH,UAAU;GAAE,MAAM;GAAU;EAAW;CACzC;AACF"}
|
|
1
|
+
{"version":3,"file":"template_cache.cjs","names":["resourceType","notEmpty","createHash","PlTemplateLibV1","PlTemplateSoftwareV1","PlWasmV1","PlTemplateV1","field","PlTemplateOverrideV1","ensureSignedResourceIdNotNull","toGlobalResourceId","parseTemplate","_","getDebugFlags"],"sources":["../../../src/mutator/template/template_cache.ts"],"sourcesContent":["import { createHash } from \"node:crypto\";\nimport type {\n AnyResourceRef,\n PlClient,\n PlTransaction,\n SignedResourceId,\n ResourceRef,\n} from \"@milaboratories/pl-client\";\nimport {\n ensureSignedResourceIdNotNull,\n field,\n resourceType,\n toGlobalResourceId,\n} from \"@milaboratories/pl-client\";\nimport {\n parseTemplate,\n PlTemplateLibV1,\n PlTemplateOverrideV1,\n PlTemplateSoftwareV1,\n PlTemplateV1,\n PlWasmV1,\n} from \"@milaboratories/pl-model-backend\";\nimport type {\n CompiledTemplateV3,\n TemplateData,\n TemplateDataV3,\n TemplateLibData,\n TemplateLibDataV3,\n TemplateSoftwareData,\n TemplateSoftwareDataV3,\n TemplateWasmDataV3,\n} from \"@milaboratories/pl-model-backend\";\nimport { notEmpty } from \"@milaboratories/ts-helpers\";\nimport type { BlockPackSpecPrepared } from \"../../model\";\nimport type { InstallablePackTemplate, TemplateSpecPrepared } from \"../../model/template_spec\";\nimport type { BlockPackPreparer } from \"../block-pack/block_pack\";\nimport { throwIfMissingServerCapabilities } from \"../block-pack/required_capabilities\";\nimport { getDebugFlags } from \"../../debug\";\n\nexport const TemplateCacheType = resourceType(\"TemplateCache\", \"1\");\n\nexport const TemplateCacheFieldName = \"__templateCache\";\nconst BATCH_SIZE = 50;\n/** @internal exported for testing */\nexport const GC_ACCESS_THRESHOLD = 30;\n/** @internal exported for testing */\nexport const GC_MAX_ENTRIES = 3000;\n/** @internal exported for testing */\nexport const ACCESS_COUNT_KEY = \"_accessCount\";\n/** @internal exported for testing */\nexport const ACCESS_KEY_PREFIX = \"access_\";\n\nexport type TemplateCacheStat = {\n totalMs: number;\n flattenMs: number;\n cacheInitMs: number;\n materializeMs: number;\n totalNodes: number;\n cacheHits: number;\n cacheMisses: number;\n batchCount: number;\n happyPath: boolean;\n gcTriggered: boolean;\n retries: number;\n templateFormat: string;\n};\n\nfunction initialStat(): TemplateCacheStat {\n return {\n totalMs: 0,\n flattenMs: 0,\n cacheInitMs: 0,\n materializeMs: 0,\n totalNodes: 0,\n cacheHits: 0,\n cacheMisses: 0,\n batchCount: 0,\n happyPath: false,\n gcTriggered: false,\n retries: 0,\n templateFormat: \"\",\n };\n}\n\ninterface CacheableNode {\n /** SHA-256 content hash (includes all descendant content) */\n hash: string;\n /** Creates this node's resource in a transaction.\n * childRefs maps child hash → already-resolved ResourceRef or SignedResourceId */\n create: (tx: PlTransaction, childRefs: ReadonlyMap<string, AnyResourceRef>) => ResourceRef;\n /** Hashes of direct child nodes this node depends on */\n childHashes: string[];\n}\n\nfunction getSourceCode(name: string, sources: Record<string, string>, sourceHash: string): string {\n return notEmpty(\n sources[sourceHash],\n `trying to get \"${name}\" source: sources map doesn't contain source hash ${sourceHash}`,\n );\n}\n\n/**\n * Bottom-up hash composition: each node hashes its OWN content + child hash STRINGS.\n * This means each unique node is hashed exactly once → O(n) instead of O(n * depth).\n */\n\n// V2 leaf hashes (libs, software — no children)\n\nfunction hashLibV2(lib: TemplateLibData): string {\n return createHash(\"sha256\")\n .update(PlTemplateLibV1.type.name)\n .update(PlTemplateLibV1.type.version)\n .update(lib.name)\n .update(lib.version)\n .update(lib.src)\n .digest(\"hex\");\n}\n\nfunction hashSoftwareV2(sw: TemplateSoftwareData): string {\n return createHash(\"sha256\")\n .update(PlTemplateSoftwareV1.type.name)\n .update(PlTemplateSoftwareV1.type.version)\n .update(sw.name)\n .update(sw.version)\n .update(sw.src)\n .digest(\"hex\");\n}\n\n// V3 leaf hashes — use sourceHash directly instead of resolving source content\n\nfunction hashLibV3(lib: TemplateLibDataV3): string {\n return createHash(\"sha256\")\n .update(PlTemplateLibV1.type.name)\n .update(PlTemplateLibV1.type.version)\n .update(lib.name)\n .update(lib.version)\n .update(lib.sourceHash)\n .digest(\"hex\");\n}\n\nfunction hashSoftwareV3(sw: TemplateSoftwareDataV3): string {\n return createHash(\"sha256\")\n .update(PlTemplateSoftwareV1.type.name)\n .update(PlTemplateSoftwareV1.type.version)\n .update(sw.name)\n .update(sw.version)\n .update(sw.sourceHash)\n .digest(\"hex\");\n}\n\nfunction hashWasmV3(wasm: TemplateWasmDataV3): string {\n return createHash(\"sha256\")\n .update(PlWasmV1.type.name)\n .update(PlWasmV1.type.version)\n .update(wasm.name)\n .update(wasm.version)\n .update(wasm.sourceHash)\n .digest(\"hex\");\n}\n\n// ─── Tree flattening ─────────────────────────────────────────────────────────\n\nfunction flattenV2Tree(data: TemplateData): CacheableNode[] {\n const nodes: CacheableNode[] = [];\n const seen = new Set<string>();\n\n function processLib(lib: TemplateLibData): string {\n const hash = hashLibV2(lib);\n if (!seen.has(hash)) {\n seen.add(hash);\n nodes.push({\n hash,\n create: (tx) =>\n tx.createValue(\n PlTemplateLibV1.type,\n JSON.stringify(PlTemplateLibV1.fromV2Data(lib).data),\n ),\n childHashes: [],\n });\n }\n return hash;\n }\n\n function processSoftware(sw: TemplateSoftwareData): string {\n const hash = hashSoftwareV2(sw);\n if (!seen.has(hash)) {\n seen.add(hash);\n nodes.push({\n hash,\n create: (tx) => {\n const swData = PlTemplateSoftwareV1.fromV2Data(sw);\n const ref = tx.createStruct(PlTemplateSoftwareV1.type, swData.data);\n tx.setKValue(ref, PlTemplateSoftwareV1.metaNameKey, JSON.stringify(swData.name));\n tx.lock(ref);\n return ref;\n },\n childHashes: [],\n });\n }\n return hash;\n }\n\n function processTemplate(tpl: TemplateData): string {\n // Process children first (bottom-up) — their hashes are computed before ours\n const childHashes: string[] = [];\n const children: { fieldName: string; hash: string }[] = [];\n\n for (const [libId, lib] of Object.entries(tpl.libs ?? {})) {\n const h = processLib(lib);\n childHashes.push(h);\n children.push({ fieldName: `${PlTemplateV1.libPrefix}/${libId}`, hash: h });\n }\n for (const [swId, sw] of Object.entries(tpl.software ?? {})) {\n const h = processSoftware(sw);\n childHashes.push(h);\n children.push({ fieldName: `${PlTemplateV1.softPrefix}/${swId}`, hash: h });\n }\n for (const [swId, sw] of Object.entries(tpl.assets ?? {})) {\n const h = processSoftware(sw);\n childHashes.push(h);\n children.push({ fieldName: `${PlTemplateV1.softPrefix}/${swId}`, hash: h });\n }\n for (const [tplId, sub] of Object.entries(tpl.templates ?? {})) {\n const h = processTemplate(sub);\n childHashes.push(h);\n children.push({ fieldName: `${PlTemplateV1.tplPrefix}/${tplId}`, hash: h });\n }\n\n // Compose hash from own content + child hash strings (NOT child content)\n const h = createHash(\"sha256\")\n .update(PlTemplateV1.type.name)\n .update(PlTemplateV1.type.version)\n .update(tpl.hashOverride ?? \"no-override\")\n .update(tpl.name)\n .update(tpl.version)\n .update(tpl.src);\n for (const child of children) {\n h.update(\"child:\" + child.fieldName + \":\" + child.hash);\n }\n const hash = h.digest(\"hex\");\n\n if (seen.has(hash)) return hash;\n seen.add(hash);\n nodes.push({\n hash,\n create: (tx, childRefs) => {\n const tplRef = tx.createStruct(\n PlTemplateV1.type,\n JSON.stringify(PlTemplateV1.fromV2Data(tpl).data),\n );\n for (const child of children) {\n const fld = field(tplRef, child.fieldName);\n tx.createField(fld, \"Input\");\n tx.setField(fld, notEmpty(childRefs.get(child.hash), `missing child ref ${child.hash}`));\n }\n tx.lock(tplRef);\n\n if (!tpl.hashOverride) return tplRef;\n\n const overrideRef = tx.createStruct(\n PlTemplateOverrideV1.type,\n JSON.stringify(PlTemplateOverrideV1.fromV2Data(tpl)),\n );\n const overrideFld = PlTemplateOverrideV1.tplField(overrideRef);\n tx.createField(overrideFld, \"Service\");\n tx.setField(overrideFld, tplRef);\n tx.lock(overrideRef);\n return overrideRef;\n },\n childHashes,\n });\n\n return hash;\n }\n\n processTemplate(data);\n return nodes;\n}\n\nfunction flattenV3Tree(data: CompiledTemplateV3): CacheableNode[] {\n const nodes: CacheableNode[] = [];\n const seen = new Set<string>();\n const sources = data.hashToSource;\n\n function processLib(lib: TemplateLibDataV3): string {\n const hash = hashLibV3(lib);\n if (!seen.has(hash)) {\n seen.add(hash);\n nodes.push({\n hash,\n create: (tx) =>\n tx.createValue(\n PlTemplateLibV1.type,\n JSON.stringify(\n PlTemplateLibV1.fromV3Data(lib, getSourceCode(lib.name, sources, lib.sourceHash))\n .data,\n ),\n ),\n childHashes: [],\n });\n }\n return hash;\n }\n\n function processSoftware(sw: TemplateSoftwareDataV3): string {\n const hash = hashSoftwareV3(sw);\n if (!seen.has(hash)) {\n seen.add(hash);\n nodes.push({\n hash,\n create: (tx) => {\n const swData = PlTemplateSoftwareV1.fromV3Data(\n sw,\n getSourceCode(sw.name, sources, sw.sourceHash),\n );\n const ref = tx.createStruct(PlTemplateSoftwareV1.type, swData.data);\n tx.setKValue(ref, PlTemplateSoftwareV1.metaNameKey, JSON.stringify(swData.name));\n tx.lock(ref);\n return ref;\n },\n childHashes: [],\n });\n }\n return hash;\n }\n\n function processWasm(wasm: TemplateWasmDataV3): string {\n const hash = hashWasmV3(wasm);\n if (!seen.has(hash)) {\n seen.add(hash);\n nodes.push({\n hash,\n create: (tx) =>\n tx.createValue(\n PlWasmV1.type,\n JSON.stringify(\n PlWasmV1.fromV3Data(wasm, getSourceCode(wasm.name, sources, wasm.sourceHash)).data,\n ),\n ),\n childHashes: [],\n });\n }\n return hash;\n }\n\n function processTemplate(tpl: TemplateDataV3): string {\n // Defensive: a template can carry no embedded version at runtime even\n // though the type says `string` — the compiler writes `packageJson.version`\n // unchecked, so a template built from a package with no `version` field\n // yields undefined. Identity is fully covered by name + sourceHash, so the\n // placeholder is safe for both the cache key and the backend resource's\n // required Version field.\n const version = tpl.version ?? \"0.0.0\";\n\n // Process children first (bottom-up)\n const childHashes: string[] = [];\n const children: { fieldName: string; hash: string }[] = [];\n\n for (const [libId, lib] of Object.entries(tpl.libs ?? {})) {\n const h = processLib(lib);\n childHashes.push(h);\n children.push({ fieldName: `${PlTemplateV1.libPrefix}/${libId}`, hash: h });\n }\n for (const [swId, sw] of Object.entries(tpl.software ?? {})) {\n const h = processSoftware(sw);\n childHashes.push(h);\n children.push({ fieldName: `${PlTemplateV1.softPrefix}/${swId}`, hash: h });\n }\n for (const [swId, sw] of Object.entries(tpl.assets ?? {})) {\n const h = processSoftware(sw);\n childHashes.push(h);\n children.push({ fieldName: `${PlTemplateV1.softPrefix}/${swId}`, hash: h });\n }\n for (const [tplId, sub] of Object.entries(tpl.templates ?? {})) {\n const h = processTemplate(sub);\n childHashes.push(h);\n children.push({ fieldName: `${PlTemplateV1.tplPrefix}/${tplId}`, hash: h });\n }\n for (const [wasmId, wasm] of Object.entries(tpl.wasm ?? {})) {\n const h = processWasm(wasm);\n childHashes.push(h);\n children.push({ fieldName: `${PlTemplateV1.wasmPrefix}/${wasmId}`, hash: h });\n }\n\n // Compose hash from own content + child hash strings (NOT child content).\n // Uses sourceHash directly — it already uniquely identifies the source.\n const h = createHash(\"sha256\")\n .update(PlTemplateV1.type.name)\n .update(PlTemplateV1.type.version)\n .update(tpl.hashOverride ?? \"no-override\")\n .update(tpl.name)\n .update(version)\n .update(tpl.sourceHash);\n for (const child of children) {\n h.update(\"child:\" + child.fieldName + \":\" + child.hash);\n }\n const hash = h.digest(\"hex\");\n\n if (seen.has(hash)) return hash;\n seen.add(hash);\n nodes.push({\n hash,\n create: (tx, childRefs) => {\n const sourceCode = getSourceCode(tpl.name, sources, tpl.sourceHash);\n const tplRef = tx.createStruct(\n PlTemplateV1.type,\n JSON.stringify(PlTemplateV1.fromV3Data({ ...tpl, version }, sourceCode).data),\n );\n for (const child of children) {\n const fld = field(tplRef, child.fieldName);\n tx.createField(fld, \"Input\");\n tx.setField(fld, notEmpty(childRefs.get(child.hash), `missing child ref ${child.hash}`));\n }\n tx.lock(tplRef);\n\n if (!tpl.hashOverride) return tplRef;\n\n const overrideRef = tx.createStruct(\n PlTemplateOverrideV1.type,\n JSON.stringify(PlTemplateOverrideV1.fromV3Data(tpl)),\n );\n const overrideFld = PlTemplateOverrideV1.tplField(overrideRef);\n tx.createField(overrideFld, \"Service\");\n tx.setField(overrideFld, tplRef);\n tx.lock(overrideRef);\n return overrideRef;\n },\n childHashes,\n });\n\n return hash;\n }\n\n processTemplate(data.template);\n return nodes;\n}\n\n/** Flatten template tree into a topologically ordered list of cacheable nodes (leaves first). */\nexport function flattenTemplateTree(data: TemplateData | CompiledTemplateV3): CacheableNode[] {\n if (data.type === \"pl.tengo-template.v2\") {\n return flattenV2Tree(data);\n } else {\n return flattenV3Tree(data);\n }\n}\n\n/** In-memory cache for the TemplateCache SignedResourceId per PlClient instance. */\nconst cacheRidMap = new WeakMap<PlClient, SignedResourceId>();\n\n/** Clear the in-memory cacheRid entry (call on errors referencing the cache resource). */\nexport function invalidateTemplateCacheId(pl: PlClient): void {\n cacheRidMap.delete(pl);\n}\n\n/** Find or create the TemplateCache/1 resource on user root. */\nexport async function getOrCreateTemplateCache(pl: PlClient): Promise<SignedResourceId> {\n // Check in-memory cache first (0ms after first call)\n const cached = cacheRidMap.get(pl);\n if (cached !== undefined) return cached;\n\n // Try read-only check\n const existing = await pl.withReadTx(\"templateCache:check\", async (tx) => {\n const fd = await tx.getFieldIfExists(field(pl.clientRoot, TemplateCacheFieldName));\n return fd ? ensureSignedResourceIdNotNull(fd.value) : undefined;\n });\n if (existing) {\n cacheRidMap.set(pl, existing);\n return existing;\n }\n\n const result = await pl.withWriteTx(\"templateCache:init\", async (tx) => {\n // Double-check inside write tx (another instance may have created it)\n const fd = await tx.getFieldIfExists(field(pl.clientRoot, TemplateCacheFieldName));\n if (fd) return ensureSignedResourceIdNotNull(fd.value);\n\n const cache = tx.createStruct(TemplateCacheType);\n tx.createField(field(pl.clientRoot, TemplateCacheFieldName), \"Dynamic\", cache);\n tx.lock(cache);\n await tx.commit();\n return await cache.globalId;\n });\n cacheRidMap.set(pl, result);\n return result;\n}\n\n/** Remove the template cache from user root. */\nexport async function dropTemplateCache(pl: PlClient): Promise<void> {\n await pl.withWriteTx(\"templateCache:drop\", async (tx) => {\n const cacheField = field(pl.clientRoot, TemplateCacheFieldName);\n const fd = await tx.getFieldIfExists(cacheField);\n if (fd) {\n tx.removeField(cacheField);\n await tx.commit();\n }\n });\n invalidateTemplateCacheId(pl);\n}\n\n/**\n * Run count-based garbage collection on the template cache.\n * Evicts least-recently-used entries when the cache exceeds maxEntries.\n * Always resets the access counter to 0.\n *\n * @internal exported for testing (maxEntries parameter allows low thresholds in tests)\n * @returns true if entries were evicted\n */\nexport async function runGc(\n pl: PlClient,\n cacheRid: SignedResourceId,\n maxEntries: number = GC_MAX_ENTRIES,\n): Promise<boolean> {\n return await pl.withWriteTx(\"templateCache:gc\", async (tx) => {\n const kvs = await tx.listKeyValuesString(cacheRid);\n const entries: { hash: string; timestamp: number }[] = [];\n for (const { key, value } of kvs) {\n if (!key.startsWith(ACCESS_KEY_PREFIX)) continue;\n entries.push({\n hash: key.slice(ACCESS_KEY_PREFIX.length),\n timestamp: parseInt(value, 10),\n });\n }\n\n // Always reset counter\n tx.setKValue(cacheRid, ACCESS_COUNT_KEY, \"0\");\n\n if (entries.length <= maxEntries) {\n await tx.commit();\n return false;\n }\n\n // Sort oldest first, evict until under limit\n entries.sort((a, b) => a.timestamp - b.timestamp);\n const toEvict = entries.length - maxEntries;\n for (let i = 0; i < toEvict; i++) {\n tx.removeField(field(cacheRid, entries[i].hash));\n tx.deleteKValue(cacheRid, ACCESS_KEY_PREFIX + entries[i].hash);\n }\n\n await tx.commit();\n return true;\n });\n}\n\n/** Create a batch of cache nodes in the current transaction. */\nfunction createBatchNodes(\n tx: PlTransaction,\n cacheRid: SignedResourceId,\n batch: CacheableNode[],\n resolvedIds: ReadonlyMap<string, SignedResourceId>,\n newRefs: Map<string, ResourceRef>,\n now: string,\n): void {\n for (const node of batch) {\n const childRefs = new Map<string, AnyResourceRef>();\n for (const ch of node.childHashes) {\n const resolved = resolvedIds.get(ch) ?? newRefs.get(ch);\n if (resolved === undefined) {\n throw new Error(`BUG: child ${ch} not resolved`);\n }\n childRefs.set(ch, resolved);\n }\n const ref = node.create(tx, childRefs);\n newRefs.set(node.hash, ref);\n tx.createField(field(cacheRid, node.hash), \"Dynamic\", ref);\n tx.setKValue(cacheRid, ACCESS_KEY_PREFIX + node.hash, now);\n }\n}\n\n/**\n * Materialize a template tree via the cache using \"probe all + batched creation\".\n *\n * Phase 1 (single write tx):\n * - Check existence of ALL hashes in one roundtrip\n * - Happy path: if root cached, update access tracking and return\n * - Otherwise: fetch ResourceIds for all cache hits, create first batch of missing nodes\n *\n * Phase 2..N (one write tx per batch):\n * - Create remaining missing nodes in BATCH_SIZE chunks\n *\n * @returns root SignedResourceId and current access count (for GC decision)\n */\nasync function materialize(\n pl: PlClient,\n cacheRid: SignedResourceId,\n rootHash: string,\n nodes: CacheableNode[],\n stat: TemplateCacheStat,\n): Promise<{ rootId: SignedResourceId; accessCount: number }> {\n const allHashes = nodes.map((n) => n.hash);\n const resolvedIds = new Map<string, SignedResourceId>();\n\n // Phase 1: probe all + first batch\n const phase1 = await pl.withWriteTx(\"templateCache:materialize\", async (tx) => {\n // 1 roundtrip: check all hashes + read access count\n const [exists, countStr] = await Promise.all([\n Promise.all(allHashes.map((h) => tx.fieldExists(field(cacheRid, h)))),\n tx.getKValueStringIfExists(cacheRid, ACCESS_COUNT_KEY),\n ]);\n\n const prevCount = countStr ? parseInt(countStr, 10) : 0;\n const newCount = prevCount + 1;\n const now = Date.now().toString();\n const rootIdx = allHashes.length - 1;\n\n // Happy path: root already cached\n if (exists[rootIdx]) {\n const rootFd = await tx.getField(field(cacheRid, rootHash));\n const rootRid = ensureSignedResourceIdNotNull(rootFd.value);\n tx.setKValue(cacheRid, ACCESS_KEY_PREFIX + rootHash, now);\n tx.setKValue(cacheRid, ACCESS_COUNT_KEY, newCount.toString());\n await tx.commit();\n stat.happyPath = true;\n stat.cacheHits = stat.totalNodes;\n stat.batchCount = 1;\n return { done: true as const, rootId: rootRid, accessCount: newCount };\n }\n\n // Fetch ResourceIds for all cache hits (1 roundtrip)\n const hitIndices: number[] = [];\n for (let i = 0; i < allHashes.length; i++) {\n if (exists[i]) hitIndices.push(i);\n }\n\n if (hitIndices.length > 0) {\n const hitFields = await Promise.all(\n hitIndices.map((i) => tx.getField(field(cacheRid, allHashes[i]))),\n );\n for (let j = 0; j < hitIndices.length; j++) {\n resolvedIds.set(\n allHashes[hitIndices[j]],\n ensureSignedResourceIdNotNull(hitFields[j].value),\n );\n }\n }\n stat.cacheHits = hitIndices.length;\n\n // Missing nodes (topo order preserved from flatten)\n const missing = nodes.filter((n) => !resolvedIds.has(n.hash));\n stat.cacheMisses = missing.length;\n\n // Create first batch of missing nodes\n const firstBatch = missing.slice(0, BATCH_SIZE);\n const newRefs = new Map<string, ResourceRef>();\n createBatchNodes(tx, cacheRid, firstBatch, resolvedIds, newRefs, now);\n\n // Update access tracking for cache hits\n for (const i of hitIndices) {\n tx.setKValue(cacheRid, ACCESS_KEY_PREFIX + allHashes[i], now);\n }\n tx.setKValue(cacheRid, ACCESS_COUNT_KEY, newCount.toString());\n\n await tx.commit();\n\n // Resolve new refs to global IDs (after commit)\n for (const [hash, ref] of newRefs) {\n resolvedIds.set(hash, await toGlobalResourceId(ref));\n }\n\n return {\n done: false as const,\n remaining: missing.slice(BATCH_SIZE),\n accessCount: newCount,\n };\n });\n\n if (phase1.done) {\n return { rootId: phase1.rootId, accessCount: phase1.accessCount };\n }\n\n stat.batchCount = 1;\n\n // Phase 2+: remaining batches\n const { remaining } = phase1;\n for (let i = 0; i < remaining.length; i += BATCH_SIZE) {\n const batch = remaining.slice(i, i + BATCH_SIZE);\n stat.batchCount++;\n\n await pl.withWriteTx(\"templateCache:create\", async (tx) => {\n const newRefs = new Map<string, ResourceRef>();\n const now = Date.now().toString();\n createBatchNodes(tx, cacheRid, batch, resolvedIds, newRefs, now);\n await tx.commit();\n\n for (const [hash, ref] of newRefs) {\n resolvedIds.set(hash, await toGlobalResourceId(ref));\n }\n });\n }\n\n const rootId = resolvedIds.get(rootHash);\n if (!rootId) throw new Error(\"BUG: root hash not resolved after all batches\");\n return { rootId, accessCount: phase1.accessCount };\n}\n\n/**\n * Materialize a template tree via the cache.\n * Manages its own transactions internally — do NOT call inside an existing tx.\n *\n * @returns concrete SignedResourceId of the root template\n */\nexport async function loadTemplateCached(\n pl: PlClient,\n spec: TemplateSpecPrepared,\n options?: { cacheResourceId?: SignedResourceId },\n): Promise<SignedResourceId> {\n const stat = initialStat();\n const t0 = performance.now();\n\n try {\n // Parse to data if needed\n let tplData: TemplateData | CompiledTemplateV3;\n switch (spec.type) {\n case \"explicit\":\n tplData = parseTemplate(spec.content);\n break;\n case \"prepared\":\n tplData = spec.data;\n break;\n case \"cached\":\n return spec.resourceId;\n case \"from-registry\":\n throw new Error(\n \"loadTemplateCached does not support from-registry specs; use loadTemplate instead\",\n );\n default: {\n const _: never = spec;\n throw new Error(`unexpected spec type: ${(_ as any).type}`);\n }\n }\n\n stat.templateFormat = tplData.type;\n\n // Flatten to ordered nodes\n const tFlatten = performance.now();\n const nodes = flattenTemplateTree(tplData);\n stat.flattenMs = performance.now() - tFlatten;\n if (nodes.length === 0) throw new Error(\"template tree produced no nodes\");\n\n stat.totalNodes = nodes.length;\n const rootHash = nodes[nodes.length - 1].hash;\n\n // Resolve or create cache resource\n const tCacheInit = performance.now();\n const cacheRid = options?.cacheResourceId ?? (await getOrCreateTemplateCache(pl));\n stat.cacheInitMs = performance.now() - tCacheInit;\n\n // Retry loop: if a write tx fails (e.g. concurrent GC invalidated a cached resource),\n // restart materialization from scratch.\n const MAX_RETRIES = 3;\n for (let attempt = 0; attempt < MAX_RETRIES; attempt++) {\n try {\n const tMat = performance.now();\n const result = await materialize(pl, cacheRid, rootHash, nodes, stat);\n stat.materializeMs = performance.now() - tMat;\n stat.retries = attempt;\n\n // GC in separate tx if access count exceeded threshold\n if (result.accessCount >= GC_ACCESS_THRESHOLD) {\n await runGc(pl, cacheRid);\n stat.gcTriggered = true;\n }\n\n return result.rootId;\n } catch (e) {\n if (attempt === MAX_RETRIES - 1) throw e;\n // Retry from scratch — previous batch results may reference GC'd resources\n stat.cacheHits = 0;\n stat.cacheMisses = 0;\n }\n }\n\n throw new Error(\"BUG: unreachable\");\n } finally {\n stat.totalMs = performance.now() - t0;\n if (getDebugFlags().logTemplateCacheStat) {\n console.log(`[templateCache] ${JSON.stringify(stat)}`);\n }\n }\n}\n\ntype CacheBlockPackOptions = {\n cacheResourceId?: SignedResourceId;\n /** Loads registry and local packs. */\n preparer?: BlockPackPreparer;\n};\n\n/**\n * Pre-materialize a block pack's template via cache.\n * Returns a copy of the spec with the template replaced by a cached reference.\n * If the template is already cached, returns the spec unchanged.\n */\nexport async function cacheBlockPackTemplate(\n pl: PlClient,\n spec: BlockPackSpecPrepared,\n options?: CacheBlockPackOptions,\n): Promise<BlockPackSpecPrepared> {\n if (spec.template.type === \"cached\") return spec;\n\n const resourceId =\n spec.template.type === \"registry-pack\" || spec.template.type === \"local-pack\"\n ? await installPackOnClient(pl, spec.template, options)\n : await loadTemplateCached(pl, spec.template, options);\n return {\n ...spec,\n template: { type: \"cached\", resourceId },\n };\n}\n\nasync function installPackOnClient(\n pl: PlClient,\n template: InstallablePackTemplate,\n options?: CacheBlockPackOptions,\n): Promise<SignedResourceId> {\n if (options?.preparer === undefined) throw new Error(\"BUG: a pack needs a preparer to load it\");\n const loaded = await options.preparer.loadPack(template);\n // The manifest may predate the requiredCapabilities field: check what the pack declares.\n throwIfMissingServerCapabilities(pl, loaded.requiredCapabilities);\n return await loadTemplateCached(pl, loaded.template, options);\n}\n"],"mappings":";;;;;;;AAuCA,MAAa,qBAAA,GAAoBA,0BAAAA,aAAAA,CAAa,iBAAiB,GAAG;AAElE,MAAa,yBAAyB;AACtC,MAAM,aAAa;;AAEnB,MAAa,sBAAsB;;AAEnC,MAAa,iBAAiB;;AAE9B,MAAa,mBAAmB;;AAEhC,MAAa,oBAAoB;AAiBjC,SAAS,cAAiC;CACxC,OAAO;EACL,SAAS;EACT,WAAW;EACX,aAAa;EACb,eAAe;EACf,YAAY;EACZ,WAAW;EACX,aAAa;EACb,YAAY;EACZ,WAAW;EACX,aAAa;EACb,SAAS;EACT,gBAAgB;CAClB;AACF;AAYA,SAAS,cAAc,MAAc,SAAiC,YAA4B;CAChG,QAAA,GAAOC,2BAAAA,SAAAA,CACL,QAAQ,aACR,kBAAkB,KAAK,oDAAoD,YAC7E;AACF;;;;;AASA,SAAS,UAAU,KAA8B;CAC/C,QAAA,GAAOC,YAAAA,WAAAA,CAAW,QAAQ,CAAC,CACxB,OAAOC,iCAAAA,gBAAgB,KAAK,IAAI,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,OAAO;EAChB,SAAS,GAAG;GACV,IAAI,YAAY,GAAiB,MAAM;GAEvC,KAAK,YAAY;GACjB,KAAK,cAAc;EACrB;EAGF,MAAM,IAAI,MAAM,kBAAkB;CACpC,UAAU;EACR,KAAK,UAAU,YAAY,IAAI,IAAI;EACnC,IAAIC,cAAAA,cAAc,CAAC,CAAC,sBAClB,QAAQ,IAAI,mBAAmB,KAAK,UAAU,IAAI,GAAG;CAEzD;AACF;;;;;;AAaA,eAAsB,uBACpB,IACA,MACA,SACgC;CAChC,IAAI,KAAK,SAAS,SAAS,UAAU,OAAO;CAE5C,MAAM,aACJ,KAAK,SAAS,SAAS,mBAAmB,KAAK,SAAS,SAAS,eAC7D,MAAM,oBAAoB,IAAI,KAAK,UAAU,OAAO,IACpD,MAAM,mBAAmB,IAAI,KAAK,UAAU,OAAO;CACzD,OAAO;EACL,GAAG;EACH,UAAU;GAAE,MAAM;GAAU;EAAW;CACzC;AACF;AAEA,eAAe,oBACb,IACA,UACA,SAC2B;CAC3B,IAAI,SAAS,aAAa,KAAA,GAAW,MAAM,IAAI,MAAM,yCAAyC;CAC9F,MAAM,SAAS,MAAM,QAAQ,SAAS,SAAS,QAAQ;CAEvD,8BAAA,iCAAiC,IAAI,OAAO,oBAAoB;CAChE,OAAO,MAAM,mBAAmB,IAAI,OAAO,UAAU,OAAO;AAC9D"}
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { TemplateSpecPrepared } from "../../model/template_spec.js";
|
|
2
2
|
import { BlockPackSpecPrepared } from "../../model/block_pack_spec.js";
|
|
3
3
|
import "../../model/index.js";
|
|
4
|
+
import { BlockPackPreparer } from "../block-pack/block_pack.js";
|
|
4
5
|
import { AnyResourceRef, PlClient, PlTransaction, ResourceRef, SignedResourceId } from "@milaboratories/pl-client";
|
|
5
6
|
import { CompiledTemplateV3, TemplateData } from "@milaboratories/pl-model-backend";
|
|
6
7
|
export declare const TemplateCacheType: import("@milaboratories/pl-client").ResourceType;
|
|
@@ -62,13 +63,16 @@ export declare function runGc(pl: PlClient, cacheRid: SignedResourceId, maxEntri
|
|
|
62
63
|
export declare function loadTemplateCached(pl: PlClient, spec: TemplateSpecPrepared, options?: {
|
|
63
64
|
cacheResourceId?: SignedResourceId;
|
|
64
65
|
}): Promise<SignedResourceId>;
|
|
66
|
+
type CacheBlockPackOptions = {
|
|
67
|
+
cacheResourceId?: SignedResourceId;
|
|
68
|
+
/** Loads registry and local packs. */
|
|
69
|
+
preparer?: BlockPackPreparer;
|
|
70
|
+
};
|
|
65
71
|
/**
|
|
66
72
|
* Pre-materialize a block pack's template via cache.
|
|
67
73
|
* Returns a copy of the spec with the template replaced by a cached reference.
|
|
68
74
|
* If the template is already cached, returns the spec unchanged.
|
|
69
75
|
*/
|
|
70
|
-
export declare function cacheBlockPackTemplate(pl: PlClient, spec: BlockPackSpecPrepared, options?:
|
|
71
|
-
cacheResourceId?: SignedResourceId;
|
|
72
|
-
}): Promise<BlockPackSpecPrepared>;
|
|
76
|
+
export declare function cacheBlockPackTemplate(pl: PlClient, spec: BlockPackSpecPrepared, options?: CacheBlockPackOptions): Promise<BlockPackSpecPrepared>;
|
|
73
77
|
export {};
|
|
74
78
|
//# sourceMappingURL=template_cache.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"template_cache.d.ts","names":[],"sources":["../../../src/mutator/template/template_cache.ts"],"mappings":"
|
|
1
|
+
{"version":3,"file":"template_cache.d.ts","names":[],"sources":["../../../src/mutator/template/template_cache.ts"],"mappings":";;;;;;qBAuCa,uDAAiB;qBAEjB;;qBAGA;;qBAEA;;qBAEA;;qBAEA;YAED;EACV;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;;UAoBQ;;EAER;;;EAGA,SAAS,IAAI,eAAe,WAAW,oBAAoB,oBAAoB;;EAE/E;;;wBA2Vc,oBAAoB,MAAM,eAAe,qBAAqB;;wBAY9D,0BAA0B,IAAI;;wBAKxB,yBAAyB,IAAI,WAAW,QAAQ;;wBA+BhD,kBAAkB,IAAI,WAAW;;;;;;;;;wBAoBjC,MACpB,IAAI,UACJ,UAAU,kBACV,sBACC;;;;;;;wBA8LmB,mBACpB,IAAI,UACJ,MAAM,sBACN;EAAY,kBAAkB;IAC7B,QAAQ;KA4EN;EACH,kBAAkB;;EAElB,WAAW;;;;;;;wBAQS,uBACpB,IAAI,UACJ,MAAM,uBACN,UAAU,wBACT,QAAQ"}
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { throwIfMissingServerCapabilities } from "../block-pack/required_capabilities.js";
|
|
1
2
|
import { getDebugFlags } from "../../debug/index.js";
|
|
2
3
|
import { notEmpty } from "@milaboratories/ts-helpers";
|
|
3
4
|
import { ensureSignedResourceIdNotNull, field, resourceType, toGlobalResourceId } from "@milaboratories/pl-client";
|
|
@@ -512,7 +513,7 @@ async function loadTemplateCached(pl, spec, options) {
|
|
|
512
513
|
*/
|
|
513
514
|
async function cacheBlockPackTemplate(pl, spec, options) {
|
|
514
515
|
if (spec.template.type === "cached") return spec;
|
|
515
|
-
const resourceId = await loadTemplateCached(pl, spec.template, options);
|
|
516
|
+
const resourceId = spec.template.type === "registry-pack" || spec.template.type === "local-pack" ? await installPackOnClient(pl, spec.template, options) : await loadTemplateCached(pl, spec.template, options);
|
|
516
517
|
return {
|
|
517
518
|
...spec,
|
|
518
519
|
template: {
|
|
@@ -521,6 +522,12 @@ async function cacheBlockPackTemplate(pl, spec, options) {
|
|
|
521
522
|
}
|
|
522
523
|
};
|
|
523
524
|
}
|
|
525
|
+
async function installPackOnClient(pl, template, options) {
|
|
526
|
+
if (options?.preparer === void 0) throw new Error("BUG: a pack needs a preparer to load it");
|
|
527
|
+
const loaded = await options.preparer.loadPack(template);
|
|
528
|
+
throwIfMissingServerCapabilities(pl, loaded.requiredCapabilities);
|
|
529
|
+
return await loadTemplateCached(pl, loaded.template, options);
|
|
530
|
+
}
|
|
524
531
|
export { ACCESS_COUNT_KEY, ACCESS_KEY_PREFIX, GC_ACCESS_THRESHOLD, GC_MAX_ENTRIES, TemplateCacheFieldName, TemplateCacheType, cacheBlockPackTemplate, dropTemplateCache, flattenTemplateTree, getOrCreateTemplateCache, invalidateTemplateCacheId, loadTemplateCached, runGc };
|
|
525
532
|
|
|
526
533
|
//# sourceMappingURL=template_cache.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"template_cache.js","names":["_"],"sources":["../../../src/mutator/template/template_cache.ts"],"sourcesContent":["import { createHash } from \"node:crypto\";\nimport type {\n AnyResourceRef,\n PlClient,\n PlTransaction,\n SignedResourceId,\n ResourceRef,\n} from \"@milaboratories/pl-client\";\nimport {\n ensureSignedResourceIdNotNull,\n field,\n resourceType,\n toGlobalResourceId,\n} from \"@milaboratories/pl-client\";\nimport {\n parseTemplate,\n PlTemplateLibV1,\n PlTemplateOverrideV1,\n PlTemplateSoftwareV1,\n PlTemplateV1,\n PlWasmV1,\n} from \"@milaboratories/pl-model-backend\";\nimport type {\n CompiledTemplateV3,\n TemplateData,\n TemplateDataV3,\n TemplateLibData,\n TemplateLibDataV3,\n TemplateSoftwareData,\n TemplateSoftwareDataV3,\n TemplateWasmDataV3,\n} from \"@milaboratories/pl-model-backend\";\nimport { notEmpty } from \"@milaboratories/ts-helpers\";\nimport type { BlockPackSpecPrepared } from \"../../model\";\nimport type { TemplateSpecPrepared } from \"../../model/template_spec\";\nimport { getDebugFlags } from \"../../debug\";\n\nexport const TemplateCacheType = resourceType(\"TemplateCache\", \"1\");\n\nexport const TemplateCacheFieldName = \"__templateCache\";\nconst BATCH_SIZE = 50;\n/** @internal exported for testing */\nexport const GC_ACCESS_THRESHOLD = 30;\n/** @internal exported for testing */\nexport const GC_MAX_ENTRIES = 3000;\n/** @internal exported for testing */\nexport const ACCESS_COUNT_KEY = \"_accessCount\";\n/** @internal exported for testing */\nexport const ACCESS_KEY_PREFIX = \"access_\";\n\nexport type TemplateCacheStat = {\n totalMs: number;\n flattenMs: number;\n cacheInitMs: number;\n materializeMs: number;\n totalNodes: number;\n cacheHits: number;\n cacheMisses: number;\n batchCount: number;\n happyPath: boolean;\n gcTriggered: boolean;\n retries: number;\n templateFormat: string;\n};\n\nfunction initialStat(): TemplateCacheStat {\n return {\n totalMs: 0,\n flattenMs: 0,\n cacheInitMs: 0,\n materializeMs: 0,\n totalNodes: 0,\n cacheHits: 0,\n cacheMisses: 0,\n batchCount: 0,\n happyPath: false,\n gcTriggered: false,\n retries: 0,\n templateFormat: \"\",\n };\n}\n\ninterface CacheableNode {\n /** SHA-256 content hash (includes all descendant content) */\n hash: string;\n /** Creates this node's resource in a transaction.\n * childRefs maps child hash → already-resolved ResourceRef or SignedResourceId */\n create: (tx: PlTransaction, childRefs: ReadonlyMap<string, AnyResourceRef>) => ResourceRef;\n /** Hashes of direct child nodes this node depends on */\n childHashes: string[];\n}\n\nfunction getSourceCode(name: string, sources: Record<string, string>, sourceHash: string): string {\n return notEmpty(\n sources[sourceHash],\n `trying to get \"${name}\" source: sources map doesn't contain source hash ${sourceHash}`,\n );\n}\n\n/**\n * Bottom-up hash composition: each node hashes its OWN content + child hash STRINGS.\n * This means each unique node is hashed exactly once → O(n) instead of O(n * depth).\n */\n\n// V2 leaf hashes (libs, software — no children)\n\nfunction hashLibV2(lib: TemplateLibData): string {\n return createHash(\"sha256\")\n .update(PlTemplateLibV1.type.name)\n .update(PlTemplateLibV1.type.version)\n .update(lib.name)\n .update(lib.version)\n .update(lib.src)\n .digest(\"hex\");\n}\n\nfunction hashSoftwareV2(sw: TemplateSoftwareData): string {\n return createHash(\"sha256\")\n .update(PlTemplateSoftwareV1.type.name)\n .update(PlTemplateSoftwareV1.type.version)\n .update(sw.name)\n .update(sw.version)\n .update(sw.src)\n .digest(\"hex\");\n}\n\n// V3 leaf hashes — use sourceHash directly instead of resolving source content\n\nfunction hashLibV3(lib: TemplateLibDataV3): string {\n return createHash(\"sha256\")\n .update(PlTemplateLibV1.type.name)\n .update(PlTemplateLibV1.type.version)\n .update(lib.name)\n .update(lib.version)\n .update(lib.sourceHash)\n .digest(\"hex\");\n}\n\nfunction hashSoftwareV3(sw: TemplateSoftwareDataV3): string {\n return createHash(\"sha256\")\n .update(PlTemplateSoftwareV1.type.name)\n .update(PlTemplateSoftwareV1.type.version)\n .update(sw.name)\n .update(sw.version)\n .update(sw.sourceHash)\n .digest(\"hex\");\n}\n\nfunction hashWasmV3(wasm: TemplateWasmDataV3): string {\n return createHash(\"sha256\")\n .update(PlWasmV1.type.name)\n .update(PlWasmV1.type.version)\n .update(wasm.name)\n .update(wasm.version)\n .update(wasm.sourceHash)\n .digest(\"hex\");\n}\n\n// ─── Tree flattening ─────────────────────────────────────────────────────────\n\nfunction flattenV2Tree(data: TemplateData): CacheableNode[] {\n const nodes: CacheableNode[] = [];\n const seen = new Set<string>();\n\n function processLib(lib: TemplateLibData): string {\n const hash = hashLibV2(lib);\n if (!seen.has(hash)) {\n seen.add(hash);\n nodes.push({\n hash,\n create: (tx) =>\n tx.createValue(\n PlTemplateLibV1.type,\n JSON.stringify(PlTemplateLibV1.fromV2Data(lib).data),\n ),\n childHashes: [],\n });\n }\n return hash;\n }\n\n function processSoftware(sw: TemplateSoftwareData): string {\n const hash = hashSoftwareV2(sw);\n if (!seen.has(hash)) {\n seen.add(hash);\n nodes.push({\n hash,\n create: (tx) => {\n const swData = PlTemplateSoftwareV1.fromV2Data(sw);\n const ref = tx.createStruct(PlTemplateSoftwareV1.type, swData.data);\n tx.setKValue(ref, PlTemplateSoftwareV1.metaNameKey, JSON.stringify(swData.name));\n tx.lock(ref);\n return ref;\n },\n childHashes: [],\n });\n }\n return hash;\n }\n\n function processTemplate(tpl: TemplateData): string {\n // Process children first (bottom-up) — their hashes are computed before ours\n const childHashes: string[] = [];\n const children: { fieldName: string; hash: string }[] = [];\n\n for (const [libId, lib] of Object.entries(tpl.libs ?? {})) {\n const h = processLib(lib);\n childHashes.push(h);\n children.push({ fieldName: `${PlTemplateV1.libPrefix}/${libId}`, hash: h });\n }\n for (const [swId, sw] of Object.entries(tpl.software ?? {})) {\n const h = processSoftware(sw);\n childHashes.push(h);\n children.push({ fieldName: `${PlTemplateV1.softPrefix}/${swId}`, hash: h });\n }\n for (const [swId, sw] of Object.entries(tpl.assets ?? {})) {\n const h = processSoftware(sw);\n childHashes.push(h);\n children.push({ fieldName: `${PlTemplateV1.softPrefix}/${swId}`, hash: h });\n }\n for (const [tplId, sub] of Object.entries(tpl.templates ?? {})) {\n const h = processTemplate(sub);\n childHashes.push(h);\n children.push({ fieldName: `${PlTemplateV1.tplPrefix}/${tplId}`, hash: h });\n }\n\n // Compose hash from own content + child hash strings (NOT child content)\n const h = createHash(\"sha256\")\n .update(PlTemplateV1.type.name)\n .update(PlTemplateV1.type.version)\n .update(tpl.hashOverride ?? \"no-override\")\n .update(tpl.name)\n .update(tpl.version)\n .update(tpl.src);\n for (const child of children) {\n h.update(\"child:\" + child.fieldName + \":\" + child.hash);\n }\n const hash = h.digest(\"hex\");\n\n if (seen.has(hash)) return hash;\n seen.add(hash);\n nodes.push({\n hash,\n create: (tx, childRefs) => {\n const tplRef = tx.createStruct(\n PlTemplateV1.type,\n JSON.stringify(PlTemplateV1.fromV2Data(tpl).data),\n );\n for (const child of children) {\n const fld = field(tplRef, child.fieldName);\n tx.createField(fld, \"Input\");\n tx.setField(fld, notEmpty(childRefs.get(child.hash), `missing child ref ${child.hash}`));\n }\n tx.lock(tplRef);\n\n if (!tpl.hashOverride) return tplRef;\n\n const overrideRef = tx.createStruct(\n PlTemplateOverrideV1.type,\n JSON.stringify(PlTemplateOverrideV1.fromV2Data(tpl)),\n );\n const overrideFld = PlTemplateOverrideV1.tplField(overrideRef);\n tx.createField(overrideFld, \"Service\");\n tx.setField(overrideFld, tplRef);\n tx.lock(overrideRef);\n return overrideRef;\n },\n childHashes,\n });\n\n return hash;\n }\n\n processTemplate(data);\n return nodes;\n}\n\nfunction flattenV3Tree(data: CompiledTemplateV3): CacheableNode[] {\n const nodes: CacheableNode[] = [];\n const seen = new Set<string>();\n const sources = data.hashToSource;\n\n function processLib(lib: TemplateLibDataV3): string {\n const hash = hashLibV3(lib);\n if (!seen.has(hash)) {\n seen.add(hash);\n nodes.push({\n hash,\n create: (tx) =>\n tx.createValue(\n PlTemplateLibV1.type,\n JSON.stringify(\n PlTemplateLibV1.fromV3Data(lib, getSourceCode(lib.name, sources, lib.sourceHash))\n .data,\n ),\n ),\n childHashes: [],\n });\n }\n return hash;\n }\n\n function processSoftware(sw: TemplateSoftwareDataV3): string {\n const hash = hashSoftwareV3(sw);\n if (!seen.has(hash)) {\n seen.add(hash);\n nodes.push({\n hash,\n create: (tx) => {\n const swData = PlTemplateSoftwareV1.fromV3Data(\n sw,\n getSourceCode(sw.name, sources, sw.sourceHash),\n );\n const ref = tx.createStruct(PlTemplateSoftwareV1.type, swData.data);\n tx.setKValue(ref, PlTemplateSoftwareV1.metaNameKey, JSON.stringify(swData.name));\n tx.lock(ref);\n return ref;\n },\n childHashes: [],\n });\n }\n return hash;\n }\n\n function processWasm(wasm: TemplateWasmDataV3): string {\n const hash = hashWasmV3(wasm);\n if (!seen.has(hash)) {\n seen.add(hash);\n nodes.push({\n hash,\n create: (tx) =>\n tx.createValue(\n PlWasmV1.type,\n JSON.stringify(\n PlWasmV1.fromV3Data(wasm, getSourceCode(wasm.name, sources, wasm.sourceHash)).data,\n ),\n ),\n childHashes: [],\n });\n }\n return hash;\n }\n\n function processTemplate(tpl: TemplateDataV3): string {\n // Defensive: a template can carry no embedded version at runtime even\n // though the type says `string` — the compiler writes `packageJson.version`\n // unchecked, so a template built from a package with no `version` field\n // yields undefined. Identity is fully covered by name + sourceHash, so the\n // placeholder is safe for both the cache key and the backend resource's\n // required Version field.\n const version = tpl.version ?? \"0.0.0\";\n\n // Process children first (bottom-up)\n const childHashes: string[] = [];\n const children: { fieldName: string; hash: string }[] = [];\n\n for (const [libId, lib] of Object.entries(tpl.libs ?? {})) {\n const h = processLib(lib);\n childHashes.push(h);\n children.push({ fieldName: `${PlTemplateV1.libPrefix}/${libId}`, hash: h });\n }\n for (const [swId, sw] of Object.entries(tpl.software ?? {})) {\n const h = processSoftware(sw);\n childHashes.push(h);\n children.push({ fieldName: `${PlTemplateV1.softPrefix}/${swId}`, hash: h });\n }\n for (const [swId, sw] of Object.entries(tpl.assets ?? {})) {\n const h = processSoftware(sw);\n childHashes.push(h);\n children.push({ fieldName: `${PlTemplateV1.softPrefix}/${swId}`, hash: h });\n }\n for (const [tplId, sub] of Object.entries(tpl.templates ?? {})) {\n const h = processTemplate(sub);\n childHashes.push(h);\n children.push({ fieldName: `${PlTemplateV1.tplPrefix}/${tplId}`, hash: h });\n }\n for (const [wasmId, wasm] of Object.entries(tpl.wasm ?? {})) {\n const h = processWasm(wasm);\n childHashes.push(h);\n children.push({ fieldName: `${PlTemplateV1.wasmPrefix}/${wasmId}`, hash: h });\n }\n\n // Compose hash from own content + child hash strings (NOT child content).\n // Uses sourceHash directly — it already uniquely identifies the source.\n const h = createHash(\"sha256\")\n .update(PlTemplateV1.type.name)\n .update(PlTemplateV1.type.version)\n .update(tpl.hashOverride ?? \"no-override\")\n .update(tpl.name)\n .update(version)\n .update(tpl.sourceHash);\n for (const child of children) {\n h.update(\"child:\" + child.fieldName + \":\" + child.hash);\n }\n const hash = h.digest(\"hex\");\n\n if (seen.has(hash)) return hash;\n seen.add(hash);\n nodes.push({\n hash,\n create: (tx, childRefs) => {\n const sourceCode = getSourceCode(tpl.name, sources, tpl.sourceHash);\n const tplRef = tx.createStruct(\n PlTemplateV1.type,\n JSON.stringify(PlTemplateV1.fromV3Data({ ...tpl, version }, sourceCode).data),\n );\n for (const child of children) {\n const fld = field(tplRef, child.fieldName);\n tx.createField(fld, \"Input\");\n tx.setField(fld, notEmpty(childRefs.get(child.hash), `missing child ref ${child.hash}`));\n }\n tx.lock(tplRef);\n\n if (!tpl.hashOverride) return tplRef;\n\n const overrideRef = tx.createStruct(\n PlTemplateOverrideV1.type,\n JSON.stringify(PlTemplateOverrideV1.fromV3Data(tpl)),\n );\n const overrideFld = PlTemplateOverrideV1.tplField(overrideRef);\n tx.createField(overrideFld, \"Service\");\n tx.setField(overrideFld, tplRef);\n tx.lock(overrideRef);\n return overrideRef;\n },\n childHashes,\n });\n\n return hash;\n }\n\n processTemplate(data.template);\n return nodes;\n}\n\n/** Flatten template tree into a topologically ordered list of cacheable nodes (leaves first). */\nexport function flattenTemplateTree(data: TemplateData | CompiledTemplateV3): CacheableNode[] {\n if (data.type === \"pl.tengo-template.v2\") {\n return flattenV2Tree(data);\n } else {\n return flattenV3Tree(data);\n }\n}\n\n/** In-memory cache for the TemplateCache SignedResourceId per PlClient instance. */\nconst cacheRidMap = new WeakMap<PlClient, SignedResourceId>();\n\n/** Clear the in-memory cacheRid entry (call on errors referencing the cache resource). */\nexport function invalidateTemplateCacheId(pl: PlClient): void {\n cacheRidMap.delete(pl);\n}\n\n/** Find or create the TemplateCache/1 resource on user root. */\nexport async function getOrCreateTemplateCache(pl: PlClient): Promise<SignedResourceId> {\n // Check in-memory cache first (0ms after first call)\n const cached = cacheRidMap.get(pl);\n if (cached !== undefined) return cached;\n\n // Try read-only check\n const existing = await pl.withReadTx(\"templateCache:check\", async (tx) => {\n const fd = await tx.getFieldIfExists(field(pl.clientRoot, TemplateCacheFieldName));\n return fd ? ensureSignedResourceIdNotNull(fd.value) : undefined;\n });\n if (existing) {\n cacheRidMap.set(pl, existing);\n return existing;\n }\n\n const result = await pl.withWriteTx(\"templateCache:init\", async (tx) => {\n // Double-check inside write tx (another instance may have created it)\n const fd = await tx.getFieldIfExists(field(pl.clientRoot, TemplateCacheFieldName));\n if (fd) return ensureSignedResourceIdNotNull(fd.value);\n\n const cache = tx.createStruct(TemplateCacheType);\n tx.createField(field(pl.clientRoot, TemplateCacheFieldName), \"Dynamic\", cache);\n tx.lock(cache);\n await tx.commit();\n return await cache.globalId;\n });\n cacheRidMap.set(pl, result);\n return result;\n}\n\n/** Remove the template cache from user root. */\nexport async function dropTemplateCache(pl: PlClient): Promise<void> {\n await pl.withWriteTx(\"templateCache:drop\", async (tx) => {\n const cacheField = field(pl.clientRoot, TemplateCacheFieldName);\n const fd = await tx.getFieldIfExists(cacheField);\n if (fd) {\n tx.removeField(cacheField);\n await tx.commit();\n }\n });\n invalidateTemplateCacheId(pl);\n}\n\n/**\n * Run count-based garbage collection on the template cache.\n * Evicts least-recently-used entries when the cache exceeds maxEntries.\n * Always resets the access counter to 0.\n *\n * @internal exported for testing (maxEntries parameter allows low thresholds in tests)\n * @returns true if entries were evicted\n */\nexport async function runGc(\n pl: PlClient,\n cacheRid: SignedResourceId,\n maxEntries: number = GC_MAX_ENTRIES,\n): Promise<boolean> {\n return await pl.withWriteTx(\"templateCache:gc\", async (tx) => {\n const kvs = await tx.listKeyValuesString(cacheRid);\n const entries: { hash: string; timestamp: number }[] = [];\n for (const { key, value } of kvs) {\n if (!key.startsWith(ACCESS_KEY_PREFIX)) continue;\n entries.push({\n hash: key.slice(ACCESS_KEY_PREFIX.length),\n timestamp: parseInt(value, 10),\n });\n }\n\n // Always reset counter\n tx.setKValue(cacheRid, ACCESS_COUNT_KEY, \"0\");\n\n if (entries.length <= maxEntries) {\n await tx.commit();\n return false;\n }\n\n // Sort oldest first, evict until under limit\n entries.sort((a, b) => a.timestamp - b.timestamp);\n const toEvict = entries.length - maxEntries;\n for (let i = 0; i < toEvict; i++) {\n tx.removeField(field(cacheRid, entries[i].hash));\n tx.deleteKValue(cacheRid, ACCESS_KEY_PREFIX + entries[i].hash);\n }\n\n await tx.commit();\n return true;\n });\n}\n\n/** Create a batch of cache nodes in the current transaction. */\nfunction createBatchNodes(\n tx: PlTransaction,\n cacheRid: SignedResourceId,\n batch: CacheableNode[],\n resolvedIds: ReadonlyMap<string, SignedResourceId>,\n newRefs: Map<string, ResourceRef>,\n now: string,\n): void {\n for (const node of batch) {\n const childRefs = new Map<string, AnyResourceRef>();\n for (const ch of node.childHashes) {\n const resolved = resolvedIds.get(ch) ?? newRefs.get(ch);\n if (resolved === undefined) {\n throw new Error(`BUG: child ${ch} not resolved`);\n }\n childRefs.set(ch, resolved);\n }\n const ref = node.create(tx, childRefs);\n newRefs.set(node.hash, ref);\n tx.createField(field(cacheRid, node.hash), \"Dynamic\", ref);\n tx.setKValue(cacheRid, ACCESS_KEY_PREFIX + node.hash, now);\n }\n}\n\n/**\n * Materialize a template tree via the cache using \"probe all + batched creation\".\n *\n * Phase 1 (single write tx):\n * - Check existence of ALL hashes in one roundtrip\n * - Happy path: if root cached, update access tracking and return\n * - Otherwise: fetch ResourceIds for all cache hits, create first batch of missing nodes\n *\n * Phase 2..N (one write tx per batch):\n * - Create remaining missing nodes in BATCH_SIZE chunks\n *\n * @returns root SignedResourceId and current access count (for GC decision)\n */\nasync function materialize(\n pl: PlClient,\n cacheRid: SignedResourceId,\n rootHash: string,\n nodes: CacheableNode[],\n stat: TemplateCacheStat,\n): Promise<{ rootId: SignedResourceId; accessCount: number }> {\n const allHashes = nodes.map((n) => n.hash);\n const resolvedIds = new Map<string, SignedResourceId>();\n\n // Phase 1: probe all + first batch\n const phase1 = await pl.withWriteTx(\"templateCache:materialize\", async (tx) => {\n // 1 roundtrip: check all hashes + read access count\n const [exists, countStr] = await Promise.all([\n Promise.all(allHashes.map((h) => tx.fieldExists(field(cacheRid, h)))),\n tx.getKValueStringIfExists(cacheRid, ACCESS_COUNT_KEY),\n ]);\n\n const prevCount = countStr ? parseInt(countStr, 10) : 0;\n const newCount = prevCount + 1;\n const now = Date.now().toString();\n const rootIdx = allHashes.length - 1;\n\n // Happy path: root already cached\n if (exists[rootIdx]) {\n const rootFd = await tx.getField(field(cacheRid, rootHash));\n const rootRid = ensureSignedResourceIdNotNull(rootFd.value);\n tx.setKValue(cacheRid, ACCESS_KEY_PREFIX + rootHash, now);\n tx.setKValue(cacheRid, ACCESS_COUNT_KEY, newCount.toString());\n await tx.commit();\n stat.happyPath = true;\n stat.cacheHits = stat.totalNodes;\n stat.batchCount = 1;\n return { done: true as const, rootId: rootRid, accessCount: newCount };\n }\n\n // Fetch ResourceIds for all cache hits (1 roundtrip)\n const hitIndices: number[] = [];\n for (let i = 0; i < allHashes.length; i++) {\n if (exists[i]) hitIndices.push(i);\n }\n\n if (hitIndices.length > 0) {\n const hitFields = await Promise.all(\n hitIndices.map((i) => tx.getField(field(cacheRid, allHashes[i]))),\n );\n for (let j = 0; j < hitIndices.length; j++) {\n resolvedIds.set(\n allHashes[hitIndices[j]],\n ensureSignedResourceIdNotNull(hitFields[j].value),\n );\n }\n }\n stat.cacheHits = hitIndices.length;\n\n // Missing nodes (topo order preserved from flatten)\n const missing = nodes.filter((n) => !resolvedIds.has(n.hash));\n stat.cacheMisses = missing.length;\n\n // Create first batch of missing nodes\n const firstBatch = missing.slice(0, BATCH_SIZE);\n const newRefs = new Map<string, ResourceRef>();\n createBatchNodes(tx, cacheRid, firstBatch, resolvedIds, newRefs, now);\n\n // Update access tracking for cache hits\n for (const i of hitIndices) {\n tx.setKValue(cacheRid, ACCESS_KEY_PREFIX + allHashes[i], now);\n }\n tx.setKValue(cacheRid, ACCESS_COUNT_KEY, newCount.toString());\n\n await tx.commit();\n\n // Resolve new refs to global IDs (after commit)\n for (const [hash, ref] of newRefs) {\n resolvedIds.set(hash, await toGlobalResourceId(ref));\n }\n\n return {\n done: false as const,\n remaining: missing.slice(BATCH_SIZE),\n accessCount: newCount,\n };\n });\n\n if (phase1.done) {\n return { rootId: phase1.rootId, accessCount: phase1.accessCount };\n }\n\n stat.batchCount = 1;\n\n // Phase 2+: remaining batches\n const { remaining } = phase1;\n for (let i = 0; i < remaining.length; i += BATCH_SIZE) {\n const batch = remaining.slice(i, i + BATCH_SIZE);\n stat.batchCount++;\n\n await pl.withWriteTx(\"templateCache:create\", async (tx) => {\n const newRefs = new Map<string, ResourceRef>();\n const now = Date.now().toString();\n createBatchNodes(tx, cacheRid, batch, resolvedIds, newRefs, now);\n await tx.commit();\n\n for (const [hash, ref] of newRefs) {\n resolvedIds.set(hash, await toGlobalResourceId(ref));\n }\n });\n }\n\n const rootId = resolvedIds.get(rootHash);\n if (!rootId) throw new Error(\"BUG: root hash not resolved after all batches\");\n return { rootId, accessCount: phase1.accessCount };\n}\n\n/**\n * Materialize a template tree via the cache.\n * Manages its own transactions internally — do NOT call inside an existing tx.\n *\n * @returns concrete SignedResourceId of the root template\n */\nexport async function loadTemplateCached(\n pl: PlClient,\n spec: TemplateSpecPrepared,\n options?: { cacheResourceId?: SignedResourceId },\n): Promise<SignedResourceId> {\n const stat = initialStat();\n const t0 = performance.now();\n\n try {\n // Parse to data if needed\n let tplData: TemplateData | CompiledTemplateV3;\n switch (spec.type) {\n case \"explicit\":\n tplData = parseTemplate(spec.content);\n break;\n case \"prepared\":\n tplData = spec.data;\n break;\n case \"cached\":\n return spec.resourceId;\n case \"from-registry\":\n throw new Error(\n \"loadTemplateCached does not support from-registry specs; use loadTemplate instead\",\n );\n default: {\n const _: never = spec;\n throw new Error(`unexpected spec type: ${(_ as any).type}`);\n }\n }\n\n stat.templateFormat = tplData.type;\n\n // Flatten to ordered nodes\n const tFlatten = performance.now();\n const nodes = flattenTemplateTree(tplData);\n stat.flattenMs = performance.now() - tFlatten;\n if (nodes.length === 0) throw new Error(\"template tree produced no nodes\");\n\n stat.totalNodes = nodes.length;\n const rootHash = nodes[nodes.length - 1].hash;\n\n // Resolve or create cache resource\n const tCacheInit = performance.now();\n const cacheRid = options?.cacheResourceId ?? (await getOrCreateTemplateCache(pl));\n stat.cacheInitMs = performance.now() - tCacheInit;\n\n // Retry loop: if a write tx fails (e.g. concurrent GC invalidated a cached resource),\n // restart materialization from scratch.\n const MAX_RETRIES = 3;\n for (let attempt = 0; attempt < MAX_RETRIES; attempt++) {\n try {\n const tMat = performance.now();\n const result = await materialize(pl, cacheRid, rootHash, nodes, stat);\n stat.materializeMs = performance.now() - tMat;\n stat.retries = attempt;\n\n // GC in separate tx if access count exceeded threshold\n if (result.accessCount >= GC_ACCESS_THRESHOLD) {\n await runGc(pl, cacheRid);\n stat.gcTriggered = true;\n }\n\n return result.rootId;\n } catch (e) {\n if (attempt === MAX_RETRIES - 1) throw e;\n // Retry from scratch — previous batch results may reference GC'd resources\n stat.cacheHits = 0;\n stat.cacheMisses = 0;\n }\n }\n\n throw new Error(\"BUG: unreachable\");\n } finally {\n stat.totalMs = performance.now() - t0;\n if (getDebugFlags().logTemplateCacheStat) {\n console.log(`[templateCache] ${JSON.stringify(stat)}`);\n }\n }\n}\n\n/**\n * Pre-materialize a block pack's template via cache.\n * Returns a copy of the spec with the template replaced by a cached reference.\n * If the template is already cached, returns the spec unchanged.\n */\nexport async function cacheBlockPackTemplate(\n pl: PlClient,\n spec: BlockPackSpecPrepared,\n options?: { cacheResourceId?: SignedResourceId },\n): Promise<BlockPackSpecPrepared> {\n if (spec.template.type === \"cached\") return spec;\n\n const resourceId = await loadTemplateCached(pl, spec.template, options);\n return {\n ...spec,\n template: { type: \"cached\", resourceId },\n };\n}\n"],"mappings":";;;;;;AAqCA,MAAa,oBAAoB,aAAa,iBAAiB,GAAG;AAElE,MAAa,yBAAyB;AACtC,MAAM,aAAa;;AAEnB,MAAa,sBAAsB;;AAEnC,MAAa,iBAAiB;;AAE9B,MAAa,mBAAmB;;AAEhC,MAAa,oBAAoB;AAiBjC,SAAS,cAAiC;CACxC,OAAO;EACL,SAAS;EACT,WAAW;EACX,aAAa;EACb,eAAe;EACf,YAAY;EACZ,WAAW;EACX,aAAa;EACb,YAAY;EACZ,WAAW;EACX,aAAa;EACb,SAAS;EACT,gBAAgB;CAClB;AACF;AAYA,SAAS,cAAc,MAAc,SAAiC,YAA4B;CAChG,OAAO,SACL,QAAQ,aACR,kBAAkB,KAAK,oDAAoD,YAC7E;AACF;;;;;AASA,SAAS,UAAU,KAA8B;CAC/C,OAAO,WAAW,QAAQ,CAAC,CACxB,OAAO,gBAAgB,KAAK,IAAI,CAAC,CACjC,OAAO,gBAAgB,KAAK,OAAO,CAAC,CACpC,OAAO,IAAI,IAAI,CAAC,CAChB,OAAO,IAAI,OAAO,CAAC,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I;GACzC,KAAK,UAAU;GAGf,IAAI,OAAO,eAAA,IAAoC;IAC7C,MAAM,MAAM,IAAI,QAAQ;IACxB,KAAK,cAAc;GACrB;GAEA,OAAO,OAAO;EAChB,SAAS,GAAG;GACV,IAAI,YAAY,GAAiB,MAAM;GAEvC,KAAK,YAAY;GACjB,KAAK,cAAc;EACrB;EAGF,MAAM,IAAI,MAAM,kBAAkB;CACpC,UAAU;EACR,KAAK,UAAU,YAAY,IAAI,IAAI;EACnC,IAAI,cAAc,CAAC,CAAC,sBAClB,QAAQ,IAAI,mBAAmB,KAAK,UAAU,IAAI,GAAG;CAEzD;AACF;;;;;;AAOA,eAAsB,uBACpB,IACA,MACA,SACgC;CAChC,IAAI,KAAK,SAAS,SAAS,UAAU,OAAO;CAE5C,MAAM,aAAa,MAAM,mBAAmB,IAAI,KAAK,UAAU,OAAO;CACtE,OAAO;EACL,GAAG;EACH,UAAU;GAAE,MAAM;GAAU;EAAW;CACzC;AACF"}
|
|
1
|
+
{"version":3,"file":"template_cache.js","names":["_"],"sources":["../../../src/mutator/template/template_cache.ts"],"sourcesContent":["import { createHash } from \"node:crypto\";\nimport type {\n AnyResourceRef,\n PlClient,\n PlTransaction,\n SignedResourceId,\n ResourceRef,\n} from \"@milaboratories/pl-client\";\nimport {\n ensureSignedResourceIdNotNull,\n field,\n resourceType,\n toGlobalResourceId,\n} from \"@milaboratories/pl-client\";\nimport {\n parseTemplate,\n PlTemplateLibV1,\n PlTemplateOverrideV1,\n PlTemplateSoftwareV1,\n PlTemplateV1,\n PlWasmV1,\n} from \"@milaboratories/pl-model-backend\";\nimport type {\n CompiledTemplateV3,\n TemplateData,\n TemplateDataV3,\n TemplateLibData,\n TemplateLibDataV3,\n TemplateSoftwareData,\n TemplateSoftwareDataV3,\n TemplateWasmDataV3,\n} from \"@milaboratories/pl-model-backend\";\nimport { notEmpty } from \"@milaboratories/ts-helpers\";\nimport type { BlockPackSpecPrepared } from \"../../model\";\nimport type { InstallablePackTemplate, TemplateSpecPrepared } from \"../../model/template_spec\";\nimport type { BlockPackPreparer } from \"../block-pack/block_pack\";\nimport { throwIfMissingServerCapabilities } from \"../block-pack/required_capabilities\";\nimport { getDebugFlags } from \"../../debug\";\n\nexport const TemplateCacheType = resourceType(\"TemplateCache\", \"1\");\n\nexport const TemplateCacheFieldName = \"__templateCache\";\nconst BATCH_SIZE = 50;\n/** @internal exported for testing */\nexport const GC_ACCESS_THRESHOLD = 30;\n/** @internal exported for testing */\nexport const GC_MAX_ENTRIES = 3000;\n/** @internal exported for testing */\nexport const ACCESS_COUNT_KEY = \"_accessCount\";\n/** @internal exported for testing */\nexport const ACCESS_KEY_PREFIX = \"access_\";\n\nexport type TemplateCacheStat = {\n totalMs: number;\n flattenMs: number;\n cacheInitMs: number;\n materializeMs: number;\n totalNodes: number;\n cacheHits: number;\n cacheMisses: number;\n batchCount: number;\n happyPath: boolean;\n gcTriggered: boolean;\n retries: number;\n templateFormat: string;\n};\n\nfunction initialStat(): TemplateCacheStat {\n return {\n totalMs: 0,\n flattenMs: 0,\n cacheInitMs: 0,\n materializeMs: 0,\n totalNodes: 0,\n cacheHits: 0,\n cacheMisses: 0,\n batchCount: 0,\n happyPath: false,\n gcTriggered: false,\n retries: 0,\n templateFormat: \"\",\n };\n}\n\ninterface CacheableNode {\n /** SHA-256 content hash (includes all descendant content) */\n hash: string;\n /** Creates this node's resource in a transaction.\n * childRefs maps child hash → already-resolved ResourceRef or SignedResourceId */\n create: (tx: PlTransaction, childRefs: ReadonlyMap<string, AnyResourceRef>) => ResourceRef;\n /** Hashes of direct child nodes this node depends on */\n childHashes: string[];\n}\n\nfunction getSourceCode(name: string, sources: Record<string, string>, sourceHash: string): string {\n return notEmpty(\n sources[sourceHash],\n `trying to get \"${name}\" source: sources map doesn't contain source hash ${sourceHash}`,\n );\n}\n\n/**\n * Bottom-up hash composition: each node hashes its OWN content + child hash STRINGS.\n * This means each unique node is hashed exactly once → O(n) instead of O(n * depth).\n */\n\n// V2 leaf hashes (libs, software — no children)\n\nfunction hashLibV2(lib: TemplateLibData): string {\n return createHash(\"sha256\")\n .update(PlTemplateLibV1.type.name)\n .update(PlTemplateLibV1.type.version)\n .update(lib.name)\n .update(lib.version)\n .update(lib.src)\n .digest(\"hex\");\n}\n\nfunction hashSoftwareV2(sw: TemplateSoftwareData): string {\n return createHash(\"sha256\")\n .update(PlTemplateSoftwareV1.type.name)\n .update(PlTemplateSoftwareV1.type.version)\n .update(sw.name)\n .update(sw.version)\n .update(sw.src)\n .digest(\"hex\");\n}\n\n// V3 leaf hashes — use sourceHash directly instead of resolving source content\n\nfunction hashLibV3(lib: TemplateLibDataV3): string {\n return createHash(\"sha256\")\n .update(PlTemplateLibV1.type.name)\n .update(PlTemplateLibV1.type.version)\n .update(lib.name)\n .update(lib.version)\n .update(lib.sourceHash)\n .digest(\"hex\");\n}\n\nfunction hashSoftwareV3(sw: TemplateSoftwareDataV3): string {\n return createHash(\"sha256\")\n .update(PlTemplateSoftwareV1.type.name)\n .update(PlTemplateSoftwareV1.type.version)\n .update(sw.name)\n .update(sw.version)\n .update(sw.sourceHash)\n .digest(\"hex\");\n}\n\nfunction hashWasmV3(wasm: TemplateWasmDataV3): string {\n return createHash(\"sha256\")\n .update(PlWasmV1.type.name)\n .update(PlWasmV1.type.version)\n .update(wasm.name)\n .update(wasm.version)\n .update(wasm.sourceHash)\n .digest(\"hex\");\n}\n\n// ─── Tree flattening ─────────────────────────────────────────────────────────\n\nfunction flattenV2Tree(data: TemplateData): CacheableNode[] {\n const nodes: CacheableNode[] = [];\n const seen = new Set<string>();\n\n function processLib(lib: TemplateLibData): string {\n const hash = hashLibV2(lib);\n if (!seen.has(hash)) {\n seen.add(hash);\n nodes.push({\n hash,\n create: (tx) =>\n tx.createValue(\n PlTemplateLibV1.type,\n JSON.stringify(PlTemplateLibV1.fromV2Data(lib).data),\n ),\n childHashes: [],\n });\n }\n return hash;\n }\n\n function processSoftware(sw: TemplateSoftwareData): string {\n const hash = hashSoftwareV2(sw);\n if (!seen.has(hash)) {\n seen.add(hash);\n nodes.push({\n hash,\n create: (tx) => {\n const swData = PlTemplateSoftwareV1.fromV2Data(sw);\n const ref = tx.createStruct(PlTemplateSoftwareV1.type, swData.data);\n tx.setKValue(ref, PlTemplateSoftwareV1.metaNameKey, JSON.stringify(swData.name));\n tx.lock(ref);\n return ref;\n },\n childHashes: [],\n });\n }\n return hash;\n }\n\n function processTemplate(tpl: TemplateData): string {\n // Process children first (bottom-up) — their hashes are computed before ours\n const childHashes: string[] = [];\n const children: { fieldName: string; hash: string }[] = [];\n\n for (const [libId, lib] of Object.entries(tpl.libs ?? {})) {\n const h = processLib(lib);\n childHashes.push(h);\n children.push({ fieldName: `${PlTemplateV1.libPrefix}/${libId}`, hash: h });\n }\n for (const [swId, sw] of Object.entries(tpl.software ?? {})) {\n const h = processSoftware(sw);\n childHashes.push(h);\n children.push({ fieldName: `${PlTemplateV1.softPrefix}/${swId}`, hash: h });\n }\n for (const [swId, sw] of Object.entries(tpl.assets ?? {})) {\n const h = processSoftware(sw);\n childHashes.push(h);\n children.push({ fieldName: `${PlTemplateV1.softPrefix}/${swId}`, hash: h });\n }\n for (const [tplId, sub] of Object.entries(tpl.templates ?? {})) {\n const h = processTemplate(sub);\n childHashes.push(h);\n children.push({ fieldName: `${PlTemplateV1.tplPrefix}/${tplId}`, hash: h });\n }\n\n // Compose hash from own content + child hash strings (NOT child content)\n const h = createHash(\"sha256\")\n .update(PlTemplateV1.type.name)\n .update(PlTemplateV1.type.version)\n .update(tpl.hashOverride ?? \"no-override\")\n .update(tpl.name)\n .update(tpl.version)\n .update(tpl.src);\n for (const child of children) {\n h.update(\"child:\" + child.fieldName + \":\" + child.hash);\n }\n const hash = h.digest(\"hex\");\n\n if (seen.has(hash)) return hash;\n seen.add(hash);\n nodes.push({\n hash,\n create: (tx, childRefs) => {\n const tplRef = tx.createStruct(\n PlTemplateV1.type,\n JSON.stringify(PlTemplateV1.fromV2Data(tpl).data),\n );\n for (const child of children) {\n const fld = field(tplRef, child.fieldName);\n tx.createField(fld, \"Input\");\n tx.setField(fld, notEmpty(childRefs.get(child.hash), `missing child ref ${child.hash}`));\n }\n tx.lock(tplRef);\n\n if (!tpl.hashOverride) return tplRef;\n\n const overrideRef = tx.createStruct(\n PlTemplateOverrideV1.type,\n JSON.stringify(PlTemplateOverrideV1.fromV2Data(tpl)),\n );\n const overrideFld = PlTemplateOverrideV1.tplField(overrideRef);\n tx.createField(overrideFld, \"Service\");\n tx.setField(overrideFld, tplRef);\n tx.lock(overrideRef);\n return overrideRef;\n },\n childHashes,\n });\n\n return hash;\n }\n\n processTemplate(data);\n return nodes;\n}\n\nfunction flattenV3Tree(data: CompiledTemplateV3): CacheableNode[] {\n const nodes: CacheableNode[] = [];\n const seen = new Set<string>();\n const sources = data.hashToSource;\n\n function processLib(lib: TemplateLibDataV3): string {\n const hash = hashLibV3(lib);\n if (!seen.has(hash)) {\n seen.add(hash);\n nodes.push({\n hash,\n create: (tx) =>\n tx.createValue(\n PlTemplateLibV1.type,\n JSON.stringify(\n PlTemplateLibV1.fromV3Data(lib, getSourceCode(lib.name, sources, lib.sourceHash))\n .data,\n ),\n ),\n childHashes: [],\n });\n }\n return hash;\n }\n\n function processSoftware(sw: TemplateSoftwareDataV3): string {\n const hash = hashSoftwareV3(sw);\n if (!seen.has(hash)) {\n seen.add(hash);\n nodes.push({\n hash,\n create: (tx) => {\n const swData = PlTemplateSoftwareV1.fromV3Data(\n sw,\n getSourceCode(sw.name, sources, sw.sourceHash),\n );\n const ref = tx.createStruct(PlTemplateSoftwareV1.type, swData.data);\n tx.setKValue(ref, PlTemplateSoftwareV1.metaNameKey, JSON.stringify(swData.name));\n tx.lock(ref);\n return ref;\n },\n childHashes: [],\n });\n }\n return hash;\n }\n\n function processWasm(wasm: TemplateWasmDataV3): string {\n const hash = hashWasmV3(wasm);\n if (!seen.has(hash)) {\n seen.add(hash);\n nodes.push({\n hash,\n create: (tx) =>\n tx.createValue(\n PlWasmV1.type,\n JSON.stringify(\n PlWasmV1.fromV3Data(wasm, getSourceCode(wasm.name, sources, wasm.sourceHash)).data,\n ),\n ),\n childHashes: [],\n });\n }\n return hash;\n }\n\n function processTemplate(tpl: TemplateDataV3): string {\n // Defensive: a template can carry no embedded version at runtime even\n // though the type says `string` — the compiler writes `packageJson.version`\n // unchecked, so a template built from a package with no `version` field\n // yields undefined. Identity is fully covered by name + sourceHash, so the\n // placeholder is safe for both the cache key and the backend resource's\n // required Version field.\n const version = tpl.version ?? \"0.0.0\";\n\n // Process children first (bottom-up)\n const childHashes: string[] = [];\n const children: { fieldName: string; hash: string }[] = [];\n\n for (const [libId, lib] of Object.entries(tpl.libs ?? {})) {\n const h = processLib(lib);\n childHashes.push(h);\n children.push({ fieldName: `${PlTemplateV1.libPrefix}/${libId}`, hash: h });\n }\n for (const [swId, sw] of Object.entries(tpl.software ?? {})) {\n const h = processSoftware(sw);\n childHashes.push(h);\n children.push({ fieldName: `${PlTemplateV1.softPrefix}/${swId}`, hash: h });\n }\n for (const [swId, sw] of Object.entries(tpl.assets ?? {})) {\n const h = processSoftware(sw);\n childHashes.push(h);\n children.push({ fieldName: `${PlTemplateV1.softPrefix}/${swId}`, hash: h });\n }\n for (const [tplId, sub] of Object.entries(tpl.templates ?? {})) {\n const h = processTemplate(sub);\n childHashes.push(h);\n children.push({ fieldName: `${PlTemplateV1.tplPrefix}/${tplId}`, hash: h });\n }\n for (const [wasmId, wasm] of Object.entries(tpl.wasm ?? {})) {\n const h = processWasm(wasm);\n childHashes.push(h);\n children.push({ fieldName: `${PlTemplateV1.wasmPrefix}/${wasmId}`, hash: h });\n }\n\n // Compose hash from own content + child hash strings (NOT child content).\n // Uses sourceHash directly — it already uniquely identifies the source.\n const h = createHash(\"sha256\")\n .update(PlTemplateV1.type.name)\n .update(PlTemplateV1.type.version)\n .update(tpl.hashOverride ?? \"no-override\")\n .update(tpl.name)\n .update(version)\n .update(tpl.sourceHash);\n for (const child of children) {\n h.update(\"child:\" + child.fieldName + \":\" + child.hash);\n }\n const hash = h.digest(\"hex\");\n\n if (seen.has(hash)) return hash;\n seen.add(hash);\n nodes.push({\n hash,\n create: (tx, childRefs) => {\n const sourceCode = getSourceCode(tpl.name, sources, tpl.sourceHash);\n const tplRef = tx.createStruct(\n PlTemplateV1.type,\n JSON.stringify(PlTemplateV1.fromV3Data({ ...tpl, version }, sourceCode).data),\n );\n for (const child of children) {\n const fld = field(tplRef, child.fieldName);\n tx.createField(fld, \"Input\");\n tx.setField(fld, notEmpty(childRefs.get(child.hash), `missing child ref ${child.hash}`));\n }\n tx.lock(tplRef);\n\n if (!tpl.hashOverride) return tplRef;\n\n const overrideRef = tx.createStruct(\n PlTemplateOverrideV1.type,\n JSON.stringify(PlTemplateOverrideV1.fromV3Data(tpl)),\n );\n const overrideFld = PlTemplateOverrideV1.tplField(overrideRef);\n tx.createField(overrideFld, \"Service\");\n tx.setField(overrideFld, tplRef);\n tx.lock(overrideRef);\n return overrideRef;\n },\n childHashes,\n });\n\n return hash;\n }\n\n processTemplate(data.template);\n return nodes;\n}\n\n/** Flatten template tree into a topologically ordered list of cacheable nodes (leaves first). */\nexport function flattenTemplateTree(data: TemplateData | CompiledTemplateV3): CacheableNode[] {\n if (data.type === \"pl.tengo-template.v2\") {\n return flattenV2Tree(data);\n } else {\n return flattenV3Tree(data);\n }\n}\n\n/** In-memory cache for the TemplateCache SignedResourceId per PlClient instance. */\nconst cacheRidMap = new WeakMap<PlClient, SignedResourceId>();\n\n/** Clear the in-memory cacheRid entry (call on errors referencing the cache resource). */\nexport function invalidateTemplateCacheId(pl: PlClient): void {\n cacheRidMap.delete(pl);\n}\n\n/** Find or create the TemplateCache/1 resource on user root. */\nexport async function getOrCreateTemplateCache(pl: PlClient): Promise<SignedResourceId> {\n // Check in-memory cache first (0ms after first call)\n const cached = cacheRidMap.get(pl);\n if (cached !== undefined) return cached;\n\n // Try read-only check\n const existing = await pl.withReadTx(\"templateCache:check\", async (tx) => {\n const fd = await tx.getFieldIfExists(field(pl.clientRoot, TemplateCacheFieldName));\n return fd ? ensureSignedResourceIdNotNull(fd.value) : undefined;\n });\n if (existing) {\n cacheRidMap.set(pl, existing);\n return existing;\n }\n\n const result = await pl.withWriteTx(\"templateCache:init\", async (tx) => {\n // Double-check inside write tx (another instance may have created it)\n const fd = await tx.getFieldIfExists(field(pl.clientRoot, TemplateCacheFieldName));\n if (fd) return ensureSignedResourceIdNotNull(fd.value);\n\n const cache = tx.createStruct(TemplateCacheType);\n tx.createField(field(pl.clientRoot, TemplateCacheFieldName), \"Dynamic\", cache);\n tx.lock(cache);\n await tx.commit();\n return await cache.globalId;\n });\n cacheRidMap.set(pl, result);\n return result;\n}\n\n/** Remove the template cache from user root. */\nexport async function dropTemplateCache(pl: PlClient): Promise<void> {\n await pl.withWriteTx(\"templateCache:drop\", async (tx) => {\n const cacheField = field(pl.clientRoot, TemplateCacheFieldName);\n const fd = await tx.getFieldIfExists(cacheField);\n if (fd) {\n tx.removeField(cacheField);\n await tx.commit();\n }\n });\n invalidateTemplateCacheId(pl);\n}\n\n/**\n * Run count-based garbage collection on the template cache.\n * Evicts least-recently-used entries when the cache exceeds maxEntries.\n * Always resets the access counter to 0.\n *\n * @internal exported for testing (maxEntries parameter allows low thresholds in tests)\n * @returns true if entries were evicted\n */\nexport async function runGc(\n pl: PlClient,\n cacheRid: SignedResourceId,\n maxEntries: number = GC_MAX_ENTRIES,\n): Promise<boolean> {\n return await pl.withWriteTx(\"templateCache:gc\", async (tx) => {\n const kvs = await tx.listKeyValuesString(cacheRid);\n const entries: { hash: string; timestamp: number }[] = [];\n for (const { key, value } of kvs) {\n if (!key.startsWith(ACCESS_KEY_PREFIX)) continue;\n entries.push({\n hash: key.slice(ACCESS_KEY_PREFIX.length),\n timestamp: parseInt(value, 10),\n });\n }\n\n // Always reset counter\n tx.setKValue(cacheRid, ACCESS_COUNT_KEY, \"0\");\n\n if (entries.length <= maxEntries) {\n await tx.commit();\n return false;\n }\n\n // Sort oldest first, evict until under limit\n entries.sort((a, b) => a.timestamp - b.timestamp);\n const toEvict = entries.length - maxEntries;\n for (let i = 0; i < toEvict; i++) {\n tx.removeField(field(cacheRid, entries[i].hash));\n tx.deleteKValue(cacheRid, ACCESS_KEY_PREFIX + entries[i].hash);\n }\n\n await tx.commit();\n return true;\n });\n}\n\n/** Create a batch of cache nodes in the current transaction. */\nfunction createBatchNodes(\n tx: PlTransaction,\n cacheRid: SignedResourceId,\n batch: CacheableNode[],\n resolvedIds: ReadonlyMap<string, SignedResourceId>,\n newRefs: Map<string, ResourceRef>,\n now: string,\n): void {\n for (const node of batch) {\n const childRefs = new Map<string, AnyResourceRef>();\n for (const ch of node.childHashes) {\n const resolved = resolvedIds.get(ch) ?? newRefs.get(ch);\n if (resolved === undefined) {\n throw new Error(`BUG: child ${ch} not resolved`);\n }\n childRefs.set(ch, resolved);\n }\n const ref = node.create(tx, childRefs);\n newRefs.set(node.hash, ref);\n tx.createField(field(cacheRid, node.hash), \"Dynamic\", ref);\n tx.setKValue(cacheRid, ACCESS_KEY_PREFIX + node.hash, now);\n }\n}\n\n/**\n * Materialize a template tree via the cache using \"probe all + batched creation\".\n *\n * Phase 1 (single write tx):\n * - Check existence of ALL hashes in one roundtrip\n * - Happy path: if root cached, update access tracking and return\n * - Otherwise: fetch ResourceIds for all cache hits, create first batch of missing nodes\n *\n * Phase 2..N (one write tx per batch):\n * - Create remaining missing nodes in BATCH_SIZE chunks\n *\n * @returns root SignedResourceId and current access count (for GC decision)\n */\nasync function materialize(\n pl: PlClient,\n cacheRid: SignedResourceId,\n rootHash: string,\n nodes: CacheableNode[],\n stat: TemplateCacheStat,\n): Promise<{ rootId: SignedResourceId; accessCount: number }> {\n const allHashes = nodes.map((n) => n.hash);\n const resolvedIds = new Map<string, SignedResourceId>();\n\n // Phase 1: probe all + first batch\n const phase1 = await pl.withWriteTx(\"templateCache:materialize\", async (tx) => {\n // 1 roundtrip: check all hashes + read access count\n const [exists, countStr] = await Promise.all([\n Promise.all(allHashes.map((h) => tx.fieldExists(field(cacheRid, h)))),\n tx.getKValueStringIfExists(cacheRid, ACCESS_COUNT_KEY),\n ]);\n\n const prevCount = countStr ? parseInt(countStr, 10) : 0;\n const newCount = prevCount + 1;\n const now = Date.now().toString();\n const rootIdx = allHashes.length - 1;\n\n // Happy path: root already cached\n if (exists[rootIdx]) {\n const rootFd = await tx.getField(field(cacheRid, rootHash));\n const rootRid = ensureSignedResourceIdNotNull(rootFd.value);\n tx.setKValue(cacheRid, ACCESS_KEY_PREFIX + rootHash, now);\n tx.setKValue(cacheRid, ACCESS_COUNT_KEY, newCount.toString());\n await tx.commit();\n stat.happyPath = true;\n stat.cacheHits = stat.totalNodes;\n stat.batchCount = 1;\n return { done: true as const, rootId: rootRid, accessCount: newCount };\n }\n\n // Fetch ResourceIds for all cache hits (1 roundtrip)\n const hitIndices: number[] = [];\n for (let i = 0; i < allHashes.length; i++) {\n if (exists[i]) hitIndices.push(i);\n }\n\n if (hitIndices.length > 0) {\n const hitFields = await Promise.all(\n hitIndices.map((i) => tx.getField(field(cacheRid, allHashes[i]))),\n );\n for (let j = 0; j < hitIndices.length; j++) {\n resolvedIds.set(\n allHashes[hitIndices[j]],\n ensureSignedResourceIdNotNull(hitFields[j].value),\n );\n }\n }\n stat.cacheHits = hitIndices.length;\n\n // Missing nodes (topo order preserved from flatten)\n const missing = nodes.filter((n) => !resolvedIds.has(n.hash));\n stat.cacheMisses = missing.length;\n\n // Create first batch of missing nodes\n const firstBatch = missing.slice(0, BATCH_SIZE);\n const newRefs = new Map<string, ResourceRef>();\n createBatchNodes(tx, cacheRid, firstBatch, resolvedIds, newRefs, now);\n\n // Update access tracking for cache hits\n for (const i of hitIndices) {\n tx.setKValue(cacheRid, ACCESS_KEY_PREFIX + allHashes[i], now);\n }\n tx.setKValue(cacheRid, ACCESS_COUNT_KEY, newCount.toString());\n\n await tx.commit();\n\n // Resolve new refs to global IDs (after commit)\n for (const [hash, ref] of newRefs) {\n resolvedIds.set(hash, await toGlobalResourceId(ref));\n }\n\n return {\n done: false as const,\n remaining: missing.slice(BATCH_SIZE),\n accessCount: newCount,\n };\n });\n\n if (phase1.done) {\n return { rootId: phase1.rootId, accessCount: phase1.accessCount };\n }\n\n stat.batchCount = 1;\n\n // Phase 2+: remaining batches\n const { remaining } = phase1;\n for (let i = 0; i < remaining.length; i += BATCH_SIZE) {\n const batch = remaining.slice(i, i + BATCH_SIZE);\n stat.batchCount++;\n\n await pl.withWriteTx(\"templateCache:create\", async (tx) => {\n const newRefs = new Map<string, ResourceRef>();\n const now = Date.now().toString();\n createBatchNodes(tx, cacheRid, batch, resolvedIds, newRefs, now);\n await tx.commit();\n\n for (const [hash, ref] of newRefs) {\n resolvedIds.set(hash, await toGlobalResourceId(ref));\n }\n });\n }\n\n const rootId = resolvedIds.get(rootHash);\n if (!rootId) throw new Error(\"BUG: root hash not resolved after all batches\");\n return { rootId, accessCount: phase1.accessCount };\n}\n\n/**\n * Materialize a template tree via the cache.\n * Manages its own transactions internally — do NOT call inside an existing tx.\n *\n * @returns concrete SignedResourceId of the root template\n */\nexport async function loadTemplateCached(\n pl: PlClient,\n spec: TemplateSpecPrepared,\n options?: { cacheResourceId?: SignedResourceId },\n): Promise<SignedResourceId> {\n const stat = initialStat();\n const t0 = performance.now();\n\n try {\n // Parse to data if needed\n let tplData: TemplateData | CompiledTemplateV3;\n switch (spec.type) {\n case \"explicit\":\n tplData = parseTemplate(spec.content);\n break;\n case \"prepared\":\n tplData = spec.data;\n break;\n case \"cached\":\n return spec.resourceId;\n case \"from-registry\":\n throw new Error(\n \"loadTemplateCached does not support from-registry specs; use loadTemplate instead\",\n );\n default: {\n const _: never = spec;\n throw new Error(`unexpected spec type: ${(_ as any).type}`);\n }\n }\n\n stat.templateFormat = tplData.type;\n\n // Flatten to ordered nodes\n const tFlatten = performance.now();\n const nodes = flattenTemplateTree(tplData);\n stat.flattenMs = performance.now() - tFlatten;\n if (nodes.length === 0) throw new Error(\"template tree produced no nodes\");\n\n stat.totalNodes = nodes.length;\n const rootHash = nodes[nodes.length - 1].hash;\n\n // Resolve or create cache resource\n const tCacheInit = performance.now();\n const cacheRid = options?.cacheResourceId ?? (await getOrCreateTemplateCache(pl));\n stat.cacheInitMs = performance.now() - tCacheInit;\n\n // Retry loop: if a write tx fails (e.g. concurrent GC invalidated a cached resource),\n // restart materialization from scratch.\n const MAX_RETRIES = 3;\n for (let attempt = 0; attempt < MAX_RETRIES; attempt++) {\n try {\n const tMat = performance.now();\n const result = await materialize(pl, cacheRid, rootHash, nodes, stat);\n stat.materializeMs = performance.now() - tMat;\n stat.retries = attempt;\n\n // GC in separate tx if access count exceeded threshold\n if (result.accessCount >= GC_ACCESS_THRESHOLD) {\n await runGc(pl, cacheRid);\n stat.gcTriggered = true;\n }\n\n return result.rootId;\n } catch (e) {\n if (attempt === MAX_RETRIES - 1) throw e;\n // Retry from scratch — previous batch results may reference GC'd resources\n stat.cacheHits = 0;\n stat.cacheMisses = 0;\n }\n }\n\n throw new Error(\"BUG: unreachable\");\n } finally {\n stat.totalMs = performance.now() - t0;\n if (getDebugFlags().logTemplateCacheStat) {\n console.log(`[templateCache] ${JSON.stringify(stat)}`);\n }\n }\n}\n\ntype CacheBlockPackOptions = {\n cacheResourceId?: SignedResourceId;\n /** Loads registry and local packs. */\n preparer?: BlockPackPreparer;\n};\n\n/**\n * Pre-materialize a block pack's template via cache.\n * Returns a copy of the spec with the template replaced by a cached reference.\n * If the template is already cached, returns the spec unchanged.\n */\nexport async function cacheBlockPackTemplate(\n pl: PlClient,\n spec: BlockPackSpecPrepared,\n options?: CacheBlockPackOptions,\n): Promise<BlockPackSpecPrepared> {\n if (spec.template.type === \"cached\") return spec;\n\n const resourceId =\n spec.template.type === \"registry-pack\" || spec.template.type === \"local-pack\"\n ? await installPackOnClient(pl, spec.template, options)\n : await loadTemplateCached(pl, spec.template, options);\n return {\n ...spec,\n template: { type: \"cached\", resourceId },\n };\n}\n\nasync function installPackOnClient(\n pl: PlClient,\n template: InstallablePackTemplate,\n options?: CacheBlockPackOptions,\n): Promise<SignedResourceId> {\n if (options?.preparer === undefined) throw new Error(\"BUG: a pack needs a preparer to load it\");\n const loaded = await options.preparer.loadPack(template);\n // The manifest may predate the requiredCapabilities field: check what the pack declares.\n throwIfMissingServerCapabilities(pl, loaded.requiredCapabilities);\n return await loadTemplateCached(pl, loaded.template, options);\n}\n"],"mappings":";;;;;;;AAuCA,MAAa,oBAAoB,aAAa,iBAAiB,GAAG;AAElE,MAAa,yBAAyB;AACtC,MAAM,aAAa;;AAEnB,MAAa,sBAAsB;;AAEnC,MAAa,iBAAiB;;AAE9B,MAAa,mBAAmB;;AAEhC,MAAa,oBAAoB;AAiBjC,SAAS,cAAiC;CACxC,OAAO;EACL,SAAS;EACT,WAAW;EACX,aAAa;EACb,eAAe;EACf,YAAY;EACZ,WAAW;EACX,aAAa;EACb,YAAY;EACZ,WAAW;EACX,aAAa;EACb,SAAS;EACT,gBAAgB;CAClB;AACF;AAYA,SAAS,cAAc,MAAc,SAAiC,YAA4B;CAChG,OAAO,SACL,QAAQ,aACR,kBAAkB,KAAK,oDAAoD,YAC7E;AACF;;;;;AASA,SAAS,UAAU,KAA8B;CAC/C,OAAO,WAAW,QAAQ,CAAC,CACxB,OAAO,gBAAgB,KAAK,IAAI,CAAC,CACjC,OAAO,gBAAgB,KAAK,OAAO,CAAC,CACpC,OAAO,IAAI,IAAI,CAAC,CAChB,OAAO,IAAI,OAAO,CAAC,CACnB,OAAO,IAAI,GAAG,CAAC,CACf,OAAO,KAAK;AACjB;AAEA,SAAS,eAAe,IAAkC;CACxD,OAAO,WAAW,QAAQ,CAAC,CACxB,OAAO,qBAAqB,KAAK,IAAI,CAAC,CACtC,OAAO,qBAAqB,KAAK,OAAO,CAAC,CACzC,OAAO,GAAG,IAAI,CAAC,CACf,OAAO,GAAG,OAAO,CAAC,CAClB,OAAO,GAAG,GAAG,CAAC,CACd,OAAO,KAAK;AACjB;AAIA,SAAS,UAAU,KAAgC;CACjD,OAAO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QAAQ,IAAI,mBAAmB,KAAK,UAAU,IAAI,GAAG;CAEzD;AACF;;;;;;AAaA,eAAsB,uBACpB,IACA,MACA,SACgC;CAChC,IAAI,KAAK,SAAS,SAAS,UAAU,OAAO;CAE5C,MAAM,aACJ,KAAK,SAAS,SAAS,mBAAmB,KAAK,SAAS,SAAS,eAC7D,MAAM,oBAAoB,IAAI,KAAK,UAAU,OAAO,IACpD,MAAM,mBAAmB,IAAI,KAAK,UAAU,OAAO;CACzD,OAAO;EACL,GAAG;EACH,UAAU;GAAE,MAAM;GAAU;EAAW;CACzC;AACF;AAEA,eAAe,oBACb,IACA,UACA,SAC2B;CAC3B,IAAI,SAAS,aAAa,KAAA,GAAW,MAAM,IAAI,MAAM,yCAAyC;CAC9F,MAAM,SAAS,MAAM,QAAQ,SAAS,SAAS,QAAQ;CAEvD,iCAAiC,IAAI,OAAO,oBAAoB;CAChE,OAAO,MAAM,mBAAmB,IAAI,OAAO,UAAU,OAAO;AAC9D"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@milaboratories/pl-middle-layer",
|
|
3
|
-
"version": "2.10.
|
|
3
|
+
"version": "2.10.1",
|
|
4
4
|
"description": "Pl Middle Layer",
|
|
5
5
|
"keywords": [],
|
|
6
6
|
"license": "UNLICENSED",
|
|
@@ -36,7 +36,7 @@
|
|
|
36
36
|
"@milaboratories/pl-tree": "1.18.13",
|
|
37
37
|
"@milaboratories/resolve-helper": "1.1.3",
|
|
38
38
|
"@milaboratories/ts-helpers": "1.9.1",
|
|
39
|
-
"@platforma-sdk/block-tools": "2.
|
|
39
|
+
"@platforma-sdk/block-tools": "2.23.0",
|
|
40
40
|
"@platforma-sdk/model": "1.96.4",
|
|
41
41
|
"@platforma-sdk/workflow-tengo": "7.2.0",
|
|
42
42
|
"canonicalize": "~2.1.0",
|
|
@@ -86,7 +86,7 @@ import type { BlockPackProvider, TemplateResolveOutcome } from "../model/templat
|
|
|
86
86
|
import { resolveTemplateEntries } from "../model/template_resolve";
|
|
87
87
|
import type { PreparedTemplateEntry } from "../mutator/template_construct";
|
|
88
88
|
import { applyTemplateEntries } from "../mutator/template_construct";
|
|
89
|
-
import { throwIfMissingServerCapabilities } from "
|
|
89
|
+
import { throwIfMissingServerCapabilities } from "../mutator/block-pack/required_capabilities";
|
|
90
90
|
import { cacheBlockPackTemplate } from "../mutator/template/template_cache";
|
|
91
91
|
import { ProjectMetaKey } from "../model/project_model";
|
|
92
92
|
import type { ProjectId } from "../model/project_model";
|
|
@@ -819,7 +819,9 @@ export class MiddleLayer {
|
|
|
819
819
|
this.env.runtimeCapabilities.throwIfIncompatible(blockCfg.featureFlags);
|
|
820
820
|
throwIfMissingServerCapabilities(this.pl, preparedBp.requiredCapabilities);
|
|
821
821
|
|
|
822
|
-
const cachedBp = await cacheBlockPackTemplate(this.pl, preparedBp
|
|
822
|
+
const cachedBp = await cacheBlockPackTemplate(this.pl, preparedBp, {
|
|
823
|
+
preparer: this.env.bpPreparer,
|
|
824
|
+
});
|
|
823
825
|
|
|
824
826
|
// Offered to the block's kind while nothing has been created yet. Every entry is
|
|
825
827
|
// checked, including one whose file omitted `params` — the parser read that as `{}`,
|
|
@@ -3,7 +3,6 @@ import type {
|
|
|
3
3
|
FieldData,
|
|
4
4
|
Filter,
|
|
5
5
|
OptionalAnyResourceId,
|
|
6
|
-
PlClient,
|
|
7
6
|
SignedResourceId,
|
|
8
7
|
} from "@milaboratories/pl-client";
|
|
9
8
|
import {
|
|
@@ -90,6 +89,7 @@ import type { ProjectOverviewLight } from "./project_overview_light";
|
|
|
90
89
|
import { projectOverviewLight } from "./project_overview_light";
|
|
91
90
|
import { applyProjectMigrations } from "../mutator/migration";
|
|
92
91
|
import { cacheBlockPackTemplate } from "../mutator/template/template_cache";
|
|
92
|
+
import { throwIfMissingServerCapabilities } from "../mutator/block-pack/required_capabilities";
|
|
93
93
|
|
|
94
94
|
type BlockStateComputables = {
|
|
95
95
|
readonly fullState: Computable<BlockStateInternalV3>;
|
|
@@ -495,7 +495,9 @@ export class Project {
|
|
|
495
495
|
}
|
|
496
496
|
|
|
497
497
|
// Pre-materialize template via cache (separate transaction(s))
|
|
498
|
-
const cachedBp = await cacheBlockPackTemplate(this.env.pl, preparedBp
|
|
498
|
+
const cachedBp = await cacheBlockPackTemplate(this.env.pl, preparedBp, {
|
|
499
|
+
preparer: this.env.bpPreparer,
|
|
500
|
+
});
|
|
499
501
|
|
|
500
502
|
// Build NewBlockSpec based on model API version
|
|
501
503
|
const newBlockSpec =
|
|
@@ -589,7 +591,9 @@ export class Project {
|
|
|
589
591
|
throwIfMissingServerCapabilities(this.env.pl, preparedBp.requiredCapabilities);
|
|
590
592
|
|
|
591
593
|
// Pre-materialize template via cache (separate transaction(s))
|
|
592
|
-
const cachedBp = await cacheBlockPackTemplate(this.env.pl, preparedBp
|
|
594
|
+
const cachedBp = await cacheBlockPackTemplate(this.env.pl, preparedBp, {
|
|
595
|
+
preparer: this.env.bpPreparer,
|
|
596
|
+
});
|
|
593
597
|
|
|
594
598
|
// resetState signals to mutator to reset storage
|
|
595
599
|
// For v2+ blocks: mutator gets initial storage directly via getInitialStorageInVM
|
|
@@ -1384,27 +1388,3 @@ function convertErrorsToStrings(
|
|
|
1384
1388
|
|
|
1385
1389
|
return result;
|
|
1386
1390
|
}
|
|
1387
|
-
|
|
1388
|
-
/** Throws when the connected backend doesn't advertise every capability the
|
|
1389
|
-
* block-pack requires (as declared in `meta.requiredCapabilities`).
|
|
1390
|
-
*
|
|
1391
|
-
* The matching set is the desktop's install gate moved server-side so both
|
|
1392
|
-
* the UI (`AddBlockModal`) and direct middle-layer callers (the MCP server's
|
|
1393
|
-
* `add_block` tool, programmatic block installs, tests) reject incompatible
|
|
1394
|
-
* blocks consistently. */
|
|
1395
|
-
export function throwIfMissingServerCapabilities(
|
|
1396
|
-
pl: PlClient,
|
|
1397
|
-
requiredCapabilities: readonly string[] | undefined,
|
|
1398
|
-
): void {
|
|
1399
|
-
if (!requiredCapabilities || requiredCapabilities.length === 0) return;
|
|
1400
|
-
const advertised = (pl.serverInfo.capabilities ?? []) as readonly string[];
|
|
1401
|
-
const filterFn = (c: string) => !advertised.includes(c);
|
|
1402
|
-
if (!requiredCapabilities.some(filterFn)) return;
|
|
1403
|
-
const missing = requiredCapabilities.filter(filterFn);
|
|
1404
|
-
throw new Error(
|
|
1405
|
-
`Block cannot be added: connected backend does not advertise capabilities ` +
|
|
1406
|
-
`${JSON.stringify(missing)}. ` +
|
|
1407
|
-
`Backend advertises ${JSON.stringify(advertised)}. ` +
|
|
1408
|
-
`Upgrade the backend or remove the requirement from the block manifest.`,
|
|
1409
|
-
);
|
|
1410
|
-
}
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import type { CachedTemplate, ExplicitTemplate, PreparedTemplate } from "./template_spec";
|
|
2
|
+
import type { InstallablePackTemplate } from "./template_spec";
|
|
2
3
|
import type { ResourceType } from "@milaboratories/pl-client";
|
|
3
4
|
import type { BlockConfigContainer } from "@platforma-sdk/model";
|
|
4
5
|
import type { BlockPackSpec } from "@milaboratories/pl-model-middle-layer";
|
|
@@ -71,13 +72,13 @@ export interface BlockPackExplicit {
|
|
|
71
72
|
/** Block-pack spec that can be materialized in pl. */
|
|
72
73
|
export type BlockPackSpecPrepared = {
|
|
73
74
|
type: "prepared";
|
|
74
|
-
template: PreparedTemplate | CachedTemplate;
|
|
75
|
+
template: PreparedTemplate | CachedTemplate | InstallablePackTemplate;
|
|
75
76
|
config: BlockConfigContainer;
|
|
76
77
|
frontend: FrontendSpec;
|
|
77
78
|
source: BlockPackSpec;
|
|
78
79
|
/** Backend-side runtime capabilities the block requires at install time.
|
|
79
80
|
* Derived from the parsed workflow template by
|
|
80
|
-
* `requiredCapabilitiesFromTemplate` during `BlockPackPreparer.prepare
|
|
81
|
+
* `requiredCapabilitiesFromTemplate` during `BlockPackPreparer.prepare`, or from the manifest.
|
|
81
82
|
* `Project.addBlock` matches this list against `pl.serverInfo.capabilities`
|
|
82
83
|
* and refuses to install when anything is missing. */
|
|
83
84
|
requiredCapabilities?: string[];
|