@milaboratories/pl-middle-layer 2.7.4 → 2.7.6
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/js_render/bundle_bytecode_cache.cjs +57 -0
- package/dist/js_render/bundle_bytecode_cache.cjs.map +1 -0
- package/dist/js_render/bundle_bytecode_cache.js +57 -0
- package/dist/js_render/bundle_bytecode_cache.js.map +1 -0
- package/dist/js_render/context.cjs +23 -0
- package/dist/js_render/context.cjs.map +1 -1
- package/dist/js_render/context.js +23 -0
- package/dist/js_render/context.js.map +1 -1
- package/dist/js_render/index.cjs +1 -1
- package/dist/js_render/index.cjs.map +1 -1
- package/dist/js_render/index.js +1 -1
- package/dist/js_render/index.js.map +1 -1
- package/dist/middle_layer/build_stamp.cjs +1 -1
- package/dist/middle_layer/build_stamp.js +1 -1
- package/package.json +3 -3
- package/src/js_render/bundle_bytecode_cache.test.ts +127 -0
- package/src/js_render/bundle_bytecode_cache.ts +89 -0
- package/src/js_render/context.ts +24 -0
- package/src/js_render/index.ts +3 -1
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
let node_crypto = require("node:crypto");
|
|
2
|
+
// src/js_render/bundle_bytecode_cache.ts
|
|
3
|
+
/** Bytecode budget. A 505 KB bundle compiles to ~1.4 MB, so this holds roughly forty. */
|
|
4
|
+
const MAX_BYTES = 67108864;
|
|
5
|
+
/** Pack id + code length -> bundle digest. Hashing once per pack keeps it off the hot path. */
|
|
6
|
+
const digestByCacheKey = /* @__PURE__ */ new Map();
|
|
7
|
+
const MAX_DIGEST_ENTRIES = 1024;
|
|
8
|
+
/** Insertion-ordered, so the oldest key is the first one `keys()` yields. */
|
|
9
|
+
const cache = /* @__PURE__ */ new Map();
|
|
10
|
+
/** Sum of `cache`'s values' byte lengths, kept alongside it to avoid rescanning on evict. */
|
|
11
|
+
let heldBytes = 0;
|
|
12
|
+
function digestFor(cacheKey, code) {
|
|
13
|
+
const memoKey = `${cacheKey}:${code.length}`;
|
|
14
|
+
const known = digestByCacheKey.get(memoKey);
|
|
15
|
+
if (known !== void 0) return known;
|
|
16
|
+
const digest = (0, node_crypto.createHash)("sha256").update(code).digest("hex");
|
|
17
|
+
digestByCacheKey.set(memoKey, digest);
|
|
18
|
+
while (digestByCacheKey.size > MAX_DIGEST_ENTRIES) {
|
|
19
|
+
const oldest = digestByCacheKey.keys().next();
|
|
20
|
+
if (oldest.done === true) break;
|
|
21
|
+
digestByCacheKey.delete(oldest.value);
|
|
22
|
+
}
|
|
23
|
+
return digest;
|
|
24
|
+
}
|
|
25
|
+
/** Bytecode for `code`, compiled on first ask. Outlives the context that compiled it. */
|
|
26
|
+
function byteCodeFor(vm, cacheKey, code) {
|
|
27
|
+
const digest = digestFor(cacheKey, code);
|
|
28
|
+
const hit = cache.get(digest);
|
|
29
|
+
if (hit !== void 0) {
|
|
30
|
+
cache.delete(digest);
|
|
31
|
+
cache.set(digest, hit);
|
|
32
|
+
return hit;
|
|
33
|
+
}
|
|
34
|
+
const compiled = vm.unwrapResult(vm.compileToByteCode(code, "bundle.js", { type: "global" })).consume((handle) => vm.getArrayBuffer(handle).consume((buf) => new Uint8Array(buf.value).buffer));
|
|
35
|
+
cache.set(digest, compiled);
|
|
36
|
+
heldBytes += compiled.byteLength;
|
|
37
|
+
while (heldBytes > MAX_BYTES && cache.size > 1) {
|
|
38
|
+
const oldest = cache.keys().next();
|
|
39
|
+
if (oldest.done === true) break;
|
|
40
|
+
heldBytes -= cache.get(oldest.value)?.byteLength ?? 0;
|
|
41
|
+
cache.delete(oldest.value);
|
|
42
|
+
}
|
|
43
|
+
return compiled;
|
|
44
|
+
}
|
|
45
|
+
/** Evaluate a block's model bundle into `vm`, reusing bytecode compiled for `cacheKey`. */
|
|
46
|
+
function evaluateBundleCached(vm, cacheKey, code) {
|
|
47
|
+
const byteCode = byteCodeFor(vm, cacheKey, code);
|
|
48
|
+
const handle = vm.newArrayBuffer(byteCode);
|
|
49
|
+
try {
|
|
50
|
+
vm.unwrapResult(vm.evalByteCode(handle)).dispose();
|
|
51
|
+
} finally {
|
|
52
|
+
handle.dispose();
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
exports.evaluateBundleCached = evaluateBundleCached;
|
|
56
|
+
|
|
57
|
+
//# sourceMappingURL=bundle_bytecode_cache.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"bundle_bytecode_cache.cjs","names":["createHash"],"sources":["../../src/js_render/bundle_bytecode_cache.ts"],"sourcesContent":["import { createHash } from \"node:crypto\";\nimport type { QuickJSContext } from \"quickjs-emscripten\";\n\n/** Bytecode budget. A 505 KB bundle compiles to ~1.4 MB, so this holds roughly forty. */\nconst MAX_BYTES = 64 * 1024 * 1024;\n\n/** Pack id + code length -> bundle digest. Hashing once per pack keeps it off the hot path. */\nconst digestByCacheKey = new Map<string, string>();\nconst MAX_DIGEST_ENTRIES = 1024;\n\n/** Insertion-ordered, so the oldest key is the first one `keys()` yields. */\nconst cache = new Map<string, ArrayBuffer>();\n\n/** Sum of `cache`'s values' byte lengths, kept alongside it to avoid rescanning on evict. */\nlet heldBytes = 0;\n\nfunction digestFor(cacheKey: string, code: string): string {\n // Pack resources are immutable (mutator/project.ts creates a new one per update), so the\n // length check only guards that invariant breaking.\n const memoKey = `${cacheKey}:${code.length}`;\n const known = digestByCacheKey.get(memoKey);\n if (known !== undefined) return known;\n\n const digest = createHash(\"sha256\").update(code).digest(\"hex\");\n digestByCacheKey.set(memoKey, digest);\n while (digestByCacheKey.size > MAX_DIGEST_ENTRIES) {\n const oldest = digestByCacheKey.keys().next();\n if (oldest.done === true) break;\n digestByCacheKey.delete(oldest.value);\n }\n return digest;\n}\n\n/** Bytecode for `code`, compiled on first ask. Outlives the context that compiled it. */\nfunction byteCodeFor(vm: QuickJSContext, cacheKey: string, code: string): ArrayBuffer {\n const digest = digestFor(cacheKey, code);\n const hit = cache.get(digest);\n if (hit !== undefined) {\n // Refresh recency: delete then set moves the key to the end of the iteration order.\n cache.delete(digest);\n cache.set(digest, hit);\n return hit;\n }\n\n const compiled = vm\n .unwrapResult(vm.compileToByteCode(code, \"bundle.js\", { type: \"global\" }))\n .consume((handle) =>\n vm.getArrayBuffer(handle).consume((buf) => new Uint8Array(buf.value).buffer),\n );\n\n cache.set(digest, compiled);\n heldBytes += compiled.byteLength;\n while (heldBytes > MAX_BYTES && cache.size > 1) {\n const oldest = cache.keys().next();\n if (oldest.done === true) break;\n heldBytes -= cache.get(oldest.value)?.byteLength ?? 0;\n cache.delete(oldest.value);\n }\n return compiled;\n}\n\n/** Evaluate a block's model bundle into `vm`, reusing bytecode compiled for `cacheKey`. */\nexport function evaluateBundleCached(vm: QuickJSContext, cacheKey: string, code: string): void {\n const byteCode = byteCodeFor(vm, cacheKey, code);\n // Not `consume`: it disposes only on a clean return, so a throwing bundle leaks the handle.\n const handle = vm.newArrayBuffer(byteCode);\n try {\n vm.unwrapResult(vm.evalByteCode(handle)).dispose();\n } finally {\n handle.dispose();\n }\n}\n\n/** Drops every compiled bundle. Exported for tests. */\nexport function clearBundleByteCodeCache(): void {\n cache.clear();\n digestByCacheKey.clear();\n heldBytes = 0;\n}\n\n/** Number of compiled bundles currently held. Exported for tests. */\nexport function bundleByteCodeCacheSize(): number {\n return cache.size;\n}\n\n/** Bytes of bytecode currently held. Exported for tests and diagnostics. */\nexport function bundleByteCodeCacheBytes(): number {\n return heldBytes;\n}\n"],"mappings":";;;AAIA,MAAM,YAAY;;AAGlB,MAAM,mCAAmB,IAAI,IAAoB;AACjD,MAAM,qBAAqB;;AAG3B,MAAM,wBAAQ,IAAI,IAAyB;;AAG3C,IAAI,YAAY;AAEhB,SAAS,UAAU,UAAkB,MAAsB;CAGzD,MAAM,UAAU,GAAG,SAAS,GAAG,KAAK;CACpC,MAAM,QAAQ,iBAAiB,IAAI,OAAO;CAC1C,IAAI,UAAU,KAAA,GAAW,OAAO;CAEhC,MAAM,UAAA,GAASA,YAAAA,WAAAA,CAAW,QAAQ,C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
import { createHash } from "node:crypto";
|
|
2
|
+
// src/js_render/bundle_bytecode_cache.ts
|
|
3
|
+
/** Bytecode budget. A 505 KB bundle compiles to ~1.4 MB, so this holds roughly forty. */
|
|
4
|
+
const MAX_BYTES = 67108864;
|
|
5
|
+
/** Pack id + code length -> bundle digest. Hashing once per pack keeps it off the hot path. */
|
|
6
|
+
const digestByCacheKey = /* @__PURE__ */ new Map();
|
|
7
|
+
const MAX_DIGEST_ENTRIES = 1024;
|
|
8
|
+
/** Insertion-ordered, so the oldest key is the first one `keys()` yields. */
|
|
9
|
+
const cache = /* @__PURE__ */ new Map();
|
|
10
|
+
/** Sum of `cache`'s values' byte lengths, kept alongside it to avoid rescanning on evict. */
|
|
11
|
+
let heldBytes = 0;
|
|
12
|
+
function digestFor(cacheKey, code) {
|
|
13
|
+
const memoKey = `${cacheKey}:${code.length}`;
|
|
14
|
+
const known = digestByCacheKey.get(memoKey);
|
|
15
|
+
if (known !== void 0) return known;
|
|
16
|
+
const digest = createHash("sha256").update(code).digest("hex");
|
|
17
|
+
digestByCacheKey.set(memoKey, digest);
|
|
18
|
+
while (digestByCacheKey.size > MAX_DIGEST_ENTRIES) {
|
|
19
|
+
const oldest = digestByCacheKey.keys().next();
|
|
20
|
+
if (oldest.done === true) break;
|
|
21
|
+
digestByCacheKey.delete(oldest.value);
|
|
22
|
+
}
|
|
23
|
+
return digest;
|
|
24
|
+
}
|
|
25
|
+
/** Bytecode for `code`, compiled on first ask. Outlives the context that compiled it. */
|
|
26
|
+
function byteCodeFor(vm, cacheKey, code) {
|
|
27
|
+
const digest = digestFor(cacheKey, code);
|
|
28
|
+
const hit = cache.get(digest);
|
|
29
|
+
if (hit !== void 0) {
|
|
30
|
+
cache.delete(digest);
|
|
31
|
+
cache.set(digest, hit);
|
|
32
|
+
return hit;
|
|
33
|
+
}
|
|
34
|
+
const compiled = vm.unwrapResult(vm.compileToByteCode(code, "bundle.js", { type: "global" })).consume((handle) => vm.getArrayBuffer(handle).consume((buf) => new Uint8Array(buf.value).buffer));
|
|
35
|
+
cache.set(digest, compiled);
|
|
36
|
+
heldBytes += compiled.byteLength;
|
|
37
|
+
while (heldBytes > MAX_BYTES && cache.size > 1) {
|
|
38
|
+
const oldest = cache.keys().next();
|
|
39
|
+
if (oldest.done === true) break;
|
|
40
|
+
heldBytes -= cache.get(oldest.value)?.byteLength ?? 0;
|
|
41
|
+
cache.delete(oldest.value);
|
|
42
|
+
}
|
|
43
|
+
return compiled;
|
|
44
|
+
}
|
|
45
|
+
/** Evaluate a block's model bundle into `vm`, reusing bytecode compiled for `cacheKey`. */
|
|
46
|
+
function evaluateBundleCached(vm, cacheKey, code) {
|
|
47
|
+
const byteCode = byteCodeFor(vm, cacheKey, code);
|
|
48
|
+
const handle = vm.newArrayBuffer(byteCode);
|
|
49
|
+
try {
|
|
50
|
+
vm.unwrapResult(vm.evalByteCode(handle)).dispose();
|
|
51
|
+
} finally {
|
|
52
|
+
handle.dispose();
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
export { evaluateBundleCached };
|
|
56
|
+
|
|
57
|
+
//# sourceMappingURL=bundle_bytecode_cache.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"bundle_bytecode_cache.js","names":[],"sources":["../../src/js_render/bundle_bytecode_cache.ts"],"sourcesContent":["import { createHash } from \"node:crypto\";\nimport type { QuickJSContext } from \"quickjs-emscripten\";\n\n/** Bytecode budget. A 505 KB bundle compiles to ~1.4 MB, so this holds roughly forty. */\nconst MAX_BYTES = 64 * 1024 * 1024;\n\n/** Pack id + code length -> bundle digest. Hashing once per pack keeps it off the hot path. */\nconst digestByCacheKey = new Map<string, string>();\nconst MAX_DIGEST_ENTRIES = 1024;\n\n/** Insertion-ordered, so the oldest key is the first one `keys()` yields. */\nconst cache = new Map<string, ArrayBuffer>();\n\n/** Sum of `cache`'s values' byte lengths, kept alongside it to avoid rescanning on evict. */\nlet heldBytes = 0;\n\nfunction digestFor(cacheKey: string, code: string): string {\n // Pack resources are immutable (mutator/project.ts creates a new one per update), so the\n // length check only guards that invariant breaking.\n const memoKey = `${cacheKey}:${code.length}`;\n const known = digestByCacheKey.get(memoKey);\n if (known !== undefined) return known;\n\n const digest = createHash(\"sha256\").update(code).digest(\"hex\");\n digestByCacheKey.set(memoKey, digest);\n while (digestByCacheKey.size > MAX_DIGEST_ENTRIES) {\n const oldest = digestByCacheKey.keys().next();\n if (oldest.done === true) break;\n digestByCacheKey.delete(oldest.value);\n }\n return digest;\n}\n\n/** Bytecode for `code`, compiled on first ask. Outlives the context that compiled it. */\nfunction byteCodeFor(vm: QuickJSContext, cacheKey: string, code: string): ArrayBuffer {\n const digest = digestFor(cacheKey, code);\n const hit = cache.get(digest);\n if (hit !== undefined) {\n // Refresh recency: delete then set moves the key to the end of the iteration order.\n cache.delete(digest);\n cache.set(digest, hit);\n return hit;\n }\n\n const compiled = vm\n .unwrapResult(vm.compileToByteCode(code, \"bundle.js\", { type: \"global\" }))\n .consume((handle) =>\n vm.getArrayBuffer(handle).consume((buf) => new Uint8Array(buf.value).buffer),\n );\n\n cache.set(digest, compiled);\n heldBytes += compiled.byteLength;\n while (heldBytes > MAX_BYTES && cache.size > 1) {\n const oldest = cache.keys().next();\n if (oldest.done === true) break;\n heldBytes -= cache.get(oldest.value)?.byteLength ?? 0;\n cache.delete(oldest.value);\n }\n return compiled;\n}\n\n/** Evaluate a block's model bundle into `vm`, reusing bytecode compiled for `cacheKey`. */\nexport function evaluateBundleCached(vm: QuickJSContext, cacheKey: string, code: string): void {\n const byteCode = byteCodeFor(vm, cacheKey, code);\n // Not `consume`: it disposes only on a clean return, so a throwing bundle leaks the handle.\n const handle = vm.newArrayBuffer(byteCode);\n try {\n vm.unwrapResult(vm.evalByteCode(handle)).dispose();\n } finally {\n handle.dispose();\n }\n}\n\n/** Drops every compiled bundle. Exported for tests. */\nexport function clearBundleByteCodeCache(): void {\n cache.clear();\n digestByCacheKey.clear();\n heldBytes = 0;\n}\n\n/** Number of compiled bundles currently held. Exported for tests. */\nexport function bundleByteCodeCacheSize(): number {\n return cache.size;\n}\n\n/** Bytes of bytecode currently held. Exported for tests and diagnostics. */\nexport function bundleByteCodeCacheBytes(): number {\n return heldBytes;\n}\n"],"mappings":";;;AAIA,MAAM,YAAY;;AAGlB,MAAM,mCAAmB,IAAI,IAAoB;AACjD,MAAM,qBAAqB;;AAG3B,MAAM,wBAAQ,IAAI,IAAyB;;AAG3C,IAAI,YAAY;AAEhB,SAAS,UAAU,UAAkB,MAAsB;CAGzD,MAAM,UAAU,GAAG,SAAS,GAAG,KAAK;CACpC,MAAM,QAAQ,iBAAiB,IAAI,OAAO;CAC1C,IAAI,UAAU,KAAA,GAAW,OAAO;CAEhC,MAAM,SAAS,WAAW,QAAQ,CAAC,CAAC,OAAO,IAAI,CAAC,CAAC,OAAO,KAAK;CAC7D,iBAAiB,IAAI,SAAS,MAAM;CACpC,OAAO,iBAAiB,OAAO,oBAAoB;EACjD,MAAM,SAAS,iBAAiB,KAAK,CAAC,CAAC,KAAK;EAC5C,IAAI,OAAO,SAAS,MAAM;EAC1B,iBAAiB,OAAO,OAAO,KAAK;CACtC;CACA,OAAO;AACT;;AAGA,SAAS,YAAY,IAAoB,UAAkB,MAA2B;CACpF,MAAM,SAAS,UAAU,UAAU,IAAI;CACvC,MAAM,MAAM,MAAM,IAAI,MAAM;CAC5B,IAAI,QAAQ,KAAA,GAAW;EAErB,MAAM,OAAO,MAAM;EACnB,MAAM,IAAI,QAAQ,GAAG;EACrB,OAAO;CACT;CAEA,MAAM,WAAW,GACd,aAAa,GAAG,kBAAkB,MAAM,aAAa,EAAE,MAAM,SAAS,CAAC,CAAC,CAAC,CACzE,SAAS,WACR,GAAG,eAAe,MAAM,CAAC,CAAC,SAAS,QAAQ,IAAI,WAAW,IAAI,KAAK,CAAC,CAAC,MAAM,CAC7E;CAEF,MAAM,IAAI,QAAQ,QAAQ;CAC1B,aAAa,SAAS;CACtB,OAAO,YAAY,aAAa,MAAM,OAAO,GAAG;EAC9C,MAAM,SAAS,MAAM,KAAK,CAAC,CAAC,KAAK;EACjC,IAAI,OAAO,SAAS,MAAM;EAC1B,aAAa,MAAM,IAAI,OAAO,KAAK,CAAC,EAAE,cAAc;EACpD,MAAM,OAAO,OAAO,KAAK;CAC3B;CACA,OAAO;AACT;;AAGA,SAAgB,qBAAqB,IAAoB,UAAkB,MAAoB;CAC7F,MAAM,WAAW,YAAY,IAAI,UAAU,IAAI;CAE/C,MAAM,SAAS,GAAG,eAAe,QAAQ;CACzC,IAAI;EACF,GAAG,aAAa,GAAG,aAAa,MAAM,CAAC,CAAC,CAAC,QAAQ;CACnD,UAAU;EACR,OAAO,QAAQ;CACjB;AACF"}
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
const require_computable_context = require("./computable_context.cjs");
|
|
2
|
+
const require_bundle_bytecode_cache = require("./bundle_bytecode_cache.cjs");
|
|
2
3
|
let _platforma_sdk_model = require("@platforma-sdk/model");
|
|
3
4
|
let _milaboratories_ts_helpers = require("@milaboratories/ts-helpers");
|
|
4
5
|
let _milaboratories_pl_client = require("@milaboratories/pl-client");
|
|
@@ -76,6 +77,28 @@ var JsExecutionContext = class JsExecutionContext {
|
|
|
76
77
|
this.stats.bundleBytes += code.length;
|
|
77
78
|
}
|
|
78
79
|
}
|
|
80
|
+
/**
|
|
81
|
+
* {@link evaluateBundle}, reusing bytecode compiled for an earlier context with the same
|
|
82
|
+
* `cacheKey`. Every lambda gets its own context and needs the whole bundle in scope, so
|
|
83
|
+
* parsing per context was the dominant cost of rendering a block.
|
|
84
|
+
*/
|
|
85
|
+
evaluateBundleCached(cacheKey, code) {
|
|
86
|
+
const t0 = performance.now();
|
|
87
|
+
try {
|
|
88
|
+
this.deadlineSetter({
|
|
89
|
+
currentExecutionTarget: "evaluateBundle",
|
|
90
|
+
deadline: Date.now() + 1e4
|
|
91
|
+
});
|
|
92
|
+
require_bundle_bytecode_cache.evaluateBundleCached(this.vm, cacheKey, code);
|
|
93
|
+
} catch (err) {
|
|
94
|
+
JsExecutionContext.cleanErrorContext(err);
|
|
95
|
+
throw err;
|
|
96
|
+
} finally {
|
|
97
|
+
this.deadlineSetter(void 0);
|
|
98
|
+
this.stats.bundleEvalMs += performance.now() - t0;
|
|
99
|
+
this.stats.bundleBytes += code.length;
|
|
100
|
+
}
|
|
101
|
+
}
|
|
79
102
|
runCallback(cbName, ...args) {
|
|
80
103
|
const t0 = performance.now();
|
|
81
104
|
try {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"context.cjs","names":["ComputableContextHelper","Scope","JsRenderInternal","randomUUID","errors","stringifyWithResourceId","PlQuickJSError"],"sources":["../../src/js_render/context.ts"],"sourcesContent":["import type { ComputableCtx } from \"@milaboratories/computable\";\nimport type { BlockCodeKnownFeatureFlags } from \"@platforma-sdk/model\";\nimport { JsRenderInternal } from \"@platforma-sdk/model\";\nimport { notEmpty } from \"@milaboratories/ts-helpers\";\nimport { randomUUID } from \"node:crypto\";\nimport type { QuickJSContext, QuickJSHandle } from \"quickjs-emscripten\";\nimport { Scope, errors } from \"quickjs-emscripten\";\nimport type { BlockContextAny } from \"../middle_layer/block_ctx\";\nimport type { MiddleLayerEnvironment } from \"../middle_layer/middle_layer\";\nimport { stringifyWithResourceId } from \"@milaboratories/pl-client\";\nimport { PlQuickJSError } from \"@milaboratories/pl-errors\";\nimport { ComputableContextHelper } from \"./computable_context\";\n\nexport type DeadlineSettings = {\n currentExecutionTarget: string;\n deadline: number;\n};\n\n/**\n * Communicates a deadline to the quickjs runtime, that if passed, will interrupt the execution.\n * Undefined can be used to reset the deadline.\n * */\nexport type DeadlineSetter = (settings: DeadlineSettings | undefined) => void;\n\nfunction isArrayBufferOrView(obj: unknown): obj is ArrayBufferLike {\n return obj instanceof ArrayBuffer || ArrayBuffer.isView(obj);\n}\n\n/**\n * Contains references to objects needed to execute lambda within computable,\n * providing access to:\n * - block context\n * - computable context\n * - middle layer environment\n * */\nexport type ComputableEnv = {\n readonly blockCtx: BlockContextAny;\n readonly mlEnv: MiddleLayerEnvironment;\n computableCtx: ComputableCtx;\n};\n\n/** Execution stats accumulated during the lifetime of a JsExecutionContext. */\nexport type JsExecStats = {\n bundleEvalMs: number;\n bundleBytes: number;\n\n callbackMs: number;\n callbackCount: number;\n\n serInMs: number;\n serInBytes: number;\n serInCalls: number;\n\n serOutMs: number;\n serOutBytes: number;\n serOutCalls: number;\n\n ctxMethodCalls: number;\n ctxMethodMs: number;\n};\n\nexport class JsExecutionContext {\n private readonly callbackRegistry: QuickJSHandle;\n private readonly fnJSONStringify: QuickJSHandle;\n private readonly fnJSONParse: QuickJSHandle;\n\n public readonly errorRepo = new ErrorRepository();\n\n public readonly computableHelper: ComputableContextHelper | undefined;\n\n public readonly stats: JsExecStats = {\n bundleEvalMs: 0,\n bundleBytes: 0,\n callbackMs: 0,\n callbackCount: 0,\n serInMs: 0,\n serInBytes: 0,\n serInCalls: 0,\n serOutMs: 0,\n serOutBytes: 0,\n serOutCalls: 0,\n ctxMethodCalls: 0,\n ctxMethodMs: 0,\n };\n\n /**\n * Creates a new JS execution context.\n *\n * @param scope - QuickJS scope for memory management\n * @param vm - QuickJS VM context\n * @param deadlineSetter - Function to set execution deadline\n * @param featureFlags - Block feature flags\n * @param computableEnv - Optional reactive computable environment (for outputs, inputsValid, etc.)\n */\n constructor(\n public readonly scope: Scope,\n public readonly vm: QuickJSContext,\n private readonly deadlineSetter: DeadlineSetter,\n featureFlags: BlockCodeKnownFeatureFlags | undefined,\n computableEnv?: ComputableEnv,\n ) {\n this.callbackRegistry = this.scope.manage(this.vm.newObject());\n\n this.fnJSONStringify = scope.manage(\n vm.getProp(vm.global, \"JSON\").consume((json) => vm.getProp(json, \"stringify\")),\n );\n if (vm.typeof(this.fnJSONStringify) !== \"function\")\n throw new Error(`JSON.stringify() not found.`);\n\n this.fnJSONParse = scope.manage(\n vm.getProp(vm.global, \"JSON\").consume((json) => vm.getProp(json, \"parse\")),\n );\n if (vm.typeof(this.fnJSONParse) !== \"function\") throw new Error(`JSON.parse() not found.`);\n\n if (computableEnv !== undefined)\n this.computableHelper = new ComputableContextHelper(\n this,\n computableEnv.blockCtx,\n computableEnv.mlEnv,\n featureFlags,\n computableEnv.computableCtx,\n );\n\n this.injectCtx();\n }\n\n public resetComputableCtx() {\n notEmpty(\n this.computableHelper,\n \"Computable context helper is not initialized\",\n ).resetComputableCtx();\n }\n\n private static cleanErrorContext(error: unknown): void {\n if (typeof error === \"object\" && error !== null && \"context\" in error) delete error[\"context\"];\n }\n\n // private static cleanError(error: unknown): unknown {\n // if (error instanceof errors.QuickJSUnwrapError) {\n // const { cause, context: _, name, message, stack, ...rest } = error;\n // const clean = new errors.QuickJSUnwrapError(cause);\n // Object.assign(clean, { ...rest, name, message, stack });\n // return clean;\n // }\n // return error;\n // }\n\n public evaluateBundle(code: string) {\n const t0 = performance.now();\n try {\n this.deadlineSetter({\n currentExecutionTarget: \"evaluateBundle\",\n deadline: Date.now() + 10000,\n });\n this.vm.unwrapResult(this.vm.evalCode(code, \"bundle.js\", { type: \"global\" })).dispose();\n } catch (err: unknown) {\n JsExecutionContext.cleanErrorContext(err);\n throw err;\n } finally {\n this.deadlineSetter(undefined);\n this.stats.bundleEvalMs += performance.now() - t0;\n this.stats.bundleBytes += code.length;\n }\n }\n\n public runCallback(cbName: string, ...args: unknown[]): QuickJSHandle {\n const t0 = performance.now();\n try {\n this.deadlineSetter({ currentExecutionTarget: cbName, deadline: Date.now() + 10000 });\n return Scope.withScope((localScope) => {\n const targetCallback = localScope.manage(this.vm.getProp(this.callbackRegistry, cbName));\n\n if (this.vm.typeof(targetCallback) !== \"function\")\n throw new Error(`No such callback: ${cbName}`);\n\n return this.scope.manage(\n this.vm.unwrapResult(\n this.vm.callFunction(\n targetCallback,\n this.vm.undefined,\n ...args.map((arg) => this.exportObjectUniversal(arg, localScope)),\n ),\n ),\n );\n });\n } catch (err: unknown) {\n JsExecutionContext.cleanErrorContext(err);\n const original = this.errorRepo.getOriginal(err);\n throw original;\n } finally {\n this.deadlineSetter(undefined);\n this.stats.callbackMs += performance.now() - t0;\n this.stats.callbackCount++;\n }\n }\n\n //\n // QuickJS Helpers\n //\n\n public exportSingleValue(\n obj: boolean | number | string | null | ArrayBuffer | undefined,\n scope?: Scope,\n ): QuickJSHandle {\n const result = this.tryExportSingleValue(obj, scope);\n if (result === undefined) {\n throw new Error(\n `Can't export value: ${obj === undefined ? \"undefined\" : JSON.stringify(obj)}`,\n );\n }\n return result;\n }\n\n public tryExportSingleValue(obj: unknown, scope?: Scope): QuickJSHandle | undefined {\n let handle: QuickJSHandle;\n let manage = false;\n switch (typeof obj) {\n case \"string\":\n handle = this.vm.newString(obj);\n manage = true;\n break;\n case \"number\":\n handle = this.vm.newNumber(obj);\n manage = true;\n break;\n case \"undefined\":\n handle = this.vm.undefined;\n break;\n case \"boolean\":\n handle = obj ? this.vm.true : this.vm.false;\n break;\n default:\n if (obj === null) {\n handle = this.vm.null;\n break;\n }\n if (isArrayBufferOrView(obj)) {\n handle = this.vm.newArrayBuffer(obj);\n manage = true;\n break;\n }\n return undefined;\n }\n return manage && scope != undefined ? scope.manage(handle) : handle;\n }\n\n public exportObjectUniversal(obj: unknown, scope?: Scope): QuickJSHandle {\n const simpleHandle = this.tryExportSingleValue(obj, scope);\n if (simpleHandle !== undefined) return simpleHandle;\n return this.exportObjectViaJson(obj, scope);\n }\n\n public exportObjectViaJson(obj: unknown, scope?: Scope): QuickJSHandle {\n const t0 = performance.now();\n const json = JSON.stringify(obj);\n this.stats.serInBytes += json.length;\n this.stats.serInCalls++;\n const result = this.vm\n .newString(json)\n .consume((jsonHandle) =>\n this.vm.unwrapResult(this.vm.callFunction(this.fnJSONParse, this.vm.undefined, jsonHandle)),\n );\n this.stats.serInMs += performance.now() - t0;\n return scope !== undefined ? scope.manage(result) : result;\n }\n\n public importObjectUniversal(handle: QuickJSHandle | undefined): unknown {\n if (handle === undefined) return undefined;\n switch (this.vm.typeof(handle)) {\n case \"undefined\":\n return undefined;\n case \"boolean\":\n case \"number\":\n case \"string\":\n return this.vm.dump(handle);\n default:\n return this.importObjectViaJson(handle);\n }\n }\n\n public importObjectViaJson(handle: QuickJSHandle): unknown {\n const t0 = performance.now();\n const text = this.vm\n .unwrapResult(this.vm.callFunction(this.fnJSONStringify, this.vm.undefined, handle))\n .consume((strHandle) => this.vm.getString(strHandle));\n this.stats.serOutBytes += text.length;\n this.stats.serOutCalls++;\n if (text === \"undefined\") {\n // special case with futures\n this.stats.serOutMs += performance.now() - t0;\n return undefined;\n }\n const result = JSON.parse(text);\n this.stats.serOutMs += performance.now() - t0;\n return result;\n }\n\n private injectCtx() {\n Scope.withScope((localScope) => {\n const configCtx = localScope.manage(this.vm.newObject());\n\n //\n // Core props\n //\n\n this.vm.setProp(configCtx, \"callbackRegistry\", this.callbackRegistry);\n this.vm.setProp(\n configCtx,\n \"featureFlags\",\n this.exportObjectUniversal(JsRenderInternal.GlobalCfgRenderCtxFeatureFlags, localScope),\n );\n\n // Inject context values from computableHelper (reactive context for outputs, inputsValid, etc.)\n if (this.computableHelper !== undefined) {\n this.computableHelper.injectCtx(configCtx);\n }\n\n //\n // Creating global variable inside the vm\n //\n\n this.vm.setProp(this.vm.global, \"cfgRenderCtx\", configCtx);\n });\n }\n}\n\n/** Holds errors that happened in the host code (like in middle-layer's drivers)\n * and then throws it where the error from quick JS is needed.\n * QuickJS couldn't throw custom errors, so we store them here, and rethrow them when we exit QuickJS side. */\nexport class ErrorRepository {\n private readonly errorIdToError = new Map<string, unknown>();\n\n /** Sets the error to the repository and returns a mimicrated error that also has uuid key of the original error. */\n public setAndRecreateForQuickJS(error: unknown): {\n name: string;\n message: string;\n } {\n const errorId = randomUUID();\n this.errorIdToError.set(errorId, error);\n\n if (error instanceof Error) {\n return {\n name: `${error.name}/uuid:${errorId}`,\n message: error.message,\n };\n }\n\n return {\n name: `UnknownErrorQuickJS/uuid:${errorId}`,\n message: `${error as any}`,\n };\n }\n\n /** Returns the original error that was stored by parsing uuid of mimicrated error. */\n public getOriginal(quickJSError: unknown): unknown {\n if (!(quickJSError instanceof errors.QuickJSUnwrapError)) {\n console.warn(\n \"ErrorRepo: quickJSError is not a QuickJSUnwrapError\",\n stringifyWithResourceId(quickJSError),\n );\n return quickJSError;\n }\n\n const cause = quickJSError.cause;\n if (\n !(\n typeof cause === \"object\" &&\n cause !== null &&\n \"name\" in cause &&\n typeof cause.name === \"string\"\n )\n ) {\n console.warn(\n \"ErrorRepo: quickJSError.cause is not an Error (can be stack limit exceeded)\",\n stringifyWithResourceId(quickJSError),\n );\n return quickJSError;\n }\n\n const causeName = cause.name;\n const uuidIdx = causeName.indexOf(\"/uuid:\");\n if (uuidIdx === -1) {\n const causeMsg = \"message\" in cause && typeof cause.message === \"string\" ? cause.message : \"\";\n throw new Error(\n `QuickJS native error: ${causeName}: ${causeMsg}, ${stringifyWithResourceId(quickJSError)}`,\n { cause: quickJSError },\n );\n }\n const errorId = causeName.slice(uuidIdx + \"/uuid:\".length);\n if (!errorId) {\n throw new Error(\n `ErrorRepo: quickJSError.cause.name does not contain errorId: ${causeName}, ${stringifyWithResourceId(quickJSError)}`,\n );\n }\n\n const error = this.errorIdToError.get(errorId);\n if (error === undefined) {\n throw new Error(\n `ErrorRepo: errorId not found: ${errorId}, ${stringifyWithResourceId(quickJSError)}`,\n );\n }\n\n return new PlQuickJSError(quickJSError, error as Error);\n }\n}\n"],"mappings":";;;;;;;;AAwBA,SAAS,oBAAoB,KAAsC;CACjE,OAAO,eAAe,eAAe,YAAY,OAAO,GAAG;AAC7D;AAmCA,IAAa,qBAAb,MAAa,mBAAmB;CAkCZ;CACA;CACC;CAnCnB;CACA;CACA;CAEA,YAA4B,IAAI,gBAAgB;CAEhD;CAEA,QAAqC;EACnC,cAAc;EACd,aAAa;EACb,YAAY;EACZ,eAAe;EACf,SAAS;EACT,YAAY;EACZ,YAAY;EACZ,UAAU;EACV,aAAa;EACb,aAAa;EACb,gBAAgB;EAChB,aAAa;CACf;;;;;;;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UAAU,SACV,OAAO,MAAM,SAAS,WAExB;GACA,QAAQ,KACN,gFAAA,GACAA,0BAAAA,wBAAAA,CAAwB,YAAY,CACtC;GACA,OAAO;EACT;EAEA,MAAM,YAAY,MAAM;EACxB,MAAM,UAAU,UAAU,QAAQ,QAAQ;EAC1C,IAAI,YAAY,IAAI;GAClB,MAAM,WAAW,aAAa,SAAS,OAAO,MAAM,YAAY,WAAW,MAAM,UAAU;GAC3F,MAAM,IAAI,MACR,yBAAyB,UAAU,IAAI,SAAS,KAAA,GAAIA,0BAAAA,wBAAAA,CAAwB,YAAY,KACxF,EAAE,OAAO,aAAa,CACxB;EACF;EACA,MAAM,UAAU,UAAU,MAAM,UAAU,CAAe;EACzD,IAAI,CAAC,SACH,MAAM,IAAI,MACR,gEAAgE,UAAU,KAAA,GAAIA,0BAAAA,wBAAAA,CAAwB,YAAY,GACpH;EAGF,MAAM,QAAQ,KAAK,eAAe,IAAI,OAAO;EAC7C,IAAI,UAAU,KAAA,GACZ,MAAM,IAAI,MACR,iCAAiC,QAAQ,KAAA,GAAIA,0BAAAA,wBAAAA,CAAwB,YAAY,GACnF;EAGF,OAAO,IAAIC,0BAAAA,eAAe,cAAc,KAAc;CACxD;AACF"}
|
|
1
|
+
{"version":3,"file":"context.cjs","names":["ComputableContextHelper","Scope","JsRenderInternal","randomUUID","errors","stringifyWithResourceId","PlQuickJSError"],"sources":["../../src/js_render/context.ts"],"sourcesContent":["import type { ComputableCtx } from \"@milaboratories/computable\";\nimport type { BlockCodeKnownFeatureFlags } from \"@platforma-sdk/model\";\nimport { JsRenderInternal } from \"@platforma-sdk/model\";\nimport { notEmpty } from \"@milaboratories/ts-helpers\";\nimport { randomUUID } from \"node:crypto\";\nimport type { QuickJSContext, QuickJSHandle } from \"quickjs-emscripten\";\nimport { Scope, errors } from \"quickjs-emscripten\";\nimport type { BlockContextAny } from \"../middle_layer/block_ctx\";\nimport type { MiddleLayerEnvironment } from \"../middle_layer/middle_layer\";\nimport { stringifyWithResourceId } from \"@milaboratories/pl-client\";\nimport { PlQuickJSError } from \"@milaboratories/pl-errors\";\nimport { ComputableContextHelper } from \"./computable_context\";\n\nimport { evaluateBundleCached } from \"./bundle_bytecode_cache\";\nexport type DeadlineSettings = {\n currentExecutionTarget: string;\n deadline: number;\n};\n\n/**\n * Communicates a deadline to the quickjs runtime, that if passed, will interrupt the execution.\n * Undefined can be used to reset the deadline.\n * */\nexport type DeadlineSetter = (settings: DeadlineSettings | undefined) => void;\n\nfunction isArrayBufferOrView(obj: unknown): obj is ArrayBufferLike {\n return obj instanceof ArrayBuffer || ArrayBuffer.isView(obj);\n}\n\n/**\n * Contains references to objects needed to execute lambda within computable,\n * providing access to:\n * - block context\n * - computable context\n * - middle layer environment\n * */\nexport type ComputableEnv = {\n readonly blockCtx: BlockContextAny;\n readonly mlEnv: MiddleLayerEnvironment;\n computableCtx: ComputableCtx;\n};\n\n/** Execution stats accumulated during the lifetime of a JsExecutionContext. */\nexport type JsExecStats = {\n bundleEvalMs: number;\n bundleBytes: number;\n\n callbackMs: number;\n callbackCount: number;\n\n serInMs: number;\n serInBytes: number;\n serInCalls: number;\n\n serOutMs: number;\n serOutBytes: number;\n serOutCalls: number;\n\n ctxMethodCalls: number;\n ctxMethodMs: number;\n};\n\nexport class JsExecutionContext {\n private readonly callbackRegistry: QuickJSHandle;\n private readonly fnJSONStringify: QuickJSHandle;\n private readonly fnJSONParse: QuickJSHandle;\n\n public readonly errorRepo = new ErrorRepository();\n\n public readonly computableHelper: ComputableContextHelper | undefined;\n\n public readonly stats: JsExecStats = {\n bundleEvalMs: 0,\n bundleBytes: 0,\n callbackMs: 0,\n callbackCount: 0,\n serInMs: 0,\n serInBytes: 0,\n serInCalls: 0,\n serOutMs: 0,\n serOutBytes: 0,\n serOutCalls: 0,\n ctxMethodCalls: 0,\n ctxMethodMs: 0,\n };\n\n /**\n * Creates a new JS execution context.\n *\n * @param scope - QuickJS scope for memory management\n * @param vm - QuickJS VM context\n * @param deadlineSetter - Function to set execution deadline\n * @param featureFlags - Block feature flags\n * @param computableEnv - Optional reactive computable environment (for outputs, inputsValid, etc.)\n */\n constructor(\n public readonly scope: Scope,\n public readonly vm: QuickJSContext,\n private readonly deadlineSetter: DeadlineSetter,\n featureFlags: BlockCodeKnownFeatureFlags | undefined,\n computableEnv?: ComputableEnv,\n ) {\n this.callbackRegistry = this.scope.manage(this.vm.newObject());\n\n this.fnJSONStringify = scope.manage(\n vm.getProp(vm.global, \"JSON\").consume((json) => vm.getProp(json, \"stringify\")),\n );\n if (vm.typeof(this.fnJSONStringify) !== \"function\")\n throw new Error(`JSON.stringify() not found.`);\n\n this.fnJSONParse = scope.manage(\n vm.getProp(vm.global, \"JSON\").consume((json) => vm.getProp(json, \"parse\")),\n );\n if (vm.typeof(this.fnJSONParse) !== \"function\") throw new Error(`JSON.parse() not found.`);\n\n if (computableEnv !== undefined)\n this.computableHelper = new ComputableContextHelper(\n this,\n computableEnv.blockCtx,\n computableEnv.mlEnv,\n featureFlags,\n computableEnv.computableCtx,\n );\n\n this.injectCtx();\n }\n\n public resetComputableCtx() {\n notEmpty(\n this.computableHelper,\n \"Computable context helper is not initialized\",\n ).resetComputableCtx();\n }\n\n private static cleanErrorContext(error: unknown): void {\n if (typeof error === \"object\" && error !== null && \"context\" in error) delete error[\"context\"];\n }\n\n // private static cleanError(error: unknown): unknown {\n // if (error instanceof errors.QuickJSUnwrapError) {\n // const { cause, context: _, name, message, stack, ...rest } = error;\n // const clean = new errors.QuickJSUnwrapError(cause);\n // Object.assign(clean, { ...rest, name, message, stack });\n // return clean;\n // }\n // return error;\n // }\n\n public evaluateBundle(code: string) {\n const t0 = performance.now();\n try {\n this.deadlineSetter({\n currentExecutionTarget: \"evaluateBundle\",\n deadline: Date.now() + 10000,\n });\n this.vm.unwrapResult(this.vm.evalCode(code, \"bundle.js\", { type: \"global\" })).dispose();\n } catch (err: unknown) {\n JsExecutionContext.cleanErrorContext(err);\n throw err;\n } finally {\n this.deadlineSetter(undefined);\n this.stats.bundleEvalMs += performance.now() - t0;\n this.stats.bundleBytes += code.length;\n }\n }\n\n /**\n * {@link evaluateBundle}, reusing bytecode compiled for an earlier context with the same\n * `cacheKey`. Every lambda gets its own context and needs the whole bundle in scope, so\n * parsing per context was the dominant cost of rendering a block.\n */\n public evaluateBundleCached(cacheKey: string, code: string) {\n const t0 = performance.now();\n try {\n this.deadlineSetter({\n currentExecutionTarget: \"evaluateBundle\",\n deadline: Date.now() + 10000,\n });\n evaluateBundleCached(this.vm, cacheKey, code);\n } catch (err: unknown) {\n JsExecutionContext.cleanErrorContext(err);\n throw err;\n } finally {\n this.deadlineSetter(undefined);\n this.stats.bundleEvalMs += performance.now() - t0;\n this.stats.bundleBytes += code.length;\n }\n }\n\n public runCallback(cbName: string, ...args: unknown[]): QuickJSHandle {\n const t0 = performance.now();\n try {\n this.deadlineSetter({ currentExecutionTarget: cbName, deadline: Date.now() + 10000 });\n return Scope.withScope((localScope) => {\n const targetCallback = localScope.manage(this.vm.getProp(this.callbackRegistry, cbName));\n\n if (this.vm.typeof(targetCallback) !== \"function\")\n throw new Error(`No such callback: ${cbName}`);\n\n return this.scope.manage(\n this.vm.unwrapResult(\n this.vm.callFunction(\n targetCallback,\n this.vm.undefined,\n ...args.map((arg) => this.exportObjectUniversal(arg, localScope)),\n ),\n ),\n );\n });\n } catch (err: unknown) {\n JsExecutionContext.cleanErrorContext(err);\n const original = this.errorRepo.getOriginal(err);\n throw original;\n } finally {\n this.deadlineSetter(undefined);\n this.stats.callbackMs += performance.now() - t0;\n this.stats.callbackCount++;\n }\n }\n\n //\n // QuickJS Helpers\n //\n\n public exportSingleValue(\n obj: boolean | number | string | null | ArrayBuffer | undefined,\n scope?: Scope,\n ): QuickJSHandle {\n const result = this.tryExportSingleValue(obj, scope);\n if (result === undefined) {\n throw new Error(\n `Can't export value: ${obj === undefined ? \"undefined\" : JSON.stringify(obj)}`,\n );\n }\n return result;\n }\n\n public tryExportSingleValue(obj: unknown, scope?: Scope): QuickJSHandle | undefined {\n let handle: QuickJSHandle;\n let manage = false;\n switch (typeof obj) {\n case \"string\":\n handle = this.vm.newString(obj);\n manage = true;\n break;\n case \"number\":\n handle = this.vm.newNumber(obj);\n manage = true;\n break;\n case \"undefined\":\n handle = this.vm.undefined;\n break;\n case \"boolean\":\n handle = obj ? this.vm.true : this.vm.false;\n break;\n default:\n if (obj === null) {\n handle = this.vm.null;\n break;\n }\n if (isArrayBufferOrView(obj)) {\n handle = this.vm.newArrayBuffer(obj);\n manage = true;\n break;\n }\n return undefined;\n }\n return manage && scope != undefined ? scope.manage(handle) : handle;\n }\n\n public exportObjectUniversal(obj: unknown, scope?: Scope): QuickJSHandle {\n const simpleHandle = this.tryExportSingleValue(obj, scope);\n if (simpleHandle !== undefined) return simpleHandle;\n return this.exportObjectViaJson(obj, scope);\n }\n\n public exportObjectViaJson(obj: unknown, scope?: Scope): QuickJSHandle {\n const t0 = performance.now();\n const json = JSON.stringify(obj);\n this.stats.serInBytes += json.length;\n this.stats.serInCalls++;\n const result = this.vm\n .newString(json)\n .consume((jsonHandle) =>\n this.vm.unwrapResult(this.vm.callFunction(this.fnJSONParse, this.vm.undefined, jsonHandle)),\n );\n this.stats.serInMs += performance.now() - t0;\n return scope !== undefined ? scope.manage(result) : result;\n }\n\n public importObjectUniversal(handle: QuickJSHandle | undefined): unknown {\n if (handle === undefined) return undefined;\n switch (this.vm.typeof(handle)) {\n case \"undefined\":\n return undefined;\n case \"boolean\":\n case \"number\":\n case \"string\":\n return this.vm.dump(handle);\n default:\n return this.importObjectViaJson(handle);\n }\n }\n\n public importObjectViaJson(handle: QuickJSHandle): unknown {\n const t0 = performance.now();\n const text = this.vm\n .unwrapResult(this.vm.callFunction(this.fnJSONStringify, this.vm.undefined, handle))\n .consume((strHandle) => this.vm.getString(strHandle));\n this.stats.serOutBytes += text.length;\n this.stats.serOutCalls++;\n if (text === \"undefined\") {\n // special case with futures\n this.stats.serOutMs += performance.now() - t0;\n return undefined;\n }\n const result = JSON.parse(text);\n this.stats.serOutMs += performance.now() - t0;\n return result;\n }\n\n private injectCtx() {\n Scope.withScope((localScope) => {\n const configCtx = localScope.manage(this.vm.newObject());\n\n //\n // Core props\n //\n\n this.vm.setProp(configCtx, \"callbackRegistry\", this.callbackRegistry);\n this.vm.setProp(\n configCtx,\n \"featureFlags\",\n this.exportObjectUniversal(JsRenderInternal.GlobalCfgRenderCtxFeatureFlags, localScope),\n );\n\n // Inject context values from computableHelper (reactive context for outputs, inputsValid, etc.)\n if (this.computableHelper !== undefined) {\n this.computableHelper.injectCtx(configCtx);\n }\n\n //\n // Creating global variable inside the vm\n //\n\n this.vm.setProp(this.vm.global, \"cfgRenderCtx\", configCtx);\n });\n }\n}\n\n/** Holds errors that happened in the host code (like in middle-layer's drivers)\n * and then throws it where the error from quick JS is needed.\n * QuickJS couldn't throw custom errors, so we store them here, and rethrow them when we exit QuickJS side. */\nexport class ErrorRepository {\n private readonly errorIdToError = new Map<string, unknown>();\n\n /** Sets the error to the repository and returns a mimicrated error that also has uuid key of the original error. */\n public setAndRecreateForQuickJS(error: unknown): {\n name: string;\n message: string;\n } {\n const errorId = randomUUID();\n this.errorIdToError.set(errorId, error);\n\n if (error instanceof Error) {\n return {\n name: `${error.name}/uuid:${errorId}`,\n message: error.message,\n };\n }\n\n return {\n name: `UnknownErrorQuickJS/uuid:${errorId}`,\n message: `${error as any}`,\n };\n }\n\n /** Returns the original error that was stored by parsing uuid of mimicrated error. */\n public getOriginal(quickJSError: unknown): unknown {\n if (!(quickJSError instanceof errors.QuickJSUnwrapError)) {\n console.warn(\n \"ErrorRepo: quickJSError is not a QuickJSUnwrapError\",\n stringifyWithResourceId(quickJSError),\n );\n return quickJSError;\n }\n\n const cause = quickJSError.cause;\n if (\n !(\n typeof cause === \"object\" &&\n cause !== null &&\n \"name\" in cause &&\n typeof cause.name === \"string\"\n )\n ) {\n console.warn(\n \"ErrorRepo: quickJSError.cause is not an Error (can be stack limit exceeded)\",\n stringifyWithResourceId(quickJSError),\n );\n return quickJSError;\n }\n\n const causeName = cause.name;\n const uuidIdx = causeName.indexOf(\"/uuid:\");\n if (uuidIdx === -1) {\n const causeMsg = \"message\" in cause && typeof cause.message === \"string\" ? cause.message : \"\";\n throw new Error(\n `QuickJS native error: ${causeName}: ${causeMsg}, ${stringifyWithResourceId(quickJSError)}`,\n { cause: quickJSError },\n );\n }\n const errorId = causeName.slice(uuidIdx + \"/uuid:\".length);\n if (!errorId) {\n throw new Error(\n `ErrorRepo: quickJSError.cause.name does not contain errorId: ${causeName}, ${stringifyWithResourceId(quickJSError)}`,\n );\n }\n\n const error = this.errorIdToError.get(errorId);\n if (error === undefined) {\n throw new Error(\n `ErrorRepo: errorId not found: ${errorId}, ${stringifyWithResourceId(quickJSError)}`,\n );\n }\n\n return new PlQuickJSError(quickJSError, error as Error);\n }\n}\n"],"mappings":";;;;;;;;;AAyBA,SAAS,oBAAoB,KAAsC;CACjE,OAAO,eAAe,eAAe,YAAY,OAAO,GAAG;AAC7D;AAmCA,IAAa,qBAAb,MAAa,mBAAmB;CAkCZ;CACA;CACC;CAnCnB;CACA;CACA;CAEA,YAA4B,IAAI,gBAAgB;CAEhD;CAEA,QAAqC;EACnC,cAAc;EACd,aAAa;EACb,YAAY;EACZ,eAAe;EACf,SAAS;EACT,YAAY;EACZ,YAAY;EACZ,UAAU;EACV,aAAa;EACb,aAAa;EACb,gBAAgB;EAChB,aAAa;CACf;;;;;;;;;;CAWA,YACE,OACA,IACA,gBACA,cACA,eACA;EALgB,KAAA,QAAA;EACA,KAAA,KAAA;EACC,KAAA,iBAAA;EAIjB,KAAK,mBAAmB,KAAK,MAAM,OAAO,KAAK,GAAG,UAAU,CAAC;EAE7D,KAAK,kBAAkB,MAAM,OAC3B,GAAG,QAAQ,GAAG,QAAQ,MAAM,CAAC,CAAC,SAAS,SAAS,GAAG,QAAQ,MAAM,WAAW,CAAC,CAC/E;EACA,IAAI,GAAG,OAAO,KAAK,eAAe,MAAM,YACtC,MAAM,IAA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B,IACE,EACE,OAAO,UAAU,YACjB,UAAU,QACV,UAAU,SACV,OAAO,MAAM,SAAS,WAExB;GACA,QAAQ,KACN,gFAAA,GACAA,0BAAAA,wBAAAA,CAAwB,YAAY,CACtC;GACA,OAAO;EACT;EAEA,MAAM,YAAY,MAAM;EACxB,MAAM,UAAU,UAAU,QAAQ,QAAQ;EAC1C,IAAI,YAAY,IAAI;GAClB,MAAM,WAAW,aAAa,SAAS,OAAO,MAAM,YAAY,WAAW,MAAM,UAAU;GAC3F,MAAM,IAAI,MACR,yBAAyB,UAAU,IAAI,SAAS,KAAA,GAAIA,0BAAAA,wBAAAA,CAAwB,YAAY,KACxF,EAAE,OAAO,aAAa,CACxB;EACF;EACA,MAAM,UAAU,UAAU,MAAM,UAAU,CAAe;EACzD,IAAI,CAAC,SACH,MAAM,IAAI,MACR,gEAAgE,UAAU,KAAA,GAAIA,0BAAAA,wBAAAA,CAAwB,YAAY,GACpH;EAGF,MAAM,QAAQ,KAAK,eAAe,IAAI,OAAO;EAC7C,IAAI,UAAU,KAAA,GACZ,MAAM,IAAI,MACR,iCAAiC,QAAQ,KAAA,GAAIA,0BAAAA,wBAAAA,CAAwB,YAAY,GACnF;EAGF,OAAO,IAAIC,0BAAAA,eAAe,cAAc,KAAc;CACxD;AACF"}
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { ComputableContextHelper } from "./computable_context.js";
|
|
2
|
+
import { evaluateBundleCached } from "./bundle_bytecode_cache.js";
|
|
2
3
|
import { JsRenderInternal } from "@platforma-sdk/model";
|
|
3
4
|
import { notEmpty } from "@milaboratories/ts-helpers";
|
|
4
5
|
import { stringifyWithResourceId } from "@milaboratories/pl-client";
|
|
@@ -76,6 +77,28 @@ var JsExecutionContext = class JsExecutionContext {
|
|
|
76
77
|
this.stats.bundleBytes += code.length;
|
|
77
78
|
}
|
|
78
79
|
}
|
|
80
|
+
/**
|
|
81
|
+
* {@link evaluateBundle}, reusing bytecode compiled for an earlier context with the same
|
|
82
|
+
* `cacheKey`. Every lambda gets its own context and needs the whole bundle in scope, so
|
|
83
|
+
* parsing per context was the dominant cost of rendering a block.
|
|
84
|
+
*/
|
|
85
|
+
evaluateBundleCached(cacheKey, code) {
|
|
86
|
+
const t0 = performance.now();
|
|
87
|
+
try {
|
|
88
|
+
this.deadlineSetter({
|
|
89
|
+
currentExecutionTarget: "evaluateBundle",
|
|
90
|
+
deadline: Date.now() + 1e4
|
|
91
|
+
});
|
|
92
|
+
evaluateBundleCached(this.vm, cacheKey, code);
|
|
93
|
+
} catch (err) {
|
|
94
|
+
JsExecutionContext.cleanErrorContext(err);
|
|
95
|
+
throw err;
|
|
96
|
+
} finally {
|
|
97
|
+
this.deadlineSetter(void 0);
|
|
98
|
+
this.stats.bundleEvalMs += performance.now() - t0;
|
|
99
|
+
this.stats.bundleBytes += code.length;
|
|
100
|
+
}
|
|
101
|
+
}
|
|
79
102
|
runCallback(cbName, ...args) {
|
|
80
103
|
const t0 = performance.now();
|
|
81
104
|
try {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"context.js","names":[],"sources":["../../src/js_render/context.ts"],"sourcesContent":["import type { ComputableCtx } from \"@milaboratories/computable\";\nimport type { BlockCodeKnownFeatureFlags } from \"@platforma-sdk/model\";\nimport { JsRenderInternal } from \"@platforma-sdk/model\";\nimport { notEmpty } from \"@milaboratories/ts-helpers\";\nimport { randomUUID } from \"node:crypto\";\nimport type { QuickJSContext, QuickJSHandle } from \"quickjs-emscripten\";\nimport { Scope, errors } from \"quickjs-emscripten\";\nimport type { BlockContextAny } from \"../middle_layer/block_ctx\";\nimport type { MiddleLayerEnvironment } from \"../middle_layer/middle_layer\";\nimport { stringifyWithResourceId } from \"@milaboratories/pl-client\";\nimport { PlQuickJSError } from \"@milaboratories/pl-errors\";\nimport { ComputableContextHelper } from \"./computable_context\";\n\nexport type DeadlineSettings = {\n currentExecutionTarget: string;\n deadline: number;\n};\n\n/**\n * Communicates a deadline to the quickjs runtime, that if passed, will interrupt the execution.\n * Undefined can be used to reset the deadline.\n * */\nexport type DeadlineSetter = (settings: DeadlineSettings | undefined) => void;\n\nfunction isArrayBufferOrView(obj: unknown): obj is ArrayBufferLike {\n return obj instanceof ArrayBuffer || ArrayBuffer.isView(obj);\n}\n\n/**\n * Contains references to objects needed to execute lambda within computable,\n * providing access to:\n * - block context\n * - computable context\n * - middle layer environment\n * */\nexport type ComputableEnv = {\n readonly blockCtx: BlockContextAny;\n readonly mlEnv: MiddleLayerEnvironment;\n computableCtx: ComputableCtx;\n};\n\n/** Execution stats accumulated during the lifetime of a JsExecutionContext. */\nexport type JsExecStats = {\n bundleEvalMs: number;\n bundleBytes: number;\n\n callbackMs: number;\n callbackCount: number;\n\n serInMs: number;\n serInBytes: number;\n serInCalls: number;\n\n serOutMs: number;\n serOutBytes: number;\n serOutCalls: number;\n\n ctxMethodCalls: number;\n ctxMethodMs: number;\n};\n\nexport class JsExecutionContext {\n private readonly callbackRegistry: QuickJSHandle;\n private readonly fnJSONStringify: QuickJSHandle;\n private readonly fnJSONParse: QuickJSHandle;\n\n public readonly errorRepo = new ErrorRepository();\n\n public readonly computableHelper: ComputableContextHelper | undefined;\n\n public readonly stats: JsExecStats = {\n bundleEvalMs: 0,\n bundleBytes: 0,\n callbackMs: 0,\n callbackCount: 0,\n serInMs: 0,\n serInBytes: 0,\n serInCalls: 0,\n serOutMs: 0,\n serOutBytes: 0,\n serOutCalls: 0,\n ctxMethodCalls: 0,\n ctxMethodMs: 0,\n };\n\n /**\n * Creates a new JS execution context.\n *\n * @param scope - QuickJS scope for memory management\n * @param vm - QuickJS VM context\n * @param deadlineSetter - Function to set execution deadline\n * @param featureFlags - Block feature flags\n * @param computableEnv - Optional reactive computable environment (for outputs, inputsValid, etc.)\n */\n constructor(\n public readonly scope: Scope,\n public readonly vm: QuickJSContext,\n private readonly deadlineSetter: DeadlineSetter,\n featureFlags: BlockCodeKnownFeatureFlags | undefined,\n computableEnv?: ComputableEnv,\n ) {\n this.callbackRegistry = this.scope.manage(this.vm.newObject());\n\n this.fnJSONStringify = scope.manage(\n vm.getProp(vm.global, \"JSON\").consume((json) => vm.getProp(json, \"stringify\")),\n );\n if (vm.typeof(this.fnJSONStringify) !== \"function\")\n throw new Error(`JSON.stringify() not found.`);\n\n this.fnJSONParse = scope.manage(\n vm.getProp(vm.global, \"JSON\").consume((json) => vm.getProp(json, \"parse\")),\n );\n if (vm.typeof(this.fnJSONParse) !== \"function\") throw new Error(`JSON.parse() not found.`);\n\n if (computableEnv !== undefined)\n this.computableHelper = new ComputableContextHelper(\n this,\n computableEnv.blockCtx,\n computableEnv.mlEnv,\n featureFlags,\n computableEnv.computableCtx,\n );\n\n this.injectCtx();\n }\n\n public resetComputableCtx() {\n notEmpty(\n this.computableHelper,\n \"Computable context helper is not initialized\",\n ).resetComputableCtx();\n }\n\n private static cleanErrorContext(error: unknown): void {\n if (typeof error === \"object\" && error !== null && \"context\" in error) delete error[\"context\"];\n }\n\n // private static cleanError(error: unknown): unknown {\n // if (error instanceof errors.QuickJSUnwrapError) {\n // const { cause, context: _, name, message, stack, ...rest } = error;\n // const clean = new errors.QuickJSUnwrapError(cause);\n // Object.assign(clean, { ...rest, name, message, stack });\n // return clean;\n // }\n // return error;\n // }\n\n public evaluateBundle(code: string) {\n const t0 = performance.now();\n try {\n this.deadlineSetter({\n currentExecutionTarget: \"evaluateBundle\",\n deadline: Date.now() + 10000,\n });\n this.vm.unwrapResult(this.vm.evalCode(code, \"bundle.js\", { type: \"global\" })).dispose();\n } catch (err: unknown) {\n JsExecutionContext.cleanErrorContext(err);\n throw err;\n } finally {\n this.deadlineSetter(undefined);\n this.stats.bundleEvalMs += performance.now() - t0;\n this.stats.bundleBytes += code.length;\n }\n }\n\n public runCallback(cbName: string, ...args: unknown[]): QuickJSHandle {\n const t0 = performance.now();\n try {\n this.deadlineSetter({ currentExecutionTarget: cbName, deadline: Date.now() + 10000 });\n return Scope.withScope((localScope) => {\n const targetCallback = localScope.manage(this.vm.getProp(this.callbackRegistry, cbName));\n\n if (this.vm.typeof(targetCallback) !== \"function\")\n throw new Error(`No such callback: ${cbName}`);\n\n return this.scope.manage(\n this.vm.unwrapResult(\n this.vm.callFunction(\n targetCallback,\n this.vm.undefined,\n ...args.map((arg) => this.exportObjectUniversal(arg, localScope)),\n ),\n ),\n );\n });\n } catch (err: unknown) {\n JsExecutionContext.cleanErrorContext(err);\n const original = this.errorRepo.getOriginal(err);\n throw original;\n } finally {\n this.deadlineSetter(undefined);\n this.stats.callbackMs += performance.now() - t0;\n this.stats.callbackCount++;\n }\n }\n\n //\n // QuickJS Helpers\n //\n\n public exportSingleValue(\n obj: boolean | number | string | null | ArrayBuffer | undefined,\n scope?: Scope,\n ): QuickJSHandle {\n const result = this.tryExportSingleValue(obj, scope);\n if (result === undefined) {\n throw new Error(\n `Can't export value: ${obj === undefined ? \"undefined\" : JSON.stringify(obj)}`,\n );\n }\n return result;\n }\n\n public tryExportSingleValue(obj: unknown, scope?: Scope): QuickJSHandle | undefined {\n let handle: QuickJSHandle;\n let manage = false;\n switch (typeof obj) {\n case \"string\":\n handle = this.vm.newString(obj);\n manage = true;\n break;\n case \"number\":\n handle = this.vm.newNumber(obj);\n manage = true;\n break;\n case \"undefined\":\n handle = this.vm.undefined;\n break;\n case \"boolean\":\n handle = obj ? this.vm.true : this.vm.false;\n break;\n default:\n if (obj === null) {\n handle = this.vm.null;\n break;\n }\n if (isArrayBufferOrView(obj)) {\n handle = this.vm.newArrayBuffer(obj);\n manage = true;\n break;\n }\n return undefined;\n }\n return manage && scope != undefined ? scope.manage(handle) : handle;\n }\n\n public exportObjectUniversal(obj: unknown, scope?: Scope): QuickJSHandle {\n const simpleHandle = this.tryExportSingleValue(obj, scope);\n if (simpleHandle !== undefined) return simpleHandle;\n return this.exportObjectViaJson(obj, scope);\n }\n\n public exportObjectViaJson(obj: unknown, scope?: Scope): QuickJSHandle {\n const t0 = performance.now();\n const json = JSON.stringify(obj);\n this.stats.serInBytes += json.length;\n this.stats.serInCalls++;\n const result = this.vm\n .newString(json)\n .consume((jsonHandle) =>\n this.vm.unwrapResult(this.vm.callFunction(this.fnJSONParse, this.vm.undefined, jsonHandle)),\n );\n this.stats.serInMs += performance.now() - t0;\n return scope !== undefined ? scope.manage(result) : result;\n }\n\n public importObjectUniversal(handle: QuickJSHandle | undefined): unknown {\n if (handle === undefined) return undefined;\n switch (this.vm.typeof(handle)) {\n case \"undefined\":\n return undefined;\n case \"boolean\":\n case \"number\":\n case \"string\":\n return this.vm.dump(handle);\n default:\n return this.importObjectViaJson(handle);\n }\n }\n\n public importObjectViaJson(handle: QuickJSHandle): unknown {\n const t0 = performance.now();\n const text = this.vm\n .unwrapResult(this.vm.callFunction(this.fnJSONStringify, this.vm.undefined, handle))\n .consume((strHandle) => this.vm.getString(strHandle));\n this.stats.serOutBytes += text.length;\n this.stats.serOutCalls++;\n if (text === \"undefined\") {\n // special case with futures\n this.stats.serOutMs += performance.now() - t0;\n return undefined;\n }\n const result = JSON.parse(text);\n this.stats.serOutMs += performance.now() - t0;\n return result;\n }\n\n private injectCtx() {\n Scope.withScope((localScope) => {\n const configCtx = localScope.manage(this.vm.newObject());\n\n //\n // Core props\n //\n\n this.vm.setProp(configCtx, \"callbackRegistry\", this.callbackRegistry);\n this.vm.setProp(\n configCtx,\n \"featureFlags\",\n this.exportObjectUniversal(JsRenderInternal.GlobalCfgRenderCtxFeatureFlags, localScope),\n );\n\n // Inject context values from computableHelper (reactive context for outputs, inputsValid, etc.)\n if (this.computableHelper !== undefined) {\n this.computableHelper.injectCtx(configCtx);\n }\n\n //\n // Creating global variable inside the vm\n //\n\n this.vm.setProp(this.vm.global, \"cfgRenderCtx\", configCtx);\n });\n }\n}\n\n/** Holds errors that happened in the host code (like in middle-layer's drivers)\n * and then throws it where the error from quick JS is needed.\n * QuickJS couldn't throw custom errors, so we store them here, and rethrow them when we exit QuickJS side. */\nexport class ErrorRepository {\n private readonly errorIdToError = new Map<string, unknown>();\n\n /** Sets the error to the repository and returns a mimicrated error that also has uuid key of the original error. */\n public setAndRecreateForQuickJS(error: unknown): {\n name: string;\n message: string;\n } {\n const errorId = randomUUID();\n this.errorIdToError.set(errorId, error);\n\n if (error instanceof Error) {\n return {\n name: `${error.name}/uuid:${errorId}`,\n message: error.message,\n };\n }\n\n return {\n name: `UnknownErrorQuickJS/uuid:${errorId}`,\n message: `${error as any}`,\n };\n }\n\n /** Returns the original error that was stored by parsing uuid of mimicrated error. */\n public getOriginal(quickJSError: unknown): unknown {\n if (!(quickJSError instanceof errors.QuickJSUnwrapError)) {\n console.warn(\n \"ErrorRepo: quickJSError is not a QuickJSUnwrapError\",\n stringifyWithResourceId(quickJSError),\n );\n return quickJSError;\n }\n\n const cause = quickJSError.cause;\n if (\n !(\n typeof cause === \"object\" &&\n cause !== null &&\n \"name\" in cause &&\n typeof cause.name === \"string\"\n )\n ) {\n console.warn(\n \"ErrorRepo: quickJSError.cause is not an Error (can be stack limit exceeded)\",\n stringifyWithResourceId(quickJSError),\n );\n return quickJSError;\n }\n\n const causeName = cause.name;\n const uuidIdx = causeName.indexOf(\"/uuid:\");\n if (uuidIdx === -1) {\n const causeMsg = \"message\" in cause && typeof cause.message === \"string\" ? cause.message : \"\";\n throw new Error(\n `QuickJS native error: ${causeName}: ${causeMsg}, ${stringifyWithResourceId(quickJSError)}`,\n { cause: quickJSError },\n );\n }\n const errorId = causeName.slice(uuidIdx + \"/uuid:\".length);\n if (!errorId) {\n throw new Error(\n `ErrorRepo: quickJSError.cause.name does not contain errorId: ${causeName}, ${stringifyWithResourceId(quickJSError)}`,\n );\n }\n\n const error = this.errorIdToError.get(errorId);\n if (error === undefined) {\n throw new Error(\n `ErrorRepo: errorId not found: ${errorId}, ${stringifyWithResourceId(quickJSError)}`,\n );\n }\n\n return new PlQuickJSError(quickJSError, error as Error);\n }\n}\n"],"mappings":";;;;;;;;AAwBA,SAAS,oBAAoB,KAAsC;CACjE,OAAO,eAAe,eAAe,YAAY,OAAO,GAAG;AAC7D;AA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AAwB,OAAO,qBAAqB;GACxD,QAAQ,KACN,uDACA,wBAAwB,YAAY,CACtC;GACA,OAAO;EACT;EAEA,MAAM,QAAQ,aAAa;EAC3B,IACE,EACE,OAAO,UAAU,YACjB,UAAU,QACV,UAAU,SACV,OAAO,MAAM,SAAS,WAExB;GACA,QAAQ,KACN,+EACA,wBAAwB,YAAY,CACtC;GACA,OAAO;EACT;EAEA,MAAM,YAAY,MAAM;EACxB,MAAM,UAAU,UAAU,QAAQ,QAAQ;EAC1C,IAAI,YAAY,IAAI;GAClB,MAAM,WAAW,aAAa,SAAS,OAAO,MAAM,YAAY,WAAW,MAAM,UAAU;GAC3F,MAAM,IAAI,MACR,yBAAyB,UAAU,IAAI,SAAS,IAAI,wBAAwB,YAAY,KACxF,EAAE,OAAO,aAAa,CACxB;EACF;EACA,MAAM,UAAU,UAAU,MAAM,UAAU,CAAe;EACzD,IAAI,CAAC,SACH,MAAM,IAAI,MACR,gEAAgE,UAAU,IAAI,wBAAwB,YAAY,GACpH;EAGF,MAAM,QAAQ,KAAK,eAAe,IAAI,OAAO;EAC7C,IAAI,UAAU,KAAA,GACZ,MAAM,IAAI,MACR,iCAAiC,QAAQ,IAAI,wBAAwB,YAAY,GACnF;EAGF,OAAO,IAAI,eAAe,cAAc,KAAc;CACxD;AACF"}
|
|
1
|
+
{"version":3,"file":"context.js","names":[],"sources":["../../src/js_render/context.ts"],"sourcesContent":["import type { ComputableCtx } from \"@milaboratories/computable\";\nimport type { BlockCodeKnownFeatureFlags } from \"@platforma-sdk/model\";\nimport { JsRenderInternal } from \"@platforma-sdk/model\";\nimport { notEmpty } from \"@milaboratories/ts-helpers\";\nimport { randomUUID } from \"node:crypto\";\nimport type { QuickJSContext, QuickJSHandle } from \"quickjs-emscripten\";\nimport { Scope, errors } from \"quickjs-emscripten\";\nimport type { BlockContextAny } from \"../middle_layer/block_ctx\";\nimport type { MiddleLayerEnvironment } from \"../middle_layer/middle_layer\";\nimport { stringifyWithResourceId } from \"@milaboratories/pl-client\";\nimport { PlQuickJSError } from \"@milaboratories/pl-errors\";\nimport { ComputableContextHelper } from \"./computable_context\";\n\nimport { evaluateBundleCached } from \"./bundle_bytecode_cache\";\nexport type DeadlineSettings = {\n currentExecutionTarget: string;\n deadline: number;\n};\n\n/**\n * Communicates a deadline to the quickjs runtime, that if passed, will interrupt the execution.\n * Undefined can be used to reset the deadline.\n * */\nexport type DeadlineSetter = (settings: DeadlineSettings | undefined) => void;\n\nfunction isArrayBufferOrView(obj: unknown): obj is ArrayBufferLike {\n return obj instanceof ArrayBuffer || ArrayBuffer.isView(obj);\n}\n\n/**\n * Contains references to objects needed to execute lambda within computable,\n * providing access to:\n * - block context\n * - computable context\n * - middle layer environment\n * */\nexport type ComputableEnv = {\n readonly blockCtx: BlockContextAny;\n readonly mlEnv: MiddleLayerEnvironment;\n computableCtx: ComputableCtx;\n};\n\n/** Execution stats accumulated during the lifetime of a JsExecutionContext. */\nexport type JsExecStats = {\n bundleEvalMs: number;\n bundleBytes: number;\n\n callbackMs: number;\n callbackCount: number;\n\n serInMs: number;\n serInBytes: number;\n serInCalls: number;\n\n serOutMs: number;\n serOutBytes: number;\n serOutCalls: number;\n\n ctxMethodCalls: number;\n ctxMethodMs: number;\n};\n\nexport class JsExecutionContext {\n private readonly callbackRegistry: QuickJSHandle;\n private readonly fnJSONStringify: QuickJSHandle;\n private readonly fnJSONParse: QuickJSHandle;\n\n public readonly errorRepo = new ErrorRepository();\n\n public readonly computableHelper: ComputableContextHelper | undefined;\n\n public readonly stats: JsExecStats = {\n bundleEvalMs: 0,\n bundleBytes: 0,\n callbackMs: 0,\n callbackCount: 0,\n serInMs: 0,\n serInBytes: 0,\n serInCalls: 0,\n serOutMs: 0,\n serOutBytes: 0,\n serOutCalls: 0,\n ctxMethodCalls: 0,\n ctxMethodMs: 0,\n };\n\n /**\n * Creates a new JS execution context.\n *\n * @param scope - QuickJS scope for memory management\n * @param vm - QuickJS VM context\n * @param deadlineSetter - Function to set execution deadline\n * @param featureFlags - Block feature flags\n * @param computableEnv - Optional reactive computable environment (for outputs, inputsValid, etc.)\n */\n constructor(\n public readonly scope: Scope,\n public readonly vm: QuickJSContext,\n private readonly deadlineSetter: DeadlineSetter,\n featureFlags: BlockCodeKnownFeatureFlags | undefined,\n computableEnv?: ComputableEnv,\n ) {\n this.callbackRegistry = this.scope.manage(this.vm.newObject());\n\n this.fnJSONStringify = scope.manage(\n vm.getProp(vm.global, \"JSON\").consume((json) => vm.getProp(json, \"stringify\")),\n );\n if (vm.typeof(this.fnJSONStringify) !== \"function\")\n throw new Error(`JSON.stringify() not found.`);\n\n this.fnJSONParse = scope.manage(\n vm.getProp(vm.global, \"JSON\").consume((json) => vm.getProp(json, \"parse\")),\n );\n if (vm.typeof(this.fnJSONParse) !== \"function\") throw new Error(`JSON.parse() not found.`);\n\n if (computableEnv !== undefined)\n this.computableHelper = new ComputableContextHelper(\n this,\n computableEnv.blockCtx,\n computableEnv.mlEnv,\n featureFlags,\n computableEnv.computableCtx,\n );\n\n this.injectCtx();\n }\n\n public resetComputableCtx() {\n notEmpty(\n this.computableHelper,\n \"Computable context helper is not initialized\",\n ).resetComputableCtx();\n }\n\n private static cleanErrorContext(error: unknown): void {\n if (typeof error === \"object\" && error !== null && \"context\" in error) delete error[\"context\"];\n }\n\n // private static cleanError(error: unknown): unknown {\n // if (error instanceof errors.QuickJSUnwrapError) {\n // const { cause, context: _, name, message, stack, ...rest } = error;\n // const clean = new errors.QuickJSUnwrapError(cause);\n // Object.assign(clean, { ...rest, name, message, stack });\n // return clean;\n // }\n // return error;\n // }\n\n public evaluateBundle(code: string) {\n const t0 = performance.now();\n try {\n this.deadlineSetter({\n currentExecutionTarget: \"evaluateBundle\",\n deadline: Date.now() + 10000,\n });\n this.vm.unwrapResult(this.vm.evalCode(code, \"bundle.js\", { type: \"global\" })).dispose();\n } catch (err: unknown) {\n JsExecutionContext.cleanErrorContext(err);\n throw err;\n } finally {\n this.deadlineSetter(undefined);\n this.stats.bundleEvalMs += performance.now() - t0;\n this.stats.bundleBytes += code.length;\n }\n }\n\n /**\n * {@link evaluateBundle}, reusing bytecode compiled for an earlier context with the same\n * `cacheKey`. Every lambda gets its own context and needs the whole bundle in scope, so\n * parsing per context was the dominant cost of rendering a block.\n */\n public evaluateBundleCached(cacheKey: string, code: string) {\n const t0 = performance.now();\n try {\n this.deadlineSetter({\n currentExecutionTarget: \"evaluateBundle\",\n deadline: Date.now() + 10000,\n });\n evaluateBundleCached(this.vm, cacheKey, code);\n } catch (err: unknown) {\n JsExecutionContext.cleanErrorContext(err);\n throw err;\n } finally {\n this.deadlineSetter(undefined);\n this.stats.bundleEvalMs += performance.now() - t0;\n this.stats.bundleBytes += code.length;\n }\n }\n\n public runCallback(cbName: string, ...args: unknown[]): QuickJSHandle {\n const t0 = performance.now();\n try {\n this.deadlineSetter({ currentExecutionTarget: cbName, deadline: Date.now() + 10000 });\n return Scope.withScope((localScope) => {\n const targetCallback = localScope.manage(this.vm.getProp(this.callbackRegistry, cbName));\n\n if (this.vm.typeof(targetCallback) !== \"function\")\n throw new Error(`No such callback: ${cbName}`);\n\n return this.scope.manage(\n this.vm.unwrapResult(\n this.vm.callFunction(\n targetCallback,\n this.vm.undefined,\n ...args.map((arg) => this.exportObjectUniversal(arg, localScope)),\n ),\n ),\n );\n });\n } catch (err: unknown) {\n JsExecutionContext.cleanErrorContext(err);\n const original = this.errorRepo.getOriginal(err);\n throw original;\n } finally {\n this.deadlineSetter(undefined);\n this.stats.callbackMs += performance.now() - t0;\n this.stats.callbackCount++;\n }\n }\n\n //\n // QuickJS Helpers\n //\n\n public exportSingleValue(\n obj: boolean | number | string | null | ArrayBuffer | undefined,\n scope?: Scope,\n ): QuickJSHandle {\n const result = this.tryExportSingleValue(obj, scope);\n if (result === undefined) {\n throw new Error(\n `Can't export value: ${obj === undefined ? \"undefined\" : JSON.stringify(obj)}`,\n );\n }\n return result;\n }\n\n public tryExportSingleValue(obj: unknown, scope?: Scope): QuickJSHandle | undefined {\n let handle: QuickJSHandle;\n let manage = false;\n switch (typeof obj) {\n case \"string\":\n handle = this.vm.newString(obj);\n manage = true;\n break;\n case \"number\":\n handle = this.vm.newNumber(obj);\n manage = true;\n break;\n case \"undefined\":\n handle = this.vm.undefined;\n break;\n case \"boolean\":\n handle = obj ? this.vm.true : this.vm.false;\n break;\n default:\n if (obj === null) {\n handle = this.vm.null;\n break;\n }\n if (isArrayBufferOrView(obj)) {\n handle = this.vm.newArrayBuffer(obj);\n manage = true;\n break;\n }\n return undefined;\n }\n return manage && scope != undefined ? scope.manage(handle) : handle;\n }\n\n public exportObjectUniversal(obj: unknown, scope?: Scope): QuickJSHandle {\n const simpleHandle = this.tryExportSingleValue(obj, scope);\n if (simpleHandle !== undefined) return simpleHandle;\n return this.exportObjectViaJson(obj, scope);\n }\n\n public exportObjectViaJson(obj: unknown, scope?: Scope): QuickJSHandle {\n const t0 = performance.now();\n const json = JSON.stringify(obj);\n this.stats.serInBytes += json.length;\n this.stats.serInCalls++;\n const result = this.vm\n .newString(json)\n .consume((jsonHandle) =>\n this.vm.unwrapResult(this.vm.callFunction(this.fnJSONParse, this.vm.undefined, jsonHandle)),\n );\n this.stats.serInMs += performance.now() - t0;\n return scope !== undefined ? scope.manage(result) : result;\n }\n\n public importObjectUniversal(handle: QuickJSHandle | undefined): unknown {\n if (handle === undefined) return undefined;\n switch (this.vm.typeof(handle)) {\n case \"undefined\":\n return undefined;\n case \"boolean\":\n case \"number\":\n case \"string\":\n return this.vm.dump(handle);\n default:\n return this.importObjectViaJson(handle);\n }\n }\n\n public importObjectViaJson(handle: QuickJSHandle): unknown {\n const t0 = performance.now();\n const text = this.vm\n .unwrapResult(this.vm.callFunction(this.fnJSONStringify, this.vm.undefined, handle))\n .consume((strHandle) => this.vm.getString(strHandle));\n this.stats.serOutBytes += text.length;\n this.stats.serOutCalls++;\n if (text === \"undefined\") {\n // special case with futures\n this.stats.serOutMs += performance.now() - t0;\n return undefined;\n }\n const result = JSON.parse(text);\n this.stats.serOutMs += performance.now() - t0;\n return result;\n }\n\n private injectCtx() {\n Scope.withScope((localScope) => {\n const configCtx = localScope.manage(this.vm.newObject());\n\n //\n // Core props\n //\n\n this.vm.setProp(configCtx, \"callbackRegistry\", this.callbackRegistry);\n this.vm.setProp(\n configCtx,\n \"featureFlags\",\n this.exportObjectUniversal(JsRenderInternal.GlobalCfgRenderCtxFeatureFlags, localScope),\n );\n\n // Inject context values from computableHelper (reactive context for outputs, inputsValid, etc.)\n if (this.computableHelper !== undefined) {\n this.computableHelper.injectCtx(configCtx);\n }\n\n //\n // Creating global variable inside the vm\n //\n\n this.vm.setProp(this.vm.global, \"cfgRenderCtx\", configCtx);\n });\n }\n}\n\n/** Holds errors that happened in the host code (like in middle-layer's drivers)\n * and then throws it where the error from quick JS is needed.\n * QuickJS couldn't throw custom errors, so we store them here, and rethrow them when we exit QuickJS side. */\nexport class ErrorRepository {\n private readonly errorIdToError = new Map<string, unknown>();\n\n /** Sets the error to the repository and returns a mimicrated error that also has uuid key of the original error. */\n public setAndRecreateForQuickJS(error: unknown): {\n name: string;\n message: string;\n } {\n const errorId = randomUUID();\n this.errorIdToError.set(errorId, error);\n\n if (error instanceof Error) {\n return {\n name: `${error.name}/uuid:${errorId}`,\n message: error.message,\n };\n }\n\n return {\n name: `UnknownErrorQuickJS/uuid:${errorId}`,\n message: `${error as any}`,\n };\n }\n\n /** Returns the original error that was stored by parsing uuid of mimicrated error. */\n public getOriginal(quickJSError: unknown): unknown {\n if (!(quickJSError instanceof errors.QuickJSUnwrapError)) {\n console.warn(\n \"ErrorRepo: quickJSError is not a QuickJSUnwrapError\",\n stringifyWithResourceId(quickJSError),\n );\n return quickJSError;\n }\n\n const cause = quickJSError.cause;\n if (\n !(\n typeof cause === \"object\" &&\n cause !== null &&\n \"name\" in cause &&\n typeof cause.name === \"string\"\n )\n ) {\n console.warn(\n \"ErrorRepo: quickJSError.cause is not an Error (can be stack limit exceeded)\",\n stringifyWithResourceId(quickJSError),\n );\n return quickJSError;\n }\n\n const causeName = cause.name;\n const uuidIdx = causeName.indexOf(\"/uuid:\");\n if (uuidIdx === -1) {\n const causeMsg = \"message\" in cause && typeof cause.message === \"string\" ? cause.message : \"\";\n throw new Error(\n `QuickJS native error: ${causeName}: ${causeMsg}, ${stringifyWithResourceId(quickJSError)}`,\n { cause: quickJSError },\n );\n }\n const errorId = causeName.slice(uuidIdx + \"/uuid:\".length);\n if (!errorId) {\n throw new Error(\n `ErrorRepo: quickJSError.cause.name does not contain errorId: ${causeName}, ${stringifyWithResourceId(quickJSError)}`,\n );\n }\n\n const error = this.errorIdToError.get(errorId);\n if (error === undefined) {\n throw new Error(\n `ErrorRepo: errorId not found: ${errorId}, ${stringifyWithResourceId(quickJSError)}`,\n );\n }\n\n return new PlQuickJSError(quickJSError, error as Error);\n }\n}\n"],"mappings":";;;;;;;;;AAyBA,SAAS,oBAAoB,KAAsC;CACjE,OAAO,eAAe,eAAe,YAAY,OAAO,GAAG;AAC7D;AAmCA,IAAa,qBAAb,MAAa,mBAAmB;CAkCZ;CACA;CACC;CAnCnB;CACA;CACA;CAEA,YAA4B,IAAI,gBAAgB;CAEhD;CAEA,QAAqC;EACnC,cAAc;EACd,aAAa;EACb,YAAY;EACZ,eAAe;EACf,SAAS;EACT,YAAY;EACZ,YAAY;EACZ,UAAU;EACV,aAAa;EACb,aAAa;EACb,gBAAgB;EAChB,aAAa;CACf;;;;;;;;;;CAWA,YACE,OACA,IACA,gBACA,cACA,eACA;EALgB,KAAA,QAAA;EACA,KAAA,KAAA;EACC,KAAA,iBAAA;EAIjB,KAAK,mBAAmB,KAAK,MAAM,OAAO,KAAK,GAAG,UAAU,CAAC;EAE7D,KAAK,kBAAkB,MAAM,OAC3B,GAAG,QAAQ,GAAG,QAAQ,MAAM,CAAC,CAAC,SAAS,SAAS,GAAG,QAAQ,MAAM,WAAW,CAAC,CAC/E;EACA,IAAI,GAAG,OAAO,KAAK,eAAe,MAAM,YACtC,MAAM,IAAI,MAAM,6BAA6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EA,MAAM,YAAY,MAAM;EACxB,MAAM,UAAU,UAAU,QAAQ,QAAQ;EAC1C,IAAI,YAAY,IAAI;GAClB,MAAM,WAAW,aAAa,SAAS,OAAO,MAAM,YAAY,WAAW,MAAM,UAAU;GAC3F,MAAM,IAAI,MACR,yBAAyB,UAAU,IAAI,SAAS,IAAI,wBAAwB,YAAY,KACxF,EAAE,OAAO,aAAa,CACxB;EACF;EACA,MAAM,UAAU,UAAU,MAAM,UAAU,CAAe;EACzD,IAAI,CAAC,SACH,MAAM,IAAI,MACR,gEAAgE,UAAU,IAAI,wBAAwB,YAAY,GACpH;EAGF,MAAM,QAAQ,KAAK,eAAe,IAAI,OAAO;EAC7C,IAAI,UAAU,KAAA,GACZ,MAAM,IAAI,MACR,iCAAiC,QAAQ,IAAI,wBAAwB,YAAY,GACnF;EAGF,OAAO,IAAI,eAAe,cAAc,KAAc;CACxD;AACF"}
|
package/dist/js_render/index.cjs
CHANGED
|
@@ -104,7 +104,7 @@ function computableFromRF(env, ctx, fh, codeWithInfo, configKey, ops = {}, block
|
|
|
104
104
|
getStats: () => ({ ...rCtx.stats })
|
|
105
105
|
};
|
|
106
106
|
return (0, _milaboratories_pl_crash_recorder.recordModelRenderSync)(crashRecorder, renderInfo, () => {
|
|
107
|
-
rCtx.
|
|
107
|
+
rCtx.evaluateBundleCached(configKey, code.content);
|
|
108
108
|
const result = rCtx.runCallback(fh.handle);
|
|
109
109
|
rCtx.resetComputableCtx();
|
|
110
110
|
const toBeResolved = rCtx.computableHelper.computablesToResolve;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.cjs","names":["getDebugFlags","Computable","Scope","JsExecutionContext","recordModelRenderSync"],"sources":["../../src/js_render/index.ts"],"sourcesContent":["import type { MiddleLayerEnvironment } from \"../middle_layer/middle_layer\";\nimport type { BlockCodeWithInfo, ConfigRenderLambda } from \"@platforma-sdk/model\";\nimport type { BlockPackSpec } from \"@milaboratories/pl-model-middle-layer\";\nimport type { ComputableRenderingOps } from \"@milaboratories/computable\";\nimport { Computable } from \"@milaboratories/computable\";\nimport type { QuickJSWASMModule } from \"quickjs-emscripten\";\nimport { Scope } from \"quickjs-emscripten\";\nimport type { DeadlineSettings } from \"./context\";\nimport { JsExecutionContext } from \"./context\";\nimport type { BlockContextAny } from \"../middle_layer/block_ctx\";\nimport { getDebugFlags } from \"../debug\";\nimport { recordModelRenderSync } from \"@milaboratories/pl-crash-recorder\";\n\n/** Memory ceiling applied to every QuickJS runtime that evaluates model code. */\nconst QUICK_JS_MEMORY_LIMIT = 1024 * 1024 * 8;\n\nfunction logOutputStatus(\n handle: string,\n renderedResult: unknown,\n stable: boolean,\n recalculationCounter: number,\n unstableMarker?: string,\n) {\n if (getDebugFlags().logOutputStatus && (getDebugFlags().logOutputStatus === \"any\" || !stable)) {\n if (stable)\n console.log(\n `Stable output ${handle} calculated ${renderedResult !== undefined ? \"defined\" : \"undefined\"}; (#${recalculationCounter})`,\n );\n else\n console.log(\n `Unstable output ${handle}; marker = ${unstableMarker}; ${renderedResult !== undefined ? \"defined\" : \"undefined\"} (#${recalculationCounter})`,\n );\n }\n}\n\n/**\n * Creates a Computable that executes a render function (`fh`) from a block's code in a QuickJS virtual machine.\n * This function handles both synchronous and asynchronous execution patterns of the sandboxed JS code.\n *\n * The overall data flow is as follows:\n * 1. A QuickJS VM is initialized.\n * 2. A `JsExecutionContext` is created to bridge the host (TypeScript) and guest (QuickJS) environments. It injects a\n * context object (`cfgRenderCtx`) into the VM, providing helper methods for the sandboxed code to interact with the\n * platform (e.g., to request data).\n * 3. The block's Javascript bundle is evaluated in the VM.\n * 4. The specified render function (`fh.handle`) is executed.\n *\n * Two execution paths are possible depending on the behavior of the render function:\n *\n * ### Synchronous Path\n * If the render function computes its result without requesting any external data requiring asynchronous calculations,\n * it executes synchronously.\n * - The `computablesToResolve` map in `JsExecutionContext` remains empty.\n * - The function returns an object with an `ir` field holding the result (`{ ir: importedResult }`).\n * Since `postprocessValue` is not specified, `ir` is treated as the final resolved value of the Computable.\n * - The QuickJS VM is disposed of immediately as it's no longer needed.\n *\n * ### Asynchronous Path (with `postprocessValue`)\n * If the render function needs external data requiring asynchronous calculations (e.g., fetching a file), it calls\n * one of the injected helper methods. These methods don't return data directly. Instead, they:\n * a. Create a new `Computable` for the data request (e.g., to fetch a blob).\n * b. Register this new `Computable` in the `computablesToResolve` map.\n * c. Return a handle (string) to the sandboxed code.\n *\n * In this case:\n * - The initial execution of the render function returns a scaffold of the final result, which depends on the pending\n * computables.\n * - The `computablesToResolve` map is passed as the `ir` (initial result) to `Computable.makeRaw`.\n * - The `postprocessValue` function is provided to handle the results once the computables are resolved.\n * - The QuickJS VM is kept alive (`keepVmAlive = true`) because its state is needed in `postprocessValue`.\n * - Once the `computable` framework resolves all dependencies, it calls `postprocessValue` with the resolved data.\n * - `postprocessValue` feeds the resolved data back into the VM, allowing the sandboxed code to compute the final\n * result.\n * - The VM is eventually disposed of when the host Computable is destroyed.\n *\n * @param env The middle layer environment.\n * @param ctx The block context.\n * @param fh The config render lambda to execute.\n * @param codeWithInfo The block's code and feature flags.\n * @param configKey A key for the configuration, used for cache busting.\n * @param ops Options for the computable.\n * @returns A `Computable` that will resolve to the result of the lambda execution.\n */\nexport function computableFromRF(\n env: MiddleLayerEnvironment,\n ctx: BlockContextAny,\n fh: ConfigRenderLambda,\n codeWithInfo: BlockCodeWithInfo,\n configKey: string,\n ops: Partial<ComputableRenderingOps> = {},\n blockPack?: BlockPackSpec,\n): Computable<unknown> {\n // adding configKey to reload all outputs on block-pack update\n const key = `${ctx.blockId}#lambda#${configKey}#${fh.handle}`;\n ops = { ...ops, key };\n if (ops.mode === undefined && fh.retentive === true) ops.mode = \"StableOnlyRetentive\";\n return Computable.makeRaw((cCtx) => {\n const { code, featureFlags } = codeWithInfo;\n\n if (getDebugFlags().logOutputRecalculations)\n console.log(\n `Block lambda recalculation : ${key} (${cCtx.changeSourceMarker}; ${cCtx.bodyInvocations} invocations)`,\n );\n\n const scope = new Scope();\n let keepVmAlive = false;\n cCtx.addOnDestroy(() => {\n // If keepVmAlive is false, the scope will be disposed by the finally block,\n // no need to dispose it here.\n if (keepVmAlive) scope.dispose();\n });\n\n try {\n const runtime = scope.manage(env.quickJs.newRuntime());\n runtime.setMemoryLimit(QUICK_JS_MEMORY_LIMIT);\n runtime.setMaxStackSize(1024 * 320);\n\n let deadlineSettings: DeadlineSettings | undefined;\n runtime.setInterruptHandler(() => {\n if (deadlineSettings === undefined) return false;\n if (Date.now() > deadlineSettings.deadline) return true;\n return false;\n });\n const vm = scope.manage(runtime.newContext());\n const rCtx = new JsExecutionContext(\n scope,\n vm,\n (s) => {\n deadlineSettings = s;\n },\n featureFlags,\n { computableCtx: cCtx, blockCtx: ctx, mlEnv: env },\n );\n\n const crashRecorder = env.driverKit.crashRecorder;\n const renderInfo = {\n blockId: ctx.blockId,\n // A block id is unique to one project; these say which code it is, so a\n // log can be read against the right version without the project.\n ...describeBlockPack(blockPack),\n sdkVersion: codeWithInfo.sdkVersion,\n key,\n lambda: fh.handle,\n // The sandbox has its own 8 MB ceiling, so the model's own objects can\n // never exhaust the host heap. What can is the volume crossing out of\n // it, which `stats` counts.\n sandboxMemoryLimit: QUICK_JS_MEMORY_LIMIT,\n getStats: () => ({ ...rCtx.stats }),\n };\n\n return recordModelRenderSync(crashRecorder, renderInfo, () => {\n rCtx.evaluateBundle(code.content);\n const result = rCtx.runCallback(fh.handle);\n\n rCtx.resetComputableCtx();\n\n const toBeResolved = rCtx.computableHelper!.computablesToResolve;\n\n if (Object.keys(toBeResolved).length === 0) {\n const importedResult = rCtx.importObjectUniversal(result);\n if (getDebugFlags().logJsExecStat)\n console.log(`[jsExec] ${key}: ${JSON.stringify(rCtx.stats)}`);\n logOutputStatus(\n fh.handle,\n importedResult,\n cCtx.unstableMarker === undefined,\n -1,\n cCtx.unstableMarker,\n );\n return { ir: importedResult };\n }\n\n let recalculationCounter = 0;\n if (getDebugFlags().logOutputStatus)\n console.log(\n `Output ${fh.handle} scaffold calculated (not all computables resolved yet).`,\n );\n keepVmAlive = true;\n\n return {\n ir: toBeResolved,\n postprocessValue: (resolved: Record<string, unknown>, { unstableMarker, stable }) => {\n recalculationCounter++;\n // A deferred render resumes here, potentially many times, and each\n // resumption can build joins of its own, so each gets its own span.\n return recordModelRenderSync(\n crashRecorder,\n { ...renderInfo, recalculation: recalculationCounter },\n () => {\n // resolving futures\n for (const [handle, value] of Object.entries(resolved))\n rCtx.runCallback(handle, value);\n\n // rendering result\n const renderedResult = rCtx.importObjectUniversal(result);\n\n // logging\n if (getDebugFlags().logJsExecStat)\n console.log(\n `[jsExec] ${key} #${recalculationCounter}: ${JSON.stringify(rCtx.stats)}`,\n );\n logOutputStatus(\n fh.handle,\n renderedResult,\n stable,\n recalculationCounter,\n unstableMarker,\n );\n\n return renderedResult;\n },\n );\n },\n };\n });\n } catch (e) {\n keepVmAlive = false;\n throw e;\n } finally {\n if (!keepVmAlive) scope.dispose();\n }\n }, ops);\n}\n\nexport function executeSingleLambda(\n quickJs: QuickJSWASMModule,\n fh: ConfigRenderLambda,\n codeWithInfo: BlockCodeWithInfo,\n ...args: unknown[]\n): unknown {\n const { code, featureFlags } = codeWithInfo;\n const scope = new Scope();\n try {\n const runtime = scope.manage(quickJs.newRuntime());\n runtime.setMemoryLimit(QUICK_JS_MEMORY_LIMIT);\n runtime.setMaxStackSize(1024 * 320);\n\n let deadlineSettings: DeadlineSettings | undefined;\n runtime.setInterruptHandler(() => {\n if (deadlineSettings === undefined) return false;\n if (Date.now() > deadlineSettings.deadline) return true;\n return false;\n });\n const vm = scope.manage(runtime.newContext());\n const rCtx = new JsExecutionContext(\n scope,\n vm,\n (s) => {\n deadlineSettings = s;\n },\n featureFlags,\n );\n\n // Initializing the model\n rCtx.evaluateBundle(code.content);\n\n // Running the lambda with arguments (e.g., state for args(), args for enrichmentTargets())\n const importedResult = rCtx.importObjectUniversal(rCtx.runCallback(fh.handle, ...args));\n if (getDebugFlags().logJsExecStat)\n console.log(`[jsExec] ${fh.handle}: ${JSON.stringify(rCtx.stats)}`);\n return importedResult;\n } finally {\n scope.dispose();\n }\n}\n\n/**\n * The part of a block pack that names the code, and nothing else.\n *\n * Registry packs carry an organization, name and version, which is what a reader\n * needs to open the right source. Local and development packs carry a filesystem\n * path instead; the path is deliberately not recorded — it identifies the\n * machine rather than the code, and its `type` already says that no published\n * version exists to look up.\n */\nfunction describeBlockPack(spec: BlockPackSpec | undefined): {\n block?: string;\n blockVersion?: string;\n blockSource?: string;\n} {\n if (spec === undefined) return {};\n if (spec.type === \"from-registry-v1\" || spec.type === \"from-registry-v2\") {\n return {\n block: `${spec.id.organization}:${spec.id.name}`,\n blockVersion: spec.id.version,\n blockSource: spec.type,\n };\n }\n return { block: \"(unpublished)\", blockSource: spec.type };\n}\n"],"mappings":";;;;;;;AAcA,MAAM,wBAAwB;AAE9B,SAAS,gBACP,QACA,gBACA,QACA,sBACA,gBACA;CACA,IAAIA,cAAAA,cAAc,CAAC,CAAC,oBAAoBA,cAAAA,cAAc,CAAC,CAAC,oBAAoB,SAAS,CAAC,SAAS;EAC7F,IAAI,QACF,QAAQ,IACN,iBAAiB,OAAO,cAAc,mBAAmB,KAAA,IAAY,YAAY,YAAY,MAAM,qBAAqB,EAC1H;OAEA,QAAQ,IACN,mBAAmB,OAAO,aAAa,eAAe,IAAI,mBAAmB,KAAA,IAAY,YAAY,YAAY,KAAK,qBAAqB,EAC7I;CACJ;AACF;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAkDA,SAAgB,iBACd,KACA,KACA,IACA,cACA,WACA,MAAuC,CAAC,GACxC,WACqB;CAErB,MAAM,MAAM,GAAG,IAAI,QAAQ,UAAU,UAAU,GAAG,GAAG;CACrD,MAAM;EAAE,GAAG;EAAK;CAAI;CACpB,IAAI,IAAI,SAAS,KAAA,KAAa,GAAG,cAAc,MAAM,IAAI,OAAO;CAChE,OAAOC,2BAAAA,WAAW,SAAS,SAAS;EACl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AK,IAAI,IAAI,iBAAiB,UAAU,OAAO;GACnD,OAAO;EACT,CAAC;EACD,MAAM,KAAK,MAAM,OAAO,QAAQ,WAAW,CAAC;EAC5C,MAAM,OAAO,IAAIC,gBAAAA,mBACf,OACA,KACC,MAAM;GACL,mBAAmB;EACrB,GACA,YACF;EAGA,KAAK,eAAe,KAAK,OAAO;EAGhC,MAAM,iBAAiB,KAAK,sBAAsB,KAAK,YAAY,GAAG,QAAQ,GAAG,IAAI,CAAC;EACtF,IAAIH,cAAAA,cAAc,CAAC,CAAC,eAClB,QAAQ,IAAI,YAAY,GAAG,OAAO,IAAI,KAAK,UAAU,KAAK,KAAK,GAAG;EACpE,OAAO;CACT,UAAU;EACR,MAAM,QAAQ;CAChB;AACF;;;;;;;;;;AAWA,SAAS,kBAAkB,MAIzB;CACA,IAAI,SAAS,KAAA,GAAW,OAAO,CAAC;CAChC,IAAI,KAAK,SAAS,sBAAsB,KAAK,SAAS,oBACpD,OAAO;EACL,OAAO,GAAG,KAAK,GAAG,aAAa,GAAG,KAAK,GAAG;EAC1C,cAAc,KAAK,GAAG;EACtB,aAAa,KAAK;CACpB;CAEF,OAAO;EAAE,OAAO;EAAiB,aAAa,KAAK;CAAK;AAC1D"}
|
|
1
|
+
{"version":3,"file":"index.cjs","names":["getDebugFlags","Computable","Scope","JsExecutionContext","recordModelRenderSync"],"sources":["../../src/js_render/index.ts"],"sourcesContent":["import type { MiddleLayerEnvironment } from \"../middle_layer/middle_layer\";\nimport type { BlockCodeWithInfo, ConfigRenderLambda } from \"@platforma-sdk/model\";\nimport type { BlockPackSpec } from \"@milaboratories/pl-model-middle-layer\";\nimport type { ComputableRenderingOps } from \"@milaboratories/computable\";\nimport { Computable } from \"@milaboratories/computable\";\nimport type { QuickJSWASMModule } from \"quickjs-emscripten\";\nimport { Scope } from \"quickjs-emscripten\";\nimport type { DeadlineSettings } from \"./context\";\nimport { JsExecutionContext } from \"./context\";\nimport type { BlockContextAny } from \"../middle_layer/block_ctx\";\nimport { getDebugFlags } from \"../debug\";\nimport { recordModelRenderSync } from \"@milaboratories/pl-crash-recorder\";\n\n/** Memory ceiling applied to every QuickJS runtime that evaluates model code. */\nconst QUICK_JS_MEMORY_LIMIT = 1024 * 1024 * 8;\n\nfunction logOutputStatus(\n handle: string,\n renderedResult: unknown,\n stable: boolean,\n recalculationCounter: number,\n unstableMarker?: string,\n) {\n if (getDebugFlags().logOutputStatus && (getDebugFlags().logOutputStatus === \"any\" || !stable)) {\n if (stable)\n console.log(\n `Stable output ${handle} calculated ${renderedResult !== undefined ? \"defined\" : \"undefined\"}; (#${recalculationCounter})`,\n );\n else\n console.log(\n `Unstable output ${handle}; marker = ${unstableMarker}; ${renderedResult !== undefined ? \"defined\" : \"undefined\"} (#${recalculationCounter})`,\n );\n }\n}\n\n/**\n * Creates a Computable that executes a render function (`fh`) from a block's code in a QuickJS virtual machine.\n * This function handles both synchronous and asynchronous execution patterns of the sandboxed JS code.\n *\n * The overall data flow is as follows:\n * 1. A QuickJS VM is initialized.\n * 2. A `JsExecutionContext` is created to bridge the host (TypeScript) and guest (QuickJS) environments. It injects a\n * context object (`cfgRenderCtx`) into the VM, providing helper methods for the sandboxed code to interact with the\n * platform (e.g., to request data).\n * 3. The block's Javascript bundle is evaluated in the VM.\n * 4. The specified render function (`fh.handle`) is executed.\n *\n * Two execution paths are possible depending on the behavior of the render function:\n *\n * ### Synchronous Path\n * If the render function computes its result without requesting any external data requiring asynchronous calculations,\n * it executes synchronously.\n * - The `computablesToResolve` map in `JsExecutionContext` remains empty.\n * - The function returns an object with an `ir` field holding the result (`{ ir: importedResult }`).\n * Since `postprocessValue` is not specified, `ir` is treated as the final resolved value of the Computable.\n * - The QuickJS VM is disposed of immediately as it's no longer needed.\n *\n * ### Asynchronous Path (with `postprocessValue`)\n * If the render function needs external data requiring asynchronous calculations (e.g., fetching a file), it calls\n * one of the injected helper methods. These methods don't return data directly. Instead, they:\n * a. Create a new `Computable` for the data request (e.g., to fetch a blob).\n * b. Register this new `Computable` in the `computablesToResolve` map.\n * c. Return a handle (string) to the sandboxed code.\n *\n * In this case:\n * - The initial execution of the render function returns a scaffold of the final result, which depends on the pending\n * computables.\n * - The `computablesToResolve` map is passed as the `ir` (initial result) to `Computable.makeRaw`.\n * - The `postprocessValue` function is provided to handle the results once the computables are resolved.\n * - The QuickJS VM is kept alive (`keepVmAlive = true`) because its state is needed in `postprocessValue`.\n * - Once the `computable` framework resolves all dependencies, it calls `postprocessValue` with the resolved data.\n * - `postprocessValue` feeds the resolved data back into the VM, allowing the sandboxed code to compute the final\n * result.\n * - The VM is eventually disposed of when the host Computable is destroyed.\n *\n * @param env The middle layer environment.\n * @param ctx The block context.\n * @param fh The config render lambda to execute.\n * @param codeWithInfo The block's code and feature flags.\n * @param configKey A key for the configuration, used for cache busting.\n * @param ops Options for the computable.\n * @returns A `Computable` that will resolve to the result of the lambda execution.\n */\nexport function computableFromRF(\n env: MiddleLayerEnvironment,\n ctx: BlockContextAny,\n fh: ConfigRenderLambda,\n codeWithInfo: BlockCodeWithInfo,\n configKey: string,\n ops: Partial<ComputableRenderingOps> = {},\n blockPack?: BlockPackSpec,\n): Computable<unknown> {\n // adding configKey to reload all outputs on block-pack update\n const key = `${ctx.blockId}#lambda#${configKey}#${fh.handle}`;\n ops = { ...ops, key };\n if (ops.mode === undefined && fh.retentive === true) ops.mode = \"StableOnlyRetentive\";\n return Computable.makeRaw((cCtx) => {\n const { code, featureFlags } = codeWithInfo;\n\n if (getDebugFlags().logOutputRecalculations)\n console.log(\n `Block lambda recalculation : ${key} (${cCtx.changeSourceMarker}; ${cCtx.bodyInvocations} invocations)`,\n );\n\n const scope = new Scope();\n let keepVmAlive = false;\n cCtx.addOnDestroy(() => {\n // If keepVmAlive is false, the scope will be disposed by the finally block,\n // no need to dispose it here.\n if (keepVmAlive) scope.dispose();\n });\n\n try {\n const runtime = scope.manage(env.quickJs.newRuntime());\n runtime.setMemoryLimit(QUICK_JS_MEMORY_LIMIT);\n runtime.setMaxStackSize(1024 * 320);\n\n let deadlineSettings: DeadlineSettings | undefined;\n runtime.setInterruptHandler(() => {\n if (deadlineSettings === undefined) return false;\n if (Date.now() > deadlineSettings.deadline) return true;\n return false;\n });\n const vm = scope.manage(runtime.newContext());\n const rCtx = new JsExecutionContext(\n scope,\n vm,\n (s) => {\n deadlineSettings = s;\n },\n featureFlags,\n { computableCtx: cCtx, blockCtx: ctx, mlEnv: env },\n );\n\n const crashRecorder = env.driverKit.crashRecorder;\n const renderInfo = {\n blockId: ctx.blockId,\n // A block id is unique to one project; these say which code it is, so a\n // log can be read against the right version without the project.\n ...describeBlockPack(blockPack),\n sdkVersion: codeWithInfo.sdkVersion,\n key,\n lambda: fh.handle,\n // The sandbox has its own 8 MB ceiling, so the model's own objects can\n // never exhaust the host heap. What can is the volume crossing out of\n // it, which `stats` counts.\n sandboxMemoryLimit: QUICK_JS_MEMORY_LIMIT,\n getStats: () => ({ ...rCtx.stats }),\n };\n\n return recordModelRenderSync(crashRecorder, renderInfo, () => {\n // configKey already identifies this block pack's config, and exists to invalidate\n // rendered outputs when the pack changes, so it keys the compiled bundle too.\n rCtx.evaluateBundleCached(configKey, code.content);\n const result = rCtx.runCallback(fh.handle);\n\n rCtx.resetComputableCtx();\n\n const toBeResolved = rCtx.computableHelper!.computablesToResolve;\n\n if (Object.keys(toBeResolved).length === 0) {\n const importedResult = rCtx.importObjectUniversal(result);\n if (getDebugFlags().logJsExecStat)\n console.log(`[jsExec] ${key}: ${JSON.stringify(rCtx.stats)}`);\n logOutputStatus(\n fh.handle,\n importedResult,\n cCtx.unstableMarker === undefined,\n -1,\n cCtx.unstableMarker,\n );\n return { ir: importedResult };\n }\n\n let recalculationCounter = 0;\n if (getDebugFlags().logOutputStatus)\n console.log(\n `Output ${fh.handle} scaffold calculated (not all computables resolved yet).`,\n );\n keepVmAlive = true;\n\n return {\n ir: toBeResolved,\n postprocessValue: (resolved: Record<string, unknown>, { unstableMarker, stable }) => {\n recalculationCounter++;\n // A deferred render resumes here, potentially many times, and each\n // resumption can build joins of its own, so each gets its own span.\n return recordModelRenderSync(\n crashRecorder,\n { ...renderInfo, recalculation: recalculationCounter },\n () => {\n // resolving futures\n for (const [handle, value] of Object.entries(resolved))\n rCtx.runCallback(handle, value);\n\n // rendering result\n const renderedResult = rCtx.importObjectUniversal(result);\n\n // logging\n if (getDebugFlags().logJsExecStat)\n console.log(\n `[jsExec] ${key} #${recalculationCounter}: ${JSON.stringify(rCtx.stats)}`,\n );\n logOutputStatus(\n fh.handle,\n renderedResult,\n stable,\n recalculationCounter,\n unstableMarker,\n );\n\n return renderedResult;\n },\n );\n },\n };\n });\n } catch (e) {\n keepVmAlive = false;\n throw e;\n } finally {\n if (!keepVmAlive) scope.dispose();\n }\n }, ops);\n}\n\nexport function executeSingleLambda(\n quickJs: QuickJSWASMModule,\n fh: ConfigRenderLambda,\n codeWithInfo: BlockCodeWithInfo,\n ...args: unknown[]\n): unknown {\n const { code, featureFlags } = codeWithInfo;\n const scope = new Scope();\n try {\n const runtime = scope.manage(quickJs.newRuntime());\n runtime.setMemoryLimit(QUICK_JS_MEMORY_LIMIT);\n runtime.setMaxStackSize(1024 * 320);\n\n let deadlineSettings: DeadlineSettings | undefined;\n runtime.setInterruptHandler(() => {\n if (deadlineSettings === undefined) return false;\n if (Date.now() > deadlineSettings.deadline) return true;\n return false;\n });\n const vm = scope.manage(runtime.newContext());\n const rCtx = new JsExecutionContext(\n scope,\n vm,\n (s) => {\n deadlineSettings = s;\n },\n featureFlags,\n );\n\n // Initializing the model\n rCtx.evaluateBundle(code.content);\n\n // Running the lambda with arguments (e.g., state for args(), args for enrichmentTargets())\n const importedResult = rCtx.importObjectUniversal(rCtx.runCallback(fh.handle, ...args));\n if (getDebugFlags().logJsExecStat)\n console.log(`[jsExec] ${fh.handle}: ${JSON.stringify(rCtx.stats)}`);\n return importedResult;\n } finally {\n scope.dispose();\n }\n}\n\n/**\n * The part of a block pack that names the code, and nothing else.\n *\n * Registry packs carry an organization, name and version, which is what a reader\n * needs to open the right source. Local and development packs carry a filesystem\n * path instead; the path is deliberately not recorded — it identifies the\n * machine rather than the code, and its `type` already says that no published\n * version exists to look up.\n */\nfunction describeBlockPack(spec: BlockPackSpec | undefined): {\n block?: string;\n blockVersion?: string;\n blockSource?: string;\n} {\n if (spec === undefined) return {};\n if (spec.type === \"from-registry-v1\" || spec.type === \"from-registry-v2\") {\n return {\n block: `${spec.id.organization}:${spec.id.name}`,\n blockVersion: spec.id.version,\n blockSource: spec.type,\n };\n }\n return { block: \"(unpublished)\", blockSource: spec.type };\n}\n"],"mappings":";;;;;;;AAcA,MAAM,wBAAwB;AAE9B,SAAS,gBACP,QACA,gBACA,QACA,sBACA,gBACA;CACA,IAAIA,cAAAA,cAAc,CAAC,CAAC,oBAAoBA,cAAAA,cAAc,CAAC,CAAC,oBAAoB,SAAS,CAAC,SAAS;EAC7F,IAAI,QACF,QAAQ,IACN,iBAAiB,OAAO,cAAc,mBAAmB,KAAA,IAAY,YAAY,YAAY,MAAM,qBAAqB,EAC1H;OAEA,QAAQ,IACN,mBAAmB,OAAO,aAAa,eAAe,IAAI,mBAAmB,KAAA,IAAY,YAAY,YAAY,KAAK,qBAAqB,EAC7I;CACJ;AACF;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAkDA,SAAgB,iBACd,KACA,KACA,IACA,cACA,WACA,MAAuC,CAAC,GACxC,WACqB;CAErB,MAAM,MAAM,GAAG,IAAI,QAAQ,UAAU,UAAU,GAAG,GAAG;CACrD,MAAM;EAAE,GAAG;EAAK;CAAI;CACpB,IAAI,IAAI,SAAS,KAAA,KAAa,GAAG,cAAc,MAAM,IAAI,OAAO;CAChE,OAAOC,2BAAAA,WAAW,SAAS,SAAS;EAClC,MAAM,EAAE,MAAM,iBAAiB;EAE/B,IAAID,cAAAA,cAAc,CAAC,CAAC,yBAClB,QAAQ,IACN,gCAAgC,IAAI,IAAI,KAAK,mBAAmB,IAAI,KAAK,gBA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AIC,gBAAAA,mBACf,OACA,KACC,MAAM;GACL,mBAAmB;EACrB,GACA,YACF;EAGA,KAAK,eAAe,KAAK,OAAO;EAGhC,MAAM,iBAAiB,KAAK,sBAAsB,KAAK,YAAY,GAAG,QAAQ,GAAG,IAAI,CAAC;EACtF,IAAIH,cAAAA,cAAc,CAAC,CAAC,eAClB,QAAQ,IAAI,YAAY,GAAG,OAAO,IAAI,KAAK,UAAU,KAAK,KAAK,GAAG;EACpE,OAAO;CACT,UAAU;EACR,MAAM,QAAQ;CAChB;AACF;;;;;;;;;;AAWA,SAAS,kBAAkB,MAIzB;CACA,IAAI,SAAS,KAAA,GAAW,OAAO,CAAC;CAChC,IAAI,KAAK,SAAS,sBAAsB,KAAK,SAAS,oBACpD,OAAO;EACL,OAAO,GAAG,KAAK,GAAG,aAAa,GAAG,KAAK,GAAG;EAC1C,cAAc,KAAK,GAAG;EACtB,aAAa,KAAK;CACpB;CAEF,OAAO;EAAE,OAAO;EAAiB,aAAa,KAAK;CAAK;AAC1D"}
|
package/dist/js_render/index.js
CHANGED
|
@@ -104,7 +104,7 @@ function computableFromRF(env, ctx, fh, codeWithInfo, configKey, ops = {}, block
|
|
|
104
104
|
getStats: () => ({ ...rCtx.stats })
|
|
105
105
|
};
|
|
106
106
|
return recordModelRenderSync(crashRecorder, renderInfo, () => {
|
|
107
|
-
rCtx.
|
|
107
|
+
rCtx.evaluateBundleCached(configKey, code.content);
|
|
108
108
|
const result = rCtx.runCallback(fh.handle);
|
|
109
109
|
rCtx.resetComputableCtx();
|
|
110
110
|
const toBeResolved = rCtx.computableHelper.computablesToResolve;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":[],"sources":["../../src/js_render/index.ts"],"sourcesContent":["import type { MiddleLayerEnvironment } from \"../middle_layer/middle_layer\";\nimport type { BlockCodeWithInfo, ConfigRenderLambda } from \"@platforma-sdk/model\";\nimport type { BlockPackSpec } from \"@milaboratories/pl-model-middle-layer\";\nimport type { ComputableRenderingOps } from \"@milaboratories/computable\";\nimport { Computable } from \"@milaboratories/computable\";\nimport type { QuickJSWASMModule } from \"quickjs-emscripten\";\nimport { Scope } from \"quickjs-emscripten\";\nimport type { DeadlineSettings } from \"./context\";\nimport { JsExecutionContext } from \"./context\";\nimport type { BlockContextAny } from \"../middle_layer/block_ctx\";\nimport { getDebugFlags } from \"../debug\";\nimport { recordModelRenderSync } from \"@milaboratories/pl-crash-recorder\";\n\n/** Memory ceiling applied to every QuickJS runtime that evaluates model code. */\nconst QUICK_JS_MEMORY_LIMIT = 1024 * 1024 * 8;\n\nfunction logOutputStatus(\n handle: string,\n renderedResult: unknown,\n stable: boolean,\n recalculationCounter: number,\n unstableMarker?: string,\n) {\n if (getDebugFlags().logOutputStatus && (getDebugFlags().logOutputStatus === \"any\" || !stable)) {\n if (stable)\n console.log(\n `Stable output ${handle} calculated ${renderedResult !== undefined ? \"defined\" : \"undefined\"}; (#${recalculationCounter})`,\n );\n else\n console.log(\n `Unstable output ${handle}; marker = ${unstableMarker}; ${renderedResult !== undefined ? \"defined\" : \"undefined\"} (#${recalculationCounter})`,\n );\n }\n}\n\n/**\n * Creates a Computable that executes a render function (`fh`) from a block's code in a QuickJS virtual machine.\n * This function handles both synchronous and asynchronous execution patterns of the sandboxed JS code.\n *\n * The overall data flow is as follows:\n * 1. A QuickJS VM is initialized.\n * 2. A `JsExecutionContext` is created to bridge the host (TypeScript) and guest (QuickJS) environments. It injects a\n * context object (`cfgRenderCtx`) into the VM, providing helper methods for the sandboxed code to interact with the\n * platform (e.g., to request data).\n * 3. The block's Javascript bundle is evaluated in the VM.\n * 4. The specified render function (`fh.handle`) is executed.\n *\n * Two execution paths are possible depending on the behavior of the render function:\n *\n * ### Synchronous Path\n * If the render function computes its result without requesting any external data requiring asynchronous calculations,\n * it executes synchronously.\n * - The `computablesToResolve` map in `JsExecutionContext` remains empty.\n * - The function returns an object with an `ir` field holding the result (`{ ir: importedResult }`).\n * Since `postprocessValue` is not specified, `ir` is treated as the final resolved value of the Computable.\n * - The QuickJS VM is disposed of immediately as it's no longer needed.\n *\n * ### Asynchronous Path (with `postprocessValue`)\n * If the render function needs external data requiring asynchronous calculations (e.g., fetching a file), it calls\n * one of the injected helper methods. These methods don't return data directly. Instead, they:\n * a. Create a new `Computable` for the data request (e.g., to fetch a blob).\n * b. Register this new `Computable` in the `computablesToResolve` map.\n * c. Return a handle (string) to the sandboxed code.\n *\n * In this case:\n * - The initial execution of the render function returns a scaffold of the final result, which depends on the pending\n * computables.\n * - The `computablesToResolve` map is passed as the `ir` (initial result) to `Computable.makeRaw`.\n * - The `postprocessValue` function is provided to handle the results once the computables are resolved.\n * - The QuickJS VM is kept alive (`keepVmAlive = true`) because its state is needed in `postprocessValue`.\n * - Once the `computable` framework resolves all dependencies, it calls `postprocessValue` with the resolved data.\n * - `postprocessValue` feeds the resolved data back into the VM, allowing the sandboxed code to compute the final\n * result.\n * - The VM is eventually disposed of when the host Computable is destroyed.\n *\n * @param env The middle layer environment.\n * @param ctx The block context.\n * @param fh The config render lambda to execute.\n * @param codeWithInfo The block's code and feature flags.\n * @param configKey A key for the configuration, used for cache busting.\n * @param ops Options for the computable.\n * @returns A `Computable` that will resolve to the result of the lambda execution.\n */\nexport function computableFromRF(\n env: MiddleLayerEnvironment,\n ctx: BlockContextAny,\n fh: ConfigRenderLambda,\n codeWithInfo: BlockCodeWithInfo,\n configKey: string,\n ops: Partial<ComputableRenderingOps> = {},\n blockPack?: BlockPackSpec,\n): Computable<unknown> {\n // adding configKey to reload all outputs on block-pack update\n const key = `${ctx.blockId}#lambda#${configKey}#${fh.handle}`;\n ops = { ...ops, key };\n if (ops.mode === undefined && fh.retentive === true) ops.mode = \"StableOnlyRetentive\";\n return Computable.makeRaw((cCtx) => {\n const { code, featureFlags } = codeWithInfo;\n\n if (getDebugFlags().logOutputRecalculations)\n console.log(\n `Block lambda recalculation : ${key} (${cCtx.changeSourceMarker}; ${cCtx.bodyInvocations} invocations)`,\n );\n\n const scope = new Scope();\n let keepVmAlive = false;\n cCtx.addOnDestroy(() => {\n // If keepVmAlive is false, the scope will be disposed by the finally block,\n // no need to dispose it here.\n if (keepVmAlive) scope.dispose();\n });\n\n try {\n const runtime = scope.manage(env.quickJs.newRuntime());\n runtime.setMemoryLimit(QUICK_JS_MEMORY_LIMIT);\n runtime.setMaxStackSize(1024 * 320);\n\n let deadlineSettings: DeadlineSettings | undefined;\n runtime.setInterruptHandler(() => {\n if (deadlineSettings === undefined) return false;\n if (Date.now() > deadlineSettings.deadline) return true;\n return false;\n });\n const vm = scope.manage(runtime.newContext());\n const rCtx = new JsExecutionContext(\n scope,\n vm,\n (s) => {\n deadlineSettings = s;\n },\n featureFlags,\n { computableCtx: cCtx, blockCtx: ctx, mlEnv: env },\n );\n\n const crashRecorder = env.driverKit.crashRecorder;\n const renderInfo = {\n blockId: ctx.blockId,\n // A block id is unique to one project; these say which code it is, so a\n // log can be read against the right version without the project.\n ...describeBlockPack(blockPack),\n sdkVersion: codeWithInfo.sdkVersion,\n key,\n lambda: fh.handle,\n // The sandbox has its own 8 MB ceiling, so the model's own objects can\n // never exhaust the host heap. What can is the volume crossing out of\n // it, which `stats` counts.\n sandboxMemoryLimit: QUICK_JS_MEMORY_LIMIT,\n getStats: () => ({ ...rCtx.stats }),\n };\n\n return recordModelRenderSync(crashRecorder, renderInfo, () => {\n rCtx.evaluateBundle(code.content);\n const result = rCtx.runCallback(fh.handle);\n\n rCtx.resetComputableCtx();\n\n const toBeResolved = rCtx.computableHelper!.computablesToResolve;\n\n if (Object.keys(toBeResolved).length === 0) {\n const importedResult = rCtx.importObjectUniversal(result);\n if (getDebugFlags().logJsExecStat)\n console.log(`[jsExec] ${key}: ${JSON.stringify(rCtx.stats)}`);\n logOutputStatus(\n fh.handle,\n importedResult,\n cCtx.unstableMarker === undefined,\n -1,\n cCtx.unstableMarker,\n );\n return { ir: importedResult };\n }\n\n let recalculationCounter = 0;\n if (getDebugFlags().logOutputStatus)\n console.log(\n `Output ${fh.handle} scaffold calculated (not all computables resolved yet).`,\n );\n keepVmAlive = true;\n\n return {\n ir: toBeResolved,\n postprocessValue: (resolved: Record<string, unknown>, { unstableMarker, stable }) => {\n recalculationCounter++;\n // A deferred render resumes here, potentially many times, and each\n // resumption can build joins of its own, so each gets its own span.\n return recordModelRenderSync(\n crashRecorder,\n { ...renderInfo, recalculation: recalculationCounter },\n () => {\n // resolving futures\n for (const [handle, value] of Object.entries(resolved))\n rCtx.runCallback(handle, value);\n\n // rendering result\n const renderedResult = rCtx.importObjectUniversal(result);\n\n // logging\n if (getDebugFlags().logJsExecStat)\n console.log(\n `[jsExec] ${key} #${recalculationCounter}: ${JSON.stringify(rCtx.stats)}`,\n );\n logOutputStatus(\n fh.handle,\n renderedResult,\n stable,\n recalculationCounter,\n unstableMarker,\n );\n\n return renderedResult;\n },\n );\n },\n };\n });\n } catch (e) {\n keepVmAlive = false;\n throw e;\n } finally {\n if (!keepVmAlive) scope.dispose();\n }\n }, ops);\n}\n\nexport function executeSingleLambda(\n quickJs: QuickJSWASMModule,\n fh: ConfigRenderLambda,\n codeWithInfo: BlockCodeWithInfo,\n ...args: unknown[]\n): unknown {\n const { code, featureFlags } = codeWithInfo;\n const scope = new Scope();\n try {\n const runtime = scope.manage(quickJs.newRuntime());\n runtime.setMemoryLimit(QUICK_JS_MEMORY_LIMIT);\n runtime.setMaxStackSize(1024 * 320);\n\n let deadlineSettings: DeadlineSettings | undefined;\n runtime.setInterruptHandler(() => {\n if (deadlineSettings === undefined) return false;\n if (Date.now() > deadlineSettings.deadline) return true;\n return false;\n });\n const vm = scope.manage(runtime.newContext());\n const rCtx = new JsExecutionContext(\n scope,\n vm,\n (s) => {\n deadlineSettings = s;\n },\n featureFlags,\n );\n\n // Initializing the model\n rCtx.evaluateBundle(code.content);\n\n // Running the lambda with arguments (e.g., state for args(), args for enrichmentTargets())\n const importedResult = rCtx.importObjectUniversal(rCtx.runCallback(fh.handle, ...args));\n if (getDebugFlags().logJsExecStat)\n console.log(`[jsExec] ${fh.handle}: ${JSON.stringify(rCtx.stats)}`);\n return importedResult;\n } finally {\n scope.dispose();\n }\n}\n\n/**\n * The part of a block pack that names the code, and nothing else.\n *\n * Registry packs carry an organization, name and version, which is what a reader\n * needs to open the right source. Local and development packs carry a filesystem\n * path instead; the path is deliberately not recorded — it identifies the\n * machine rather than the code, and its `type` already says that no published\n * version exists to look up.\n */\nfunction describeBlockPack(spec: BlockPackSpec | undefined): {\n block?: string;\n blockVersion?: string;\n blockSource?: string;\n} {\n if (spec === undefined) return {};\n if (spec.type === \"from-registry-v1\" || spec.type === \"from-registry-v2\") {\n return {\n block: `${spec.id.organization}:${spec.id.name}`,\n blockVersion: spec.id.version,\n blockSource: spec.type,\n };\n }\n return { block: \"(unpublished)\", blockSource: spec.type };\n}\n"],"mappings":";;;;;;;AAcA,MAAM,wBAAwB;AAE9B,SAAS,gBACP,QACA,gBACA,QACA,sBACA,gBACA;CACA,IAAI,cAAc,CAAC,CAAC,oBAAoB,cAAc,CAAC,CAAC,oBAAoB,SAAS,CAAC,SAAS;EAC7F,IAAI,QACF,QAAQ,IACN,iBAAiB,OAAO,cAAc,mBAAmB,KAAA,IAAY,YAAY,YAAY,MAAM,qBAAqB,EAC1H;OAEA,QAAQ,IACN,mBAAmB,OAAO,aAAa,eAAe,IAAI,mBAAmB,KAAA,IAAY,YAAY,YAAY,KAAK,qBAAqB,EAC7I;CACJ;AACF;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAkDA,SAAgB,iBACd,KACA,KACA,IACA,cACA,WACA,MAAuC,CAAC,GACxC,WACqB;CAErB,MAAM,MAAM,GAAG,IAAI,QAAQ,UAAU,UAAU,GAAG,GAAG;CACrD,MAAM;EAAE,GAAG;EAAK;CAAI;CACpB,IAAI,IAAI,SAAS,KAAA,KAAa,GAAG,cAAc,MAAM,IAAI,OAAO;CAChE,OAAO,WAAW,SAAS,SAAS;EAClC,MAAM,EAAE,MAAM,iBAA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ACf,OACA,KACC,MAAM;GACL,mBAAmB;EACrB,GACA,YACF;EAGA,KAAK,eAAe,KAAK,OAAO;EAGhC,MAAM,iBAAiB,KAAK,sBAAsB,KAAK,YAAY,GAAG,QAAQ,GAAG,IAAI,CAAC;EACtF,IAAI,cAAc,CAAC,CAAC,eAClB,QAAQ,IAAI,YAAY,GAAG,OAAO,IAAI,KAAK,UAAU,KAAK,KAAK,GAAG;EACpE,OAAO;CACT,UAAU;EACR,MAAM,QAAQ;CAChB;AACF;;;;;;;;;;AAWA,SAAS,kBAAkB,MAIzB;CACA,IAAI,SAAS,KAAA,GAAW,OAAO,CAAC;CAChC,IAAI,KAAK,SAAS,sBAAsB,KAAK,SAAS,oBACpD,OAAO;EACL,OAAO,GAAG,KAAK,GAAG,aAAa,GAAG,KAAK,GAAG;EAC1C,cAAc,KAAK,GAAG;EACtB,aAAa,KAAK;CACpB;CAEF,OAAO;EAAE,OAAO;EAAiB,aAAa,KAAK;CAAK;AAC1D"}
|
|
1
|
+
{"version":3,"file":"index.js","names":[],"sources":["../../src/js_render/index.ts"],"sourcesContent":["import type { MiddleLayerEnvironment } from \"../middle_layer/middle_layer\";\nimport type { BlockCodeWithInfo, ConfigRenderLambda } from \"@platforma-sdk/model\";\nimport type { BlockPackSpec } from \"@milaboratories/pl-model-middle-layer\";\nimport type { ComputableRenderingOps } from \"@milaboratories/computable\";\nimport { Computable } from \"@milaboratories/computable\";\nimport type { QuickJSWASMModule } from \"quickjs-emscripten\";\nimport { Scope } from \"quickjs-emscripten\";\nimport type { DeadlineSettings } from \"./context\";\nimport { JsExecutionContext } from \"./context\";\nimport type { BlockContextAny } from \"../middle_layer/block_ctx\";\nimport { getDebugFlags } from \"../debug\";\nimport { recordModelRenderSync } from \"@milaboratories/pl-crash-recorder\";\n\n/** Memory ceiling applied to every QuickJS runtime that evaluates model code. */\nconst QUICK_JS_MEMORY_LIMIT = 1024 * 1024 * 8;\n\nfunction logOutputStatus(\n handle: string,\n renderedResult: unknown,\n stable: boolean,\n recalculationCounter: number,\n unstableMarker?: string,\n) {\n if (getDebugFlags().logOutputStatus && (getDebugFlags().logOutputStatus === \"any\" || !stable)) {\n if (stable)\n console.log(\n `Stable output ${handle} calculated ${renderedResult !== undefined ? \"defined\" : \"undefined\"}; (#${recalculationCounter})`,\n );\n else\n console.log(\n `Unstable output ${handle}; marker = ${unstableMarker}; ${renderedResult !== undefined ? \"defined\" : \"undefined\"} (#${recalculationCounter})`,\n );\n }\n}\n\n/**\n * Creates a Computable that executes a render function (`fh`) from a block's code in a QuickJS virtual machine.\n * This function handles both synchronous and asynchronous execution patterns of the sandboxed JS code.\n *\n * The overall data flow is as follows:\n * 1. A QuickJS VM is initialized.\n * 2. A `JsExecutionContext` is created to bridge the host (TypeScript) and guest (QuickJS) environments. It injects a\n * context object (`cfgRenderCtx`) into the VM, providing helper methods for the sandboxed code to interact with the\n * platform (e.g., to request data).\n * 3. The block's Javascript bundle is evaluated in the VM.\n * 4. The specified render function (`fh.handle`) is executed.\n *\n * Two execution paths are possible depending on the behavior of the render function:\n *\n * ### Synchronous Path\n * If the render function computes its result without requesting any external data requiring asynchronous calculations,\n * it executes synchronously.\n * - The `computablesToResolve` map in `JsExecutionContext` remains empty.\n * - The function returns an object with an `ir` field holding the result (`{ ir: importedResult }`).\n * Since `postprocessValue` is not specified, `ir` is treated as the final resolved value of the Computable.\n * - The QuickJS VM is disposed of immediately as it's no longer needed.\n *\n * ### Asynchronous Path (with `postprocessValue`)\n * If the render function needs external data requiring asynchronous calculations (e.g., fetching a file), it calls\n * one of the injected helper methods. These methods don't return data directly. Instead, they:\n * a. Create a new `Computable` for the data request (e.g., to fetch a blob).\n * b. Register this new `Computable` in the `computablesToResolve` map.\n * c. Return a handle (string) to the sandboxed code.\n *\n * In this case:\n * - The initial execution of the render function returns a scaffold of the final result, which depends on the pending\n * computables.\n * - The `computablesToResolve` map is passed as the `ir` (initial result) to `Computable.makeRaw`.\n * - The `postprocessValue` function is provided to handle the results once the computables are resolved.\n * - The QuickJS VM is kept alive (`keepVmAlive = true`) because its state is needed in `postprocessValue`.\n * - Once the `computable` framework resolves all dependencies, it calls `postprocessValue` with the resolved data.\n * - `postprocessValue` feeds the resolved data back into the VM, allowing the sandboxed code to compute the final\n * result.\n * - The VM is eventually disposed of when the host Computable is destroyed.\n *\n * @param env The middle layer environment.\n * @param ctx The block context.\n * @param fh The config render lambda to execute.\n * @param codeWithInfo The block's code and feature flags.\n * @param configKey A key for the configuration, used for cache busting.\n * @param ops Options for the computable.\n * @returns A `Computable` that will resolve to the result of the lambda execution.\n */\nexport function computableFromRF(\n env: MiddleLayerEnvironment,\n ctx: BlockContextAny,\n fh: ConfigRenderLambda,\n codeWithInfo: BlockCodeWithInfo,\n configKey: string,\n ops: Partial<ComputableRenderingOps> = {},\n blockPack?: BlockPackSpec,\n): Computable<unknown> {\n // adding configKey to reload all outputs on block-pack update\n const key = `${ctx.blockId}#lambda#${configKey}#${fh.handle}`;\n ops = { ...ops, key };\n if (ops.mode === undefined && fh.retentive === true) ops.mode = \"StableOnlyRetentive\";\n return Computable.makeRaw((cCtx) => {\n const { code, featureFlags } = codeWithInfo;\n\n if (getDebugFlags().logOutputRecalculations)\n console.log(\n `Block lambda recalculation : ${key} (${cCtx.changeSourceMarker}; ${cCtx.bodyInvocations} invocations)`,\n );\n\n const scope = new Scope();\n let keepVmAlive = false;\n cCtx.addOnDestroy(() => {\n // If keepVmAlive is false, the scope will be disposed by the finally block,\n // no need to dispose it here.\n if (keepVmAlive) scope.dispose();\n });\n\n try {\n const runtime = scope.manage(env.quickJs.newRuntime());\n runtime.setMemoryLimit(QUICK_JS_MEMORY_LIMIT);\n runtime.setMaxStackSize(1024 * 320);\n\n let deadlineSettings: DeadlineSettings | undefined;\n runtime.setInterruptHandler(() => {\n if (deadlineSettings === undefined) return false;\n if (Date.now() > deadlineSettings.deadline) return true;\n return false;\n });\n const vm = scope.manage(runtime.newContext());\n const rCtx = new JsExecutionContext(\n scope,\n vm,\n (s) => {\n deadlineSettings = s;\n },\n featureFlags,\n { computableCtx: cCtx, blockCtx: ctx, mlEnv: env },\n );\n\n const crashRecorder = env.driverKit.crashRecorder;\n const renderInfo = {\n blockId: ctx.blockId,\n // A block id is unique to one project; these say which code it is, so a\n // log can be read against the right version without the project.\n ...describeBlockPack(blockPack),\n sdkVersion: codeWithInfo.sdkVersion,\n key,\n lambda: fh.handle,\n // The sandbox has its own 8 MB ceiling, so the model's own objects can\n // never exhaust the host heap. What can is the volume crossing out of\n // it, which `stats` counts.\n sandboxMemoryLimit: QUICK_JS_MEMORY_LIMIT,\n getStats: () => ({ ...rCtx.stats }),\n };\n\n return recordModelRenderSync(crashRecorder, renderInfo, () => {\n // configKey already identifies this block pack's config, and exists to invalidate\n // rendered outputs when the pack changes, so it keys the compiled bundle too.\n rCtx.evaluateBundleCached(configKey, code.content);\n const result = rCtx.runCallback(fh.handle);\n\n rCtx.resetComputableCtx();\n\n const toBeResolved = rCtx.computableHelper!.computablesToResolve;\n\n if (Object.keys(toBeResolved).length === 0) {\n const importedResult = rCtx.importObjectUniversal(result);\n if (getDebugFlags().logJsExecStat)\n console.log(`[jsExec] ${key}: ${JSON.stringify(rCtx.stats)}`);\n logOutputStatus(\n fh.handle,\n importedResult,\n cCtx.unstableMarker === undefined,\n -1,\n cCtx.unstableMarker,\n );\n return { ir: importedResult };\n }\n\n let recalculationCounter = 0;\n if (getDebugFlags().logOutputStatus)\n console.log(\n `Output ${fh.handle} scaffold calculated (not all computables resolved yet).`,\n );\n keepVmAlive = true;\n\n return {\n ir: toBeResolved,\n postprocessValue: (resolved: Record<string, unknown>, { unstableMarker, stable }) => {\n recalculationCounter++;\n // A deferred render resumes here, potentially many times, and each\n // resumption can build joins of its own, so each gets its own span.\n return recordModelRenderSync(\n crashRecorder,\n { ...renderInfo, recalculation: recalculationCounter },\n () => {\n // resolving futures\n for (const [handle, value] of Object.entries(resolved))\n rCtx.runCallback(handle, value);\n\n // rendering result\n const renderedResult = rCtx.importObjectUniversal(result);\n\n // logging\n if (getDebugFlags().logJsExecStat)\n console.log(\n `[jsExec] ${key} #${recalculationCounter}: ${JSON.stringify(rCtx.stats)}`,\n );\n logOutputStatus(\n fh.handle,\n renderedResult,\n stable,\n recalculationCounter,\n unstableMarker,\n );\n\n return renderedResult;\n },\n );\n },\n };\n });\n } catch (e) {\n keepVmAlive = false;\n throw e;\n } finally {\n if (!keepVmAlive) scope.dispose();\n }\n }, ops);\n}\n\nexport function executeSingleLambda(\n quickJs: QuickJSWASMModule,\n fh: ConfigRenderLambda,\n codeWithInfo: BlockCodeWithInfo,\n ...args: unknown[]\n): unknown {\n const { code, featureFlags } = codeWithInfo;\n const scope = new Scope();\n try {\n const runtime = scope.manage(quickJs.newRuntime());\n runtime.setMemoryLimit(QUICK_JS_MEMORY_LIMIT);\n runtime.setMaxStackSize(1024 * 320);\n\n let deadlineSettings: DeadlineSettings | undefined;\n runtime.setInterruptHandler(() => {\n if (deadlineSettings === undefined) return false;\n if (Date.now() > deadlineSettings.deadline) return true;\n return false;\n });\n const vm = scope.manage(runtime.newContext());\n const rCtx = new JsExecutionContext(\n scope,\n vm,\n (s) => {\n deadlineSettings = s;\n },\n featureFlags,\n );\n\n // Initializing the model\n rCtx.evaluateBundle(code.content);\n\n // Running the lambda with arguments (e.g., state for args(), args for enrichmentTargets())\n const importedResult = rCtx.importObjectUniversal(rCtx.runCallback(fh.handle, ...args));\n if (getDebugFlags().logJsExecStat)\n console.log(`[jsExec] ${fh.handle}: ${JSON.stringify(rCtx.stats)}`);\n return importedResult;\n } finally {\n scope.dispose();\n }\n}\n\n/**\n * The part of a block pack that names the code, and nothing else.\n *\n * Registry packs carry an organization, name and version, which is what a reader\n * needs to open the right source. Local and development packs carry a filesystem\n * path instead; the path is deliberately not recorded — it identifies the\n * machine rather than the code, and its `type` already says that no published\n * version exists to look up.\n */\nfunction describeBlockPack(spec: BlockPackSpec | undefined): {\n block?: string;\n blockVersion?: string;\n blockSource?: string;\n} {\n if (spec === undefined) return {};\n if (spec.type === \"from-registry-v1\" || spec.type === \"from-registry-v2\") {\n return {\n block: `${spec.id.organization}:${spec.id.name}`,\n blockVersion: spec.id.version,\n blockSource: spec.type,\n };\n }\n return { block: \"(unpublished)\", blockSource: spec.type };\n}\n"],"mappings":";;;;;;;AAcA,MAAM,wBAAwB;AAE9B,SAAS,gBACP,QACA,gBACA,QACA,sBACA,gBACA;CACA,IAAI,cAAc,CAAC,CAAC,oBAAoB,cAAc,CAAC,CAAC,oBAAoB,SAAS,CAAC,SAAS;EAC7F,IAAI,QACF,QAAQ,IACN,iBAAiB,OAAO,cAAc,mBAAmB,KAAA,IAAY,YAAY,YAAY,MAAM,qBAAqB,EAC1H;OAEA,QAAQ,IACN,mBAAmB,OAAO,aAAa,eAAe,IAAI,mBAAmB,KAAA,IAAY,YAAY,YAAY,KAAK,qBAAqB,EAC7I;CACJ;AACF;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAkDA,SAAgB,iBACd,KACA,KACA,IACA,cACA,WACA,MAAuC,CAAC,GACxC,WACqB;CAErB,MAAM,MAAM,GAAG,IAAI,QAAQ,UAAU,UAAU,GAAG,GAAG;CACrD,MAAM;EAAE,GAAG;EAAK;CAAI;CACpB,IAAI,IAAI,SAAS,KAAA,KAAa,GAAG,cAAc,MAAM,IAAI,OAAO;CAChE,OAAO,WAAW,SAAS,SAAS;EAClC,MAAM,EAAE,MAAM,iBAAiB;EAE/B,IAAI,cAAc,CAAC,CAAC,yBAClB,QAAQ,IACN,gCAAgC,IAAI,IAAI,KAAK,mBAAmB,IAAI,KAAK,gBAAgB,cAC3F;EAEF,MAAM,QAAQ,IAAI,MAAM;EACxB,IAAI,cAAc;EAClB,KAAK,mBAAmB;GAGtB,IAAI,aAAa,MAAM,QAAQ;EACjC,CAAC;EAED,IAAI;GACF,MAAM,UAAU,MAAM,OAAO,IAAI,QAAQ,WAAW,CAAC;GACrD,QAAQ,eAAe,qBAAqB;GAC5C,QAAQ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A,SAAS,kBAAkB,MAIzB;CACA,IAAI,SAAS,KAAA,GAAW,OAAO,CAAC;CAChC,IAAI,KAAK,SAAS,sBAAsB,KAAK,SAAS,oBACpD,OAAO;EACL,OAAO,GAAG,KAAK,GAAG,aAAa,GAAG,KAAK,GAAG;EAC1C,cAAc,KAAK,GAAG;EACtB,aAAa,KAAK;CACpB;CAEF,OAAO;EAAE,OAAO;EAAiB,aAAa,KAAK;CAAK;AAC1D"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@milaboratories/pl-middle-layer",
|
|
3
|
-
"version": "2.7.
|
|
3
|
+
"version": "2.7.6",
|
|
4
4
|
"description": "Pl Middle Layer",
|
|
5
5
|
"keywords": [],
|
|
6
6
|
"license": "UNLICENSED",
|
|
@@ -38,12 +38,12 @@
|
|
|
38
38
|
"@milaboratories/ts-helpers": "1.9.1",
|
|
39
39
|
"@platforma-sdk/block-tools": "2.20.4",
|
|
40
40
|
"@platforma-sdk/model": "1.90.2",
|
|
41
|
-
"@platforma-sdk/workflow-tengo": "6.
|
|
41
|
+
"@platforma-sdk/workflow-tengo": "6.24.0",
|
|
42
42
|
"canonicalize": "~2.1.0",
|
|
43
43
|
"denque": "^2.1.0",
|
|
44
44
|
"es-toolkit": "^1.39.10",
|
|
45
45
|
"lru-cache": "^11.5.3",
|
|
46
|
-
"quickjs-emscripten": "0.32.
|
|
46
|
+
"quickjs-emscripten": "https://github.com/xnacly/quickjs-emscripten/releases/download/v0.32.1-bytecode.1/quickjs-emscripten-0.32.1-bytecode.1.tgz",
|
|
47
47
|
"semver": "^7.7.2",
|
|
48
48
|
"undici": "~7.30.2",
|
|
49
49
|
"utility-types": "^3.11.0",
|
|
@@ -0,0 +1,127 @@
|
|
|
1
|
+
import { test, expect, beforeEach } from "vitest";
|
|
2
|
+
import { getQuickJS, type QuickJSContext, type QuickJSRuntime } from "quickjs-emscripten";
|
|
3
|
+
import {
|
|
4
|
+
bundleByteCodeCacheBytes,
|
|
5
|
+
bundleByteCodeCacheSize,
|
|
6
|
+
clearBundleByteCodeCache,
|
|
7
|
+
evaluateBundleCached,
|
|
8
|
+
} from "./bundle_bytecode_cache";
|
|
9
|
+
|
|
10
|
+
const QuickJS = await getQuickJS();
|
|
11
|
+
|
|
12
|
+
/** A context with the same limits `computableFromRF` applies, disposed by the caller. */
|
|
13
|
+
function newContext(): { runtime: QuickJSRuntime; vm: QuickJSContext } {
|
|
14
|
+
const runtime = QuickJS.newRuntime();
|
|
15
|
+
runtime.setMemoryLimit(1024 * 1024 * 8);
|
|
16
|
+
runtime.setMaxStackSize(1024 * 320);
|
|
17
|
+
return { runtime, vm: runtime.newContext() };
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
function withContext<T>(block: (vm: QuickJSContext) => T): T {
|
|
21
|
+
const { runtime, vm } = newContext();
|
|
22
|
+
try {
|
|
23
|
+
return block(vm);
|
|
24
|
+
} finally {
|
|
25
|
+
vm.dispose();
|
|
26
|
+
runtime.dispose();
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
const readNumber = (vm: QuickJSContext, expression: string): number =>
|
|
31
|
+
vm.unwrapResult(vm.evalCode(expression)).consume((handle) => vm.getNumber(handle));
|
|
32
|
+
|
|
33
|
+
beforeEach(() => clearBundleByteCodeCache());
|
|
34
|
+
|
|
35
|
+
test("bytecode compiled for one context evaluates in another, after the first is gone", () => {
|
|
36
|
+
const code = `globalThis.answer = 42`;
|
|
37
|
+
|
|
38
|
+
withContext((vm) => evaluateBundleCached(vm, "k", code));
|
|
39
|
+
expect(bundleByteCodeCacheSize()).toBe(1);
|
|
40
|
+
|
|
41
|
+
// The context that compiled the bundle is disposed by now, so a hit here proves the
|
|
42
|
+
// cached bytes outlive the context they came from.
|
|
43
|
+
withContext((vm) => {
|
|
44
|
+
evaluateBundleCached(vm, "k", code);
|
|
45
|
+
expect(readNumber(vm, "globalThis.answer")).toBe(42);
|
|
46
|
+
});
|
|
47
|
+
expect(bundleByteCodeCacheSize()).toBe(1);
|
|
48
|
+
});
|
|
49
|
+
|
|
50
|
+
test("a cache hit does not carry state between contexts", () => {
|
|
51
|
+
const code = `globalThis.counter = (globalThis.counter ?? 0) + 1`;
|
|
52
|
+
|
|
53
|
+
withContext((vm) => {
|
|
54
|
+
evaluateBundleCached(vm, "k", code);
|
|
55
|
+
expect(readNumber(vm, "globalThis.counter")).toBe(1);
|
|
56
|
+
// Mutating here must not be visible to the next context.
|
|
57
|
+
vm.unwrapResult(vm.evalCode(`globalThis.counter = 99`)).dispose();
|
|
58
|
+
});
|
|
59
|
+
|
|
60
|
+
withContext((vm) => {
|
|
61
|
+
evaluateBundleCached(vm, "k", code);
|
|
62
|
+
expect(readNumber(vm, "globalThis.counter")).toBe(1);
|
|
63
|
+
});
|
|
64
|
+
});
|
|
65
|
+
|
|
66
|
+
test("a different key compiles separately rather than reusing the first bundle", () => {
|
|
67
|
+
withContext((vm) => evaluateBundleCached(vm, "a", `globalThis.v = 1`));
|
|
68
|
+
withContext((vm) => {
|
|
69
|
+
evaluateBundleCached(vm, "b", `globalThis.v = 2`);
|
|
70
|
+
expect(readNumber(vm, "globalThis.v")).toBe(2);
|
|
71
|
+
});
|
|
72
|
+
expect(bundleByteCodeCacheSize()).toBe(2);
|
|
73
|
+
});
|
|
74
|
+
|
|
75
|
+
test("a bundle that fails to compile throws and is not cached", () => {
|
|
76
|
+
withContext((vm) => {
|
|
77
|
+
expect(() => evaluateBundleCached(vm, "bad", `this is ( not js`)).toThrow();
|
|
78
|
+
});
|
|
79
|
+
expect(bundleByteCodeCacheSize()).toBe(0);
|
|
80
|
+
});
|
|
81
|
+
|
|
82
|
+
test("a bundle that throws while running is not cached as a failure", () => {
|
|
83
|
+
// Compilation succeeds, execution does not. The bytes are valid either way, so the entry
|
|
84
|
+
// stays: the failure belongs to the run, not to the compiled bundle.
|
|
85
|
+
withContext((vm) => {
|
|
86
|
+
expect(() => evaluateBundleCached(vm, "boom", `throw new Error("boom")`)).toThrow();
|
|
87
|
+
});
|
|
88
|
+
expect(bundleByteCodeCacheSize()).toBe(1);
|
|
89
|
+
});
|
|
90
|
+
|
|
91
|
+
test("two blocks on the same pack share one compiled bundle", () => {
|
|
92
|
+
const code = `globalThis.shared = 1`;
|
|
93
|
+
|
|
94
|
+
// Distinct keys: block pack ids are per resource, so two blocks on the same pack version
|
|
95
|
+
// arrive here under different keys with identical code.
|
|
96
|
+
withContext((vm) => evaluateBundleCached(vm, "pack-resource-a", code));
|
|
97
|
+
const afterFirst = bundleByteCodeCacheBytes();
|
|
98
|
+
withContext((vm) => evaluateBundleCached(vm, "pack-resource-b", code));
|
|
99
|
+
|
|
100
|
+
expect(bundleByteCodeCacheSize()).toBe(1);
|
|
101
|
+
expect(bundleByteCodeCacheBytes()).toBe(afterFirst);
|
|
102
|
+
});
|
|
103
|
+
|
|
104
|
+
test("the same key with a differently sized bundle recompiles", () => {
|
|
105
|
+
withContext((vm) => {
|
|
106
|
+
evaluateBundleCached(vm, "k", `globalThis.v = 1`);
|
|
107
|
+
expect(readNumber(vm, "globalThis.v")).toBe(1);
|
|
108
|
+
});
|
|
109
|
+
withContext((vm) => {
|
|
110
|
+
evaluateBundleCached(vm, "k", `globalThis.v = 22222`);
|
|
111
|
+
expect(readNumber(vm, "globalThis.v")).toBe(22222);
|
|
112
|
+
});
|
|
113
|
+
});
|
|
114
|
+
|
|
115
|
+
test("clearing the cache forces a recompile rather than returning stale bytes", () => {
|
|
116
|
+
withContext((vm) => evaluateBundleCached(vm, "k", `globalThis.v = 1`));
|
|
117
|
+
expect(bundleByteCodeCacheSize()).toBe(1);
|
|
118
|
+
|
|
119
|
+
clearBundleByteCodeCache();
|
|
120
|
+
expect(bundleByteCodeCacheSize()).toBe(0);
|
|
121
|
+
|
|
122
|
+
// Same key, different code: a stale hit would leave v at 1.
|
|
123
|
+
withContext((vm) => {
|
|
124
|
+
evaluateBundleCached(vm, "k", `globalThis.v = 2`);
|
|
125
|
+
expect(readNumber(vm, "globalThis.v")).toBe(2);
|
|
126
|
+
});
|
|
127
|
+
});
|
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
import { createHash } from "node:crypto";
|
|
2
|
+
import type { QuickJSContext } from "quickjs-emscripten";
|
|
3
|
+
|
|
4
|
+
/** Bytecode budget. A 505 KB bundle compiles to ~1.4 MB, so this holds roughly forty. */
|
|
5
|
+
const MAX_BYTES = 64 * 1024 * 1024;
|
|
6
|
+
|
|
7
|
+
/** Pack id + code length -> bundle digest. Hashing once per pack keeps it off the hot path. */
|
|
8
|
+
const digestByCacheKey = new Map<string, string>();
|
|
9
|
+
const MAX_DIGEST_ENTRIES = 1024;
|
|
10
|
+
|
|
11
|
+
/** Insertion-ordered, so the oldest key is the first one `keys()` yields. */
|
|
12
|
+
const cache = new Map<string, ArrayBuffer>();
|
|
13
|
+
|
|
14
|
+
/** Sum of `cache`'s values' byte lengths, kept alongside it to avoid rescanning on evict. */
|
|
15
|
+
let heldBytes = 0;
|
|
16
|
+
|
|
17
|
+
function digestFor(cacheKey: string, code: string): string {
|
|
18
|
+
// Pack resources are immutable (mutator/project.ts creates a new one per update), so the
|
|
19
|
+
// length check only guards that invariant breaking.
|
|
20
|
+
const memoKey = `${cacheKey}:${code.length}`;
|
|
21
|
+
const known = digestByCacheKey.get(memoKey);
|
|
22
|
+
if (known !== undefined) return known;
|
|
23
|
+
|
|
24
|
+
const digest = createHash("sha256").update(code).digest("hex");
|
|
25
|
+
digestByCacheKey.set(memoKey, digest);
|
|
26
|
+
while (digestByCacheKey.size > MAX_DIGEST_ENTRIES) {
|
|
27
|
+
const oldest = digestByCacheKey.keys().next();
|
|
28
|
+
if (oldest.done === true) break;
|
|
29
|
+
digestByCacheKey.delete(oldest.value);
|
|
30
|
+
}
|
|
31
|
+
return digest;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/** Bytecode for `code`, compiled on first ask. Outlives the context that compiled it. */
|
|
35
|
+
function byteCodeFor(vm: QuickJSContext, cacheKey: string, code: string): ArrayBuffer {
|
|
36
|
+
const digest = digestFor(cacheKey, code);
|
|
37
|
+
const hit = cache.get(digest);
|
|
38
|
+
if (hit !== undefined) {
|
|
39
|
+
// Refresh recency: delete then set moves the key to the end of the iteration order.
|
|
40
|
+
cache.delete(digest);
|
|
41
|
+
cache.set(digest, hit);
|
|
42
|
+
return hit;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
const compiled = vm
|
|
46
|
+
.unwrapResult(vm.compileToByteCode(code, "bundle.js", { type: "global" }))
|
|
47
|
+
.consume((handle) =>
|
|
48
|
+
vm.getArrayBuffer(handle).consume((buf) => new Uint8Array(buf.value).buffer),
|
|
49
|
+
);
|
|
50
|
+
|
|
51
|
+
cache.set(digest, compiled);
|
|
52
|
+
heldBytes += compiled.byteLength;
|
|
53
|
+
while (heldBytes > MAX_BYTES && cache.size > 1) {
|
|
54
|
+
const oldest = cache.keys().next();
|
|
55
|
+
if (oldest.done === true) break;
|
|
56
|
+
heldBytes -= cache.get(oldest.value)?.byteLength ?? 0;
|
|
57
|
+
cache.delete(oldest.value);
|
|
58
|
+
}
|
|
59
|
+
return compiled;
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/** Evaluate a block's model bundle into `vm`, reusing bytecode compiled for `cacheKey`. */
|
|
63
|
+
export function evaluateBundleCached(vm: QuickJSContext, cacheKey: string, code: string): void {
|
|
64
|
+
const byteCode = byteCodeFor(vm, cacheKey, code);
|
|
65
|
+
// Not `consume`: it disposes only on a clean return, so a throwing bundle leaks the handle.
|
|
66
|
+
const handle = vm.newArrayBuffer(byteCode);
|
|
67
|
+
try {
|
|
68
|
+
vm.unwrapResult(vm.evalByteCode(handle)).dispose();
|
|
69
|
+
} finally {
|
|
70
|
+
handle.dispose();
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
/** Drops every compiled bundle. Exported for tests. */
|
|
75
|
+
export function clearBundleByteCodeCache(): void {
|
|
76
|
+
cache.clear();
|
|
77
|
+
digestByCacheKey.clear();
|
|
78
|
+
heldBytes = 0;
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
/** Number of compiled bundles currently held. Exported for tests. */
|
|
82
|
+
export function bundleByteCodeCacheSize(): number {
|
|
83
|
+
return cache.size;
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
/** Bytes of bytecode currently held. Exported for tests and diagnostics. */
|
|
87
|
+
export function bundleByteCodeCacheBytes(): number {
|
|
88
|
+
return heldBytes;
|
|
89
|
+
}
|
package/src/js_render/context.ts
CHANGED
|
@@ -11,6 +11,7 @@ import { stringifyWithResourceId } from "@milaboratories/pl-client";
|
|
|
11
11
|
import { PlQuickJSError } from "@milaboratories/pl-errors";
|
|
12
12
|
import { ComputableContextHelper } from "./computable_context";
|
|
13
13
|
|
|
14
|
+
import { evaluateBundleCached } from "./bundle_bytecode_cache";
|
|
14
15
|
export type DeadlineSettings = {
|
|
15
16
|
currentExecutionTarget: string;
|
|
16
17
|
deadline: number;
|
|
@@ -163,6 +164,29 @@ export class JsExecutionContext {
|
|
|
163
164
|
}
|
|
164
165
|
}
|
|
165
166
|
|
|
167
|
+
/**
|
|
168
|
+
* {@link evaluateBundle}, reusing bytecode compiled for an earlier context with the same
|
|
169
|
+
* `cacheKey`. Every lambda gets its own context and needs the whole bundle in scope, so
|
|
170
|
+
* parsing per context was the dominant cost of rendering a block.
|
|
171
|
+
*/
|
|
172
|
+
public evaluateBundleCached(cacheKey: string, code: string) {
|
|
173
|
+
const t0 = performance.now();
|
|
174
|
+
try {
|
|
175
|
+
this.deadlineSetter({
|
|
176
|
+
currentExecutionTarget: "evaluateBundle",
|
|
177
|
+
deadline: Date.now() + 10000,
|
|
178
|
+
});
|
|
179
|
+
evaluateBundleCached(this.vm, cacheKey, code);
|
|
180
|
+
} catch (err: unknown) {
|
|
181
|
+
JsExecutionContext.cleanErrorContext(err);
|
|
182
|
+
throw err;
|
|
183
|
+
} finally {
|
|
184
|
+
this.deadlineSetter(undefined);
|
|
185
|
+
this.stats.bundleEvalMs += performance.now() - t0;
|
|
186
|
+
this.stats.bundleBytes += code.length;
|
|
187
|
+
}
|
|
188
|
+
}
|
|
189
|
+
|
|
166
190
|
public runCallback(cbName: string, ...args: unknown[]): QuickJSHandle {
|
|
167
191
|
const t0 = performance.now();
|
|
168
192
|
try {
|
package/src/js_render/index.ts
CHANGED
|
@@ -149,7 +149,9 @@ export function computableFromRF(
|
|
|
149
149
|
};
|
|
150
150
|
|
|
151
151
|
return recordModelRenderSync(crashRecorder, renderInfo, () => {
|
|
152
|
-
|
|
152
|
+
// configKey already identifies this block pack's config, and exists to invalidate
|
|
153
|
+
// rendered outputs when the pack changes, so it keys the compiled bundle too.
|
|
154
|
+
rCtx.evaluateBundleCached(configKey, code.content);
|
|
153
155
|
const result = rCtx.runCallback(fh.handle);
|
|
154
156
|
|
|
155
157
|
rCtx.resetComputableCtx();
|