@milaboratories/pl-middle-layer 2.9.1 → 2.10.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 (35) hide show
  1. package/dist/index.cjs +4 -0
  2. package/dist/index.d.ts +2 -1
  3. package/dist/index.js +2 -1
  4. package/dist/middle_layer/build_stamp.cjs +1 -1
  5. package/dist/middle_layer/build_stamp.js +1 -1
  6. package/dist/middle_layer/index.cjs +4 -0
  7. package/dist/middle_layer/index.d.ts +2 -1
  8. package/dist/middle_layer/index.js +2 -1
  9. package/dist/middle_layer/middle_layer.cjs +96 -28
  10. package/dist/middle_layer/middle_layer.cjs.map +1 -1
  11. package/dist/middle_layer/middle_layer.d.ts +54 -8
  12. package/dist/middle_layer/middle_layer.d.ts.map +1 -1
  13. package/dist/middle_layer/middle_layer.js +96 -28
  14. package/dist/middle_layer/middle_layer.js.map +1 -1
  15. package/dist/middle_layer/project.cjs +39 -17
  16. package/dist/middle_layer/project.cjs.map +1 -1
  17. package/dist/middle_layer/project.d.ts +17 -2
  18. package/dist/middle_layer/project.d.ts.map +1 -1
  19. package/dist/middle_layer/project.js +39 -17
  20. package/dist/middle_layer/project.js.map +1 -1
  21. package/dist/middle_layer/project_holds.cjs +266 -0
  22. package/dist/middle_layer/project_holds.cjs.map +1 -0
  23. package/dist/middle_layer/project_holds.d.ts +50 -0
  24. package/dist/middle_layer/project_holds.d.ts.map +1 -0
  25. package/dist/middle_layer/project_holds.js +262 -0
  26. package/dist/middle_layer/project_holds.js.map +1 -0
  27. package/package.json +6 -6
  28. package/src/middle_layer/index.ts +2 -0
  29. package/src/middle_layer/middle_layer.ts +117 -38
  30. package/src/middle_layer/project.ts +40 -15
  31. package/src/middle_layer/project_close_during_write.test.ts +142 -0
  32. package/src/middle_layer/project_handles.test.ts +168 -0
  33. package/src/middle_layer/project_holds.ts +359 -0
  34. package/src/middle_layer/project_slots.test.ts +331 -0
  35. package/src/test/write_tx_hooks.ts +75 -0
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@milaboratories/pl-middle-layer",
3
- "version": "2.9.1",
3
+ "version": "2.10.0",
4
4
  "description": "Pl Middle Layer",
5
5
  "keywords": [],
6
6
  "license": "UNLICENSED",
@@ -22,8 +22,8 @@
22
22
  "@milaboratories/columns-collection-driver": "0.3.4",
23
23
  "@milaboratories/computable": "2.9.10",
24
24
  "@milaboratories/helpers": "1.14.7",
25
- "@milaboratories/pf-driver": "1.9.24",
26
- "@milaboratories/pf-spec-driver": "1.6.6",
25
+ "@milaboratories/pf-driver": "1.9.25",
26
+ "@milaboratories/pf-spec-driver": "1.6.7",
27
27
  "@milaboratories/pframes-rs-node": "1.3.1",
28
28
  "@milaboratories/pl-client": "3.28.2",
29
29
  "@milaboratories/pl-crash-recorder": "0.3.16",
@@ -32,12 +32,12 @@
32
32
  "@milaboratories/pl-http": "1.2.7",
33
33
  "@milaboratories/pl-model-backend": "1.4.58",
34
34
  "@milaboratories/pl-model-common": "1.60.0",
35
- "@milaboratories/pl-model-middle-layer": "1.41.4",
35
+ "@milaboratories/pl-model-middle-layer": "1.41.5",
36
36
  "@milaboratories/pl-tree": "1.18.13",
37
37
  "@milaboratories/resolve-helper": "1.1.3",
