@milaboratories/pl-middle-layer 2.10.0 → 2.11.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (181) hide show
  1. package/dist/block_registry/registry-v2-provider.cjs +8 -1
  2. package/dist/block_registry/registry-v2-provider.cjs.map +1 -1
  3. package/dist/block_registry/registry-v2-provider.d.ts.map +1 -1
  4. package/dist/block_registry/registry-v2-provider.js +8 -1
  5. package/dist/block_registry/registry-v2-provider.js.map +1 -1
  6. package/dist/index.cjs +25 -1
  7. package/dist/index.d.ts +12 -5
  8. package/dist/index.js +5 -3
  9. package/dist/js_render/bundle_bytecode_cache.cjs +6 -1
  10. package/dist/js_render/bundle_bytecode_cache.cjs.map +1 -1
  11. package/dist/js_render/bundle_bytecode_cache.js +6 -1
  12. package/dist/js_render/bundle_bytecode_cache.js.map +1 -1
  13. package/dist/js_render/column_registry.cjs +17 -0
  14. package/dist/js_render/column_registry.cjs.map +1 -1
  15. package/dist/js_render/column_registry.js +16 -1
  16. package/dist/js_render/column_registry.js.map +1 -1
  17. package/dist/js_render/computable_context.cjs +1 -1
  18. package/dist/js_render/computable_context.js +1 -1
  19. package/dist/js_render/context.cjs +3 -2
  20. package/dist/js_render/context.cjs.map +1 -1
  21. package/dist/js_render/context.js +3 -2
  22. package/dist/js_render/context.js.map +1 -1
  23. package/dist/js_render/index.cjs +1 -1
  24. package/dist/js_render/index.cjs.map +1 -1
  25. package/dist/js_render/index.js +1 -1
  26. package/dist/js_render/index.js.map +1 -1
  27. package/dist/js_render/service_injectors.cjs +2 -9
  28. package/dist/js_render/service_injectors.cjs.map +1 -1
  29. package/dist/js_render/service_injectors.js +2 -9
  30. package/dist/js_render/service_injectors.js.map +1 -1
  31. package/dist/middle_layer/block.cjs +48 -0
  32. package/dist/middle_layer/block.cjs.map +1 -1
  33. package/dist/middle_layer/block.js +51 -4
  34. package/dist/middle_layer/block.js.map +1 -1
  35. package/dist/middle_layer/block_pack_description.cjs +80 -0
  36. package/dist/middle_layer/block_pack_description.cjs.map +1 -0
  37. package/dist/middle_layer/block_pack_description.d.ts +36 -0
  38. package/dist/middle_layer/block_pack_description.d.ts.map +1 -0
  39. package/dist/middle_layer/block_pack_description.js +78 -0
  40. package/dist/middle_layer/block_pack_description.js.map +1 -0
  41. package/dist/middle_layer/build_stamp.cjs +1 -1
  42. package/dist/middle_layer/build_stamp.js +1 -1
  43. package/dist/middle_layer/index.cjs +11 -0
  44. package/dist/middle_layer/index.d.ts +8 -2
  45. package/dist/middle_layer/index.js +3 -1
  46. package/dist/middle_layer/legacy_project_holds.cjs +61 -0
  47. package/dist/middle_layer/legacy_project_holds.cjs.map +1 -0
  48. package/dist/middle_layer/legacy_project_holds.js +61 -0
  49. package/dist/middle_layer/legacy_project_holds.js.map +1 -0
  50. package/dist/middle_layer/middle_layer.cjs +22 -24
  51. package/dist/middle_layer/middle_layer.cjs.map +1 -1
  52. package/dist/middle_layer/middle_layer.d.ts +13 -3
  53. package/dist/middle_layer/middle_layer.d.ts.map +1 -1
  54. package/dist/middle_layer/middle_layer.js +21 -23
  55. package/dist/middle_layer/middle_layer.js.map +1 -1
  56. package/dist/middle_layer/pool_columns.cjs +160 -0
  57. package/dist/middle_layer/pool_columns.cjs.map +1 -0
  58. package/dist/middle_layer/pool_columns.d.ts +59 -0
  59. package/dist/middle_layer/pool_columns.d.ts.map +1 -0
  60. package/dist/middle_layer/pool_columns.js +157 -0
  61. package/dist/middle_layer/pool_columns.js.map +1 -0
  62. package/dist/middle_layer/pool_frame.cjs +82 -0
  63. package/dist/middle_layer/pool_frame.cjs.map +1 -0
  64. package/dist/middle_layer/pool_frame.d.ts +37 -0
  65. package/dist/middle_layer/pool_frame.d.ts.map +1 -0
  66. package/dist/middle_layer/pool_frame.js +81 -0
  67. package/dist/middle_layer/pool_frame.js.map +1 -0
  68. package/dist/middle_layer/pool_table.cjs +66 -0
  69. package/dist/middle_layer/pool_table.cjs.map +1 -0
  70. package/dist/middle_layer/pool_table.d.ts +27 -0
  71. package/dist/middle_layer/pool_table.d.ts.map +1 -0
  72. package/dist/middle_layer/pool_table.js +66 -0
  73. package/dist/middle_layer/pool_table.js.map +1 -0
  74. package/dist/middle_layer/project.cjs +89 -23
  75. package/dist/middle_layer/project.cjs.map +1 -1
  76. package/dist/middle_layer/project.d.ts +70 -4
  77. package/dist/middle_layer/project.d.ts.map +1 -1
  78. package/dist/middle_layer/project.js +89 -22
  79. package/dist/middle_layer/project.js.map +1 -1
  80. package/dist/middle_layer/rich_column_query.cjs +180 -0
  81. package/dist/middle_layer/rich_column_query.cjs.map +1 -0
  82. package/dist/middle_layer/rich_column_query.d.ts +34 -0
  83. package/dist/middle_layer/rich_column_query.d.ts.map +1 -0
  84. package/dist/middle_layer/rich_column_query.js +176 -0
  85. package/dist/middle_layer/rich_column_query.js.map +1 -0
  86. package/dist/model/args.cjs +23 -0
  87. package/dist/model/args.cjs.map +1 -1
  88. package/dist/model/args.js +24 -2
  89. package/dist/model/args.js.map +1 -1
  90. package/dist/model/args_derivation.cjs +60 -2
  91. package/dist/model/args_derivation.cjs.map +1 -1
  92. package/dist/model/args_derivation.d.ts +73 -3
  93. package/dist/model/args_derivation.d.ts.map +1 -1
  94. package/dist/model/args_derivation.js +60 -3
  95. package/dist/model/args_derivation.js.map +1 -1
  96. package/dist/model/block_pack_spec.cjs.map +1 -1
  97. package/dist/model/block_pack_spec.d.ts +3 -3
  98. package/dist/model/block_pack_spec.d.ts.map +1 -1
  99. package/dist/model/block_pack_spec.js.map +1 -1
  100. package/dist/model/block_params_model.cjs +42 -0
  101. package/dist/model/block_params_model.cjs.map +1 -0
  102. package/dist/model/block_params_model.d.ts +45 -0
  103. package/dist/model/block_params_model.d.ts.map +1 -0
  104. package/dist/model/block_params_model.js +42 -0
  105. package/dist/model/block_params_model.js.map +1 -0
  106. package/dist/model/index.d.ts +3 -1
  107. package/dist/model/project_helper.cjs +50 -6
  108. package/dist/model/project_helper.cjs.map +1 -1
  109. package/dist/model/project_helper.d.ts +25 -1
  110. package/dist/model/project_helper.d.ts.map +1 -1
  111. package/dist/model/project_helper.js +51 -7
  112. package/dist/model/project_helper.js.map +1 -1
  113. package/dist/model/template_spec.d.ts +18 -0
  114. package/dist/model/template_spec.d.ts.map +1 -1
  115. package/dist/mutator/block-pack/block_pack.cjs +90 -3
  116. package/dist/mutator/block-pack/block_pack.cjs.map +1 -1
  117. package/dist/mutator/block-pack/block_pack.d.ts +16 -0
  118. package/dist/mutator/block-pack/block_pack.d.ts.map +1 -1
  119. package/dist/mutator/block-pack/block_pack.js +91 -5
  120. package/dist/mutator/block-pack/block_pack.js.map +1 -1
  121. package/dist/mutator/block-pack/required_capabilities.cjs +16 -0
  122. package/dist/mutator/block-pack/required_capabilities.cjs.map +1 -1
  123. package/dist/mutator/block-pack/required_capabilities.js +16 -1
  124. package/dist/mutator/block-pack/required_capabilities.js.map +1 -1
  125. package/dist/mutator/project.cjs +4 -0
  126. package/dist/mutator/project.cjs.map +1 -1
  127. package/dist/mutator/project.d.ts +1 -1
  128. package/dist/mutator/project.d.ts.map +1 -1
  129. package/dist/mutator/project.js +4 -0
  130. package/dist/mutator/project.js.map +1 -1
  131. package/dist/mutator/template/template_cache.cjs +8 -1
  132. package/dist/mutator/template/template_cache.cjs.map +1 -1
  133. package/dist/mutator/template/template_cache.d.ts +7 -3
  134. package/dist/mutator/template/template_cache.d.ts.map +1 -1
  135. package/dist/mutator/template/template_cache.js +8 -1
  136. package/dist/mutator/template/template_cache.js.map +1 -1
  137. package/package.json +9 -9
  138. package/src/block_registry/registry-v2-provider.test.ts +23 -0
  139. package/src/block_registry/registry-v2-provider.ts +11 -1
  140. package/src/index.ts +2 -0
  141. package/src/js_render/bundle_bytecode_cache.ts +15 -4
  142. package/src/js_render/column_registry.ts +24 -3
  143. package/src/js_render/context.ts +4 -3
  144. package/src/js_render/index.ts +3 -2
  145. package/src/js_render/service_injectors.ts +2 -11
  146. package/src/middle_layer/block.ts +61 -2
  147. package/src/middle_layer/block_pack_description.test.ts +235 -0
  148. package/src/middle_layer/block_pack_description.ts +143 -0
  149. package/src/middle_layer/index.ts +9 -1
  150. package/src/middle_layer/legacy_project_holds.test.ts +133 -0
  151. package/src/middle_layer/legacy_project_holds.ts +73 -0
  152. package/src/middle_layer/middle_layer.ts +27 -28
  153. package/src/middle_layer/pool_columns.test.ts +217 -0
  154. package/src/middle_layer/pool_columns.ts +250 -0
  155. package/src/middle_layer/pool_frame.test.ts +144 -0
  156. package/src/middle_layer/pool_frame.ts +127 -0
  157. package/src/middle_layer/pool_table.test.ts +182 -0
  158. package/src/middle_layer/pool_table.ts +98 -0
  159. package/src/middle_layer/project.ts +135 -32
  160. package/src/middle_layer/rich_column_query.test.ts +311 -0
  161. package/src/middle_layer/rich_column_query.ts +214 -0
  162. package/src/model/args.test.ts +23 -1
  163. package/src/model/args.ts +29 -1
  164. package/src/model/args_derivation.test.ts +129 -12
  165. package/src/model/args_derivation.ts +112 -8
  166. package/src/model/block_pack_spec.ts +3 -2
  167. package/src/model/block_params_model.test.ts +194 -0
  168. package/src/model/block_params_model.ts +117 -0
  169. package/src/model/index.ts +6 -0
  170. package/src/model/project_helper.ts +101 -20
  171. package/src/model/template_spec.ts +21 -0
  172. package/src/mutator/block-pack/block_pack.test.ts +10 -1
  173. package/src/mutator/block-pack/block_pack.ts +102 -2
  174. package/src/mutator/block-pack/block_pack_load.test.ts +52 -0
  175. package/src/mutator/block-pack/required_capabilities.ts +25 -0
  176. package/src/mutator/project-v3.test.ts +27 -16
  177. package/src/mutator/project.ts +5 -0
  178. package/src/mutator/template/template_cache.ts +26 -3
  179. package/src/pool/result_pool_markers.test.ts +47 -0
  180. package/src/test/block_packs.ts +12 -0
  181. package/src/test/fake_project.ts +33 -6
