@milaboratories/pl-middle-layer 2.3.0 → 2.4.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/middle_layer/block_status_fold.cjs +51 -6
- package/dist/middle_layer/block_status_fold.cjs.map +1 -1
- package/dist/middle_layer/block_status_fold.js +50 -7
- package/dist/middle_layer/block_status_fold.js.map +1 -1
- package/dist/middle_layer/block_status_tree.cjs +39 -9
- package/dist/middle_layer/block_status_tree.cjs.map +1 -1
- package/dist/middle_layer/block_status_tree.js +39 -9
- package/dist/middle_layer/block_status_tree.js.map +1 -1
- package/dist/middle_layer/block_status_tree_fold.cjs +96 -0
- package/dist/middle_layer/block_status_tree_fold.cjs.map +1 -0
- package/dist/middle_layer/block_status_tree_fold.js +95 -0
- package/dist/middle_layer/block_status_tree_fold.js.map +1 -0
- package/dist/middle_layer/build_stamp.cjs +1 -1
- package/dist/middle_layer/build_stamp.js +1 -1
- package/dist/middle_layer/project.cjs +22 -2
- package/dist/middle_layer/project.cjs.map +1 -1
- package/dist/middle_layer/project.d.ts +13 -1
- package/dist/middle_layer/project.d.ts.map +1 -1
- package/dist/middle_layer/project.js +22 -2
- package/dist/middle_layer/project.js.map +1 -1
- package/package.json +7 -7
- package/src/middle_layer/block_status_bench.test.ts +139 -48
- package/src/middle_layer/block_status_fold.test.ts +2 -61
- package/src/middle_layer/block_status_fold.ts +68 -6
- package/src/middle_layer/block_status_test_utils.ts +62 -0
- package/src/middle_layer/block_status_tree.test.ts +23 -0
- package/src/middle_layer/block_status_tree.ts +62 -10
- package/src/middle_layer/block_status_tree_fold.test.ts +198 -0
- package/src/middle_layer/block_status_tree_fold.ts +150 -0
- package/src/middle_layer/project.ts +37 -4
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"block_status_tree.cjs","names":["treeFilter","ResourceTypeName","projectFieldName","isNullSignedResourceId","Computable","childContexts","foldContext","mergeSubtree","UnreadableBlockStatusSummary","summarize","WatchableValue","ActionContextLinkCapability","EmptyBlockStatusSummary","UnsupportedBlockStatusSummary","setTimeout","SynchronizedTreeState"],"sources":["../../src/middle_layer/block_status_tree.ts"],"sourcesContent":["/**\n * The live action-context tree of one block render, and the computable that folds it.\n *\n * A status tree is its own {@link SynchronizedTreeState}, seeded at the root action context of the\n * render rather than at the project. It has to be separate: the project tree prunes the context\n * fields (see `ProjectStatusFieldPattern`), because a context holds the whole subtree of its render\n * and every report into it is a KV write.\n *\n * One tree per watched block, held while anyone watches, terminated when the last holder lets go.\n */\n\nimport type { PlClient, SignedResourceId } from \"@milaboratories/pl-client\";\nimport { isNullSignedResourceId, ResourceTypeName, treeFilter } from \"@milaboratories/pl-client\";\nimport { Computable, WatchableValue } from \"@milaboratories/computable\";\nimport type { PlTreeEntry, PlTreeNodeAccessor } from \"@milaboratories/pl-tree\";\nimport { SynchronizedTreeState } from \"@milaboratories/pl-tree\";\nimport type { BlockStatusSummary } from \"@milaboratories/pl-model-middle-layer\";\nimport {\n EmptyBlockStatusSummary,\n UnreadableBlockStatusSummary,\n UnsupportedBlockStatusSummary,\n} from \"@milaboratories/pl-model-middle-layer\";\nimport { setTimeout } from \"node:timers/promises\";\nimport type { ActionContextNode, SubtreeFold } from \"./block_status_fold\";\nimport { childContexts, foldContext, mergeSubtree, summarize } from \"./block_status_fold\";\nimport type { BlockActionContextMode } from \"./block_action_context\";\nimport { ActionContextLinkCapability } from \"../mutator/template/render_block\";\nimport { projectFieldName } from \"../model/project_model\";\nimport type { MiddleLayerEnvironment } from \"./middle_layer\";\n\n/**\n * How long the refetch loop waits between looks at the project's change generation.\n *\n * The tick itself reads an in-memory counter. It opens a read transaction only when the project\n * has changed since the last look, which while a block runs is most ticks: one read transaction\n * per second per watched block, which is the cost of noticing a re-run promptly.\n */\nconst RefetchDebounceMs = 1_000;\n\n/** The poll floor of a status tree, as the spec sets it. */\nconst StatusTreePollingIntervalMs = 5_000;\n\n/**\n * Deadline for the first load of a status tree.\n *\n * Deliberately NOT the project tree's, which disables the timeout outright: a status tree is\n * opened and closed while the app runs, and {@link BlockStatusWatch.terminate} awaits the loop, so\n * an init that never returns would hang a project close and with it the app's shutdown.\n */\nconst StatusTreeInitialLoadTimeoutMs = 30_000;\n\n/** The status tree walks action contexts and nothing else. */\nconst statusTreeFieldFilter = treeFilter.resourceTypeEq(ResourceTypeName.ActionContext);\n\n/**\n * The root action context of a block render, read once from the project.\n *\n * Undefined when the block has no context: it was never rendered, or it ran against a backend or a\n * middle layer that did not create one.\n */\nexport async function readBlockActionContextRoot(\n pl: PlClient,\n projectRid: SignedResourceId,\n blockId: string,\n mode: BlockActionContextMode,\n): Promise<SignedResourceId | undefined> {\n return await pl.withReadTx(\"readBlockActionContextRoot\", async (tx) => {\n const project = await tx.getResourceData(projectRid, true);\n const fieldName = projectFieldName(\n blockId,\n mode === \"prod\" ? \"prodActionContext\" : \"stagingActionContext\",\n );\n const statusField = project.fields.find((f) => f.name === fieldName);\n if (statusField === undefined || isNullSignedResourceId(statusField.value)) return undefined;\n return statusField.value;\n });\n}\n\n/** Adapts a tree node accessor to what the fold reads. */\nexport function actionContextNode(acc: PlTreeNodeAccessor): ActionContextNode {\n return {\n id: String(acc.id),\n getData: () => acc.getDataAsJson<Record<string, unknown>>(),\n listKeyValuesAsString: (prefix: string) => acc.listKeyValuesAsString(prefix),\n listFields: () => acc.listFields(),\n traverse: (field: string) => {\n // A child that carries an error is skipped rather than thrown: the status surface is\n // diagnostic, and one broken branch must not take the whole line down with it.\n const child = acc.traverse({ field, ignoreError: true });\n return child === undefined ? undefined : actionContextNode(child);\n },\n };\n}\n\n/**\n * The fold of the context an entry points at and everything under it, one computable per context.\n *\n * A report is a KV write into one context, and only that context's computable reads its KV, so a\n * report re-reads that one context. Each computable above it re-merges its direct children, which\n * are cached, and nothing else in the tree is read again.\n *\n * Undefined when the context cannot be read. A context that is gone is the ordinary case, not a\n * fault: an ephemeral context is dropped as soon as the project stops holding it, which happens the\n * moment the block is run again, and the watch is briefly pointed at it until the next look for a\n * new render. A child that cannot be read is left out rather than breaking the whole run's status.\n * The cause is logged, so a genuine fault is not silent.\n */\nexport function subtreeFold(\n entry: PlTreeEntry,\n path: ReadonlySet<string>,\n onError: (err: unknown) => void,\n): Computable<SubtreeFold | undefined> {\n return Computable.make(\n (ctx) => {\n try {\n const acc = ctx.accessor(entry).node({ ignoreError: true });\n if (acc === undefined) return undefined;\n const node = actionContextNode(acc);\n const below = new Set(path).add(node.id);\n const children = childContexts(\n acc.listFields(),\n // A child that carries an error is skipped rather than thrown, as in actionContextNode.\n (field) => acc.traverse({ field, ignoreError: true }),\n below,\n ).map((child) => subtreeFold(child.persist(), below, onError));\n return { own: foldContext(node), children };\n } catch (err: unknown) {\n onError(err);\n return undefined;\n }\n },\n {\n key: `block-status-context/${entry.id}`,\n postprocessValue: (value) => {\n if (value === undefined) return undefined;\n const children: SubtreeFold[] = [];\n for (const child of value.children) if (child !== undefined) children.push(child);\n return mergeSubtree(value.own, children);\n },\n },\n );\n}\n\n/** The summary of the run whose root context an entry points at. */\nexport function entrySummary(\n entry: PlTreeEntry,\n reportsSupported: boolean,\n onError: (err: unknown) => void,\n): Computable<BlockStatusSummary> {\n return Computable.make(() => ({ fold: subtreeFold(entry, new Set(), onError) }), {\n key: `block-status-summary/${entry.id}`,\n postprocessValue: ({ fold }) => {\n // The counters of a context that could not be read are unknown, not zero.\n if (fold === undefined) return UnreadableBlockStatusSummary;\n const summary = summarize(fold);\n if (reportsSupported || summary.totalContexts === 0) return summary;\n // The context exists and carries its data, but no transition can ever arrive.\n return { ...summary, availability: \"unsupported\" as const };\n },\n });\n}\n\n/** What {@link BlockStatusWatch.start} watches. */\nexport type BlockStatusWatchParams = {\n readonly env: MiddleLayerEnvironment;\n readonly projectRid: SignedResourceId;\n readonly blockId: string;\n readonly mode: BlockActionContextMode;\n /** The project tree's change generation, the trigger for looking for a new render. */\n readonly projectGeneration: () => number;\n};\n\n/**\n * The live status of one block render.\n *\n * The summary is stable across runs of the block: clicking Run creates a new render with a new\n * status context, and the watch re-seeds itself onto it rather than handing the caller a new\n * computable. The watch is shared between callers and reference counted; the tree lives until the\n * last holder releases it.\n */\nexport class BlockStatusWatch {\n /** The entry of the tree currently seeded, swapped when the block is run again. */\n private readonly source = new WatchableValue<PlTreeEntry | undefined>(undefined);\n private current?: { readonly root: SignedResourceId; readonly tree: SynchronizedTreeState };\n private readonly abortController = new AbortController();\n private loop?: Promise<void>;\n\n /**\n * Orders the seeds. A reseed that started before the one that last installed a root is stale by\n * the time it finishes, however long its tree took to open, and must not displace it.\n */\n private seedSequence = 0;\n private installedSeed = -1;\n\n /** How many callers hold this watch. The tree is terminated when it reaches zero. */\n private holders = 0;\n\n public readonly summary: Computable<BlockStatusSummary>;\n\n private readonly env: MiddleLayerEnvironment;\n private readonly projectRid: SignedResourceId;\n private readonly blockId: string;\n private readonly mode: BlockActionContextMode;\n private readonly projectGeneration: () => number;\n\n private constructor({\n env,\n projectRid,\n blockId,\n mode,\n projectGeneration,\n }: BlockStatusWatchParams) {\n this.env = env;\n this.projectRid = projectRid;\n this.blockId = blockId;\n this.mode = mode;\n this.projectGeneration = projectGeneration;\n // Without the `actionContext` link a block has no context and nothing is ever reported.\n const reportsSupported = env.pl.hasCapability(ActionContextLinkCapability);\n // One computable for the life of the watch, reading whichever tree is seeded now, so a caller\n // keeps its handle across a re-run of the block.\n this.summary = Computable.make((ctx) => {\n const entry = this.source.getValue(ctx);\n if (entry === undefined)\n return reportsSupported ? EmptyBlockStatusSummary : UnsupportedBlockStatusSummary;\n return entrySummary(entry, reportsSupported, (err) =>\n this.env.logger.warn(new Error(\"block status fold failed\", { cause: err })),\n );\n });\n }\n\n /**\n * Starts watching the status of a block render.\n *\n * The first seed is awaited, so the caller gets a handle that already reports whatever the\n * current render has reported. A block with no status context yet still gets a handle: it\n * reports an empty summary and seeds itself when a render that has one appears.\n *\n * The refetch loop is started only once that first seed has settled. Starting it in the\n * constructor would leave it running with nobody holding a reference to stop it if this throws.\n */\n public static async start(params: BlockStatusWatchParams): Promise<BlockStatusWatch> {\n const watch = new BlockStatusWatch(params);\n try {\n await watch.reseed();\n } catch (err: unknown) {\n await watch.terminateNow();\n throw err;\n }\n watch.begin();\n return watch;\n }\n\n /** Takes the first holder and starts looking for new renders, once the first seed settled. */\n private begin(): void {\n this.holders = 1;\n // The loop handles its own errors; this catch is only a backstop, so the promise kept here\n // never rejects and can be awaited as is.\n this.loop = this.refetchLoop().catch((err: unknown) => {\n this.env.logger.warn(new Error(\"block status refetch loop failed\", { cause: err }));\n });\n }\n\n /** Records one more caller holding this watch. */\n public retain(): void {\n this.holders++;\n }\n\n /**\n * Releases one caller's hold. The tree is terminated, and the watch is finished, only when the\n * last holder lets go; returns true when that happened.\n */\n public async release(): Promise<boolean> {\n if (this.holders > 0) this.holders--;\n if (this.holders > 0) return false;\n await this.terminateNow();\n return true;\n }\n\n /**\n * Stops the watch whatever the holder count, for a project being torn down. An ordinary caller\n * uses {@link release}.\n */\n public async terminate(): Promise<void> {\n this.holders = 0;\n await this.terminateNow();\n }\n\n /** Stops the loop, terminates the tree and releases the computable's holders. */\n private async terminateNow(): Promise<void> {\n this.abortController.abort();\n await this.loop;\n const held = this.current;\n this.current = undefined;\n this.source.setValue(undefined, \"block status watch terminated\");\n this.summary.resetState();\n await this.terminateTree(held?.tree);\n }\n\n /**\n * Looks for a new render while the caller watches.\n *\n * The project field holding the root context is pruned from the project tree, so the re-point is\n * not visible there; what is visible is that the project changed at all. A tick that finds the\n * same root installs nothing.\n */\n private async refetchLoop(): Promise<void> {\n let seen = this.projectGeneration();\n while (!this.abortController.signal.aborted) {\n try {\n await setTimeout(RefetchDebounceMs, undefined, { signal: this.abortController.signal });\n } catch {\n return; // aborted\n }\n\n const generation = this.projectGeneration();\n if (generation === seen) continue;\n\n try {\n await this.reseed();\n // Only once the look succeeded, so a failed one is retried on the next tick rather than\n // waiting for the project to change again.\n seen = generation;\n } catch (err: unknown) {\n if (this.abortController.signal.aborted) return;\n // The current tree stays in place: the surface keeps showing what it has rather than\n // going blank, and the next tick tries again.\n this.env.logger.warn(new Error(\"block status reseed failed\", { cause: err }));\n }\n }\n }\n\n /** Points the summary at the current render's context, replacing any earlier one. */\n private async reseed(): Promise<void> {\n const seed = ++this.seedSequence;\n\n const root = await readBlockActionContextRoot(\n this.env.pl,\n this.projectRid,\n this.blockId,\n this.mode,\n );\n if (this.abortController.signal.aborted) return;\n if (seed < this.installedSeed) return;\n if (root === this.current?.root) return;\n\n const tree =\n root === undefined\n ? undefined\n : await SynchronizedTreeState.init(\n this.env.pl,\n root,\n {\n ...this.env.ops.defaultTreeOptions,\n pollingInterval: StatusTreePollingIntervalMs,\n initialTreeLoadingTimeout: StatusTreeInitialLoadTimeoutMs,\n fieldFilter: statusTreeFieldFilter,\n // A context never becomes final: the backend keeps reporting into it for as long as\n // its render lives, so every poll has to seed it again.\n rootsNeverFinal: true,\n },\n this.env.logger,\n );\n\n // Opening the tree took time, and a later reseed may have installed a newer root meanwhile.\n // Terminating the tree just opened is the whole cost of losing that race.\n if (this.abortController.signal.aborted || seed < this.installedSeed) {\n await this.terminateTree(tree);\n return;\n }\n\n const previous = this.current;\n this.installedSeed = seed;\n this.current = root !== undefined && tree !== undefined ? { root, tree } : undefined;\n\n // Swapped before the old tree is terminated. A computable body runs to completion\n // synchronously, so after this returns no reader is inside the old tree.\n this.source.setValue(tree?.entry(), \"block status root changed\");\n await this.terminateTree(previous?.tree);\n }\n\n private async terminateTree(tree: SynchronizedTreeState | undefined): Promise<void> {\n if (tree === undefined) return;\n try {\n await tree.terminate();\n } catch (err: unknown) {\n // terminate() can throw when the sync loop had already failed; nothing is left to clean up.\n this.env.logger.warn(new Error(\"block status tree termination failed\", { cause: err }));\n }\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;AAqCA,MAAM,oBAAoB;;AAG1B,MAAM,8BAA8B;;;;;;;;AASpC,MAAM,iCAAiC;;AAGvC,MAAM,wBAAwBA,0BAAAA,WAAW,eAAeC,0BAA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F,MAAM,KAAK,UAAU;EACvB,SAAS,KAAc;GAErB,KAAK,IAAI,OAAO,KAAK,IAAI,MAAM,wCAAwC,EAAE,OAAO,IAAI,CAAC,CAAC;EACxF;CACF;AACF"}
|
|
1
|
+
{"version":3,"file":"block_status_tree.cjs","names":["treeFilter","ResourceTypeName","projectFieldName","isNullSignedResourceId","Computable","childContexts","foldContext","mergeSubtree","UnreadableBlockStatusSummary","summarize","WatchableValue","ActionContextLinkCapability","EmptyBlockStatusSummary","UnsupportedBlockStatusSummary","emptyBlockStatusTree","blockStatusTree","setTimeout","SynchronizedTreeState"],"sources":["../../src/middle_layer/block_status_tree.ts"],"sourcesContent":["/**\n * The live action-context tree of one block render, and the computables that fold it.\n *\n * A status tree is its own {@link SynchronizedTreeState}, seeded at the root action context of the\n * render rather than at the project. It has to be separate: the project tree prunes the context\n * fields (see `ProjectStatusFieldPattern`), because a context holds the whole subtree of its render\n * and every report into it is a KV write.\n *\n * One tree per watched block, held while anyone watches, terminated when the last holder lets go.\n */\n\nimport type { PlClient, SignedResourceId } from \"@milaboratories/pl-client\";\nimport { isNullSignedResourceId, ResourceTypeName, treeFilter } from \"@milaboratories/pl-client\";\nimport { Computable, WatchableValue } from \"@milaboratories/computable\";\nimport type { PlTreeEntry, PlTreeNodeAccessor } from \"@milaboratories/pl-tree\";\nimport { SynchronizedTreeState } from \"@milaboratories/pl-tree\";\nimport type { BlockStatusSummary, BlockStatusTree } from \"@milaboratories/pl-model-middle-layer\";\nimport {\n EmptyBlockStatusSummary,\n UnreadableBlockStatusSummary,\n UnsupportedBlockStatusSummary,\n} from \"@milaboratories/pl-model-middle-layer\";\nimport { setTimeout } from \"node:timers/promises\";\nimport type { ActionContextNode, SubtreeFold } from \"./block_status_fold\";\nimport { childContexts, foldContext, mergeSubtree, summarize } from \"./block_status_fold\";\nimport { blockStatusTree, emptyBlockStatusTree } from \"./block_status_tree_fold\";\nimport type { BlockActionContextMode } from \"./block_action_context\";\nimport { ActionContextLinkCapability } from \"../mutator/template/render_block\";\nimport { projectFieldName } from \"../model/project_model\";\nimport type { MiddleLayerEnvironment } from \"./middle_layer\";\n\n/**\n * How long the refetch loop waits between looks at the project's change generation.\n *\n * The tick itself reads an in-memory counter. It opens a read transaction only when the project\n * has changed since the last look, which while a block runs is most ticks: one read transaction\n * per second per watched block, which is the cost of noticing a re-run promptly.\n */\nconst RefetchDebounceMs = 1_000;\n\n/** The poll floor of a status tree, as the spec sets it. */\nconst StatusTreePollingIntervalMs = 5_000;\n\n/**\n * Deadline for the first load of a status tree.\n *\n * Deliberately NOT the project tree's, which disables the timeout outright: a status tree is\n * opened and closed while the app runs, and {@link BlockStatusWatch.terminate} awaits the loop, so\n * an init that never returns would hang a project close and with it the app's shutdown.\n */\nconst StatusTreeInitialLoadTimeoutMs = 30_000;\n\n/** The status tree walks action contexts and nothing else. */\nconst statusTreeFieldFilter = treeFilter.resourceTypeEq(ResourceTypeName.ActionContext);\n\n/**\n * The root action context of a block render, read once from the project.\n *\n * Undefined when the block has no context: it was never rendered, or it ran against a backend or a\n * middle layer that did not create one.\n */\nexport async function readBlockActionContextRoot(\n pl: PlClient,\n projectRid: SignedResourceId,\n blockId: string,\n mode: BlockActionContextMode,\n): Promise<SignedResourceId | undefined> {\n return await pl.withReadTx(\"readBlockActionContextRoot\", async (tx) => {\n const project = await tx.getResourceData(projectRid, true);\n const fieldName = projectFieldName(\n blockId,\n mode === \"prod\" ? \"prodActionContext\" : \"stagingActionContext\",\n );\n const statusField = project.fields.find((f) => f.name === fieldName);\n if (statusField === undefined || isNullSignedResourceId(statusField.value)) return undefined;\n return statusField.value;\n });\n}\n\n/** Adapts a tree node accessor to what the fold reads. */\nexport function actionContextNode(acc: PlTreeNodeAccessor): ActionContextNode {\n return {\n id: String(acc.id),\n getData: () => acc.getDataAsJson<Record<string, unknown>>(),\n listKeyValuesAsString: (prefix: string) => acc.listKeyValuesAsString(prefix),\n listFields: () => acc.listFields(),\n traverse: (field: string) => {\n // A child that carries an error is skipped rather than thrown: the status surface is\n // diagnostic, and one broken branch must not take the whole line down with it.\n const child = acc.traverse({ field, ignoreError: true });\n return child === undefined ? undefined : actionContextNode(child);\n },\n };\n}\n\n/**\n * The fold of the context an entry points at and everything under it, one computable per context.\n *\n * A report is a KV write into one context, and only that context's computable reads its KV, so a\n * report re-reads that one context. Each computable above it re-merges its direct children, which\n * are cached, and nothing else in the tree is read again.\n *\n * Undefined when the context cannot be read. A context that is gone is the ordinary case, not a\n * fault: an ephemeral context is dropped as soon as the project stops holding it, which happens the\n * moment the block is run again, and the watch is briefly pointed at it until the next look for a\n * new render. A child that cannot be read is left out rather than breaking the whole run's status.\n * The cause is logged, so a genuine fault is not silent.\n */\nexport function subtreeFold(\n entry: PlTreeEntry,\n path: ReadonlySet<string>,\n onError: (err: unknown) => void,\n): Computable<SubtreeFold | undefined> {\n return Computable.make(\n (ctx) => {\n try {\n const acc = ctx.accessor(entry).node({ ignoreError: true });\n if (acc === undefined) return undefined;\n const node = actionContextNode(acc);\n const below = new Set(path).add(node.id);\n const children = childContexts(\n acc.listFields(),\n // A child that carries an error is skipped rather than thrown, as in actionContextNode.\n (field) => acc.traverse({ field, ignoreError: true }),\n below,\n ).map((child) => subtreeFold(child.persist(), below, onError));\n return { own: foldContext(node), children };\n } catch (err: unknown) {\n onError(err);\n return undefined;\n }\n },\n {\n key: `block-status-context/${entry.id}`,\n postprocessValue: (value) => {\n if (value === undefined) return undefined;\n const children: SubtreeFold[] = [];\n for (const child of value.children) if (child !== undefined) children.push(child);\n return mergeSubtree(value.own, children);\n },\n },\n );\n}\n\n/** The summary of the run whose root context an entry points at. */\nexport function entrySummary(\n entry: PlTreeEntry,\n reportsSupported: boolean,\n onError: (err: unknown) => void,\n): Computable<BlockStatusSummary> {\n return Computable.make(() => ({ fold: subtreeFold(entry, new Set(), onError) }), {\n key: `block-status-summary/${entry.id}`,\n postprocessValue: ({ fold }) => summaryOfFold(fold, reportsSupported),\n });\n}\n\n/** The summary of a fold, or of a root context that could not be read. */\nfunction summaryOfFold(\n fold: SubtreeFold | undefined,\n reportsSupported: boolean,\n): BlockStatusSummary {\n // The counters of a context that could not be read are unknown, not zero.\n if (fold === undefined) return UnreadableBlockStatusSummary;\n const summary = summarize(fold);\n if (reportsSupported || summary.totalContexts === 0) return summary;\n // The context exists and carries its data, but no transition can ever arrive.\n return { ...summary, availability: \"unsupported\" };\n}\n\n/** What {@link BlockStatusWatch.start} watches. */\nexport type BlockStatusWatchParams = {\n readonly env: MiddleLayerEnvironment;\n readonly projectRid: SignedResourceId;\n readonly blockId: string;\n readonly mode: BlockActionContextMode;\n /** The project tree's change generation, the trigger for looking for a new render. */\n readonly projectGeneration: () => number;\n};\n\n/**\n * The live status of one block render.\n *\n * The summary is stable across runs of the block: clicking Run creates a new render with a new\n * status context, and the watch re-seeds itself onto it rather than handing the caller a new\n * computable. The watch is shared between callers and reference counted; the tree lives until the\n * last holder releases it.\n */\nexport class BlockStatusWatch {\n /** The entry of the tree currently seeded, swapped when the block is run again. */\n private readonly source = new WatchableValue<PlTreeEntry | undefined>(undefined);\n private current?: { readonly root: SignedResourceId; readonly tree: SynchronizedTreeState };\n private readonly abortController = new AbortController();\n private loop?: Promise<void>;\n\n /**\n * Orders the seeds. A reseed that started before the one that last installed a root is stale by\n * the time it finishes, however long its tree took to open, and must not displace it.\n */\n private seedSequence = 0;\n private installedSeed = -1;\n\n /** How many callers hold this watch. The tree is terminated when it reaches zero. */\n private holders = 0;\n\n public readonly summary: Computable<BlockStatusSummary>;\n\n /**\n * The contexts whose children {@link tree} shows. Shared by every holder: two windows on one\n * block see one expansion.\n */\n private readonly expanded = new WatchableValue<ReadonlySet<string>>(new Set());\n\n /**\n * The run's tree, context by context, over the same synchronized tree as {@link summary}. It\n * keeps its own per-context computables, so watching it doubles the cost of a report.\n */\n public readonly tree: Computable<BlockStatusTree>;\n\n private readonly env: MiddleLayerEnvironment;\n private readonly projectRid: SignedResourceId;\n private readonly blockId: string;\n private readonly mode: BlockActionContextMode;\n private readonly projectGeneration: () => number;\n\n private constructor({\n env,\n projectRid,\n blockId,\n mode,\n projectGeneration,\n }: BlockStatusWatchParams) {\n this.env = env;\n this.projectRid = projectRid;\n this.blockId = blockId;\n this.mode = mode;\n this.projectGeneration = projectGeneration;\n // Without the `actionContext` link a block has no context and nothing is ever reported.\n const reportsSupported = env.pl.hasCapability(ActionContextLinkCapability);\n // One computable for the life of the watch, reading whichever tree is seeded now, so a caller\n // keeps its handle across a re-run of the block.\n this.summary = Computable.make((ctx) => {\n const entry = this.source.getValue(ctx);\n if (entry === undefined)\n return reportsSupported ? EmptyBlockStatusSummary : UnsupportedBlockStatusSummary;\n return entrySummary(entry, reportsSupported, (err) =>\n this.env.logger.warn(new Error(\"block status fold failed\", { cause: err })),\n );\n });\n // The expansion is read in the body, so expanding re-runs it; the per-context computables\n // under it keep their keys and so their cached folds.\n this.tree = Computable.make(\n (ctx) => {\n const entry = this.source.getValue(ctx);\n return {\n seeded: entry !== undefined,\n expanded: [...this.expanded.getValue(ctx)],\n fold:\n entry === undefined\n ? undefined\n : subtreeFold(entry, new Set(), (err) =>\n this.env.logger.warn(new Error(\"block status tree fold failed\", { cause: err })),\n ),\n };\n },\n {\n postprocessValue: ({ seeded, expanded, fold }) => {\n if (!seeded)\n return emptyBlockStatusTree(\n reportsSupported ? EmptyBlockStatusSummary : UnsupportedBlockStatusSummary,\n );\n if (fold === undefined) return emptyBlockStatusTree(UnreadableBlockStatusSummary);\n return blockStatusTree(fold, summaryOfFold(fold, reportsSupported), new Set(expanded));\n },\n },\n );\n }\n\n /** Replaces the set of contexts whose children {@link tree} shows. */\n public setExpanded(contextIds: readonly string[]): void {\n this.expanded.setValue(new Set(contextIds), \"block status tree expansion changed\");\n }\n\n /**\n * Starts watching the status of a block render.\n *\n * The first seed is awaited, so the caller gets a handle that already reports whatever the\n * current render has reported. A block with no status context yet still gets a handle: it\n * reports an empty summary and seeds itself when a render that has one appears.\n *\n * The refetch loop is started only once that first seed has settled. Starting it in the\n * constructor would leave it running with nobody holding a reference to stop it if this throws.\n */\n public static async start(params: BlockStatusWatchParams): Promise<BlockStatusWatch> {\n const watch = new BlockStatusWatch(params);\n try {\n await watch.reseed();\n } catch (err: unknown) {\n await watch.terminateNow();\n throw err;\n }\n watch.begin();\n return watch;\n }\n\n /** Takes the first holder and starts looking for new renders, once the first seed settled. */\n private begin(): void {\n this.holders = 1;\n // The loop handles its own errors; this catch is only a backstop, so the promise kept here\n // never rejects and can be awaited as is.\n this.loop = this.refetchLoop().catch((err: unknown) => {\n this.env.logger.warn(new Error(\"block status refetch loop failed\", { cause: err }));\n });\n }\n\n /** Records one more caller holding this watch. */\n public retain(): void {\n this.holders++;\n }\n\n /**\n * Releases one caller's hold. The tree is terminated, and the watch is finished, only when the\n * last holder lets go; returns true when that happened.\n */\n public async release(): Promise<boolean> {\n if (this.holders > 0) this.holders--;\n if (this.holders > 0) return false;\n await this.terminateNow();\n return true;\n }\n\n /**\n * Stops the watch whatever the holder count, for a project being torn down. An ordinary caller\n * uses {@link release}.\n */\n public async terminate(): Promise<void> {\n this.holders = 0;\n await this.terminateNow();\n }\n\n /** Stops the loop, terminates the tree and releases the computable's holders. */\n private async terminateNow(): Promise<void> {\n this.abortController.abort();\n await this.loop;\n const held = this.current;\n this.current = undefined;\n this.source.setValue(undefined, \"block status watch terminated\");\n this.summary.resetState();\n this.tree.resetState();\n await this.terminateTree(held?.tree);\n }\n\n /**\n * Looks for a new render while the caller watches.\n *\n * The project field holding the root context is pruned from the project tree, so the re-point is\n * not visible there; what is visible is that the project changed at all. A tick that finds the\n * same root installs nothing.\n */\n private async refetchLoop(): Promise<void> {\n let seen = this.projectGeneration();\n while (!this.abortController.signal.aborted) {\n try {\n await setTimeout(RefetchDebounceMs, undefined, { signal: this.abortController.signal });\n } catch {\n return; // aborted\n }\n\n const generation = this.projectGeneration();\n if (generation === seen) continue;\n\n try {\n await this.reseed();\n // Only once the look succeeded, so a failed one is retried on the next tick rather than\n // waiting for the project to change again.\n seen = generation;\n } catch (err: unknown) {\n if (this.abortController.signal.aborted) return;\n // The current tree stays in place: the surface keeps showing what it has rather than\n // going blank, and the next tick tries again.\n this.env.logger.warn(new Error(\"block status reseed failed\", { cause: err }));\n }\n }\n }\n\n /** Points the summary at the current render's context, replacing any earlier one. */\n private async reseed(): Promise<void> {\n const seed = ++this.seedSequence;\n\n const root = await readBlockActionContextRoot(\n this.env.pl,\n this.projectRid,\n this.blockId,\n this.mode,\n );\n if (this.abortController.signal.aborted) return;\n if (seed < this.installedSeed) return;\n if (root === this.current?.root) return;\n\n const tree =\n root === undefined\n ? undefined\n : await SynchronizedTreeState.init(\n this.env.pl,\n root,\n {\n ...this.env.ops.defaultTreeOptions,\n pollingInterval: StatusTreePollingIntervalMs,\n initialTreeLoadingTimeout: StatusTreeInitialLoadTimeoutMs,\n fieldFilter: statusTreeFieldFilter,\n // A context never becomes final: the backend keeps reporting into it for as long as\n // its render lives, so every poll has to seed it again.\n rootsNeverFinal: true,\n },\n this.env.logger,\n );\n\n // Opening the tree took time, and a later reseed may have installed a newer root meanwhile.\n // Terminating the tree just opened is the whole cost of losing that race.\n if (this.abortController.signal.aborted || seed < this.installedSeed) {\n await this.terminateTree(tree);\n return;\n }\n\n const previous = this.current;\n this.installedSeed = seed;\n this.current = root !== undefined && tree !== undefined ? { root, tree } : undefined;\n\n // Swapped before the old tree is terminated. A computable body runs to completion\n // synchronously, so after this returns no reader is inside the old tree.\n this.source.setValue(tree?.entry(), \"block status root changed\");\n await this.terminateTree(previous?.tree);\n }\n\n private async terminateTree(tree: SynchronizedTreeState | undefined): Promise<void> {\n if (tree === undefined) return;\n try {\n await tree.terminate();\n } catch (err: unknown) {\n // terminate() can throw when the sync loop had already failed; nothing is left to clean up.\n this.env.logger.warn(new Error(\"block status tree termination failed\", { cause: err }));\n }\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AAsCA,MAAM,oBAAoB;;AAG1B,MAAM,8BAA8B;;;;;;;;AASpC,MAAM,iCAAiC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,KAAK,IAAI,OAAO,KAAK,IAAI,MAAM,8BAA8B,EAAE,OAAO,IAAI,CAAC,CAAC;GAC9E;EACF;CACF;;CAGA,MAAc,SAAwB;EACpC,MAAM,OAAO,EAAE,KAAK;EAEpB,MAAM,OAAO,MAAM,2BACjB,KAAK,IAAI,IACT,KAAK,YACL,KAAK,SACL,KAAK,IACP;EACA,IAAI,KAAK,gBAAgB,OAAO,SAAS;EACzC,IAAI,OAAO,KAAK,eAAe;EAC/B,IAAI,SAAS,KAAK,SAAS,MAAM;EAEjC,MAAM,OACJ,SAAS,KAAA,IACL,KAAA,IACA,MAAMC,wBAAAA,sBAAsB,KAC1B,KAAK,IAAI,IACT,MACA;GACE,GAAG,KAAK,IAAI,IAAI;GAChB,iBAAiB;GACjB,2BAA2B;GAC3B,aAAa;GAGb,iBAAiB;EACnB,GACA,KAAK,IAAI,MACX;EAIN,IAAI,KAAK,gBAAgB,OAAO,WAAW,OAAO,KAAK,eAAe;GACpE,MAAM,KAAK,cAAc,IAAI;GAC7B;EACF;EAEA,MAAM,WAAW,KAAK;EACtB,KAAK,gBAAgB;EACrB,KAAK,UAAU,SAAS,KAAA,KAAa,SAAS,KAAA,IAAY;GAAE;GAAM;EAAK,IAAI,KAAA;EAI3E,KAAK,OAAO,SAAS,MAAM,MAAM,GAAG,2BAA2B;EAC/D,MAAM,KAAK,cAAc,UAAU,IAAI;CACzC;CAEA,MAAc,cAAc,MAAwD;EAClF,IAAI,SAAS,KAAA,GAAW;EACxB,IAAI;GACF,MAAM,KAAK,UAAU;EACvB,SAAS,KAAc;GAErB,KAAK,IAAI,OAAO,KAAK,IAAI,MAAM,wCAAwC,EAAE,OAAO,IAAI,CAAC,CAAC;EACxF;CACF;AACF"}
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { projectFieldName } from "../model/project_model.js";
|
|
2
2
|
import { ActionContextLinkCapability } from "../mutator/template/render_block.js";
|
|
3
3
|
import { childContexts, foldContext, mergeSubtree, summarize } from "./block_status_fold.js";
|
|
4
|
+
import { blockStatusTree, emptyBlockStatusTree } from "./block_status_tree_fold.js";
|
|
4
5
|
import { EmptyBlockStatusSummary, UnreadableBlockStatusSummary, UnsupportedBlockStatusSummary } from "@milaboratories/pl-model-middle-layer";
|
|
5
6
|
import { Computable, WatchableValue } from "@milaboratories/computable";
|
|
6
7
|
import { setTimeout } from "node:timers/promises";
|
|
@@ -104,17 +105,19 @@ function subtreeFold(entry, path, onError) {
|
|
|
104
105
|
function entrySummary(entry, reportsSupported, onError) {
|
|
105
106
|
return Computable.make(() => ({ fold: subtreeFold(entry, /* @__PURE__ */ new Set(), onError) }), {
|
|
106
107
|
key: `block-status-summary/${entry.id}`,
|
|
107
|
-
postprocessValue: ({ fold }) =>
|
|
108
|
-
if (fold === void 0) return UnreadableBlockStatusSummary;
|
|
109
|
-
const summary = summarize(fold);
|
|
110
|
-
if (reportsSupported || summary.totalContexts === 0) return summary;
|
|
111
|
-
return {
|
|
112
|
-
...summary,
|
|
113
|
-
availability: "unsupported"
|
|
114
|
-
};
|
|
115
|
-
}
|
|
108
|
+
postprocessValue: ({ fold }) => summaryOfFold(fold, reportsSupported)
|
|
116
109
|
});
|
|
117
110
|
}
|
|
111
|
+
/** The summary of a fold, or of a root context that could not be read. */
|
|
112
|
+
function summaryOfFold(fold, reportsSupported) {
|
|
113
|
+
if (fold === void 0) return UnreadableBlockStatusSummary;
|
|
114
|
+
const summary = summarize(fold);
|
|
115
|
+
if (reportsSupported || summary.totalContexts === 0) return summary;
|
|
116
|
+
return {
|
|
117
|
+
...summary,
|
|
118
|
+
availability: "unsupported"
|
|
119
|
+
};
|
|
120
|
+
}
|
|
118
121
|
/**
|
|
119
122
|
* The live status of one block render.
|
|
120
123
|
*
|
|
@@ -138,6 +141,16 @@ var BlockStatusWatch = class BlockStatusWatch {
|
|
|
138
141
|
/** How many callers hold this watch. The tree is terminated when it reaches zero. */
|
|
139
142
|
holders = 0;
|
|
140
143
|
summary;
|
|
144
|
+
/**
|
|
145
|
+
* The contexts whose children {@link tree} shows. Shared by every holder: two windows on one
|
|
146
|
+
* block see one expansion.
|
|
147
|
+
*/
|
|
148
|
+
expanded = new WatchableValue(/* @__PURE__ */ new Set());
|
|
149
|
+
/**
|
|
150
|
+
* The run's tree, context by context, over the same synchronized tree as {@link summary}. It
|
|
151
|
+
* keeps its own per-context computables, so watching it doubles the cost of a report.
|
|
152
|
+
*/
|
|
153
|
+
tree;
|
|
141
154
|
env;
|
|
142
155
|
projectRid;
|
|
143
156
|
blockId;
|
|
@@ -155,6 +168,22 @@ var BlockStatusWatch = class BlockStatusWatch {
|
|
|
155
168
|
if (entry === void 0) return reportsSupported ? EmptyBlockStatusSummary : UnsupportedBlockStatusSummary;
|
|
156
169
|
return entrySummary(entry, reportsSupported, (err) => this.env.logger.warn(new Error("block status fold failed", { cause: err })));
|
|
157
170
|
});
|
|
171
|
+
this.tree = Computable.make((ctx) => {
|
|
172
|
+
const entry = this.source.getValue(ctx);
|
|
173
|
+
return {
|
|
174
|
+
seeded: entry !== void 0,
|
|
175
|
+
expanded: [...this.expanded.getValue(ctx)],
|
|
176
|
+
fold: entry === void 0 ? void 0 : subtreeFold(entry, /* @__PURE__ */ new Set(), (err) => this.env.logger.warn(new Error("block status tree fold failed", { cause: err })))
|
|
177
|
+
};
|
|
178
|
+
}, { postprocessValue: ({ seeded, expanded, fold }) => {
|
|
179
|
+
if (!seeded) return emptyBlockStatusTree(reportsSupported ? EmptyBlockStatusSummary : UnsupportedBlockStatusSummary);
|
|
180
|
+
if (fold === void 0) return emptyBlockStatusTree(UnreadableBlockStatusSummary);
|
|
181
|
+
return blockStatusTree(fold, summaryOfFold(fold, reportsSupported), new Set(expanded));
|
|
182
|
+
} });
|
|
183
|
+
}
|
|
184
|
+
/** Replaces the set of contexts whose children {@link tree} shows. */
|
|
185
|
+
setExpanded(contextIds) {
|
|
186
|
+
this.expanded.setValue(new Set(contextIds), "block status tree expansion changed");
|
|
158
187
|
}
|
|
159
188
|
/**
|
|
160
189
|
* Starts watching the status of a block render.
|
|
@@ -214,6 +243,7 @@ var BlockStatusWatch = class BlockStatusWatch {
|
|
|
214
243
|
this.current = void 0;
|
|
215
244
|
this.source.setValue(void 0, "block status watch terminated");
|
|
216
245
|
this.summary.resetState();
|
|
246
|
+
this.tree.resetState();
|
|
217
247
|
await this.terminateTree(held?.tree);
|
|
218
248
|
}
|
|
219
249
|
/**
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"block_status_tree.js","names":[],"sources":["../../src/middle_layer/block_status_tree.ts"],"sourcesContent":["/**\n * The live action-context tree of one block render, and the computable that folds it.\n *\n * A status tree is its own {@link SynchronizedTreeState}, seeded at the root action context of the\n * render rather than at the project. It has to be separate: the project tree prunes the context\n * fields (see `ProjectStatusFieldPattern`), because a context holds the whole subtree of its render\n * and every report into it is a KV write.\n *\n * One tree per watched block, held while anyone watches, terminated when the last holder lets go.\n */\n\nimport type { PlClient, SignedResourceId } from \"@milaboratories/pl-client\";\nimport { isNullSignedResourceId, ResourceTypeName, treeFilter } from \"@milaboratories/pl-client\";\nimport { Computable, WatchableValue } from \"@milaboratories/computable\";\nimport type { PlTreeEntry, PlTreeNodeAccessor } from \"@milaboratories/pl-tree\";\nimport { SynchronizedTreeState } from \"@milaboratories/pl-tree\";\nimport type { BlockStatusSummary } from \"@milaboratories/pl-model-middle-layer\";\nimport {\n EmptyBlockStatusSummary,\n UnreadableBlockStatusSummary,\n UnsupportedBlockStatusSummary,\n} from \"@milaboratories/pl-model-middle-layer\";\nimport { setTimeout } from \"node:timers/promises\";\nimport type { ActionContextNode, SubtreeFold } from \"./block_status_fold\";\nimport { childContexts, foldContext, mergeSubtree, summarize } from \"./block_status_fold\";\nimport type { BlockActionContextMode } from \"./block_action_context\";\nimport { ActionContextLinkCapability } from \"../mutator/template/render_block\";\nimport { projectFieldName } from \"../model/project_model\";\nimport type { MiddleLayerEnvironment } from \"./middle_layer\";\n\n/**\n * How long the refetch loop waits between looks at the project's change generation.\n *\n * The tick itself reads an in-memory counter. It opens a read transaction only when the project\n * has changed since the last look, which while a block runs is most ticks: one read transaction\n * per second per watched block, which is the cost of noticing a re-run promptly.\n */\nconst RefetchDebounceMs = 1_000;\n\n/** The poll floor of a status tree, as the spec sets it. */\nconst StatusTreePollingIntervalMs = 5_000;\n\n/**\n * Deadline for the first load of a status tree.\n *\n * Deliberately NOT the project tree's, which disables the timeout outright: a status tree is\n * opened and closed while the app runs, and {@link BlockStatusWatch.terminate} awaits the loop, so\n * an init that never returns would hang a project close and with it the app's shutdown.\n */\nconst StatusTreeInitialLoadTimeoutMs = 30_000;\n\n/** The status tree walks action contexts and nothing else. */\nconst statusTreeFieldFilter = treeFilter.resourceTypeEq(ResourceTypeName.ActionContext);\n\n/**\n * The root action context of a block render, read once from the project.\n *\n * Undefined when the block has no context: it was never rendered, or it ran against a backend or a\n * middle layer that did not create one.\n */\nexport async function readBlockActionContextRoot(\n pl: PlClient,\n projectRid: SignedResourceId,\n blockId: string,\n mode: BlockActionContextMode,\n): Promise<SignedResourceId | undefined> {\n return await pl.withReadTx(\"readBlockActionContextRoot\", async (tx) => {\n const project = await tx.getResourceData(projectRid, true);\n const fieldName = projectFieldName(\n blockId,\n mode === \"prod\" ? \"prodActionContext\" : \"stagingActionContext\",\n );\n const statusField = project.fields.find((f) => f.name === fieldName);\n if (statusField === undefined || isNullSignedResourceId(statusField.value)) return undefined;\n return statusField.value;\n });\n}\n\n/** Adapts a tree node accessor to what the fold reads. */\nexport function actionContextNode(acc: PlTreeNodeAccessor): ActionContextNode {\n return {\n id: String(acc.id),\n getData: () => acc.getDataAsJson<Record<string, unknown>>(),\n listKeyValuesAsString: (prefix: string) => acc.listKeyValuesAsString(prefix),\n listFields: () => acc.listFields(),\n traverse: (field: string) => {\n // A child that carries an error is skipped rather than thrown: the status surface is\n // diagnostic, and one broken branch must not take the whole line down with it.\n const child = acc.traverse({ field, ignoreError: true });\n return child === undefined ? undefined : actionContextNode(child);\n },\n };\n}\n\n/**\n * The fold of the context an entry points at and everything under it, one computable per context.\n *\n * A report is a KV write into one context, and only that context's computable reads its KV, so a\n * report re-reads that one context. Each computable above it re-merges its direct children, which\n * are cached, and nothing else in the tree is read again.\n *\n * Undefined when the context cannot be read. A context that is gone is the ordinary case, not a\n * fault: an ephemeral context is dropped as soon as the project stops holding it, which happens the\n * moment the block is run again, and the watch is briefly pointed at it until the next look for a\n * new render. A child that cannot be read is left out rather than breaking the whole run's status.\n * The cause is logged, so a genuine fault is not silent.\n */\nexport function subtreeFold(\n entry: PlTreeEntry,\n path: ReadonlySet<string>,\n onError: (err: unknown) => void,\n): Computable<SubtreeFold | undefined> {\n return Computable.make(\n (ctx) => {\n try {\n const acc = ctx.accessor(entry).node({ ignoreError: true });\n if (acc === undefined) return undefined;\n const node = actionContextNode(acc);\n const below = new Set(path).add(node.id);\n const children = childContexts(\n acc.listFields(),\n // A child that carries an error is skipped rather than thrown, as in actionContextNode.\n (field) => acc.traverse({ field, ignoreError: true }),\n below,\n ).map((child) => subtreeFold(child.persist(), below, onError));\n return { own: foldContext(node), children };\n } catch (err: unknown) {\n onError(err);\n return undefined;\n }\n },\n {\n key: `block-status-context/${entry.id}`,\n postprocessValue: (value) => {\n if (value === undefined) return undefined;\n const children: SubtreeFold[] = [];\n for (const child of value.children) if (child !== undefined) children.push(child);\n return mergeSubtree(value.own, children);\n },\n },\n );\n}\n\n/** The summary of the run whose root context an entry points at. */\nexport function entrySummary(\n entry: PlTreeEntry,\n reportsSupported: boolean,\n onError: (err: unknown) => void,\n): Computable<BlockStatusSummary> {\n return Computable.make(() => ({ fold: subtreeFold(entry, new Set(), onError) }), {\n key: `block-status-summary/${entry.id}`,\n postprocessValue: ({ fold }) => {\n // The counters of a context that could not be read are unknown, not zero.\n if (fold === undefined) return UnreadableBlockStatusSummary;\n const summary = summarize(fold);\n if (reportsSupported || summary.totalContexts === 0) return summary;\n // The context exists and carries its data, but no transition can ever arrive.\n return { ...summary, availability: \"unsupported\" as const };\n },\n });\n}\n\n/** What {@link BlockStatusWatch.start} watches. */\nexport type BlockStatusWatchParams = {\n readonly env: MiddleLayerEnvironment;\n readonly projectRid: SignedResourceId;\n readonly blockId: string;\n readonly mode: BlockActionContextMode;\n /** The project tree's change generation, the trigger for looking for a new render. */\n readonly projectGeneration: () => number;\n};\n\n/**\n * The live status of one block render.\n *\n * The summary is stable across runs of the block: clicking Run creates a new render with a new\n * status context, and the watch re-seeds itself onto it rather than handing the caller a new\n * computable. The watch is shared between callers and reference counted; the tree lives until the\n * last holder releases it.\n */\nexport class BlockStatusWatch {\n /** The entry of the tree currently seeded, swapped when the block is run again. */\n private readonly source = new WatchableValue<PlTreeEntry | undefined>(undefined);\n private current?: { readonly root: SignedResourceId; readonly tree: SynchronizedTreeState };\n private readonly abortController = new AbortController();\n private loop?: Promise<void>;\n\n /**\n * Orders the seeds. A reseed that started before the one that last installed a root is stale by\n * the time it finishes, however long its tree took to open, and must not displace it.\n */\n private seedSequence = 0;\n private installedSeed = -1;\n\n /** How many callers hold this watch. The tree is terminated when it reaches zero. */\n private holders = 0;\n\n public readonly summary: Computable<BlockStatusSummary>;\n\n private readonly env: MiddleLayerEnvironment;\n private readonly projectRid: SignedResourceId;\n private readonly blockId: string;\n private readonly mode: BlockActionContextMode;\n private readonly projectGeneration: () => number;\n\n private constructor({\n env,\n projectRid,\n blockId,\n mode,\n projectGeneration,\n }: BlockStatusWatchParams) {\n this.env = env;\n this.projectRid = projectRid;\n this.blockId = blockId;\n this.mode = mode;\n this.projectGeneration = projectGeneration;\n // Without the `actionContext` link a block has no context and nothing is ever reported.\n const reportsSupported = env.pl.hasCapability(ActionContextLinkCapability);\n // One computable for the life of the watch, reading whichever tree is seeded now, so a caller\n // keeps its handle across a re-run of the block.\n this.summary = Computable.make((ctx) => {\n const entry = this.source.getValue(ctx);\n if (entry === undefined)\n return reportsSupported ? EmptyBlockStatusSummary : UnsupportedBlockStatusSummary;\n return entrySummary(entry, reportsSupported, (err) =>\n this.env.logger.warn(new Error(\"block status fold failed\", { cause: err })),\n );\n });\n }\n\n /**\n * Starts watching the status of a block render.\n *\n * The first seed is awaited, so the caller gets a handle that already reports whatever the\n * current render has reported. A block with no status context yet still gets a handle: it\n * reports an empty summary and seeds itself when a render that has one appears.\n *\n * The refetch loop is started only once that first seed has settled. Starting it in the\n * constructor would leave it running with nobody holding a reference to stop it if this throws.\n */\n public static async start(params: BlockStatusWatchParams): Promise<BlockStatusWatch> {\n const watch = new BlockStatusWatch(params);\n try {\n await watch.reseed();\n } catch (err: unknown) {\n await watch.terminateNow();\n throw err;\n }\n watch.begin();\n return watch;\n }\n\n /** Takes the first holder and starts looking for new renders, once the first seed settled. */\n private begin(): void {\n this.holders = 1;\n // The loop handles its own errors; this catch is only a backstop, so the promise kept here\n // never rejects and can be awaited as is.\n this.loop = this.refetchLoop().catch((err: unknown) => {\n this.env.logger.warn(new Error(\"block status refetch loop failed\", { cause: err }));\n });\n }\n\n /** Records one more caller holding this watch. */\n public retain(): void {\n this.holders++;\n }\n\n /**\n * Releases one caller's hold. The tree is terminated, and the watch is finished, only when the\n * last holder lets go; returns true when that happened.\n */\n public async release(): Promise<boolean> {\n if (this.holders > 0) this.holders--;\n if (this.holders > 0) return false;\n await this.terminateNow();\n return true;\n }\n\n /**\n * Stops the watch whatever the holder count, for a project being torn down. An ordinary caller\n * uses {@link release}.\n */\n public async terminate(): Promise<void> {\n this.holders = 0;\n await this.terminateNow();\n }\n\n /** Stops the loop, terminates the tree and releases the computable's holders. */\n private async terminateNow(): Promise<void> {\n this.abortController.abort();\n await this.loop;\n const held = this.current;\n this.current = undefined;\n this.source.setValue(undefined, \"block status watch terminated\");\n this.summary.resetState();\n await this.terminateTree(held?.tree);\n }\n\n /**\n * Looks for a new render while the caller watches.\n *\n * The project field holding the root context is pruned from the project tree, so the re-point is\n * not visible there; what is visible is that the project changed at all. A tick that finds the\n * same root installs nothing.\n */\n private async refetchLoop(): Promise<void> {\n let seen = this.projectGeneration();\n while (!this.abortController.signal.aborted) {\n try {\n await setTimeout(RefetchDebounceMs, undefined, { signal: this.abortController.signal });\n } catch {\n return; // aborted\n }\n\n const generation = this.projectGeneration();\n if (generation === seen) continue;\n\n try {\n await this.reseed();\n // Only once the look succeeded, so a failed one is retried on the next tick rather than\n // waiting for the project to change again.\n seen = generation;\n } catch (err: unknown) {\n if (this.abortController.signal.aborted) return;\n // The current tree stays in place: the surface keeps showing what it has rather than\n // going blank, and the next tick tries again.\n this.env.logger.warn(new Error(\"block status reseed failed\", { cause: err }));\n }\n }\n }\n\n /** Points the summary at the current render's context, replacing any earlier one. */\n private async reseed(): Promise<void> {\n const seed = ++this.seedSequence;\n\n const root = await readBlockActionContextRoot(\n this.env.pl,\n this.projectRid,\n this.blockId,\n this.mode,\n );\n if (this.abortController.signal.aborted) return;\n if (seed < this.installedSeed) return;\n if (root === this.current?.root) return;\n\n const tree =\n root === undefined\n ? undefined\n : await SynchronizedTreeState.init(\n this.env.pl,\n root,\n {\n ...this.env.ops.defaultTreeOptions,\n pollingInterval: StatusTreePollingIntervalMs,\n initialTreeLoadingTimeout: StatusTreeInitialLoadTimeoutMs,\n fieldFilter: statusTreeFieldFilter,\n // A context never becomes final: the backend keeps reporting into it for as long as\n // its render lives, so every poll has to seed it again.\n rootsNeverFinal: true,\n },\n this.env.logger,\n );\n\n // Opening the tree took time, and a later reseed may have installed a newer root meanwhile.\n // Terminating the tree just opened is the whole cost of losing that race.\n if (this.abortController.signal.aborted || seed < this.installedSeed) {\n await this.terminateTree(tree);\n return;\n }\n\n const previous = this.current;\n this.installedSeed = seed;\n this.current = root !== undefined && tree !== undefined ? { root, tree } : undefined;\n\n // Swapped before the old tree is terminated. A computable body runs to completion\n // synchronously, so after this returns no reader is inside the old tree.\n this.source.setValue(tree?.entry(), \"block status root changed\");\n await this.terminateTree(previous?.tree);\n }\n\n private async terminateTree(tree: SynchronizedTreeState | undefined): Promise<void> {\n if (tree === undefined) return;\n try {\n await tree.terminate();\n } catch (err: unknown) {\n // terminate() can throw when the sync loop had already failed; nothing is left to clean up.\n this.env.logger.warn(new Error(\"block status tree termination failed\", { cause: err }));\n }\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;AAqCA,MAAM,oBAAoB;;AAG1B,MAAM,8BAA8B;;;;;;;;AASpC,MAAM,iCAAiC;;AAGvC,MAAM,wBAAwB,WAAW,eAAe,iBAAiB,aAAa;;;;;;;AAQtF,eAAsB,2BACpB,IACA,YACA,SACA,MACuC;CACvC,OAAO,MAAM,GAAG,WAAW,8BAA8B,OAAO,OAAO;EACrE,MAAM,UAAU,MAAM,GAAG,gBAAgB,YAAY,IAAI;EACzD,MAAM,YAAY,iBAChB,SACA,SAAS,SAAS,sBAAsB,sBAC1C;EACA,MAAM,cAAc,QAAQ,OAAO,MAAM,MAAM,EAAE,SAAS,SAAS;EACnE,IAAI,gBAAgB,KAAA,KAAa,uBAAuB,YAAY,KAAK,GAAG,OAAO,KAAA;EACnF,OAAO,YAAY;CACrB,CAAC;AACH;;AAGA,SAAgB,kBAAkB,KAA4C;CAC5E,OAAO;EACL,IAAI,OAAO,IAAI,EAAE;EACjB,eAAe,IAAI,cAAuC;EAC1D,wBAAwB,WAAmB,IAAI,sBAAsB,MAAM;EAC3E,kBAAkB,IAAI,WAAW;EACjC,WAAW,UAAkB;GAG3B,MAAM,QAAQ,IAAI,SAAS;IAAE;IAAO,aAAa;GAAK,CAAC;GACvD,OAAO,UAAU,KAAA,IAAY,KAAA,IAAY,kBAAkB,KAAK;EAClE;CACF;AACF;;;;;;;;;;;;;;AAeA,SAAgB,YACd,OACA,MACA,SACqC;CACrC,OAAO,WAAW,MACf,QAAQ;EACP,IAAI;GACF,MAAM,MAAM,IAAI,SAAS,KAAK,CAAC,CAAC,KAAK,EAAE,aAAa,KAAK,CAAC;GAC1D,IAAI,QAAQ,KAAA,GAAW,OAAO,KAAA;GAC9B,MAAM,OAAO,kBAAkB,GAAG;GAClC,MAAM,QAAQ,IAAI,IAAI,IAAI,CAAC,CAAC,IAAI,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,SAAS,KAAA,GAAW;EACxB,IAAI;GACF,MAAM,KAAK,UAAU;EACvB,SAAS,KAAc;GAErB,KAAK,IAAI,OAAO,KAAK,IAAI,MAAM,wCAAwC,EAAE,OAAO,IAAI,CAAC,CAAC;EACxF;CACF;AACF"}
|
|
1
|
+
{"version":3,"file":"block_status_tree.js","names":[],"sources":["../../src/middle_layer/block_status_tree.ts"],"sourcesContent":["/**\n * The live action-context tree of one block render, and the computables that fold it.\n *\n * A status tree is its own {@link SynchronizedTreeState}, seeded at the root action context of the\n * render rather than at the project. It has to be separate: the project tree prunes the context\n * fields (see `ProjectStatusFieldPattern`), because a context holds the whole subtree of its render\n * and every report into it is a KV write.\n *\n * One tree per watched block, held while anyone watches, terminated when the last holder lets go.\n */\n\nimport type { PlClient, SignedResourceId } from \"@milaboratories/pl-client\";\nimport { isNullSignedResourceId, ResourceTypeName, treeFilter } from \"@milaboratories/pl-client\";\nimport { Computable, WatchableValue } from \"@milaboratories/computable\";\nimport type { PlTreeEntry, PlTreeNodeAccessor } from \"@milaboratories/pl-tree\";\nimport { SynchronizedTreeState } from \"@milaboratories/pl-tree\";\nimport type { BlockStatusSummary, BlockStatusTree } from \"@milaboratories/pl-model-middle-layer\";\nimport {\n EmptyBlockStatusSummary,\n UnreadableBlockStatusSummary,\n UnsupportedBlockStatusSummary,\n} from \"@milaboratories/pl-model-middle-layer\";\nimport { setTimeout } from \"node:timers/promises\";\nimport type { ActionContextNode, SubtreeFold } from \"./block_status_fold\";\nimport { childContexts, foldContext, mergeSubtree, summarize } from \"./block_status_fold\";\nimport { blockStatusTree, emptyBlockStatusTree } from \"./block_status_tree_fold\";\nimport type { BlockActionContextMode } from \"./block_action_context\";\nimport { ActionContextLinkCapability } from \"../mutator/template/render_block\";\nimport { projectFieldName } from \"../model/project_model\";\nimport type { MiddleLayerEnvironment } from \"./middle_layer\";\n\n/**\n * How long the refetch loop waits between looks at the project's change generation.\n *\n * The tick itself reads an in-memory counter. It opens a read transaction only when the project\n * has changed since the last look, which while a block runs is most ticks: one read transaction\n * per second per watched block, which is the cost of noticing a re-run promptly.\n */\nconst RefetchDebounceMs = 1_000;\n\n/** The poll floor of a status tree, as the spec sets it. */\nconst StatusTreePollingIntervalMs = 5_000;\n\n/**\n * Deadline for the first load of a status tree.\n *\n * Deliberately NOT the project tree's, which disables the timeout outright: a status tree is\n * opened and closed while the app runs, and {@link BlockStatusWatch.terminate} awaits the loop, so\n * an init that never returns would hang a project close and with it the app's shutdown.\n */\nconst StatusTreeInitialLoadTimeoutMs = 30_000;\n\n/** The status tree walks action contexts and nothing else. */\nconst statusTreeFieldFilter = treeFilter.resourceTypeEq(ResourceTypeName.ActionContext);\n\n/**\n * The root action context of a block render, read once from the project.\n *\n * Undefined when the block has no context: it was never rendered, or it ran against a backend or a\n * middle layer that did not create one.\n */\nexport async function readBlockActionContextRoot(\n pl: PlClient,\n projectRid: SignedResourceId,\n blockId: string,\n mode: BlockActionContextMode,\n): Promise<SignedResourceId | undefined> {\n return await pl.withReadTx(\"readBlockActionContextRoot\", async (tx) => {\n const project = await tx.getResourceData(projectRid, true);\n const fieldName = projectFieldName(\n blockId,\n mode === \"prod\" ? \"prodActionContext\" : \"stagingActionContext\",\n );\n const statusField = project.fields.find((f) => f.name === fieldName);\n if (statusField === undefined || isNullSignedResourceId(statusField.value)) return undefined;\n return statusField.value;\n });\n}\n\n/** Adapts a tree node accessor to what the fold reads. */\nexport function actionContextNode(acc: PlTreeNodeAccessor): ActionContextNode {\n return {\n id: String(acc.id),\n getData: () => acc.getDataAsJson<Record<string, unknown>>(),\n listKeyValuesAsString: (prefix: string) => acc.listKeyValuesAsString(prefix),\n listFields: () => acc.listFields(),\n traverse: (field: string) => {\n // A child that carries an error is skipped rather than thrown: the status surface is\n // diagnostic, and one broken branch must not take the whole line down with it.\n const child = acc.traverse({ field, ignoreError: true });\n return child === undefined ? undefined : actionContextNode(child);\n },\n };\n}\n\n/**\n * The fold of the context an entry points at and everything under it, one computable per context.\n *\n * A report is a KV write into one context, and only that context's computable reads its KV, so a\n * report re-reads that one context. Each computable above it re-merges its direct children, which\n * are cached, and nothing else in the tree is read again.\n *\n * Undefined when the context cannot be read. A context that is gone is the ordinary case, not a\n * fault: an ephemeral context is dropped as soon as the project stops holding it, which happens the\n * moment the block is run again, and the watch is briefly pointed at it until the next look for a\n * new render. A child that cannot be read is left out rather than breaking the whole run's status.\n * The cause is logged, so a genuine fault is not silent.\n */\nexport function subtreeFold(\n entry: PlTreeEntry,\n path: ReadonlySet<string>,\n onError: (err: unknown) => void,\n): Computable<SubtreeFold | undefined> {\n return Computable.make(\n (ctx) => {\n try {\n const acc = ctx.accessor(entry).node({ ignoreError: true });\n if (acc === undefined) return undefined;\n const node = actionContextNode(acc);\n const below = new Set(path).add(node.id);\n const children = childContexts(\n acc.listFields(),\n // A child that carries an error is skipped rather than thrown, as in actionContextNode.\n (field) => acc.traverse({ field, ignoreError: true }),\n below,\n ).map((child) => subtreeFold(child.persist(), below, onError));\n return { own: foldContext(node), children };\n } catch (err: unknown) {\n onError(err);\n return undefined;\n }\n },\n {\n key: `block-status-context/${entry.id}`,\n postprocessValue: (value) => {\n if (value === undefined) return undefined;\n const children: SubtreeFold[] = [];\n for (const child of value.children) if (child !== undefined) children.push(child);\n return mergeSubtree(value.own, children);\n },\n },\n );\n}\n\n/** The summary of the run whose root context an entry points at. */\nexport function entrySummary(\n entry: PlTreeEntry,\n reportsSupported: boolean,\n onError: (err: unknown) => void,\n): Computable<BlockStatusSummary> {\n return Computable.make(() => ({ fold: subtreeFold(entry, new Set(), onError) }), {\n key: `block-status-summary/${entry.id}`,\n postprocessValue: ({ fold }) => summaryOfFold(fold, reportsSupported),\n });\n}\n\n/** The summary of a fold, or of a root context that could not be read. */\nfunction summaryOfFold(\n fold: SubtreeFold | undefined,\n reportsSupported: boolean,\n): BlockStatusSummary {\n // The counters of a context that could not be read are unknown, not zero.\n if (fold === undefined) return UnreadableBlockStatusSummary;\n const summary = summarize(fold);\n if (reportsSupported || summary.totalContexts === 0) return summary;\n // The context exists and carries its data, but no transition can ever arrive.\n return { ...summary, availability: \"unsupported\" };\n}\n\n/** What {@link BlockStatusWatch.start} watches. */\nexport type BlockStatusWatchParams = {\n readonly env: MiddleLayerEnvironment;\n readonly projectRid: SignedResourceId;\n readonly blockId: string;\n readonly mode: BlockActionContextMode;\n /** The project tree's change generation, the trigger for looking for a new render. */\n readonly projectGeneration: () => number;\n};\n\n/**\n * The live status of one block render.\n *\n * The summary is stable across runs of the block: clicking Run creates a new render with a new\n * status context, and the watch re-seeds itself onto it rather than handing the caller a new\n * computable. The watch is shared between callers and reference counted; the tree lives until the\n * last holder releases it.\n */\nexport class BlockStatusWatch {\n /** The entry of the tree currently seeded, swapped when the block is run again. */\n private readonly source = new WatchableValue<PlTreeEntry | undefined>(undefined);\n private current?: { readonly root: SignedResourceId; readonly tree: SynchronizedTreeState };\n private readonly abortController = new AbortController();\n private loop?: Promise<void>;\n\n /**\n * Orders the seeds. A reseed that started before the one that last installed a root is stale by\n * the time it finishes, however long its tree took to open, and must not displace it.\n */\n private seedSequence = 0;\n private installedSeed = -1;\n\n /** How many callers hold this watch. The tree is terminated when it reaches zero. */\n private holders = 0;\n\n public readonly summary: Computable<BlockStatusSummary>;\n\n /**\n * The contexts whose children {@link tree} shows. Shared by every holder: two windows on one\n * block see one expansion.\n */\n private readonly expanded = new WatchableValue<ReadonlySet<string>>(new Set());\n\n /**\n * The run's tree, context by context, over the same synchronized tree as {@link summary}. It\n * keeps its own per-context computables, so watching it doubles the cost of a report.\n */\n public readonly tree: Computable<BlockStatusTree>;\n\n private readonly env: MiddleLayerEnvironment;\n private readonly projectRid: SignedResourceId;\n private readonly blockId: string;\n private readonly mode: BlockActionContextMode;\n private readonly projectGeneration: () => number;\n\n private constructor({\n env,\n projectRid,\n blockId,\n mode,\n projectGeneration,\n }: BlockStatusWatchParams) {\n this.env = env;\n this.projectRid = projectRid;\n this.blockId = blockId;\n this.mode = mode;\n this.projectGeneration = projectGeneration;\n // Without the `actionContext` link a block has no context and nothing is ever reported.\n const reportsSupported = env.pl.hasCapability(ActionContextLinkCapability);\n // One computable for the life of the watch, reading whichever tree is seeded now, so a caller\n // keeps its handle across a re-run of the block.\n this.summary = Computable.make((ctx) => {\n const entry = this.source.getValue(ctx);\n if (entry === undefined)\n return reportsSupported ? EmptyBlockStatusSummary : UnsupportedBlockStatusSummary;\n return entrySummary(entry, reportsSupported, (err) =>\n this.env.logger.warn(new Error(\"block status fold failed\", { cause: err })),\n );\n });\n // The expansion is read in the body, so expanding re-runs it; the per-context computables\n // under it keep their keys and so their cached folds.\n this.tree = Computable.make(\n (ctx) => {\n const entry = this.source.getValue(ctx);\n return {\n seeded: entry !== undefined,\n expanded: [...this.expanded.getValue(ctx)],\n fold:\n entry === undefined\n ? undefined\n : subtreeFold(entry, new Set(), (err) =>\n this.env.logger.warn(new Error(\"block status tree fold failed\", { cause: err })),\n ),\n };\n },\n {\n postprocessValue: ({ seeded, expanded, fold }) => {\n if (!seeded)\n return emptyBlockStatusTree(\n reportsSupported ? EmptyBlockStatusSummary : UnsupportedBlockStatusSummary,\n );\n if (fold === undefined) return emptyBlockStatusTree(UnreadableBlockStatusSummary);\n return blockStatusTree(fold, summaryOfFold(fold, reportsSupported), new Set(expanded));\n },\n },\n );\n }\n\n /** Replaces the set of contexts whose children {@link tree} shows. */\n public setExpanded(contextIds: readonly string[]): void {\n this.expanded.setValue(new Set(contextIds), \"block status tree expansion changed\");\n }\n\n /**\n * Starts watching the status of a block render.\n *\n * The first seed is awaited, so the caller gets a handle that already reports whatever the\n * current render has reported. A block with no status context yet still gets a handle: it\n * reports an empty summary and seeds itself when a render that has one appears.\n *\n * The refetch loop is started only once that first seed has settled. Starting it in the\n * constructor would leave it running with nobody holding a reference to stop it if this throws.\n */\n public static async start(params: BlockStatusWatchParams): Promise<BlockStatusWatch> {\n const watch = new BlockStatusWatch(params);\n try {\n await watch.reseed();\n } catch (err: unknown) {\n await watch.terminateNow();\n throw err;\n }\n watch.begin();\n return watch;\n }\n\n /** Takes the first holder and starts looking for new renders, once the first seed settled. */\n private begin(): void {\n this.holders = 1;\n // The loop handles its own errors; this catch is only a backstop, so the promise kept here\n // never rejects and can be awaited as is.\n this.loop = this.refetchLoop().catch((err: unknown) => {\n this.env.logger.warn(new Error(\"block status refetch loop failed\", { cause: err }));\n });\n }\n\n /** Records one more caller holding this watch. */\n public retain(): void {\n this.holders++;\n }\n\n /**\n * Releases one caller's hold. The tree is terminated, and the watch is finished, only when the\n * last holder lets go; returns true when that happened.\n */\n public async release(): Promise<boolean> {\n if (this.holders > 0) this.holders--;\n if (this.holders > 0) return false;\n await this.terminateNow();\n return true;\n }\n\n /**\n * Stops the watch whatever the holder count, for a project being torn down. An ordinary caller\n * uses {@link release}.\n */\n public async terminate(): Promise<void> {\n this.holders = 0;\n await this.terminateNow();\n }\n\n /** Stops the loop, terminates the tree and releases the computable's holders. */\n private async terminateNow(): Promise<void> {\n this.abortController.abort();\n await this.loop;\n const held = this.current;\n this.current = undefined;\n this.source.setValue(undefined, \"block status watch terminated\");\n this.summary.resetState();\n this.tree.resetState();\n await this.terminateTree(held?.tree);\n }\n\n /**\n * Looks for a new render while the caller watches.\n *\n * The project field holding the root context is pruned from the project tree, so the re-point is\n * not visible there; what is visible is that the project changed at all. A tick that finds the\n * same root installs nothing.\n */\n private async refetchLoop(): Promise<void> {\n let seen = this.projectGeneration();\n while (!this.abortController.signal.aborted) {\n try {\n await setTimeout(RefetchDebounceMs, undefined, { signal: this.abortController.signal });\n } catch {\n return; // aborted\n }\n\n const generation = this.projectGeneration();\n if (generation === seen) continue;\n\n try {\n await this.reseed();\n // Only once the look succeeded, so a failed one is retried on the next tick rather than\n // waiting for the project to change again.\n seen = generation;\n } catch (err: unknown) {\n if (this.abortController.signal.aborted) return;\n // The current tree stays in place: the surface keeps showing what it has rather than\n // going blank, and the next tick tries again.\n this.env.logger.warn(new Error(\"block status reseed failed\", { cause: err }));\n }\n }\n }\n\n /** Points the summary at the current render's context, replacing any earlier one. */\n private async reseed(): Promise<void> {\n const seed = ++this.seedSequence;\n\n const root = await readBlockActionContextRoot(\n this.env.pl,\n this.projectRid,\n this.blockId,\n this.mode,\n );\n if (this.abortController.signal.aborted) return;\n if (seed < this.installedSeed) return;\n if (root === this.current?.root) return;\n\n const tree =\n root === undefined\n ? undefined\n : await SynchronizedTreeState.init(\n this.env.pl,\n root,\n {\n ...this.env.ops.defaultTreeOptions,\n pollingInterval: StatusTreePollingIntervalMs,\n initialTreeLoadingTimeout: StatusTreeInitialLoadTimeoutMs,\n fieldFilter: statusTreeFieldFilter,\n // A context never becomes final: the backend keeps reporting into it for as long as\n // its render lives, so every poll has to seed it again.\n rootsNeverFinal: true,\n },\n this.env.logger,\n );\n\n // Opening the tree took time, and a later reseed may have installed a newer root meanwhile.\n // Terminating the tree just opened is the whole cost of losing that race.\n if (this.abortController.signal.aborted || seed < this.installedSeed) {\n await this.terminateTree(tree);\n return;\n }\n\n const previous = this.current;\n this.installedSeed = seed;\n this.current = root !== undefined && tree !== undefined ? { root, tree } : undefined;\n\n // Swapped before the old tree is terminated. A computable body runs to completion\n // synchronously, so after this returns no reader is inside the old tree.\n this.source.setValue(tree?.entry(), \"block status root changed\");\n await this.terminateTree(previous?.tree);\n }\n\n private async terminateTree(tree: SynchronizedTreeState | undefined): Promise<void> {\n if (tree === undefined) return;\n try {\n await tree.terminate();\n } catch (err: unknown) {\n // terminate() can throw when the sync loop had already failed; nothing is left to clean up.\n this.env.logger.warn(new Error(\"block status tree termination failed\", { cause: err }));\n }\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AAsCA,MAAM,oBAAoB;;AAG1B,MAAM,8BAA8B;;;;;;;;AASpC,MAAM,iCAAiC;;AAGvC,MAAM,wBAAwB,WAAW,eAAe,iBAAiB,aAAa;;;;;;;AAQtF,eAAsB,2BACpB,IACA,YACA,SACA,MACuC;CACvC,OAAO,MAAM,GAAG,WAAW,8BAA8B,OAAO,OAAO;EACrE,MAAM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,KAAK,IAAI,IAAI;GAChB,iBAAiB;GACjB,2BAA2B;GAC3B,aAAa;GAGb,iBAAiB;EACnB,GACA,KAAK,IAAI,MACX;EAIN,IAAI,KAAK,gBAAgB,OAAO,WAAW,OAAO,KAAK,eAAe;GACpE,MAAM,KAAK,cAAc,IAAI;GAC7B;EACF;EAEA,MAAM,WAAW,KAAK;EACtB,KAAK,gBAAgB;EACrB,KAAK,UAAU,SAAS,KAAA,KAAa,SAAS,KAAA,IAAY;GAAE;GAAM;EAAK,IAAI,KAAA;EAI3E,KAAK,OAAO,SAAS,MAAM,MAAM,GAAG,2BAA2B;EAC/D,MAAM,KAAK,cAAc,UAAU,IAAI;CACzC;CAEA,MAAc,cAAc,MAAwD;EAClF,IAAI,SAAS,KAAA,GAAW;EACxB,IAAI;GACF,MAAM,KAAK,UAAU;EACvB,SAAS,KAAc;GAErB,KAAK,IAAI,OAAO,KAAK,IAAI,MAAM,wCAAwC,EAAE,OAAO,IAAI,CAAC,CAAC;EACxF;CACF;AACF"}
|
|
@@ -0,0 +1,96 @@
|
|
|
1
|
+
const require_block_status_fold = require("./block_status_fold.cjs");
|
|
2
|
+
let _milaboratories_pl_model_middle_layer = require("@milaboratories/pl-model-middle-layer");
|
|
3
|
+
// src/middle_layer/block_status_tree_fold.ts
|
|
4
|
+
/** A tree with no context under it. */
|
|
5
|
+
function emptyBlockStatusTree(summary) {
|
|
6
|
+
return {
|
|
7
|
+
summary,
|
|
8
|
+
heaviest: {
|
|
9
|
+
byCompute: [],
|
|
10
|
+
byContexts: []
|
|
11
|
+
}
|
|
12
|
+
};
|
|
13
|
+
}
|
|
14
|
+
/**
|
|
15
|
+
* The tree of a block run.
|
|
16
|
+
*
|
|
17
|
+
* @param expanded context ids whose children the reader has opened. The root's children are
|
|
18
|
+
* always present.
|
|
19
|
+
*/
|
|
20
|
+
function blockStatusTree(root, summary, expanded) {
|
|
21
|
+
const computeMs = (fold) => {
|
|
22
|
+
const { closedNs, open, openSinceSumNs } = fold.compute;
|
|
23
|
+
const lastNs = root.lastNs === void 0 ? 0n : BigInt(root.lastNs);
|
|
24
|
+
return Number((closedNs + BigInt(open) * lastNs - openSinceSumNs) / 1000000n);
|
|
25
|
+
};
|
|
26
|
+
const node = (fold, isRoot) => {
|
|
27
|
+
const { own } = fold;
|
|
28
|
+
const { holding } = own.folded;
|
|
29
|
+
return {
|
|
30
|
+
contextId: own.id,
|
|
31
|
+
name: nameOf(own),
|
|
32
|
+
kind: kindOf(own),
|
|
33
|
+
baggage: baggageOf(own),
|
|
34
|
+
state: holding?.state,
|
|
35
|
+
onMachine: own.folded.onMachine,
|
|
36
|
+
enteredAt: holding === void 0 ? void 0 : require_block_status_fold.nsToMs(holding.ns),
|
|
37
|
+
ended: own.folded.terminal,
|
|
38
|
+
failure: own.folded.failure || void 0,
|
|
39
|
+
transitions: transitionsOf(own),
|
|
40
|
+
readings: readingsOf(own),
|
|
41
|
+
childCount: fold.children.length,
|
|
42
|
+
subtreeContexts: fold.contexts,
|
|
43
|
+
subtreeActiveContexts: fold.activeContexts,
|
|
44
|
+
subtreeComputeMs: computeMs(fold),
|
|
45
|
+
children: isRoot || expanded.has(own.id) ? fold.children.map((child) => node(child, false)) : void 0
|
|
46
|
+
};
|
|
47
|
+
};
|
|
48
|
+
/** The root's top-level contexts, ranked by one measure. One with nothing to rank is left out. */
|
|
49
|
+
const rank = (value) => root.children.map((child) => ({
|
|
50
|
+
contextId: child.own.id,
|
|
51
|
+
name: nameOf(child.own),
|
|
52
|
+
value: value(child)
|
|
53
|
+
})).filter((b) => b.value > 0).sort((a, b) => b.value - a.value || a.contextId.localeCompare(b.contextId)).slice(0, _milaboratories_pl_model_middle_layer.BlockStatusTreeHeaviestCount);
|
|
54
|
+
return {
|
|
55
|
+
summary,
|
|
56
|
+
heaviest: {
|
|
57
|
+
byCompute: rank(computeMs),
|
|
58
|
+
byContexts: rank((fold) => fold.contexts),
|
|
59
|
+
byFileSize: void 0
|
|
60
|
+
},
|
|
61
|
+
root: node(root, true),
|
|
62
|
+
firstFailurePath: root.failure?.path
|
|
63
|
+
};
|
|
64
|
+
}
|
|
65
|
+
function nameOf(own) {
|
|
66
|
+
const name = own.data?.name;
|
|
67
|
+
return typeof name === "string" && name !== "" ? name : own.id;
|
|
68
|
+
}
|
|
69
|
+
function kindOf(own) {
|
|
70
|
+
const all = own.reports.all;
|
|
71
|
+
if (all.some((t) => t.namespace === "exec")) return "command";
|
|
72
|
+
if (all.length > 0 && all.every((t) => t.namespace === "workdir")) return "workdir";
|
|
73
|
+
return "render";
|
|
74
|
+
}
|
|
75
|
+
function baggageOf(own) {
|
|
76
|
+
const out = {};
|
|
77
|
+
for (const [key, value] of Object.entries(own.data ?? {})) if (key !== "name") out[key] = typeof value === "string" ? value : JSON.stringify(value);
|
|
78
|
+
return out;
|
|
79
|
+
}
|
|
80
|
+
function transitionsOf(own) {
|
|
81
|
+
return [...own.reports.all].sort((a, b) => require_block_status_fold.compareNs(a.ns, b.ns)).map((t) => ({
|
|
82
|
+
namespace: t.namespace,
|
|
83
|
+
reporter: t.reporter,
|
|
84
|
+
state: t.state,
|
|
85
|
+
detail: t.detail || void 0,
|
|
86
|
+
reason: t.reason || void 0,
|
|
87
|
+
at: require_block_status_fold.nsToMs(t.ns)
|
|
88
|
+
}));
|
|
89
|
+
}
|
|
90
|
+
function readingsOf(own) {
|
|
91
|
+
return [...own.readings].sort((a, b) => a.namespace.localeCompare(b.namespace) || a.resource.localeCompare(b.resource) || a.key.localeCompare(b.key));
|
|
92
|
+
}
|
|
93
|
+
exports.blockStatusTree = blockStatusTree;
|
|
94
|
+
exports.emptyBlockStatusTree = emptyBlockStatusTree;
|
|
95
|
+
|
|
96
|
+
//# sourceMappingURL=block_status_tree_fold.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"block_status_tree_fold.cjs","names":["nsToMs","BlockStatusTreeHeaviestCount","compareNs"],"sources":["../../src/middle_layer/block_status_tree_fold.ts"],"sourcesContent":["/**\n * Builds the {@link BlockStatusTree} of a block run from the {@link SubtreeFold} of its root.\n *\n * Every counter it shows (contexts, active contexts, compute time, the first failure) is already\n * merged into the fold bottom up, so building the tree touches only the root, its top-level\n * contexts and the children of the expanded contexts. It reads nothing from the action-context\n * tree itself.\n *\n * Source: docs/text/work/projects/sdk/block-status/README_teo.md, \"Developer debug panel\".\n */\n\nimport type {\n BlockStatusSummary,\n BlockStatusTree,\n BlockStatusTreeBranch,\n BlockStatusTreeNode,\n BlockStatusTreeReading,\n BlockStatusTreeTransition,\n} from \"@milaboratories/pl-model-middle-layer\";\nimport { BlockStatusTreeHeaviestCount } from \"@milaboratories/pl-model-middle-layer\";\nimport type { ActionContextNode, ContextFold, SubtreeFold } from \"./block_status_fold\";\nimport {\n compareNs,\n ExecNamespace,\n foldSubtree,\n nsToMs,\n summarize,\n WorkdirNamespace,\n} from \"./block_status_fold\";\n\n/** A tree with no context under it. */\nexport function emptyBlockStatusTree(summary: BlockStatusSummary): BlockStatusTree {\n return { summary, heaviest: { byCompute: [], byContexts: [] } };\n}\n\n/**\n * The tree of a block run.\n *\n * @param expanded context ids whose children the reader has opened. The root's children are\n * always present.\n */\nexport function blockStatusTree(\n root: SubtreeFold,\n summary: BlockStatusSummary,\n expanded: ReadonlySet<string>,\n): BlockStatusTree {\n // A command still running is counted up to the run's latest report, not to now: the fold has no\n // clock, and the Desktop App extrapolates the same way for the run's own time.\n const computeMs = (fold: SubtreeFold): number => {\n const { closedNs, open, openSinceSumNs } = fold.compute;\n const lastNs = root.lastNs === undefined ? 0n : BigInt(root.lastNs);\n return Number((closedNs + BigInt(open) * lastNs - openSinceSumNs) / 1_000_000n);\n };\n\n const node = (fold: SubtreeFold, isRoot: boolean): BlockStatusTreeNode => {\n const { own } = fold;\n const { holding } = own.folded;\n return {\n contextId: own.id,\n name: nameOf(own),\n kind: kindOf(own),\n baggage: baggageOf(own),\n state: holding?.state,\n onMachine: own.folded.onMachine,\n enteredAt: holding === undefined ? undefined : nsToMs(holding.ns),\n ended: own.folded.terminal,\n failure: own.folded.failure || undefined,\n transitions: transitionsOf(own),\n readings: readingsOf(own),\n childCount: fold.children.length,\n subtreeContexts: fold.contexts,\n subtreeActiveContexts: fold.activeContexts,\n subtreeComputeMs: computeMs(fold),\n children:\n isRoot || expanded.has(own.id)\n ? fold.children.map((child) => node(child, false))\n : undefined,\n };\n };\n\n /** The root's top-level contexts, ranked by one measure. One with nothing to rank is left out. */\n const rank = (value: (fold: SubtreeFold) => number): BlockStatusTreeBranch[] =>\n root.children\n .map((child) => ({ contextId: child.own.id, name: nameOf(child.own), value: value(child) }))\n .filter((b) => b.value > 0)\n .sort((a, b) => b.value - a.value || a.contextId.localeCompare(b.contextId))\n .slice(0, BlockStatusTreeHeaviestCount);\n\n return {\n summary,\n heaviest: {\n byCompute: rank(computeMs),\n byContexts: rank((fold) => fold.contexts),\n // No reporter writes file sizes yet.\n byFileSize: undefined,\n },\n root: node(root, true),\n firstFailurePath: root.failure?.path,\n };\n}\n\n/** {@link blockStatusTree} over a tree that is read once. */\nexport function foldBlockStatusTree(\n root: ActionContextNode,\n expanded: ReadonlySet<string>,\n): BlockStatusTree {\n const fold = foldSubtree(root);\n return blockStatusTree(fold, summarize(fold), expanded);\n}\n\nfunction nameOf(own: ContextFold): string {\n const name = own.data?.name;\n return typeof name === \"string\" && name !== \"\" ? name : own.id;\n}\n\nfunction kindOf(own: ContextFold): BlockStatusTreeNode[\"kind\"] {\n const all = own.reports.all;\n if (all.some((t) => t.namespace === ExecNamespace)) return \"command\";\n if (all.length > 0 && all.every((t) => t.namespace === WorkdirNamespace)) return \"workdir\";\n return \"render\";\n}\n\nfunction baggageOf(own: ContextFold): Record<string, string> {\n const out: Record<string, string> = {};\n for (const [key, value] of Object.entries(own.data ?? {}))\n if (key !== \"name\") out[key] = typeof value === \"string\" ? value : JSON.stringify(value);\n return out;\n}\n\nfunction transitionsOf(own: ContextFold): BlockStatusTreeTransition[] {\n return [...own.reports.all]\n .sort((a, b) => compareNs(a.ns, b.ns))\n .map((t) => ({\n namespace: t.namespace,\n reporter: t.reporter,\n state: t.state,\n detail: t.detail || undefined,\n reason: t.reason || undefined,\n at: nsToMs(t.ns),\n }));\n}\n\nfunction readingsOf(own: ContextFold): BlockStatusTreeReading[] {\n return [...own.readings].sort(\n (a, b) =>\n a.namespace.localeCompare(b.namespace) ||\n a.resource.localeCompare(b.resource) ||\n a.key.localeCompare(b.key),\n );\n}\n"],"mappings":";;;;AA+BA,SAAgB,qBAAqB,SAA8C;CACjF,OAAO;EAAE;EAAS,UAAU;GAAE,WAAW,CAAC;GAAG,YAAY,CAAC;EAAE;CAAE;AAChE;;;;;;;AAQA,SAAgB,gBACd,MACA,SACA,UACiB;CAGjB,MAAM,aAAa,SAA8B;EAC/C,MAAM,EAAE,UAAU,MAAM,mBAAmB,KAAK;EAChD,MAAM,SAAS,KAAK,WAAW,KAAA,IAAY,KAAK,OAAO,KAAK,MAAM;EAClE,OAAO,QAAQ,WAAW,OAAO,IAAI,IAAI,SAAS,kBAAkB,QAAU;CAChF;CAEA,MAAM,QAAQ,MAAmB,WAAyC;EACxE,MAAM,EAAE,QAAQ;EAChB,MAAM,EAAE,YAAY,IAAI;EACxB,OAAO;GACL,WAAW,IAAI;GACf,MAAM,OAAO,GAAG;GAChB,MAAM,OAAO,GAAG;GAChB,SAAS,UAAU,GAAG;GACtB,OAAO,SAAS;GAChB,WAAW,IAAI,OAAO;GACtB,WAAW,YAAY,KAAA,IAAY,KAAA,IAAYA,0BAAAA,OAAO,QAAQ,EAAE;GAChE,OAAO,IAAI,OAAO;GAClB,SAAS,IAAI,OAAO,WAAW,KAAA;GAC/B,aAAa,cAAc,GAAG;GAC9B,UAAU,WAAW,GAAG;GACxB,YAAY,KAAK,SAAS;GAC1B,iBAAiB,KAAK;GACtB,uBAAuB,KAAK;GAC5B,kBAAkB,UAAU,IAAI;GAChC,UACE,UAAU,SAAS,IAAI,IAAI,EAAE,IACzB,KAAK,SAAS,KAAK,UAAU,KA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E,EAAE,CAAC,CAAC,CACrC,KAAK,OAAO;EACX,WAAW,EAAE;EACb,UAAU,EAAE;EACZ,OAAO,EAAE;EACT,QAAQ,EAAE,UAAU,KAAA;EACpB,QAAQ,EAAE,UAAU,KAAA;EACpB,IAAIF,0BAAAA,OAAO,EAAE,EAAE;CACjB,EAAE;AACN;AAEA,SAAS,WAAW,KAA4C;CAC9D,OAAO,CAAC,GAAG,IAAI,QAAQ,CAAC,CAAC,MACtB,GAAG,MACF,EAAE,UAAU,cAAc,EAAE,SAAS,KACrC,EAAE,SAAS,cAAc,EAAE,QAAQ,KACnC,EAAE,IAAI,cAAc,EAAE,GAAG,CAC7B;AACF"}
|
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
import { compareNs, nsToMs } from "./block_status_fold.js";
|
|
2
|
+
import { BlockStatusTreeHeaviestCount } from "@milaboratories/pl-model-middle-layer";
|
|
3
|
+
// src/middle_layer/block_status_tree_fold.ts
|
|
4
|
+
/** A tree with no context under it. */
|
|
5
|
+
function emptyBlockStatusTree(summary) {
|
|
6
|
+
return {
|
|
7
|
+
summary,
|
|
8
|
+
heaviest: {
|
|
9
|
+
byCompute: [],
|
|
10
|
+
byContexts: []
|
|
11
|
+
}
|
|
12
|
+
};
|
|
13
|
+
}
|
|
14
|
+
/**
|
|
15
|
+
* The tree of a block run.
|
|
16
|
+
*
|
|
17
|
+
* @param expanded context ids whose children the reader has opened. The root's children are
|
|
18
|
+
* always present.
|
|
19
|
+
*/
|
|
20
|
+
function blockStatusTree(root, summary, expanded) {
|
|
21
|
+
const computeMs = (fold) => {
|
|
22
|
+
const { closedNs, open, openSinceSumNs } = fold.compute;
|
|
23
|
+
const lastNs = root.lastNs === void 0 ? 0n : BigInt(root.lastNs);
|
|
24
|
+
return Number((closedNs + BigInt(open) * lastNs - openSinceSumNs) / 1000000n);
|
|
25
|
+
};
|
|
26
|
+
const node = (fold, isRoot) => {
|
|
27
|
+
const { own } = fold;
|
|
28
|
+
const { holding } = own.folded;
|
|
29
|
+
return {
|
|
30
|
+
contextId: own.id,
|
|
31
|
+
name: nameOf(own),
|
|
32
|
+
kind: kindOf(own),
|
|
33
|
+
baggage: baggageOf(own),
|
|
34
|
+
state: holding?.state,
|
|
35
|
+
onMachine: own.folded.onMachine,
|
|
36
|
+
enteredAt: holding === void 0 ? void 0 : nsToMs(holding.ns),
|
|
37
|
+
ended: own.folded.terminal,
|
|
38
|
+
failure: own.folded.failure || void 0,
|
|
39
|
+
transitions: transitionsOf(own),
|
|
40
|
+
readings: readingsOf(own),
|
|
41
|
+
childCount: fold.children.length,
|
|
42
|
+
subtreeContexts: fold.contexts,
|
|
43
|
+
subtreeActiveContexts: fold.activeContexts,
|
|
44
|
+
subtreeComputeMs: computeMs(fold),
|
|
45
|
+
children: isRoot || expanded.has(own.id) ? fold.children.map((child) => node(child, false)) : void 0
|
|
46
|
+
};
|
|
47
|
+
};
|
|
48
|
+
/** The root's top-level contexts, ranked by one measure. One with nothing to rank is left out. */
|
|
49
|
+
const rank = (value) => root.children.map((child) => ({
|
|
50
|
+
contextId: child.own.id,
|
|
51
|
+
name: nameOf(child.own),
|
|
52
|
+
value: value(child)
|
|
53
|
+
})).filter((b) => b.value > 0).sort((a, b) => b.value - a.value || a.contextId.localeCompare(b.contextId)).slice(0, BlockStatusTreeHeaviestCount);
|
|
54
|
+
return {
|
|
55
|
+
summary,
|
|
56
|
+
heaviest: {
|
|
57
|
+
byCompute: rank(computeMs),
|
|
58
|
+
byContexts: rank((fold) => fold.contexts),
|
|
59
|
+
byFileSize: void 0
|
|
60
|
+
},
|
|
61
|
+
root: node(root, true),
|
|
62
|
+
firstFailurePath: root.failure?.path
|
|
63
|
+
};
|
|
64
|
+
}
|
|
65
|
+
function nameOf(own) {
|
|
66
|
+
const name = own.data?.name;
|
|
67
|
+
return typeof name === "string" && name !== "" ? name : own.id;
|
|
68
|
+
}
|
|
69
|
+
function kindOf(own) {
|
|
70
|
+
const all = own.reports.all;
|
|
71
|
+
if (all.some((t) => t.namespace === "exec")) return "command";
|
|
72
|
+
if (all.length > 0 && all.every((t) => t.namespace === "workdir")) return "workdir";
|
|
73
|
+
return "render";
|
|
74
|
+
}
|
|
75
|
+
function baggageOf(own) {
|
|
76
|
+
const out = {};
|
|
77
|
+
for (const [key, value] of Object.entries(own.data ?? {})) if (key !== "name") out[key] = typeof value === "string" ? value : JSON.stringify(value);
|
|
78
|
+
return out;
|
|
79
|
+
}
|
|
80
|
+
function transitionsOf(own) {
|
|
81
|
+
return [...own.reports.all].sort((a, b) => compareNs(a.ns, b.ns)).map((t) => ({
|
|
82
|
+
namespace: t.namespace,
|
|
83
|
+
reporter: t.reporter,
|
|
84
|
+
state: t.state,
|
|
85
|
+
detail: t.detail || void 0,
|
|
86
|
+
reason: t.reason || void 0,
|
|
87
|
+
at: nsToMs(t.ns)
|
|
88
|
+
}));
|
|
89
|
+
}
|
|
90
|
+
function readingsOf(own) {
|
|
91
|
+
return [...own.readings].sort((a, b) => a.namespace.localeCompare(b.namespace) || a.resource.localeCompare(b.resource) || a.key.localeCompare(b.key));
|
|
92
|
+
}
|
|
93
|
+
export { blockStatusTree, emptyBlockStatusTree };
|
|
94
|
+
|
|
95
|
+
//# sourceMappingURL=block_status_tree_fold.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"block_status_tree_fold.js","names":[],"sources":["../../src/middle_layer/block_status_tree_fold.ts"],"sourcesContent":["/**\n * Builds the {@link BlockStatusTree} of a block run from the {@link SubtreeFold} of its root.\n *\n * Every counter it shows (contexts, active contexts, compute time, the first failure) is already\n * merged into the fold bottom up, so building the tree touches only the root, its top-level\n * contexts and the children of the expanded contexts. It reads nothing from the action-context\n * tree itself.\n *\n * Source: docs/text/work/projects/sdk/block-status/README_teo.md, \"Developer debug panel\".\n */\n\nimport type {\n BlockStatusSummary,\n BlockStatusTree,\n BlockStatusTreeBranch,\n BlockStatusTreeNode,\n BlockStatusTreeReading,\n BlockStatusTreeTransition,\n} from \"@milaboratories/pl-model-middle-layer\";\nimport { BlockStatusTreeHeaviestCount } from \"@milaboratories/pl-model-middle-layer\";\nimport type { ActionContextNode, ContextFold, SubtreeFold } from \"./block_status_fold\";\nimport {\n compareNs,\n ExecNamespace,\n foldSubtree,\n nsToMs,\n summarize,\n WorkdirNamespace,\n} from \"./block_status_fold\";\n\n/** A tree with no context under it. */\nexport function emptyBlockStatusTree(summary: BlockStatusSummary): BlockStatusTree {\n return { summary, heaviest: { byCompute: [], byContexts: [] } };\n}\n\n/**\n * The tree of a block run.\n *\n * @param expanded context ids whose children the reader has opened. The root's children are\n * always present.\n */\nexport function blockStatusTree(\n root: SubtreeFold,\n summary: BlockStatusSummary,\n expanded: ReadonlySet<string>,\n): BlockStatusTree {\n // A command still running is counted up to the run's latest report, not to now: the fold has no\n // clock, and the Desktop App extrapolates the same way for the run's own time.\n const computeMs = (fold: SubtreeFold): number => {\n const { closedNs, open, openSinceSumNs } = fold.compute;\n const lastNs = root.lastNs === undefined ? 0n : BigInt(root.lastNs);\n return Number((closedNs + BigInt(open) * lastNs - openSinceSumNs) / 1_000_000n);\n };\n\n const node = (fold: SubtreeFold, isRoot: boolean): BlockStatusTreeNode => {\n const { own } = fold;\n const { holding } = own.folded;\n return {\n contextId: own.id,\n name: nameOf(own),\n kind: kindOf(own),\n baggage: baggageOf(own),\n state: holding?.state,\n onMachine: own.folded.onMachine,\n enteredAt: holding === undefined ? undefined : nsToMs(holding.ns),\n ended: own.folded.terminal,\n failure: own.folded.failure || undefined,\n transitions: transitionsOf(own),\n readings: readingsOf(own),\n childCount: fold.children.length,\n subtreeContexts: fold.contexts,\n subtreeActiveContexts: fold.activeContexts,\n subtreeComputeMs: computeMs(fold),\n children:\n isRoot || expanded.has(own.id)\n ? fold.children.map((child) => node(child, false))\n : undefined,\n };\n };\n\n /** The root's top-level contexts, ranked by one measure. One with nothing to rank is left out. */\n const rank = (value: (fold: SubtreeFold) => number): BlockStatusTreeBranch[] =>\n root.children\n .map((child) => ({ contextId: child.own.id, name: nameOf(child.own), value: value(child) }))\n .filter((b) => b.value > 0)\n .sort((a, b) => b.value - a.value || a.contextId.localeCompare(b.contextId))\n .slice(0, BlockStatusTreeHeaviestCount);\n\n return {\n summary,\n heaviest: {\n byCompute: rank(computeMs),\n byContexts: rank((fold) => fold.contexts),\n // No reporter writes file sizes yet.\n byFileSize: undefined,\n },\n root: node(root, true),\n firstFailurePath: root.failure?.path,\n };\n}\n\n/** {@link blockStatusTree} over a tree that is read once. */\nexport function foldBlockStatusTree(\n root: ActionContextNode,\n expanded: ReadonlySet<string>,\n): BlockStatusTree {\n const fold = foldSubtree(root);\n return blockStatusTree(fold, summarize(fold), expanded);\n}\n\nfunction nameOf(own: ContextFold): string {\n const name = own.data?.name;\n return typeof name === \"string\" && name !== \"\" ? name : own.id;\n}\n\nfunction kindOf(own: ContextFold): BlockStatusTreeNode[\"kind\"] {\n const all = own.reports.all;\n if (all.some((t) => t.namespace === ExecNamespace)) return \"command\";\n if (all.length > 0 && all.every((t) => t.namespace === WorkdirNamespace)) return \"workdir\";\n return \"render\";\n}\n\nfunction baggageOf(own: ContextFold): Record<string, string> {\n const out: Record<string, string> = {};\n for (const [key, value] of Object.entries(own.data ?? {}))\n if (key !== \"name\") out[key] = typeof value === \"string\" ? value : JSON.stringify(value);\n return out;\n}\n\nfunction transitionsOf(own: ContextFold): BlockStatusTreeTransition[] {\n return [...own.reports.all]\n .sort((a, b) => compareNs(a.ns, b.ns))\n .map((t) => ({\n namespace: t.namespace,\n reporter: t.reporter,\n state: t.state,\n detail: t.detail || undefined,\n reason: t.reason || undefined,\n at: nsToMs(t.ns),\n }));\n}\n\nfunction readingsOf(own: ContextFold): BlockStatusTreeReading[] {\n return [...own.readings].sort(\n (a, b) =>\n a.namespace.localeCompare(b.namespace) ||\n a.resource.localeCompare(b.resource) ||\n a.key.localeCompare(b.key),\n );\n}\n"],"mappings":";;;;AA+BA,SAAgB,qBAAqB,SAA8C;CACjF,OAAO;EAAE;EAAS,UAAU;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cAAc,EAAE,GAAG,CAC7B;AACF"}
|
|
@@ -563,13 +563,33 @@ var Project = class Project {
|
|
|
563
563
|
* watch re-seeds itself onto it.
|
|
564
564
|
*/
|
|
565
565
|
async watchBlockStatus(blockId, mode = "prod") {
|
|
566
|
+
return (await this.retainBlockStatusWatch(blockId, mode)).summary;
|
|
567
|
+
}
|
|
568
|
+
/**
|
|
569
|
+
* Starts watching the action-context tree of a block render, context by context. Takes the same
|
|
570
|
+
* hold as {@link watchBlockStatus}, released by {@link unwatchBlockStatus}, and shares its
|
|
571
|
+
* synchronized tree.
|
|
572
|
+
*/
|
|
573
|
+
async watchBlockStatusTree(blockId, mode = "prod") {
|
|
574
|
+
return (await this.retainBlockStatusWatch(blockId, mode)).tree;
|
|
575
|
+
}
|
|
576
|
+
/**
|
|
577
|
+
* Sets which contexts of {@link watchBlockStatusTree} show their children. A no-op while nobody
|
|
578
|
+
* watches the block: the expansion lives with the watch.
|
|
579
|
+
*/
|
|
580
|
+
async setBlockStatusTreeExpanded(blockId, contextIds, mode = "prod") {
|
|
581
|
+
const pending = this.blockStatusWatches.get(blockStatusKey(blockId, mode));
|
|
582
|
+
if (pending === void 0) return;
|
|
583
|
+
(await pending).setExpanded(contextIds);
|
|
584
|
+
}
|
|
585
|
+
async retainBlockStatusWatch(blockId, mode) {
|
|
566
586
|
if (this.destroyed) throw new Error(`cannot watch the status of ${blockId}: the project is closed`);
|
|
567
587
|
const key = blockStatusKey(blockId, mode);
|
|
568
588
|
const existing = this.blockStatusWatches.get(key);
|
|
569
589
|
if (existing !== void 0) {
|
|
570
590
|
const watch = await existing;
|
|
571
591
|
watch.retain();
|
|
572
|
-
return watch
|
|
592
|
+
return watch;
|
|
573
593
|
}
|
|
574
594
|
const started = require_block_status_tree.BlockStatusWatch.start({
|
|
575
595
|
env: this.env,
|
|
@@ -582,7 +602,7 @@ var Project = class Project {
|
|
|
582
602
|
started.catch(() => {
|
|
583
603
|
if (this.blockStatusWatches.get(key) === started) this.blockStatusWatches.delete(key);
|
|
584
604
|
});
|
|
585
|
-
return
|
|
605
|
+
return await started;
|
|
586
606
|
}
|
|
587
607
|
/**
|
|
588
608
|
* Releases one hold taken by {@link watchBlockStatus}. The tree is terminated when the last
|