38
38
  "@milaboratories/ts-helpers": "1.9.1",
39
- "@platforma-sdk/block-tools": "2.22.5",
40
- "@platforma-sdk/model": "1.96.1",
39
+ "@platforma-sdk/block-tools": "2.22.6",
40
+ "@platforma-sdk/model": "1.96.4",
41
41
  "@platforma-sdk/workflow-tengo": "7.2.0",
42
42
  "canonicalize": "~2.1.0",
43
43
  "denque": "^2.1.0",
@@ -1,6 +1,8 @@
1
1
  export { MiddleLayer } from "./middle_layer";
2
2
  export { Project } from "./project";
3
3
  export type { AddBlockOps } from "./project";
4
+ export type { ProjectHandle, ProjectHandleEnd, ProjectHolder } from "./project_holds";
5
+ export { asProjectHolder, isProjectInUseError, ProjectInUseError } from "./project_holds";
4
6
  export * from "./driver_kit";
5
7
  export * from "./ops";
6
8
  export type { TreeSnapshotMiss, TreeSnapshotStat } from "./tree_snapshot_store";
@@ -134,6 +134,8 @@ import { HmacSha256Signer } from "@milaboratories/ts-helpers";
134
134
  import type { Computable, ComputableStableDefined } from "@milaboratories/computable";
135
135
  import { WatchableValue } from "@milaboratories/computable";
136
136
  import { Project } from "./project";
137
+ import type { ProjectHandle, ProjectHolder } from "./project_holds";
138
+ import { asProjectHolder, ProjectSlots } from "./project_holds";
137
139
  import type { MiddleLayerOps, MiddleLayerOpsConstructor } from "./ops";
138
140
  import { DefaultMiddleLayerOpsPaths, DefaultMiddleLayerOpsSettings } from "./ops";
139
141
  import { randomUUID } from "node:crypto";
@@ -177,6 +179,9 @@ import { TreeSnapshotStore } from "./tree_snapshot_store";
177
179
  * filesystem does not hold the quit open. */
178
180
  const SNAPSHOT_DRAIN_TIMEOUT_MS = 5_000;
179
181
 