@@ -0,0 +1,250 @@
1
+ import { Computable, type ComputableCtx } from "@milaboratories/computable";
2
+ import type { PlTreeEntry, PlTreeNodeAccessor } from "@milaboratories/pl-tree";
3
+ import { notEmpty } from "@milaboratories/ts-helpers";
4
+ import {
5
+ asBlockId,
6
+ extractPObjectId,
7
+ isColumnDiscoveredKey,
8
+ isColumnFilteredKey,
9
+ isColumnOverriddenKey,
10
+ isPColumnSpec,
11
+ parseColumnIdSafely,
12
+ parseJsonSafely,
13
+ PlRef,
14
+ reconstructSpecFromId,
15
+ Services,
16
+ type AnchorEntry,
17
+ type BlockId,
18
+ type ColumnRegistry,
19
+ type ColumnsCollectionDriver,
20
+ type ColumnsCollectionDriverHost,
21
+ type ColumnSelector,
22
+ type ColumnUniversalId,
23
+ type MatchingMode,
24
+ type PColumnSpec,
25
+ type PObjectId,
26
+ type UpstreamBlockCtx,
27
+ } from "@milaboratories/pl-model-common";
28
+ import { buildColumnRegistry, resolveColumnSpec } from "../js_render/column_registry";
29
+ import type { ProjectStructure } from "../model/project_model";
30
+ import { ProjectStructureKey } from "../model/project_model";
31
+ import { allBlocks } from "../model/project_model_util";
32
+ import { collectUpstreamBlockCtx } from "../pool/upstream_block_ctx";
33
+ import type { MiddleLayerEnvironment } from "./middle_layer";
34
+
35
+ /** One column of a project's result pool: its spec and how a block points at it. */
36
+ export interface PoolColumn {
37
+ /**
38
+ * The id a block's model gets for the column from `ColumnsCollection(["result_pool"])`: the
39
+ * `GlobalPObjectId` of an exported column, or, found from anchors, a discovered id around it.
40
+ */
41
+ readonly columnId: ColumnUniversalId;
42
+ /**
43
+ * The reference a block stores in its data or args to point at the column: the object form of
44
+ * `columnId`, set only when `columnId` is the `GlobalPObjectId` of an exported column.
45
+ */
46
+ readonly ref?: PlRef;
47
+ /** The name under which the block exports the column the id comes down to. */
48
+ readonly exportName: string;
49
+ /** Of a discovered id: the ids of the linker columns it was reached through, in order. */
50
+ readonly path?: ColumnUniversalId[];
51
+ /** The block that exports the column the id comes down to. */
52
+ readonly producedBy: BlockId;
53
+ /** The spec the id stands for: the exported spec with what the id changes in it applied. */
54
+ readonly spec: PColumnSpec;
55
+ }
56
+
57
+ /** The result-pool columns of a project, as {@link poolColumns} lists them. */
58
+ export interface PoolColumns {
59
+ readonly columns: PoolColumn[];
60
+ /**
61
+ * False while a block whose results the view covers is still being calculated: more columns
62
+ * may come.
63
+ */
64
+ readonly isComplete: boolean;
65
+ }
66
+
67
+ /** Which columns of the result pool {@link poolColumns} lists. */
68
+ export interface PoolColumnsQuery {
69
+ /**
70
+ * List the pool as this block sees it: the columns exported by the block and every block above
71
+ * it. Default: as the last block of the project sees it, which is every block's columns.
72
+ */
73
+ readonly viewAs?: BlockId;
74
+ /**
75
+ * Keep only columns matching these selectors, as a block model passes them to
76
+ * `ColumnsCollection(["result_pool"]).filter({ include })`.
77
+ */
78
+ readonly include?: ColumnSelector;
79
+ /** Drop columns matching these selectors, as `filter({ exclude })` does. */
80
+ readonly exclude?: ColumnSelector;
81
+ /**
82
+ * List the columns reachable from these columns, through linker columns too, as
83
+ * `ColumnsCollection(["result_pool"]).discover({ anchors })` does: with discovered ids.
84
+ */
85
+ readonly anchors?: Record<string, AnchorEntry>;
86
+ /** How axes of a discovered column may match the anchors' (default `enrichment`). */
87
+ readonly mode?: MatchingMode;
88
+ /** The most linker columns between an anchor and a discovered column (default 4). */
89
+ readonly maxHops?: number;
90
+ }
91
+
92
+ /** What {@link poolColumns} reads besides the project tree. */
93
+ export type PoolColumnsEnv = Pick<MiddleLayerEnvironment, "serviceRegistry">;
94
+
95
+ /**
96
+ * The columns of a project's result pool with their specs, no data, as a block's model gets them
97
+ * from `ColumnsCollection(["result_pool"])`, filtered the way its `filter` does. Computed only when
98
+ * its value is asked for; reads the order of the blocks and the results of the blocks in view.
99
+ *
100
+ * @throws (from the value) when `viewAs` is not a block of the project
101
+ */
102
+ export function poolColumns(
103
+ prjEntry: PlTreeEntry,
104
+ query: PoolColumnsQuery,
105
+ env: PoolColumnsEnv,
106
+ ): Computable<PoolColumns> {
107
+ return Computable.make((ctx) => {
108
+ const upstream = poolView(ctx, prjEntry, query.viewAs);
109
+ if (upstream === undefined) return { columns: [], isComplete: true };
110
+ const registry = buildColumnRegistry({ upstreamBlockCtxes: upstream });
111
+ const host: ColumnsCollectionDriverHost<PlTreeNodeAccessor> = {
112
+ resolveAccessor: () => {
113
+ throw new Error("A result pool listing has no accessor sources.");
114
+ },
115
+ getUpstreamBlockCtxes: () => upstream,
116
+ getSpecDriver: () =>
117
+ notEmpty(env.serviceRegistry.get(Services.PFrameSpec), "PFrameSpec service"),
118
+ resolveSpec: (id) => resolveColumnSpec(registry, id),
119
+ };
120
+ const driver: ColumnsCollectionDriver = notEmpty(
121
+ env.serviceRegistry.get(Services.ColumnsCollection),
122
+ "ColumnsCollection service",
123
+ );
124
+
125
+ using pool = driver.create([{ kind: "result_pool" }], host);
126
+ const isComplete = driver.isFinal(pool.key);
127
+ let ids: ColumnUniversalId[];
128
+ if (query.anchors !== undefined) {
129
+ using discovered = driver.discover(
130
+ pool.key,
131
+ {
132
+ include: query.include,
133
+ exclude: query.exclude,
134
+ anchors: query.anchors,
135
+ mode: query.mode ?? "enrichment",
136
+ maxHops: query.maxHops ?? 4,
137
+ },
138
+ host,
139
+ );
140
+ ids = driver.getColumns(discovered.key, host);
141
+ } else if (query.include === undefined && query.exclude === undefined) {
142
+ ids = driver.getColumns(pool.key, host);
143
+ } else {
144
+ using filtered = driver.filter(
145
+ pool.key,
146
+ { include: query.include, exclude: query.exclude },
147
+ host,
148
+ );
149
+ ids = driver.getColumns(filtered.key, host);
150
+ }
151
+
152
+ const columns: PoolColumn[] = [];
153
+ for (const id of ids) {
154
+ const column = poolColumnOf(registry, id);
155
+ if (column !== undefined) columns.push(column);
156
+ }
157
+ return { columns, isComplete };
158
+ });
159
+ }
160
+
161
+ /**
162
+ * The pool columns `ids` stand for, each looked up by its id as `viewAs` sees the pool, in the order
163
+ * of `ids`; `undefined` for an id that is no column of that pool. Unlike {@link poolColumns}, which
164
+ * lists one of several columns with the same spec, this finds each of them by its id.
165
+ *
166
+ * @throws (from the value) when `viewAs` is not a block of the project
167
+ */
168
+ export function poolColumnsById(
169
+ prjEntry: PlTreeEntry,
170
+ ids: readonly ColumnUniversalId[],
171
+ viewAs: BlockId | undefined,
172
+ ): Computable<(PoolColumn | undefined)[]> {
173
+ return Computable.make((ctx) => {
174
+ const upstream = poolView(ctx, prjEntry, viewAs);
175
+ if (upstream === undefined) return ids.map(() => undefined);
176
+ const registry = buildColumnRegistry({ upstreamBlockCtxes: upstream });
177
+ return ids.map((id) => {
178
+ try {
179
+ return poolColumnOf(registry, id);
180
+ } catch {
181
+ // An id whose layers do not fit the column, e.g. a filter of an axis it does not have.
182
+ return undefined;
183
+ }
184
+ });
185
+ });
186
+ }
187
+
188
+ /**
189
+ * The pool column `id` stands for: the column of the registry its leaf is, with the spec the id
190
+ * makes of it. `undefined` when the leaf is not a column a block exports, or has no spec yet.
191
+ */
192
+ function poolColumnOf(
193
+ registry: ColumnRegistry<PlTreeNodeAccessor>,
194
+ id: ColumnUniversalId,
195
+ ): PoolColumn | undefined {
196
+ const leaf = extractPObjectId(id);
197
+ const leafRef = poolRefOf(leaf);
198
+ if (leafRef === undefined) return undefined;
199
+ const leafSpec = resolveColumnSpec(registry, leaf);
200
+ if (leafSpec === undefined || !isPColumnSpec(leafSpec)) return undefined;
201
+ const path = linkerPath(id);
202
+ return {
203
+ columnId: id,
204
+ ...(id === leaf ? { ref: leafRef } : {}),
205
+ exportName: leafRef.name,
206
+ ...(path !== undefined ? { path } : {}),
207
+ producedBy: asBlockId(leafRef.blockId),
208
+ spec: reconstructSpecFromId(leafSpec, id),
209
+ };
210
+ }
211
+
212
+ /**
213
+ * The ids of the linker columns a discovered id was reached through, read through the filtered
214
+ * and overridden ids wrapped around it; `undefined` for an id with no discovered layer or no path.
215
+ */
216
+ function linkerPath(id: ColumnUniversalId): ColumnUniversalId[] | undefined {
217
+ let key = parseColumnIdSafely(id);
218
+ while (isColumnFilteredKey(key) || isColumnOverriddenKey(key))
219
+ key = parseColumnIdSafely(key.source);
220
+ if (!isColumnDiscoveredKey(key) || key.path === undefined || key.path.length === 0)
221
+ return undefined;
222
+ return key.path.map((step) => step.column);
223
+ }
224
+
225
+ /**
226
+ * The contexts of the blocks whose results the pool holds as `viewAs` sees it: the block and every
227
+ * block above it; by default the last block of the project, which sees every block's results.
228
+ * `undefined` for a project with no blocks.
229
+ *
230
+ * @throws when `viewAs` is not a block of the project
231
+ */
232
+ export function poolView(
233
+ ctx: ComputableCtx,
234
+ prjEntry: PlTreeEntry,
235
+ viewAs: BlockId | undefined,
236
+ ): UpstreamBlockCtx<PlTreeNodeAccessor>[] | undefined {
237
+ const prj = ctx.accessor(prjEntry).node();
238
+ const structure = notEmpty(prj.getKeyValueAsJson<ProjectStructure>(ProjectStructureKey));
239
+ const blockIds = [...allBlocks(structure)].map((b) => b.id);
240
+ const block = viewAs ?? blockIds.at(-1);
241
+ if (block === undefined) return undefined;
242
+ if (!blockIds.includes(block)) throw new Error(`Block ${block} not found in the project.`);
243
+ return collectUpstreamBlockCtx(ctx, prjEntry, block);
244
+ }
245
+
246
+ /** The reference a result-pool column id stands for: the id is that reference as canonical JSON. */
247
+ export function poolRefOf(columnId: PObjectId): PlRef | undefined {
248
+ const parsed = PlRef.safeParse(parseJsonSafely(columnId));
249
+ return parsed.success ? parsed.data : undefined;
250
+ }
@@ -0,0 +1,144 @@
1
+ import {
2
+ createColumnFilteredId,
3
+ createColumnOverriddenId,
4
+ createGlobalPObjectId,
5
+ stringifyColumnDiscoveredId,
6
+ type PColumnSpec,
7
+ type PFrameHandle,
8
+ } from "@milaboratories/pl-model-common";
9
+ import { describe, expect, test } from "vitest";
10
+ import { FakeProject, type Columns } from "../test/fake_project";
11
+ import { poolFrame, type PoolFrameEnv } from "./pool_frame";
12
+
13
+ const SPEC: PColumnSpec = {
14
+ kind: "PColumn",
15
+ name: "pl7.app/test/value",
16
+ valueType: "Int",
17
+ axesSpec: [{ name: "sample", type: "String" }],
18
+ };
19
+
20
+ const HANDLE = "b".repeat(64) as PFrameHandle;
21
+
22
+ /**
23
+ * A driver that records the column ids and specs of each frame it builds and counts its
24
+ * references.
25
+ */
26
+ function fakeEnv() {
27
+ const built: string[][] = [];
28
+ const specs: PColumnSpec[][] = [];
29
+ const counts = { refs: 0 };
30
+ const env: PoolFrameEnv = {
31
+ driverKit: {
32
+ pFrameDriver: {
33
+ createPFrame: (def) => {
34
+ built.push(def.map((c) => c.id));
35
+ specs.push(def.map((c) => c.spec));
36
+ counts.refs++;
37
+ const unref = () => void counts.refs--;
38
+ return { key: HANDLE, resource: {}, unref, [Symbol.dispose]: unref };
39
+ },
40
+ },
41
+ },
42
+ };
43
+ return { env, built, specs, counts };
44
+ }
45
+
46
+ /** A project of two blocks that export one column each, `a` and `b`, as `columns` say. */
47
+ function project(a: Columns[string], b: Columns[string]) {
48
+ const prj = new FakeProject();
49
+ prj.block("one", { prodCtx: prj.value("BContext", {}), prodUiCtx: prj.frame({ value: a }) });
50
+ prj.block("two", { prodCtx: prj.value("BContext", {}), prodUiCtx: prj.frame({ value: b }) });
51
+ return prj;
52
+ }
53
+
54
+ const A = createGlobalPObjectId("one", "value");
55
+ const B = createGlobalPObjectId("two", "value");
56
+
57
+ describe("poolFrame", () => {
58
+ test("builds a frame whose columns keep the ids they were asked by, released on reset", async () => {
59
+ const prj = project({ spec: SPEC, cells: ["1"] }, { spec: SPEC, cells: ["2"] });
60
+ const { env, built, counts } = fakeEnv();
61
+ const discovered = stringifyColumnDiscoveredId({
62
+ column: B,
63
+ path: [{ type: "linker", column: A }],
64
+ });
65
+ const frame = poolFrame(prj.tree().entry(), [A, discovered], env);
66
+
67
+ expect(await frame.getValue()).toEqual({ type: "ok", handle: HANDLE });
68
+ expect(built).toEqual([[A, discovered]]);
69
+ expect(counts.refs).toBe(1);
70
+
71
+ frame.resetState();
72
+ expect(counts.refs).toBe(0);
73
+ });
74
+
75
+ test("a column of an overridden id has the spec the id gives, a bare id the exported one", async () => {
76
+ const prj = project({ spec: SPEC, cells: ["1"] }, { spec: SPEC, cells: ["2"] });
77
+ const { env, built, specs } = fakeEnv();
78
+ const renamed = createColumnOverriddenId({
79
+ source: A,
80
+ specOverrides: { axesSpec: { 0: { name: "donor" } }, annotations: { a: "b" } },
81
+ });
82
+ const discovered = stringifyColumnDiscoveredId({ column: renamed });
83
+ const frame = poolFrame(prj.tree().entry(), [renamed, discovered, B], env);
84
+
85
+ expect(await frame.getValue()).toEqual({ type: "ok", handle: HANDLE });
86
+ expect(built).toEqual([[renamed, discovered, B]]);
87
+ const overridden: PColumnSpec = {
88
+ ...SPEC,
89
+ annotations: { a: "b" },
90
+ axesSpec: [{ name: "donor", type: "String" }],
91
+ };
92
+ expect(specs).toEqual([[overridden, overridden, SPEC]]);
93
+ frame.resetState();
94
+ });
95
+
96
+ test("refuses unknown columns and columns without ready data, building nothing", async () => {
97
+ const prj = project(
98
+ { spec: SPEC, cells: ["1"], data: "notReady" },
99
+ { spec: SPEC, cells: ["2"], data: "missing" },
100
+ );
101
+ const { env, built } = fakeEnv();
102
+ const unknown = createGlobalPObjectId("three", "value");
103
+ const value = await poolFrame(prj.tree().entry(), [A, B, unknown], env).getValue();
104
+
105
+ expect(value).toEqual({
106
+ type: "refused",
107
+ refused: [
108
+ { columnId: A, issue: "notReady" },
109
+ { columnId: B, issue: "noData" },
110
+ { columnId: unknown, issue: "unknown" },
111
+ ],
112
+ });
113
+ expect(built).toEqual([]);
114
+ });
115
+
116
+ test("refuses a column whose data is an error", async () => {
117
+ const prj = project({ spec: SPEC, cells: ["1"] }, { spec: SPEC, cells: ["2"], data: "failed" });
118
+ const { env, built } = fakeEnv();
119
+ const value = await poolFrame(prj.tree().entry(), [A, B], env).getValue();
120
+
121
+ expect(value).toMatchObject({
122
+ type: "refused",
123
+ refused: [{ columnId: B, issue: "failed", message: expect.stringContaining("boom") }],
124
+ });
125
+ expect(built).toEqual([]);
126
+ });
127
+
128
+ test("refuses an id that filters an axis, also inside a discovered id", async () => {
129
+ const prj = project({ spec: SPEC, cells: ["1"] }, { spec: SPEC, cells: ["2"] });
130
+ const { env, built } = fakeEnv();
131
+ const filtered = createColumnFilteredId({ source: A, axisFilters: [[0, "s0"]] });
132
+ const wrapped = stringifyColumnDiscoveredId({ column: filtered });
133
+ const value = await poolFrame(prj.tree().entry(), [filtered, wrapped, B], env).getValue();
134
+
135
+ expect(value).toEqual({
136
+ type: "refused",
137
+ refused: [
138
+ { columnId: filtered, issue: "filtered" },
139
+ { columnId: wrapped, issue: "filtered" },
140
+ ],
141
+ });
142
+ expect(built).toEqual([]);
143
+ });
144
+ });
@@ -0,0 +1,127 @@
1
+ import { Computable } from "@milaboratories/computable";
2
+ import type { PlTreeEntry, PlTreeNodeAccessor } from "@milaboratories/pl-tree";
3
+ import {
4
+ extractPObjectId,
5
+ PoolEntryGuard,
6
+ type ColumnRegistry,
7
+ type ColumnUniversalId,
8
+ type PFrameHandle,
9
+ } from "@milaboratories/pl-model-common";
10
+ import {
11
+ buildColumnRegistry,
12
+ hasAxisFilters,
13
+ resolveColumnSpec,
14
+ resolvePFrameColumnById,
15
+ } from "../js_render/column_registry";
16
+ import type { InternalPFrameDriver } from "../pool/driver";
17
+ import { poolView } from "./pool_columns";
18
+
19
+ /**
20
+ * Why a column of the result pool cannot be read:
21
+ * - `unknown`: no block of the project exports a column with this id;
22
+ * - `noData`: the column has a spec but no data, e.g. it comes from a block's pre-run only, or its
23
+ * block has not run;
24
+ * - `notReady`: its spec or data is still being calculated;
25
+ * - `failed`: its data is an error.
26
+ */
27
+ export type PoolColumnIssue = "unknown" | "noData" | "notReady" | "failed";
28
+
29
+ /** What keeps a column of the result pool from being read, as {@link poolColumnProblem} says. */
30
+ export interface PoolColumnProblem {
31
+ readonly issue: PoolColumnIssue;
32
+ /** The error of a `failed` column. */
33
+ readonly message?: string;
34
+ }
35
+
36
+ /**
37
+ * What keeps the column `id` stands for from being read; `undefined` for a column ready to read.
38
+ * Its readiness is that of its leaf, the exported column the id comes down to.
39
+ */
40
+ export function poolColumnProblem(
41
+ registry: ColumnRegistry<PlTreeNodeAccessor>,
42
+ id: ColumnUniversalId,
43
+ ): PoolColumnProblem | undefined {
44
+ const leafId = extractPObjectId(id);
45
+ const leaf = registry.resolve(leafId);
46
+ if (leaf === undefined) return { issue: "unknown" };
47
+ if (resolveColumnSpec(registry, leafId) === undefined) return { issue: "notReady" };
48
+ const data = leaf.accessor.traverseOrError({
49
+ field: `${leaf.name}.data`,
50
+ assertFieldType: "Input",
51
+ allowPermanentAbsence: true,
52
+ });
53
+ // A result list still open may get the field yet.
54
+ if (data === undefined) return { issue: leaf.accessor.getInputsLocked() ? "noData" : "notReady" };
55
+ if (!data.ok) return { issue: "failed", message: data.error.message };
56
+ if (!data.value.getIsReadyOrError()) return { issue: "notReady" };
57
+ const error = data.value.getError();
58
+ if (error !== undefined)
59
+ return { issue: "failed", message: error.getDataAsString() ?? "the data is an error" };
60
+ return undefined;
61
+ }
62
+
63
+ /**
64
+ * Why {@link poolFrame} refused a column: a {@link PoolColumnIssue}, or `filtered` for an id that
65
+ * filters an axis, whose values would be those of the whole column it filters.
66
+ */
67
+ export type PoolFrameIssue = PoolColumnIssue | "filtered";
68
+
69
+ /** A column {@link poolFrame} refused, and why. */
70
+ export interface PoolFrameRefusal {
71
+ readonly columnId: ColumnUniversalId;
72
+ readonly issue: PoolFrameIssue;
73
+ /** The error of a `failed` column. */
74
+ readonly message?: string;
75
+ }
76
+
77
+ /**
78
+ * What {@link poolFrame} computes: the handle of the frame, or, with nothing built, the columns it
79
+ * refused.
80
+ */
81
+ export type PoolFrame =
82
+ | { readonly type: "ok"; readonly handle: PFrameHandle }
83
+ | { readonly type: "refused"; readonly refused: readonly PoolFrameRefusal[] };
84
+
85
+ /** What {@link poolFrame} uses besides the project tree: the driver that builds the frame. */
86
+ export type PoolFrameEnv = {
87
+ readonly driverKit: { readonly pFrameDriver: Pick<InternalPFrameDriver, "createPFrame"> };
88
+ };
89
+
90
+ /**
91
+ * A PFrame over columns of a project's result pool, by the ids {@link poolColumns} lists, with no
92
+ * block involved: what reads the values of a pool column. Each column of the frame has the id it
93
+ * was asked by, so values read from it are named after that id, and the spec that id gives, the
94
+ * one {@link poolColumns} lists: an overridden id renames axes in the frame too.
95
+ *
96
+ * Every column must be ready: an unknown column, one whose data is missing, still being calculated
97
+ * or failed, and one whose id filters an axis are refused, and nothing is built.
98
+ *
99
+ * The frame is made when the value is first asked for and lives as long as the computable's state:
100
+ * `resetState()` releases it. Ask for the value once.
101
+ */
102
+ export function poolFrame(
103
+ prjEntry: PlTreeEntry,
104
+ ids: readonly ColumnUniversalId[],
105
+ env: PoolFrameEnv,
106
+ ): Computable<PoolFrame> {
107
+ return Computable.make((ctx): PoolFrame => {
108
+ const registry = buildColumnRegistry({
109
+ upstreamBlockCtxes: poolView(ctx, prjEntry, undefined) ?? [],
110
+ });
111
+ const unique = [...new Set(ids)];
112
+ const refused = unique.flatMap((columnId): PoolFrameRefusal[] => {
113
+ if (hasAxisFilters(columnId)) return [{ columnId, issue: "filtered" }];
114
+ const problem = poolColumnProblem(registry, columnId);
115
+ return problem === undefined ? [] : [{ columnId, ...problem }];
116
+ });
117
+ if (refused.length > 0) return { type: "refused", refused };
118
+
119
+ using guard = new PoolEntryGuard(
120
+ env.driverKit.pFrameDriver.createPFrame(
121
+ unique.map((id) => resolvePFrameColumnById(registry, id)),
122
+ ),
123
+ );
124
+ ctx.addOnDestroy(guard.entry.unref);
125
+ return { type: "ok", handle: guard.keep().key };
126
+ });
127
+ }