182
+ /** The holder of the holds {@link MiddleLayer.openProject} takes. */
183
+ const LEGACY_HOLDER = asProjectHolder("legacy");
184
+
180
185
  export interface MiddleLayerEnvironment {
181
186
  dispose(): Promise<void>;
182
187
  readonly pl: PlClient;
@@ -542,7 +547,9 @@ export class MiddleLayer {
542
547
  // resource nothing holds any more.
543
548
  for (const id of outcome.removal.projects) this.projectIdCache.delete(id);
544
549
  for (const id of outcome.removal.templates) this.templateIdCache.delete(id);
550
+ // The removed projects are taken from whoever holds them.
545
551
  await Promise.all([
552
+ ...outcome.removal.projects.map((id) => this.projectSlots.evict(id, "deleted")),
546
553
  this.foldersTree.refreshState(),
547
554
  this.projectListTree.refreshState(),
548
555
  this.templateListTree.refreshState(),
@@ -1149,15 +1156,33 @@ export class MiddleLayer {
1149
1156
  }
1150
1157
 
1151
1158
  /** Permanently deletes project from the project list, this will result in
1152
- * destruction of all attached objects, like files, analysis results etc. */
1153
- public async deleteProject(id: ProjectId): Promise<void> {
1154
- await this.pl.withWriteTx("MLRemoveProject", async (tx) => {
1155
- const entry = (await listedById(tx, this.projectListResourceId)).get(id);
1156
- if (entry === undefined) throw notListedError("Project", id);
1157
- tx.removeField(field(this.projectListResourceId, entry.fieldName));
1158
- await tx.commit();
1159
- });
1160
- this.projectIdCache.delete(id);
1159
+ * destruction of all attached objects, like files, analysis results etc.
1160
+ *
1161
+ * A loaded project is taken from every holder: each {@link ProjectHandle} ends with `deleted`
1162
+ * and the project is destroyed, with no snapshot. Holds do not prevent the delete unless
1163
+ * `refuseIfHeldBy` is given. Holds taken during the delete end with it too.
1164
+ *
1165
+ * @param options.refuseIfHeldBy refuse the delete when it returns `true` for the label of any
1166
+ * holder of the project.
1167
+ * @throws {@link ProjectInUseError} when refused; the project is left as it was
1168
+ */
1169
+ public async deleteProject(
1170
+ id: ProjectId,
1171
+ options: { refuseIfHeldBy?: (holder: ProjectHolder) => boolean } = {},
1172
+ ): Promise<void> {
1173
+ await this.projectSlots.delete(
1174
+ id,
1175
+ async () => {
1176
+ await this.pl.withWriteTx("MLRemoveProject", async (tx) => {
1177
+ const entry = (await listedById(tx, this.projectListResourceId)).get(id);
1178
+ if (entry === undefined) throw notListedError("Project", id);
1179
+ tx.removeField(field(this.projectListResourceId, entry.fieldName));
1180
+ await tx.commit();
1181
+ });
1182
+ this.projectIdCache.delete(id);
1183
+ },
1184
+ options.refuseIfHeldBy,
1185
+ );
1161
1186
  await this.projectListTree.refreshState();
1162
1187
  }
1163
1188
 
@@ -1773,9 +1798,22 @@ export class MiddleLayer {
1773
1798
  // Projects
1774
1799
  //
1775
1800
 
1776
- private readonly openedProjects = new Map<ProjectId, Project>();
1777
-
1778
- /** Snapshot writes started by {@link closeProject} and not yet finished. Held only so
1801
+ /** The loaded projects and who holds them. */
1802
+ private readonly projectSlots = new ProjectSlots<Project>({
1803
+ load: async (id, onGone) =>
1804
+ await Project.init(this.env, id, await this.resolveProjectId(id), onGone),
1805
+ trackSnapshotWrite: (write) => this.trackSnapshotWrite(write),
1806
+ publish: (open) => this.openedProjectsList.setValue(open),
1807
+ logger: {
1808
+ info: (msg) => this.env.logger.info(msg),
1809
+ warn: (msg) => this.env.logger.warn(msg),
1810
+ },
1811
+ });
1812
+
1813
+ /** The holds taken by {@link openProject}, one per project, released by {@link closeProject}. */
1814
+ private readonly legacyHolds = new Map<ProjectId, ProjectHandle>();
1815
+
1816
+ /** Snapshot writes started by a project close and not yet finished. Held only so
1779
1817
  * {@link close} can give them a bounded chance to land. */
1780
1818
  private readonly pendingSnapshotWrites = new Set<Promise<void>>();
1781
1819
 
@@ -1805,43 +1843,84 @@ export class MiddleLayer {
1805
1843
  }
1806
1844
  }
1807
1845
 
1808
- /** Opens a project, and starts corresponding project maintenance loop. */
1809
- public async openProject(id: ProjectId): Promise<void> {
1810
- if (this.openedProjects.has(id)) throw new Error(`Project ${id} already opened`);
1811
- const rid = await this.resolveProjectId(id);
1812
- this.openedProjects.set(id, await Project.init(this.env, id, rid));
1813
- this.openedProjectsList.setValue([...this.openedProjects.keys()]);
1846
+ /**
1847
+ * Takes a hold on a project, loading it when nobody holds it yet. The project stays loaded until
1848
+ * every hold is released, and is taken from all holders when it is deleted or the middle layer
1849
+ * closes; the handle's `signal` says when and why.
1850
+ *
1851
+ * Concurrent acquires share one load. An acquire while the project is being destroyed waits for
1852
+ * the destroy and loads the project anew, so there is never more than one {@link Project} per id.
1853
+ *
1854
+ * @param holder label for logs and {@link projectHolders}, e.g. `desktop` or `mcp:<instance>`
1855
+ * @throws when the project is not in the project list, its load fails, or the middle layer is
1856
+ * closed
1857
+ */
1858
+ public async acquireProject(id: ProjectId, holder: ProjectHolder): Promise<ProjectHandle> {
1859
+ return await this.projectSlots.acquire(id, holder);
1814
1860
  }
1815
1861
 
1816
- /** Closes the project, and deallocate all corresponding resources. */
1817
- public async closeProject(id: ProjectId): Promise<void> {
1818
- const prj = this.openedProjects.get(id);
1819
- if (prj === undefined) throw new Error(`Project ${id} not found among opened projects`);
1820
- this.openedProjects.delete(id);
1862
+ /** Labels of the live holds on a project, one per hold; empty when nobody holds it. */
1863
+ public projectHolders(id: ProjectId): ProjectHolder[] {
1864
+ return this.projectSlots.holders(id);
1865
+ }
1821
1866
 
1822
- // Snapshot before destroy, and here rather than inside destroy(): destroy() is also what
1823
- // application shutdown runs, and quitting should perform no snapshot work. Terminating the
1824
- // tree invalidates it, so the state has to be taken first either way.
1825
- //
1826
- // Started, not awaited. The capture happens synchronously inside, which is the part that
1827
- // needs the tree alive; the encode and write are up to ten megabytes of work that closing a
1828
- // project should not sit behind. Kept so shutdown can drain it.
1829
- this.trackSnapshotWrite(prj.snapshotOnClose());
1867
+ /**
1868
+ * Opens a project, and starts corresponding project maintenance loop: takes a hold labelled
1869
+ * `legacy`, which {@link closeProject} releases. Opening a project this API already holds does
1870
+ * nothing.
1871
+ *
1872
+ * @deprecated use {@link acquireProject}, and release the handle
1873
+ */
1874
+ public async openProject(id: ProjectId): Promise<void> {
1875
+ if (this.legacyHolds.get(id)?.ended === false) return;
1876
+ const handle = await this.projectSlots.acquire(id, LEGACY_HOLDER);
1877
+ // A concurrent open got there first.
1878
+ if (this.legacyHolds.get(id)?.ended === false) {
1879
+ await handle.release();
1880
+ return;
1881
+ }
1882
+ this.legacyHolds.set(id, handle);
1883
+ // A hold taken from this API (deleted, closed) leaves nothing behind.
1884
+ handle.signal.addEventListener(
1885
+ "abort",
1886
+ () => {
1887
+ if (this.legacyHolds.get(id) === handle) this.legacyHolds.delete(id);
1888
+ },
1889
+ { once: true },
1890
+ );
1891
+ }
1830
1892
 
1831
- await prj.destroy();
1832
- this.openedProjectsList.setValue([...this.openedProjects.keys()]);
1893
+ /**
1894
+ * Releases the hold {@link openProject} took. The project is destroyed only when nobody else
1895
+ * holds it. Closing a project this API does not hold does nothing.
1896
+ *
1897
+ * @deprecated use {@link ProjectHandle.release}
1898
+ */
1899
+ public async closeProject(id: ProjectId): Promise<void> {
1900
+ const handle = this.legacyHolds.get(id);
1901
+ this.legacyHolds.delete(id);
1902
+ if (handle === undefined || handle.ended) {
1903
+ this.env.logger.info(`closeProject: project ${id} is not held by openProject`);
1904
+ return;
1905
+ }
1906
+ await handle.release();
1833
1907
  }
1834
1908
 
1835
- /** Returns a project access object for an opened project. */
1909
+ /**
1910
+ * Returns a project access object for a loaded project, whoever holds it.
1911
+ *
1912
+ * A caller holding no {@link ProjectHandle} must not keep the result across awaits: the project
1913
+ * can be destroyed meanwhile.
1914
+ */
1836
1915
  public getOpenedProject(id: ProjectId): Project {
1837
- const prj = this.openedProjects.get(id);
1916
+ const prj = this.projectSlots.get(id);
1838
1917
  if (prj === undefined) throw new Error(`Project ${id} not found among opened projects`);
1839
1918
  return prj;
1840
1919
  }
1841
1920
 
1842
- /** Returns true if project with given id is currently opened. */
1921
+ /** Returns true if the project is currently loaded, whoever holds it. */
1843
1922
  public isProjectOpened(id: ProjectId): boolean {
1844
- return this.openedProjects.has(id);
1923
+ return this.projectSlots.get(id) !== undefined;
1845
1924
  }
1846
1925
 
1847
1926
  /** Counters for the persisted project tree mirrors, or undefined when they are switched off.
@@ -1872,7 +1951,7 @@ export class MiddleLayer {
1872
1951
  public async close() {
1873
1952
  if (this.envelopeCleanupTimer !== undefined) clearInterval(this.envelopeCleanupTimer);
1874
1953
  await this.instanceStatsWatch?.terminate();
1875
- await Promise.all([...this.openedProjects.values()].map((prj) => prj.destroy()));
1954
+ await this.projectSlots.closeAll();
1876
1955
  // this.env.quickJs;
1877
1956
  await Promise.all([
1878
1957
  this.projectListTree.terminate(),
@@ -197,6 +197,9 @@ export class Project {
197
197
  /** Whether this tree was seeded from a snapshot. When it was, the file on disk already
198
198
  * holds generation 0, so an idle warm reopen writes nothing at all. */
199
199
  restoredFromSnapshot: boolean = false,
200
+ /** Called once, from the maintenance loop, when the loop finds the project was deleted
201
+ * elsewhere. The loop has stopped by then; the owner is expected to destroy the project. */
202
+ private readonly onGone?: (project: Project) => void,
200
203
  ) {
201
204
  this.snapshotGeneration = restoredFromSnapshot ? 0 : -1;
202
205
  this.overview = projectOverview(
@@ -326,8 +329,27 @@ export class Project {
326
329
  }
327
330
  }
328
331
 
332
+ /**
333
+ * Brings the project tree up to a write that has just committed.
334
+ *
335
+ * The write is already on the backend when this runs, so a project destroyed meanwhile (closed
336
+ * by its last holder, or deleted) must not turn it into a failure: a caller told it failed would
337
+ * retry it and apply it twice. `destroy` marks the project destroyed before it terminates the
338
+ * tree, so a refresh failing on a terminated tree always finds the mark set.
339
+ */
340
+ private async refreshAfterWrite(): Promise<void> {
341
+ if (this.destroyed) return;
342
+ try {
343
+ await this.projectTree.refreshState();
344
+ } catch (e: unknown) {
345
+ if (this.destroyed) return;
346
+ throw e;
347
+ }
348
+ }
349
+
329
350
  private async refreshLoop(): Promise<void> {
330
351
  let retryState: InfiniteRetryState | undefined;
352
+ let gone = false;
331
353
  while (!this.destroyed) {
332
354
  try {
333
355
  await withProject(
@@ -370,6 +392,7 @@ export class Project {
370
392
  this.env.logger.warn(
371
393
  "project refresh routine terminated, because project was externally deleted",
372
394
  );
395
+ gone = true;
373
396
  break;
374
397
  } else if (isTimeoutOrCancelError(error)) {
375
398
  // Timeout during normal operation, continue the loop
@@ -399,6 +422,7 @@ export class Project {
399
422
  }
400
423
  }
401
424
  }
425
+ if (gone) this.onGone?.(this);
402
426
  }
403
427
 
404
428
  /**
@@ -512,7 +536,7 @@ export class Project {
512
536
  },
513
537
  );
514
538
 
515
- await this.projectTree.refreshState();
539
+ await this.refreshAfterWrite();
516
540
 
517
541
  return blockId;
518
542
  }
@@ -543,7 +567,7 @@ export class Project {
543
567
  (mut) => mut.duplicateBlock(originalBlockId, newBlockId, before),
544
568
  { name: "duplicateBlock", lockId: this.projectLockId },
545
569
  );
546
- await this.projectTree.refreshState();
570
+ await this.refreshAfterWrite();
547
571
 
548
572
  return newBlockId;
549
573
  }
@@ -586,7 +610,7 @@ export class Project {
586
610
  (mut) => mut.migrateBlockPack(blockId, cachedBp, resetState),
587
611
  { name: "updateBlockPack", lockId: this.projectLockId },
588
612
  );
589
- await this.projectTree.refreshState();
613
+ await this.refreshAfterWrite();
590
614
  }
591
615
 
592
616
  /** Deletes a block with all associated data. */
@@ -600,7 +624,7 @@ export class Project {
600
624
  { name: "deleteBlock", lockId: this.projectLockId },
601
625
  );
602
626
  this.navigationStates.deleteBlock(blockId);
603
- await this.projectTree.refreshState();
627
+ await this.refreshAfterWrite();
604
628
  }
605
629
 
606
630
  /**
@@ -640,7 +664,7 @@ export class Project {
640
664
  },
641
665
  { name: "reorderBlocks", lockId: this.projectLockId },
642
666
  );
643
- await this.projectTree.refreshState();
667
+ await this.refreshAfterWrite();
644
668
  }
645
669
 
646
670
  /**
@@ -656,7 +680,7 @@ export class Project {
656
680
  (mut) => mut.renderProduction([blockId], true),
657
681
  { name: "runBlock", lockId: this.projectLockId },
658
682
  );
659
- await this.projectTree.refreshState();
683
+ await this.refreshAfterWrite();
660
684
  }
661
685
 
662
686
  /**
@@ -672,7 +696,7 @@ export class Project {
672
696
  (mut) => mut.stopProduction(blockId),
673
697
  { name: "stopBlock", lockId: this.projectLockId },
674
698
  );
675
- await this.projectTree.refreshState();
699
+ await this.refreshAfterWrite();
676
700
  }
677
701
 
678
702
  /**
@@ -694,7 +718,7 @@ export class Project {
694
718
  },
695
719
  { name: "setBlockArgs", lockId: this.projectLockId },
696
720
  );
697
- await this.projectTree.refreshState();
721
+ await this.refreshAfterWrite();
698
722
  }
699
723
 
700
724
  /**
@@ -716,7 +740,7 @@ export class Project {
716
740
  },
717
741
  { name: "setUiState", lockId: this.projectLockId },
718
742
  );
719
- await this.projectTree.refreshState();
743
+ await this.refreshAfterWrite();
720
744
  }
721
745
 
722
746
  /**
@@ -744,7 +768,7 @@ export class Project {
744
768
  },
745
769
  { name: "setBlockArgsAndUiState", lockId: this.projectLockId },
746
770
  );
747
- await this.projectTree.refreshState();
771
+ await this.refreshAfterWrite();
748
772
  }
749
773
 
750
774
  /**
@@ -778,7 +802,7 @@ export class Project {
778
802
  (mut) => mut.setStates([{ modelAPIVersion: 2, blockId, payload }]),
779
803
  { name: "mutateBlockStorage", lockId: this.projectLockId },
780
804
  );
781
- await this.projectTree.refreshState();
805
+ await this.refreshAfterWrite();
782
806
  }
783
807
 
784
808
  /**
@@ -815,7 +839,7 @@ export class Project {
815
839
  },
816
840
  { name: "setBlockSettings" },
817
841
  );
818
- await this.projectTree.refreshState();
842
+ await this.refreshAfterWrite();
819
843
  }
820
844
 
821
845
  /**
@@ -836,7 +860,7 @@ export class Project {
836
860
  },
837
861
  { name: "setBlockStorageRaw" },
838
862
  );
839
- await this.projectTree.refreshState();
863
+ await this.refreshAfterWrite();
840
864
  }
841
865
 
842
866
  /** Resets arguments and ui state of the block to initial state */
@@ -871,7 +895,7 @@ export class Project {
871
895
  );
872
896
  await tx.commit();
873
897
  });
874
- await this.projectTree.refreshState();
898
+ await this.refreshAfterWrite();
875
899
  }
876
900
 
877
901
  private getBlockComputables(blockId: string): BlockStateComputables {
@@ -1130,6 +1154,7 @@ export class Project {
1130
1154
  env: MiddleLayerEnvironment,
1131
1155
  id: ProjectId,
1132
1156
  rid: SignedResourceId,
1157
+ onGone?: (project: Project) => void,
1133
1158
  ): Promise<Project> {
1134
1159
  // Applying migrations to the project resource, if needed
1135
1160
  await applyProjectMigrations(env.pl, rid);
@@ -1148,7 +1173,7 @@ export class Project {
1148
1173
  await fs.writeFile(`${resourceIdToString(rid)}.stats.json`, stringifyForDump(stats));
1149
1174
  }
1150
1175
 
1151
- return new Project(env, id, rid, projectTree, restored);
1176
+ return new Project(env, id, rid, projectTree, restored, onGone);
1152
1177
  }
1153
1178
  }
1154
1179
 
@@ -0,0 +1,142 @@
1
+ import path from "node:path";
2
+ import { expect, test } from "vitest";
3
+ import type { BlockPackSpec } from "@milaboratories/pl-model-middle-layer";
4
+ import type { ProjectId } from "../model/project_model";
5
+ import { withMl } from "../test/with_ml";
6
+ import { onceAfterWriteTx } from "../test/write_tx_hooks";
7
+ import type { MiddleLayer } from "./middle_layer";
8
+ import type { Project } from "./project";
9
+ import { asProjectHolder } from "./project_holds";
10
+
11
+ /**
12
+ * A write whose transaction has committed resolves even when the project is closed before the
13
+ * write's own refresh of the project tree: the close terminates that tree, and the change is
14
+ * already on the backend. Before, the write failed with `tree synchronization is terminated`
15
+ * although it had been applied, and a caller retrying it applied it twice.
16
+ *
17
+ * The close is made deterministic: it runs inside the transaction wrapper, after the commit and
18
+ * before the write returns.
19
+ */
20
+
21
+ const EnterNumbers: BlockPackSpec = {
22
+ type: "dev-v2",
23
+ folder: path.resolve(__dirname, "../../../../../etc/blocks/enter-numbers/block"),
24
+ };
25
+
26
+ /** Opens the project, runs `write` on it, and closes the project once `txName` has committed. */
27
+ async function closingAfterCommit<T>(
28
+ ml: MiddleLayer,
29
+ id: ProjectId,
30
+ txName: string,
31
+ write: (project: Project) => Promise<T>,
32
+ ): Promise<T> {
33
+ await ml.openProject(id);
34
+ const project = ml.getOpenedProject(id);
35
+ const hook = onceAfterWriteTx(ml.pl, `ProjectAction: ${txName}`, () => ml.closeProject(id));
36
+ try {
37
+ const result = await write(project);
38
+ expect(hook.fired()).toBe(true);
39
+ expect(ml.isProjectOpened(id)).toBe(false);
40
+ return result;
41
+ } finally {
42
+ hook.restore();
43
+ }
44
+ }
45
+
46
+ /** The ids of the project's blocks, read from a fresh load. */
47
+ async function blockIds(ml: MiddleLayer, id: ProjectId): Promise<string[]> {
48
+ await ml.openProject(id);
49
+ try {
50
+ const overview = await ml.getOpenedProject(id).overview.awaitStableValue();
51
+ return overview.blocks.map((b) => b.id);
52
+ } finally {
53
+ await ml.closeProject(id);
54
+ }
55
+ }
56
+
57
+ test("a committed write resolves when the project is closed before its refresh", async () => {
58
+ await withMl(async (ml) => {
59
+ const id = await ml.createProject({ label: "close during write" });
60
+
61
+ const blockId = await closingAfterCommit(ml, id, "addBlock", (p) =>
62
+ p.addBlock("Numbers", EnterNumbers),
63
+ );
64
+ expect(await blockIds(ml, id)).toEqual([blockId]);
65
+
66
+ await closingAfterCommit(ml, id, "mutateBlockStorage", (p) =>
67
+ p.mutateBlockStorage(blockId, { operation: "update-block-data", value: { numbers: [1, 2] } }),
68
+ );
69
+ await closingAfterCommit(ml, id, "runBlock", (p) => p.runBlock(blockId));
70
+ expect(await blockIds(ml, id)).toEqual([blockId]);
71
+
72
+ await closingAfterCommit(ml, id, "deleteBlock", (p) => p.deleteBlock(blockId));
73
+ expect(await blockIds(ml, id)).toEqual([]);
74
+ });
75
+ });
76
+
77
+ /**
78
+ * Replaces, once, the refresh of the project tree that a write runs after its commit. Returns the
79
+ * function that puts the original back.
80
+ */
81
+ function onceInWriteRefresh(
82
+ project: Project,
83
+ refresh: (original: () => Promise<void>) => Promise<void>,
84
+ ) {
85
+ const tree = project["projectTree"];
86
+ const unwrapped = tree.refreshState;
87
+ const original = unwrapped.bind(tree);
88
+ let fired = false;
89
+ tree.refreshState = async () => {
90
+ if (fired) return await original();
91
+ fired = true;
92
+ return await refresh(original);
93
+ };
94
+ return {
95
+ fired: () => fired,
96
+ restore: () => {
97
+ tree.refreshState = unwrapped;
98
+ },
99
+ };
100
+ }
101
+
102
+ test("a committed write resolves when the project is destroyed while its refresh runs", async () => {
103
+ await withMl(async (ml) => {
104
+ const id = await ml.createProject({ label: "destroyed during refresh" });
105
+ const handle = await ml.acquireProject(id, asProjectHolder("writer"));
106
+ const project = handle.project;
107
+ // The refresh has started when the last hold goes: it then finds the tree terminated.
108
+ const hook = onceInWriteRefresh(project, async (original) => {
109
+ await handle.release();
110
+ await original();
111
+ });
112
+ let blockId: string;
113
+ try {
114
+ blockId = await project.addBlock("Numbers", EnterNumbers);
115
+ } finally {
116
+ hook.restore();
117
+ }
118
+ expect(hook.fired()).toBe(true);
119
+ expect(ml.isProjectOpened(id)).toBe(false);
120
+ expect(await blockIds(ml, id)).toEqual([blockId]);
121
+ });
122
+ });
123
+
124
+ test("a refresh that fails on a project still loaded fails the write", async () => {
125
+ await withMl(async (ml) => {
126
+ const id = await ml.createProject({ label: "refresh fails" });
127
+ const handle = await ml.acquireProject(id, asProjectHolder("writer"));
128
+ const hook = onceInWriteRefresh(handle.project, async () => {
129
+ throw new Error("refresh failed");
130
+ });
131
+ try {
132
+ await expect(handle.project.addBlock("Numbers", EnterNumbers)).rejects.toThrow(
133
+ "refresh failed",
134
+ );
135
+ } finally {
136
+ hook.restore();
137
+ }
138
+ expect(hook.fired()).toBe(true);
139
+ expect(handle.ended).toBe(false);
140
+ await handle.release();
141
+ });
142
+ });