@milaboratories/pl-middle-layer 2.9.0 → 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 +7 -7
  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
@@ -0,0 +1,266 @@
1
+ const require_list = require("../mutator/list.cjs");
2
+ // src/middle_layer/project_holds.ts
3
+ /** Brands a label as a {@link ProjectHolder}; each holder makes its label once. */
4
+ function asProjectHolder(label) {
5
+ return label;
6
+ }
7
+ /**
8
+ * Thrown by a delete that was told to refuse while the project is held: the project is untouched.
9
+ * `holders` are the labels of the holds that caused the refusal.
10
+ */
11
+ var ProjectInUseError = class extends Error {
12
+ projectId;
13
+ holders;
14
+ name = "ProjectInUseError";
15
+ constructor(projectId, holders) {
16
+ super(`Project ${projectId} is in use by ${holders.join(", ")}`);
17
+ this.projectId = projectId;
18
+ this.holders = holders;
19
+ }
20
+ };
21
+ /** Whether `error` is a {@link ProjectInUseError}, also across copies of this package. */
22
+ function isProjectInUseError(error) {
23
+ return error instanceof Error && error.name === "ProjectInUseError";
24
+ }
25
+ /** One project's place in {@link ProjectSlots}: loading, open, or being destroyed. */
26
+ var Slot = class {
27
+ state = "loading";
28
+ project = void 0;
29
+ holds = /* @__PURE__ */ new Set();
30
+ /** Acquires waiting for the load. The slot is not closed while any wait. */
31
+ waiting = 0;
32
+ /** Set when the slot was taken away from its holders rather than released. */
33
+ evicted = void 0;
34
+ /** The destroy, once the slot is closing. */
35
+ closed = void 0;
36
+ load;
37
+ constructor(run) {
38
+ this.load = run(this);
39
+ }
40
+ };
41
+ /** A hold handed out by {@link ProjectSlots}. */
42
+ var SlotHandle = class {
43
+ id;
44
+ holder;
45
+ loaded;
46
+ slot;
47
+ owner;
48
+ controller = new AbortController();
49
+ constructor(id, holder, loaded, slot, owner) {
50
+ this.id = id;
51
+ this.holder = holder;
52
+ this.loaded = loaded;
53
+ this.slot = slot;
54
+ this.owner = owner;
55
+ }
56
+ get project() {
57
+ if (this.ended) throw new Error(`The hold of ${this.holder} on project ${this.id} has ended: ${String(this.signal.reason)}`);
58
+ return this.loaded;
59
+ }
60
+ get signal() {
61
+ return this.controller.signal;
62
+ }
63
+ get ended() {
64
+ return this.controller.signal.aborted;
65
+ }
66
+ /** Ends the hold without touching the slot; the caller does the bookkeeping. */
67
+ end(reason) {
68
+ this.controller.abort(reason);
69
+ }
70
+ release() {
71
+ return this.owner.release(this, this.slot);
72
+ }
73
+ [Symbol.asyncDispose]() {
74
+ return this.release();
75
+ }
76
+ };
77
+ const noop = () => {};
78
+ /**
79
+ * The loaded projects of a middle layer and their holders.
80
+ *
81
+ * At most one project object exists per id: concurrent acquires share one load, and an acquire
82
+ * that comes while the project is being destroyed waits for the destroy and loads it anew. The
83
+ * project is destroyed when its last hold is released, when it is deleted, and when the middle
84
+ * layer closes. Every state change that matters to a release happens synchronously, so a release
85
+ * that is not awaited followed at once by an acquire is safe.
86
+ */
87
+ var ProjectSlots = class {
88
+ deps;
89
+ slots = /* @__PURE__ */ new Map();
90
+ closing = false;
91
+ constructor(deps) {
92
+ this.deps = deps;
93
+ }
94
+ /** Takes a hold on the project, loading it when nobody holds it. */
95
+ async acquire(id, holder) {
96
+ for (;;) {
97
+ if (this.closing) throw new Error("Middle layer is closed");
98
+ const slot = this.slots.get(id) ?? this.startLoad(id, holder);
99
+ if (slot.state === "closing") {
100
+ await slot.closed;
101
+ continue;
102
+ }
103
+ if (slot.state === "loading") {
104
+ slot.waiting++;
105
+ try {
106
+ await slot.load;
107
+ } finally {
108
+ slot.waiting--;
109
+ }
110
+ if (slot.evicted !== void 0) throw evictionError(id, slot.evicted);
111
+ }
112
+ return this.addHold(slot, id, holder);
113
+ }
114
+ }
115
+ /** The loaded project, when the slot is open, whoever holds it. */
116
+ get(id) {
117
+ const slot = this.slots.get(id);
118
+ return slot?.state === "open" ? slot.project : void 0;
119
+ }
120
+ /** Labels of the live holds on the project, one per hold; empty when nobody holds it. */
121
+ holders(id) {
122
+ const slot = this.slots.get(id);
123
+ return slot === void 0 ? [] : [...slot.holds].map((h) => h.holder);
124
+ }
125
+ /**
126
+ * Deletes the project with `remove` (the backend write) and takes it from every holder, as
127
+ * {@link evict} with `deleted` does: holds taken while `remove` runs end too, and a load in
128
+ * flight is discarded.
129
+ *
130
+ * With `refuseIfHeldBy`, the delete is refused with a {@link ProjectInUseError}, and `remove`
131
+ * not run, when any of the {@link holders} at the start is one it returns `true` for.
132
+ */
133
+ async delete(id, remove, refuseIfHeldBy) {
134
+ if (refuseIfHeldBy !== void 0) {
135
+ const refused = this.holders(id).filter(refuseIfHeldBy);
136
+ if (refused.length > 0) throw new ProjectInUseError(id, refused);
137
+ }
138
+ await remove();
139
+ await this.evict(id, "deleted");
140
+ }
141
+ /**
142
+ * Takes the project away from all its holders: every hold ends with `reason`, a load in flight
143
+ * is discarded, and the loaded project is destroyed without a snapshot. Resolves when the destroy
144
+ * has finished. A load in flight is not waited for (the eviction may come from inside it): it
145
+ * destroys its project when it finishes, and the acquires waiting for it are rejected.
146
+ */
147
+ evict(id, reason) {
148
+ const slot = this.slots.get(id);
149
+ if (slot === void 0) return Promise.resolve();
150
+ if (slot.state === "loading") {
151
+ slot.evicted = reason;
152
+ slot.state = "closing";
153
+ slot.closed = slot.load.then(noop, noop).finally(() => this.remove(id, slot));
154
+ this.deps.logger.info(`project ${id}: load discarded (${reason})`);
155
+ return Promise.resolve();
156
+ }
157
+ if (slot.state === "open") {
158
+ slot.evicted = reason;
159
+ for (const hold of slot.holds) hold.end(reason);
160
+ slot.holds.clear();
161
+ this.close(slot, id, reason, void 0, false);
162
+ }
163
+ return slot.closed ?? Promise.resolve();
164
+ }
165
+ /**
166
+ * Ends every hold with `closed`, destroys every loaded project and refuses later acquires.
167
+ * Resolves when every project is destroyed, those of loads in flight included: such a load runs
168
+ * to its end, and its project is destroyed then.
169
+ */
170
+ async closeAll() {
171
+ this.closing = true;
172
+ const slots = [...this.slots.entries()];
173
+ await Promise.all(slots.map(([id]) => this.evict(id, "closed")));
174
+ await Promise.all(slots.map(([, slot]) => slot.closed));
175
+ }
176
+ /** @internal Called by {@link SlotHandle.release}. */
177
+ release(handle, slot) {
178
+ if (handle.ended) return slot.closed ?? Promise.resolve();
179
+ handle.end("released");
180
+ slot.holds.delete(handle);
181
+ if (slot.state === "open" && slot.holds.size === 0 && slot.waiting === 0) this.close(slot, handle.id, "released", handle.holder, true);
182
+ return slot.closed ?? Promise.resolve();
183
+ }
184
+ startLoad(id, holder) {
185
+ const startedAt = Date.now();
186
+ const slot = new Slot(async (s) => {
187
+ let project;
188
+ try {
189
+ project = await this.deps.load(id, (p) => this.onGone(id, p));
190
+ } catch (e) {
191
+ if (s.evicted !== void 0) throw evictionError(id, s.evicted);
192
+ throw e;
193
+ }
194
+ if (s.evicted !== void 0) {
195
+ await destroyQuietly(project, this.deps.logger);
196
+ throw evictionError(id, s.evicted);
197
+ }
198
+ s.project = project;
199
+ s.state = "open";
200
+ this.publish();
201
+ this.deps.logger.info(`project ${id}: loaded for ${holder} in ${Date.now() - startedAt} ms`);
202
+ return project;
203
+ });
204
+ this.slots.set(id, slot);
205
+ slot.load.catch((e) => {
206
+ if (slot.state !== "loading") return;
207
+ this.remove(id, slot);
208
+ this.deps.logger.info(`project ${id}: load for ${holder} failed: ${e instanceof Error ? e.message : String(e)}`);
209
+ });
210
+ return slot;
211
+ }
212
+ addHold(slot, id, holder) {
213
+ if (slot.project === void 0) throw new Error(`Project ${id} is open but not loaded`);
214
+ const handle = new SlotHandle(id, holder, slot.project, slot, this);
215
+ slot.holds.add(handle);
216
+ return handle;
217
+ }
218
+ /** Starts destroying an open slot. Everything before the first await happens synchronously. */
219
+ close(slot, id, cause, holder, snapshot) {
220
+ const project = slot.project;
221
+ if (project === void 0) throw new Error(`Project ${id} is open but not loaded`);
222
+ slot.state = "closing";
223
+ this.publish();
224
+ if (snapshot) this.deps.trackSnapshotWrite(project.snapshotOnClose());
225
+ slot.closed = (async () => {
226
+ try {
227
+ await destroyQuietly(project, this.deps.logger);
228
+ } finally {
229
+ this.remove(id, slot);
230
+ }
231
+ this.deps.logger.info(`project ${id}: destroyed (${cause}${holder === void 0 ? "" : ` by ${holder}`})`);
232
+ })();
233
+ }
234
+ onGone(id, project) {
235
+ const slot = this.slots.get(id);
236
+ if (slot === void 0) return;
237
+ if (slot.project !== project && slot.state !== "loading") return;
238
+ this.deps.logger.info(`project ${id}: deleted elsewhere`);
239
+ this.evict(id, "deleted");
240
+ }
241
+ remove(id, slot) {
242
+ if (this.slots.get(id) === slot) this.slots.delete(id);
243
+ }
244
+ publish() {
245
+ const open = [];
246
+ for (const [id, slot] of this.slots) if (slot.state === "open") open.push(id);
247
+ this.deps.publish(open);
248
+ }
249
+ };
250
+ function evictionError(id, reason) {
251
+ return reason === "deleted" ? require_list.notListedError("Project", id) : /* @__PURE__ */ new Error("Middle layer is closed");
252
+ }
253
+ async function destroyQuietly(project, logger) {
254
+ try {
255
+ await project.destroy();
256
+ } catch (e) {
257
+ logger.warn(new Error("Project destroy failed", { cause: e }));
258
+ }
259
+ }
260
+ exports.ProjectInUseError = ProjectInUseError;
261
+ exports.ProjectSlots = ProjectSlots;
262
+ exports.SlotHandle = SlotHandle;
263
+ exports.asProjectHolder = asProjectHolder;
264
+ exports.isProjectInUseError = isProjectInUseError;
265
+
266
+ //# sourceMappingURL=project_holds.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"project_holds.cjs","names":["notListedError"],"sources":["../../src/middle_layer/project_holds.ts"],"sourcesContent":["import type { Branded } from \"@milaboratories/pl-model-common\";\nimport type { MiLogger } from \"@milaboratories/ts-helpers\";\nimport type { ProjectId } from \"../model/project_model\";\nimport { notListedError } from \"../mutator/list\";\nimport type { Project } from \"./project\";\n\n/**\n * Who holds a loaded project: a free-form label for diagnostics, logs and `refuseIfHeldBy`, e.g.\n * `desktop` or `mcp:mcp-1a2b3c4d`. Not an identity: two holds with the same label are two holds.\n */\nexport type ProjectHolder = Branded<string, \"ProjectHolder\">;\n\n/** Brands a label as a {@link ProjectHolder}; each holder makes its label once. */\nexport function asProjectHolder(label: string): ProjectHolder {\n return label as ProjectHolder;\n}\n\n/** Why a {@link ProjectHandle} stopped holding its project. */\nexport type ProjectHandleEnd =\n /** The holder gave the hold back. */\n | \"released\"\n /** The project was deleted, here or by another client. */\n | \"deleted\"\n /** The middle layer was closed. */\n | \"closed\";\n\n/**\n * One holder's hold on a loaded project. A project stays loaded while anyone holds it, and is\n * destroyed when the last hold is given back; nobody else's release can take it from under a\n * holder. Every holder releases its own handle exactly when it is done with the project.\n */\nexport interface ProjectHandle extends AsyncDisposable {\n readonly id: ProjectId;\n /** Who holds the project; see {@link ProjectHolder}. */\n readonly holder: ProjectHolder;\n /** The loaded project. Throws once the handle has ended. */\n readonly project: Project;\n /** Aborted when this handle stops holding; `signal.reason` is a {@link ProjectHandleEnd}. */\n readonly signal: AbortSignal;\n /** Whether this handle no longer holds the project. */\n readonly ended: boolean;\n /** Gives the hold back. Idempotent; never throws; resolves when a destroy it caused has finished. */\n release(): Promise<void>;\n}\n\n/**\n * Thrown by a delete that was told to refuse while the project is held: the project is untouched.\n * `holders` are the labels of the holds that caused the refusal.\n */\nexport class ProjectInUseError extends Error {\n override name = \"ProjectInUseError\";\n\n constructor(\n readonly projectId: ProjectId,\n readonly holders: ProjectHolder[],\n ) {\n super(`Project ${projectId} is in use by ${holders.join(\", \")}`);\n }\n}\n\n/** Whether `error` is a {@link ProjectInUseError}, also across copies of this package. */\nexport function isProjectInUseError(error: unknown): error is ProjectInUseError {\n return error instanceof Error && error.name === \"ProjectInUseError\";\n}\n\n/** What {@link ProjectSlots} needs from a loaded project. */\nexport interface SlotProject {\n destroy(): Promise<void>;\n snapshotOnClose(): Promise<void>;\n}\n\n/** What {@link ProjectSlots} is built on. */\nexport interface ProjectSlotsDeps<P extends SlotProject> {\n /** Loads a project. The loaded project calls `onGone` when it finds it was deleted elsewhere. */\n load: (id: ProjectId, onGone: (project: P) => void) => Promise<P>;\n /** Keeps a close-boundary snapshot write, so the middle layer's close can drain it. */\n trackSnapshotWrite: (write: Promise<void>) => void;\n /** Receives the ids of the open projects every time that set changes. */\n publish: (open: ProjectId[]) => void;\n logger: Pick<MiLogger, \"info\" | \"warn\">;\n}\n\n/** One project's place in {@link ProjectSlots}: loading, open, or being destroyed. */\nclass Slot<P> {\n state: \"loading\" | \"open\" | \"closing\" = \"loading\";\n project: P | undefined = undefined;\n readonly holds = new Set<SlotHandle<P>>();\n /** Acquires waiting for the load. The slot is not closed while any wait. */\n waiting = 0;\n /** Set when the slot was taken away from its holders rather than released. */\n evicted: ProjectHandleEnd | undefined = undefined;\n /** The destroy, once the slot is closing. */\n closed: Promise<void> | undefined = undefined;\n readonly load: Promise<P>;\n\n constructor(run: (slot: Slot<P>) => Promise<P>) {\n this.load = run(this);\n }\n}\n\n/** A hold handed out by {@link ProjectSlots}. */\nexport class SlotHandle<P> {\n private readonly controller = new AbortController();\n\n constructor(\n readonly id: ProjectId,\n readonly holder: ProjectHolder,\n private readonly loaded: P,\n private readonly slot: Slot<P>,\n private readonly owner: { release(handle: SlotHandle<P>, slot: Slot<P>): Promise<void> },\n ) {}\n\n get project(): P {\n if (this.ended)\n throw new Error(\n `The hold of ${this.holder} on project ${this.id} has ended: ${String(this.signal.reason)}`,\n );\n return this.loaded;\n }\n\n get signal(): AbortSignal {\n return this.controller.signal;\n }\n\n get ended(): boolean {\n return this.controller.signal.aborted;\n }\n\n /** Ends the hold without touching the slot; the caller does the bookkeeping. */\n end(reason: ProjectHandleEnd): void {\n this.controller.abort(reason);\n }\n\n release(): Promise<void> {\n return this.owner.release(this, this.slot);\n }\n\n [Symbol.asyncDispose](): Promise<void> {\n return this.release();\n }\n}\n\nconst noop = () => {};\n\n/**\n * The loaded projects of a middle layer and their holders.\n *\n * At most one project object exists per id: concurrent acquires share one load, and an acquire\n * that comes while the project is being destroyed waits for the destroy and loads it anew. The\n * project is destroyed when its last hold is released, when it is deleted, and when the middle\n * layer closes. Every state change that matters to a release happens synchronously, so a release\n * that is not awaited followed at once by an acquire is safe.\n */\nexport class ProjectSlots<P extends SlotProject> {\n private readonly slots = new Map<ProjectId, Slot<P>>();\n private closing = false;\n\n constructor(private readonly deps: ProjectSlotsDeps<P>) {}\n\n /** Takes a hold on the project, loading it when nobody holds it. */\n async acquire(id: ProjectId, holder: ProjectHolder): Promise<SlotHandle<P>> {\n for (;;) {\n if (this.closing) throw new Error(\"Middle layer is closed\");\n const slot = this.slots.get(id) ?? this.startLoad(id, holder);\n if (slot.state === \"closing\") {\n await slot.closed;\n continue;\n }\n if (slot.state === \"loading\") {\n slot.waiting++;\n try {\n await slot.load;\n } finally {\n slot.waiting--;\n }\n // A finished load leaves the slot open unless it was evicted meanwhile.\n if (slot.evicted !== undefined) throw evictionError(id, slot.evicted);\n }\n return this.addHold(slot, id, holder);\n }\n }\n\n /** The loaded project, when the slot is open, whoever holds it. */\n get(id: ProjectId): P | undefined {\n const slot = this.slots.get(id);\n return slot?.state === \"open\" ? slot.project : undefined;\n }\n\n /** Labels of the live holds on the project, one per hold; empty when nobody holds it. */\n holders(id: ProjectId): ProjectHolder[] {\n const slot = this.slots.get(id);\n return slot === undefined ? [] : [...slot.holds].map((h) => h.holder);\n }\n\n /**\n * Deletes the project with `remove` (the backend write) and takes it from every holder, as\n * {@link evict} with `deleted` does: holds taken while `remove` runs end too, and a load in\n * flight is discarded.\n *\n * With `refuseIfHeldBy`, the delete is refused with a {@link ProjectInUseError}, and `remove`\n * not run, when any of the {@link holders} at the start is one it returns `true` for.\n */\n async delete(\n id: ProjectId,\n remove: () => Promise<void>,\n refuseIfHeldBy?: (holder: ProjectHolder) => boolean,\n ): Promise<void> {\n if (refuseIfHeldBy !== undefined) {\n const refused = this.holders(id).filter(refuseIfHeldBy);\n if (refused.length > 0) throw new ProjectInUseError(id, refused);\n }\n await remove();\n await this.evict(id, \"deleted\");\n }\n\n /**\n * Takes the project away from all its holders: every hold ends with `reason`, a load in flight\n * is discarded, and the loaded project is destroyed without a snapshot. Resolves when the destroy\n * has finished. A load in flight is not waited for (the eviction may come from inside it): it\n * destroys its project when it finishes, and the acquires waiting for it are rejected.\n */\n evict(id: ProjectId, reason: ProjectHandleEnd): Promise<void> {\n const slot = this.slots.get(id);\n if (slot === undefined) return Promise.resolve();\n if (slot.state === \"loading\") {\n slot.evicted = reason;\n slot.state = \"closing\";\n // An acquire meanwhile waits for this, then loads anew.\n slot.closed = slot.load.then(noop, noop).finally(() => this.remove(id, slot));\n this.deps.logger.info(`project ${id}: load discarded (${reason})`);\n return Promise.resolve();\n }\n if (slot.state === \"open\") {\n slot.evicted = reason;\n for (const hold of slot.holds) hold.end(reason);\n slot.holds.clear();\n this.close(slot, id, reason, undefined, false);\n }\n return slot.closed ?? Promise.resolve();\n }\n\n /**\n * Ends every hold with `closed`, destroys every loaded project and refuses later acquires.\n * Resolves when every project is destroyed, those of loads in flight included: such a load runs\n * to its end, and its project is destroyed then.\n */\n async closeAll(): Promise<void> {\n this.closing = true;\n const slots = [...this.slots.entries()];\n await Promise.all(slots.map(([id]) => this.evict(id, \"closed\")));\n await Promise.all(slots.map(([, slot]) => slot.closed));\n }\n\n /** @internal Called by {@link SlotHandle.release}. */\n release(handle: SlotHandle<P>, slot: Slot<P>): Promise<void> {\n if (handle.ended) return slot.closed ?? Promise.resolve();\n handle.end(\"released\");\n slot.holds.delete(handle);\n if (slot.state === \"open\" && slot.holds.size === 0 && slot.waiting === 0)\n this.close(slot, handle.id, \"released\", handle.holder, true);\n return slot.closed ?? Promise.resolve();\n }\n\n private startLoad(id: ProjectId, holder: ProjectHolder): Slot<P> {\n const startedAt = Date.now();\n const slot = new Slot<P>(async (s) => {\n let project: P;\n try {\n project = await this.deps.load(id, (p) => this.onGone(id, p));\n } catch (e: unknown) {\n // A load that failed because the project was deleted under it says so plainly.\n if (s.evicted !== undefined) throw evictionError(id, s.evicted);\n throw e;\n }\n if (s.evicted !== undefined) {\n await destroyQuietly(project, this.deps.logger);\n throw evictionError(id, s.evicted);\n }\n s.project = project;\n s.state = \"open\";\n this.publish();\n this.deps.logger.info(`project ${id}: loaded for ${holder} in ${Date.now() - startedAt} ms`);\n return project;\n });\n this.slots.set(id, slot);\n slot.load.catch((e: unknown) => {\n // A load that was evicted is removed by the eviction.\n if (slot.state !== \"loading\") return;\n this.remove(id, slot);\n this.deps.logger.info(\n `project ${id}: load for ${holder} failed: ${e instanceof Error ? e.message : String(e)}`,\n );\n });\n return slot;\n }\n\n private addHold(slot: Slot<P>, id: ProjectId, holder: ProjectHolder): SlotHandle<P> {\n if (slot.project === undefined) throw new Error(`Project ${id} is open but not loaded`);\n const handle = new SlotHandle(id, holder, slot.project, slot, this);\n slot.holds.add(handle);\n return handle;\n }\n\n /** Starts destroying an open slot. Everything before the first await happens synchronously. */\n private close(\n slot: Slot<P>,\n id: ProjectId,\n cause: ProjectHandleEnd,\n holder: ProjectHolder | undefined,\n snapshot: boolean,\n ): void {\n const project = slot.project;\n if (project === undefined) throw new Error(`Project ${id} is open but not loaded`);\n slot.state = \"closing\";\n this.publish();\n // The capture inside is synchronous and needs the tree alive, so it comes before destroy.\n if (snapshot) this.deps.trackSnapshotWrite(project.snapshotOnClose());\n slot.closed = (async () => {\n try {\n await destroyQuietly(project, this.deps.logger);\n } finally {\n this.remove(id, slot);\n }\n this.deps.logger.info(\n `project ${id}: destroyed (${cause}${holder === undefined ? \"\" : ` by ${holder}`})`,\n );\n })();\n }\n\n private onGone(id: ProjectId, project: P): void {\n const slot = this.slots.get(id);\n if (slot === undefined) return;\n if (slot.project !== project && slot.state !== \"loading\") return;\n this.deps.logger.info(`project ${id}: deleted elsewhere`);\n void this.evict(id, \"deleted\");\n }\n\n private remove(id: ProjectId, slot: Slot<P>): void {\n if (this.slots.get(id) === slot) this.slots.delete(id);\n }\n\n private publish(): void {\n const open: ProjectId[] = [];\n for (const [id, slot] of this.slots) if (slot.state === \"open\") open.push(id);\n this.deps.publish(open);\n }\n}\n\nfunction evictionError(id: ProjectId, reason: ProjectHandleEnd): Error {\n return reason === \"deleted\" ? notListedError(\"Project\", id) : new Error(\"Middle layer is closed\");\n}\n\nasync function destroyQuietly(project: SlotProject, logger: Pick<MiLogger, \"warn\">): Promise<void> {\n try {\n await project.destroy();\n } catch (e: unknown) {\n log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,MAAM,eAAe,SAAS,KAAK,KAAK,MAAM;GAChD,UAAU;IACR,KAAK,OAAO,IAAI,IAAI;GACtB;GACA,KAAK,KAAK,OAAO,KACf,WAAW,GAAG,eAAe,QAAQ,WAAW,KAAA,IAAY,KAAK,OAAO,SAAS,EACnF;EACF,EAAA,CAAG;CACL;CAEA,OAAe,IAAe,SAAkB;EAC9C,MAAM,OAAO,KAAK,MAAM,IAAI,EAAE;EAC9B,IAAI,SAAS,KAAA,GAAW;EACxB,IAAI,KAAK,YAAY,WAAW,KAAK,UAAU,WAAW;EAC1D,KAAK,KAAK,OAAO,KAAK,WAAW,GAAG,oBAAoB;EACxD,KAAU,MAAM,IAAI,SAAS;CAC/B;CAEA,OAAe,IAAe,MAAqB;EACjD,IAAI,KAAK,MAAM,IAAI,EAAE,MAAM,MAAM,KAAK,MAAM,OAAO,EAAE;CACvD;CAEA,UAAwB;EACtB,MAAM,OAAoB,CAAC;EAC3B,KAAK,MAAM,CAAC,IAAI,SAAS,KAAK,OAAO,IAAI,KAAK,UAAU,QAAQ,KAAK,KAAK,EAAE;EAC5E,KAAK,KAAK,QAAQ,IAAI;CACxB;AACF;AAEA,SAAS,cAAc,IAAe,QAAiC;CACrE,OAAO,WAAW,YAAYA,aAAAA,eAAe,WAAW,EAAE,oBAAI,IAAI,MAAM,wBAAwB;AAClG;AAEA,eAAe,eAAe,SAAsB,QAA+C;CACjG,IAAI;EACF,MAAM,QAAQ,QAAQ;CACxB,SAAS,GAAY;EACnB,OAAO,KAAK,IAAI,MAAM,0BAA0B,EAAE,OAAO,EAAE,CAAC,CAAC;CAC/D;AACF"}
@@ -0,0 +1,50 @@
1
+ import { ProjectId as ProjectId$1 } from "../model/project_model.js";
2
+ import { Project } from "./project.js";
3
+ import { MiLogger } from "@milaboratories/ts-helpers";
4
+ import { Branded } from "@milaboratories/pl-model-common";
5
+ /**
6
+ * Who holds a loaded project: a free-form label for diagnostics, logs and `refuseIfHeldBy`, e.g.
7
+ * `desktop` or `mcp:mcp-1a2b3c4d`. Not an identity: two holds with the same label are two holds.
8
+ */
9
+ export type ProjectHolder = Branded<string, "ProjectHolder">;
10
+ /** Brands a label as a {@link ProjectHolder}; each holder makes its label once. */
11
+ export declare function asProjectHolder(label: string): ProjectHolder;
12
+ /** Why a {@link ProjectHandle} stopped holding its project. */
13
+ export type ProjectHandleEnd =
14
+ /** The holder gave the hold back. */
15
+ "released" |
16
+ /** The project was deleted, here or by another client. */
17
+ "deleted" |
18
+ /** The middle layer was closed. */
19
+ "closed";
20
+ /**
21
+ * One holder's hold on a loaded project. A project stays loaded while anyone holds it, and is
22
+ * destroyed when the last hold is given back; nobody else's release can take it from under a
23
+ * holder. Every holder releases its own handle exactly when it is done with the project.
24
+ */
25
+ export interface ProjectHandle extends AsyncDisposable {
26
+ readonly id: ProjectId$1;
27
+ /** Who holds the project; see {@link ProjectHolder}. */
28
+ readonly holder: ProjectHolder;
29
+ /** The loaded project. Throws once the handle has ended. */
30
+ readonly project: Project;
31
+ /** Aborted when this handle stops holding; `signal.reason` is a {@link ProjectHandleEnd}. */
32
+ readonly signal: AbortSignal;
33
+ /** Whether this handle no longer holds the project. */
34
+ readonly ended: boolean;
35
+ /** Gives the hold back. Idempotent; never throws; resolves when a destroy it caused has finished. */
36
+ release(): Promise<void>;
37
+ }
38
+ /**
39
+ * Thrown by a delete that was told to refuse while the project is held: the project is untouched.
40
+ * `holders` are the labels of the holds that caused the refusal.
41
+ */
42
+ export declare class ProjectInUseError extends Error {
43
+ readonly projectId: ProjectId$1;
44
+ readonly holders: ProjectHolder[];
45
+ name: string;
46
+ constructor(projectId: ProjectId$1, holders: ProjectHolder[]);
47
+ }
48
+ /** Whether `error` is a {@link ProjectInUseError}, also across copies of this package. */
49
+ export declare function isProjectInUseError(error: unknown): error is ProjectInUseError;
50
+ //# sourceMappingURL=project_holds.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"project_holds.d.ts","names":["ProjectId"],"sources":["../../src/middle_layer/project_holds.ts"],"mappings":";;;;;;;;YAUY,gBAAgB;;wBAGZ,gBAAgB,gBAAgB;;YAKpC;;;;;;;;;;;;iBAaK,sBAAsB;WAC5B,IAAIA;;WAEJ,QAAQ;;WAER,SAAS;;WAET,QAAQ;;WAER;;EAET,WAAW;;;;;;qBAOA,0BAA0B;WAI1B,WAAWA;WACX,SAAS;EAJX;EAET,YACW,WAAWA,aACX,SAAS;;;wBAON,oBAAoB,iBAAiB,SAAS"}
@@ -0,0 +1,262 @@
1
+ import { notListedError } from "../mutator/list.js";
2
+ // src/middle_layer/project_holds.ts
3
+ /** Brands a label as a {@link ProjectHolder}; each holder makes its label once. */
4
+ function asProjectHolder(label) {
5
+ return label;
6
+ }
7
+ /**
8
+ * Thrown by a delete that was told to refuse while the project is held: the project is untouched.
9
+ * `holders` are the labels of the holds that caused the refusal.
10
+ */
11
+ var ProjectInUseError = class extends Error {
12
+ projectId;
13
+ holders;
14
+ name = "ProjectInUseError";
15
+ constructor(projectId, holders) {
16
+ super(`Project ${projectId} is in use by ${holders.join(", ")}`);
17
+ this.projectId = projectId;
18
+ this.holders = holders;
19
+ }
20
+ };
21
+ /** Whether `error` is a {@link ProjectInUseError}, also across copies of this package. */
22
+ function isProjectInUseError(error) {
23
+ return error instanceof Error && error.name === "ProjectInUseError";
24
+ }
25
+ /** One project's place in {@link ProjectSlots}: loading, open, or being destroyed. */
26
+ var Slot = class {
27
+ state = "loading";
28
+ project = void 0;
29
+ holds = /* @__PURE__ */ new Set();
30
+ /** Acquires waiting for the load. The slot is not closed while any wait. */
31
+ waiting = 0;
32
+ /** Set when the slot was taken away from its holders rather than released. */
33
+ evicted = void 0;
34
+ /** The destroy, once the slot is closing. */
35
+ closed = void 0;
36
+ load;
37
+ constructor(run) {
38
+ this.load = run(this);
39
+ }
40
+ };
41
+ /** A hold handed out by {@link ProjectSlots}. */
42
+ var SlotHandle = class {
43
+ id;
44
+ holder;
45
+ loaded;
46
+ slot;
47
+ owner;
48
+ controller = new AbortController();
49
+ constructor(id, holder, loaded, slot, owner) {
50
+ this.id = id;
51
+ this.holder = holder;
52
+ this.loaded = loaded;
53
+ this.slot = slot;
54
+ this.owner = owner;
55
+ }
56
+ get project() {
57
+ if (this.ended) throw new Error(`The hold of ${this.holder} on project ${this.id} has ended: ${String(this.signal.reason)}`);
58
+ return this.loaded;
59
+ }
60
+ get signal() {
61
+ return this.controller.signal;
62
+ }
63
+ get ended() {
64
+ return this.controller.signal.aborted;
65
+ }
66
+ /** Ends the hold without touching the slot; the caller does the bookkeeping. */
67
+ end(reason) {
68
+ this.controller.abort(reason);
69
+ }
70
+ release() {
71
+ return this.owner.release(this, this.slot);
72
+ }
73
+ [Symbol.asyncDispose]() {
74
+ return this.release();
75
+ }
76
+ };
77
+ const noop = () => {};
78
+ /**
79
+ * The loaded projects of a middle layer and their holders.
80
+ *
81
+ * At most one project object exists per id: concurrent acquires share one load, and an acquire
82
+ * that comes while the project is being destroyed waits for the destroy and loads it anew. The
83
+ * project is destroyed when its last hold is released, when it is deleted, and when the middle
84
+ * layer closes. Every state change that matters to a release happens synchronously, so a release
85
+ * that is not awaited followed at once by an acquire is safe.
86
+ */
87
+ var ProjectSlots = class {
88
+ deps;
89
+ slots = /* @__PURE__ */ new Map();
90
+ closing = false;
91
+ constructor(deps) {
92
+ this.deps = deps;
93
+ }
94
+ /** Takes a hold on the project, loading it when nobody holds it. */
95
+ async acquire(id, holder) {
96
+ for (;;) {
97
+ if (this.closing) throw new Error("Middle layer is closed");
98
+ const slot = this.slots.get(id) ?? this.startLoad(id, holder);
99
+ if (slot.state === "closing") {
100
+ await slot.closed;
101
+ continue;
102
+ }
103
+ if (slot.state === "loading") {
104
+ slot.waiting++;
105
+ try {
106
+ await slot.load;
107
+ } finally {
108
+ slot.waiting--;
109
+ }
110
+ if (slot.evicted !== void 0) throw evictionError(id, slot.evicted);
111
+ }
112
+ return this.addHold(slot, id, holder);
113
+ }
114
+ }
115
+ /** The loaded project, when the slot is open, whoever holds it. */
116
+ get(id) {
117
+ const slot = this.slots.get(id);
118
+ return slot?.state === "open" ? slot.project : void 0;
119
+ }
120
+ /** Labels of the live holds on the project, one per hold; empty when nobody holds it. */
121
+ holders(id) {
122
+ const slot = this.slots.get(id);
123
+ return slot === void 0 ? [] : [...slot.holds].map((h) => h.holder);
124
+ }
125
+ /**
126
+ * Deletes the project with `remove` (the backend write) and takes it from every holder, as
127
+ * {@link evict} with `deleted` does: holds taken while `remove` runs end too, and a load in
128
+ * flight is discarded.
129
+ *
130
+ * With `refuseIfHeldBy`, the delete is refused with a {@link ProjectInUseError}, and `remove`
131
+ * not run, when any of the {@link holders} at the start is one it returns `true` for.
132
+ */
133
+ async delete(id, remove, refuseIfHeldBy) {
134
+ if (refuseIfHeldBy !== void 0) {
135
+ const refused = this.holders(id).filter(refuseIfHeldBy);
136
+ if (refused.length > 0) throw new ProjectInUseError(id, refused);
137
+ }
138
+ await remove();
139
+ await this.evict(id, "deleted");
140
+ }
141
+ /**
142
+ * Takes the project away from all its holders: every hold ends with `reason`, a load in flight
143
+ * is discarded, and the loaded project is destroyed without a snapshot. Resolves when the destroy
144
+ * has finished. A load in flight is not waited for (the eviction may come from inside it): it
145
+ * destroys its project when it finishes, and the acquires waiting for it are rejected.
146
+ */
147
+ evict(id, reason) {
148
+ const slot = this.slots.get(id);
149
+ if (slot === void 0) return Promise.resolve();
150
+ if (slot.state === "loading") {
151
+ slot.evicted = reason;
152
+ slot.state = "closing";
153
+ slot.closed = slot.load.then(noop, noop).finally(() => this.remove(id, slot));
154
+ this.deps.logger.info(`project ${id}: load discarded (${reason})`);
155
+ return Promise.resolve();
156
+ }
157
+ if (slot.state === "open") {
158
+ slot.evicted = reason;
159
+ for (const hold of slot.holds) hold.end(reason);
160
+ slot.holds.clear();
161
+ this.close(slot, id, reason, void 0, false);
162
+ }
163
+ return slot.closed ?? Promise.resolve();
164
+ }
165
+ /**
166
+ * Ends every hold with `closed`, destroys every loaded project and refuses later acquires.
167
+ * Resolves when every project is destroyed, those of loads in flight included: such a load runs
168
+ * to its end, and its project is destroyed then.
169
+ */
170
+ async closeAll() {
171
+ this.closing = true;
172
+ const slots = [...this.slots.entries()];
173
+ await Promise.all(slots.map(([id]) => this.evict(id, "closed")));
174
+ await Promise.all(slots.map(([, slot]) => slot.closed));
175
+ }
176
+ /** @internal Called by {@link SlotHandle.release}. */
177
+ release(handle, slot) {
178
+ if (handle.ended) return slot.closed ?? Promise.resolve();
179
+ handle.end("released");
180
+ slot.holds.delete(handle);
181
+ if (slot.state === "open" && slot.holds.size === 0 && slot.waiting === 0) this.close(slot, handle.id, "released", handle.holder, true);
182
+ return slot.closed ?? Promise.resolve();
183
+ }
184
+ startLoad(id, holder) {
185
+ const startedAt = Date.now();
186
+ const slot = new Slot(async (s) => {
187
+ let project;
188
+ try {
189
+ project = await this.deps.load(id, (p) => this.onGone(id, p));
190
+ } catch (e) {
191
+ if (s.evicted !== void 0) throw evictionError(id, s.evicted);
192
+ throw e;
193
+ }
194
+ if (s.evicted !== void 0) {
195
+ await destroyQuietly(project, this.deps.logger);
196
+ throw evictionError(id, s.evicted);
197
+ }
198
+ s.project = project;
199
+ s.state = "open";
200
+ this.publish();
201
+ this.deps.logger.info(`project ${id}: loaded for ${holder} in ${Date.now() - startedAt} ms`);
202
+ return project;
203
+ });
204
+ this.slots.set(id, slot);
205
+ slot.load.catch((e) => {
206
+ if (slot.state !== "loading") return;
207
+ this.remove(id, slot);
208
+ this.deps.logger.info(`project ${id}: load for ${holder} failed: ${e instanceof Error ? e.message : String(e)}`);
209
+ });
210
+ return slot;
211
+ }
212
+ addHold(slot, id, holder) {
213
+ if (slot.project === void 0) throw new Error(`Project ${id} is open but not loaded`);
214
+ const handle = new SlotHandle(id, holder, slot.project, slot, this);
215
+ slot.holds.add(handle);
216
+ return handle;
217
+ }
218
+ /** Starts destroying an open slot. Everything before the first await happens synchronously. */
219
+ close(slot, id, cause, holder, snapshot) {
220
+ const project = slot.project;
221
+ if (project === void 0) throw new Error(`Project ${id} is open but not loaded`);
222
+ slot.state = "closing";
223
+ this.publish();
224
+ if (snapshot) this.deps.trackSnapshotWrite(project.snapshotOnClose());
225
+ slot.closed = (async () => {
226
+ try {
227
+ await destroyQuietly(project, this.deps.logger);
228
+ } finally {
229
+ this.remove(id, slot);
230
+ }
231
+ this.deps.logger.info(`project ${id}: destroyed (${cause}${holder === void 0 ? "" : ` by ${holder}`})`);
232
+ })();
233
+ }
234
+ onGone(id, project) {
235
+ const slot = this.slots.get(id);
236
+ if (slot === void 0) return;
237
+ if (slot.project !== project && slot.state !== "loading") return;
238
+ this.deps.logger.info(`project ${id}: deleted elsewhere`);
239
+ this.evict(id, "deleted");
240
+ }
241
+ remove(id, slot) {
242
+ if (this.slots.get(id) === slot) this.slots.delete(id);
243
+ }
244
+ publish() {
245
+ const open = [];
246
+ for (const [id, slot] of this.slots) if (slot.state === "open") open.push(id);
247
+ this.deps.publish(open);
248
+ }
249
+ };
250
+ function evictionError(id, reason) {
251
+ return reason === "deleted" ? notListedError("Project", id) : /* @__PURE__ */ new Error("Middle layer is closed");
252
+ }
253
+ async function destroyQuietly(project, logger) {
254
+ try {
255
+ await project.destroy();
256
+ } catch (e) {
257
+ logger.warn(new Error("Project destroy failed", { cause: e }));
258
+ }
259
+ }
260
+ export { ProjectInUseError, ProjectSlots, SlotHandle, asProjectHolder, isProjectInUseError };
261
+
262
+ //# sourceMappingURL=project_holds.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"project_holds.js","names":[],"sources":["../../src/middle_layer/project_holds.ts"],"sourcesContent":["import type { Branded } from \"@milaboratories/pl-model-common\";\nimport type { MiLogger } from \"@milaboratories/ts-helpers\";\nimport type { ProjectId } from \"../model/project_model\";\nimport { notListedError } from \"../mutator/list\";\nimport type { Project } from \"./project\";\n\n/**\n * Who holds a loaded project: a free-form label for diagnostics, logs and `refuseIfHeldBy`, e.g.\n * `desktop` or `mcp:mcp-1a2b3c4d`. Not an identity: two holds with the same label are two holds.\n */\nexport type ProjectHolder = Branded<string, \"ProjectHolder\">;\n\n/** Brands a label as a {@link ProjectHolder}; each holder makes its label once. */\nexport function asProjectHolder(label: string): ProjectHolder {\n return label as ProjectHolder;\n}\n\n/** Why a {@link ProjectHandle} stopped holding its project. */\nexport type ProjectHandleEnd =\n /** The holder gave the hold back. */\n | \"released\"\n /** The project was deleted, here or by another client. */\n | \"deleted\"\n /** The middle layer was closed. */\n | \"closed\";\n\n/**\n * One holder's hold on a loaded project. A project stays loaded while anyone holds it, and is\n * destroyed when the last hold is given back; nobody else's release can take it from under a\n * holder. Every holder releases its own handle exactly when it is done with the project.\n */\nexport interface ProjectHandle extends AsyncDisposable {\n readonly id: ProjectId;\n /** Who holds the project; see {@link ProjectHolder}. */\n readonly holder: ProjectHolder;\n /** The loaded project. Throws once the handle has ended. */\n readonly project: Project;\n /** Aborted when this handle stops holding; `signal.reason` is a {@link ProjectHandleEnd}. */\n readonly signal: AbortSignal;\n /** Whether this handle no longer holds the project. */\n readonly ended: boolean;\n /** Gives the hold back. Idempotent; never throws; resolves when a destroy it caused has finished. */\n release(): Promise<void>;\n}\n\n/**\n * Thrown by a delete that was told to refuse while the project is held: the project is untouched.\n * `holders` are the labels of the holds that caused the refusal.\n */\nexport class ProjectInUseError extends Error {\n override name = \"ProjectInUseError\";\n\n constructor(\n readonly projectId: ProjectId,\n readonly holders: ProjectHolder[],\n ) {\n super(`Project ${projectId} is in use by ${holders.join(\", \")}`);\n }\n}\n\n/** Whether `error` is a {@link ProjectInUseError}, also across copies of this package. */\nexport function isProjectInUseError(error: unknown): error is ProjectInUseError {\n return error instanceof Error && error.name === \"ProjectInUseError\";\n}\n\n/** What {@link ProjectSlots} needs from a loaded project. */\nexport interface SlotProject {\n destroy(): Promise<void>;\n snapshotOnClose(): Promise<void>;\n}\n\n/** What {@link ProjectSlots} is built on. */\nexport interface ProjectSlotsDeps<P extends SlotProject> {\n /** Loads a project. The loaded project calls `onGone` when it finds it was deleted elsewhere. */\n load: (id: ProjectId, onGone: (project: P) => void) => Promise<P>;\n /** Keeps a close-boundary snapshot write, so the middle layer's close can drain it. */\n trackSnapshotWrite: (write: Promise<void>) => void;\n /** Receives the ids of the open projects every time that set changes. */\n publish: (open: ProjectId[]) => void;\n logger: Pick<MiLogger, \"info\" | \"warn\">;\n}\n\n/** One project's place in {@link ProjectSlots}: loading, open, or being destroyed. */\nclass Slot<P> {\n state: \"loading\" | \"open\" | \"closing\" = \"loading\";\n project: P | undefined = undefined;\n readonly holds = new Set<SlotHandle<P>>();\n /** Acquires waiting for the load. The slot is not closed while any wait. */\n waiting = 0;\n /** Set when the slot was taken away from its holders rather than released. */\n evicted: ProjectHandleEnd | undefined = undefined;\n /** The destroy, once the slot is closing. */\n closed: Promise<void> | undefined = undefined;\n readonly load: Promise<P>;\n\n constructor(run: (slot: Slot<P>) => Promise<P>) {\n this.load = run(this);\n }\n}\n\n/** A hold handed out by {@link ProjectSlots}. */\nexport class SlotHandle<P> {\n private readonly controller = new AbortController();\n\n constructor(\n readonly id: ProjectId,\n readonly holder: ProjectHolder,\n private readonly loaded: P,\n private readonly slot: Slot<P>,\n private readonly owner: { release(handle: SlotHandle<P>, slot: Slot<P>): Promise<void> },\n ) {}\n\n get project(): P {\n if (this.ended)\n throw new Error(\n `The hold of ${this.holder} on project ${this.id} has ended: ${String(this.signal.reason)}`,\n );\n return this.loaded;\n }\n\n get signal(): AbortSignal {\n return this.controller.signal;\n }\n\n get ended(): boolean {\n return this.controller.signal.aborted;\n }\n\n /** Ends the hold without touching the slot; the caller does the bookkeeping. */\n end(reason: ProjectHandleEnd): void {\n this.controller.abort(reason);\n }\n\n release(): Promise<void> {\n return this.owner.release(this, this.slot);\n }\n\n [Symbol.asyncDispose](): Promise<void> {\n return this.release();\n }\n}\n\nconst noop = () => {};\n\n/**\n * The loaded projects of a middle layer and their holders.\n *\n * At most one project object exists per id: concurrent acquires share one load, and an acquire\n * that comes while the project is being destroyed waits for the destroy and loads it anew. The\n * project is destroyed when its last hold is released, when it is deleted, and when the middle\n * layer closes. Every state change that matters to a release happens synchronously, so a release\n * that is not awaited followed at once by an acquire is safe.\n */\nexport class ProjectSlots<P extends SlotProject> {\n private readonly slots = new Map<ProjectId, Slot<P>>();\n private closing = false;\n\n constructor(private readonly deps: ProjectSlotsDeps<P>) {}\n\n /** Takes a hold on the project, loading it when nobody holds it. */\n async acquire(id: ProjectId, holder: ProjectHolder): Promise<SlotHandle<P>> {\n for (;;) {\n if (this.closing) throw new Error(\"Middle layer is closed\");\n const slot = this.slots.get(id) ?? this.startLoad(id, holder);\n if (slot.state === \"closing\") {\n await slot.closed;\n continue;\n }\n if (slot.state === \"loading\") {\n slot.waiting++;\n try {\n await slot.load;\n } finally {\n slot.waiting--;\n }\n // A finished load leaves the slot open unless it was evicted meanwhile.\n if (slot.evicted !== undefined) throw evictionError(id, slot.evicted);\n }\n return this.addHold(slot, id, holder);\n }\n }\n\n /** The loaded project, when the slot is open, whoever holds it. */\n get(id: ProjectId): P | undefined {\n const slot = this.slots.get(id);\n return slot?.state === \"open\" ? slot.project : undefined;\n }\n\n /** Labels of the live holds on the project, one per hold; empty when nobody holds it. */\n holders(id: ProjectId): ProjectHolder[] {\n const slot = this.slots.get(id);\n return slot === undefined ? [] : [...slot.holds].map((h) => h.holder);\n }\n\n /**\n * Deletes the project with `remove` (the backend write) and takes it from every holder, as\n * {@link evict} with `deleted` does: holds taken while `remove` runs end too, and a load in\n * flight is discarded.\n *\n * With `refuseIfHeldBy`, the delete is refused with a {@link ProjectInUseError}, and `remove`\n * not run, when any of the {@link holders} at the start is one it returns `true` for.\n */\n async delete(\n id: ProjectId,\n remove: () => Promise<void>,\n refuseIfHeldBy?: (holder: ProjectHolder) => boolean,\n ): Promise<void> {\n if (refuseIfHeldBy !== undefined) {\n const refused = this.holders(id).filter(refuseIfHeldBy);\n if (refused.length > 0) throw new ProjectInUseError(id, refused);\n }\n await remove();\n await this.evict(id, \"deleted\");\n }\n\n /**\n * Takes the project away from all its holders: every hold ends with `reason`, a load in flight\n * is discarded, and the loaded project is destroyed without a snapshot. Resolves when the destroy\n * has finished. A load in flight is not waited for (the eviction may come from inside it): it\n * destroys its project when it finishes, and the acquires waiting for it are rejected.\n */\n evict(id: ProjectId, reason: ProjectHandleEnd): Promise<void> {\n const slot = this.slots.get(id);\n if (slot === undefined) return Promise.resolve();\n if (slot.state === \"loading\") {\n slot.evicted = reason;\n slot.state = \"closing\";\n // An acquire meanwhile waits for this, then loads anew.\n slot.closed = slot.load.then(noop, noop).finally(() => this.remove(id, slot));\n this.deps.logger.info(`project ${id}: load discarded (${reason})`);\n return Promise.resolve();\n }\n if (slot.state === \"open\") {\n slot.evicted = reason;\n for (const hold of slot.holds) hold.end(reason);\n slot.holds.clear();\n this.close(slot, id, reason, undefined, false);\n }\n return slot.closed ?? Promise.resolve();\n }\n\n /**\n * Ends every hold with `closed`, destroys every loaded project and refuses later acquires.\n * Resolves when every project is destroyed, those of loads in flight included: such a load runs\n * to its end, and its project is destroyed then.\n */\n async closeAll(): Promise<void> {\n this.closing = true;\n const slots = [...this.slots.entries()];\n await Promise.all(slots.map(([id]) => this.evict(id, \"closed\")));\n await Promise.all(slots.map(([, slot]) => slot.closed));\n }\n\n /** @internal Called by {@link SlotHandle.release}. */\n release(handle: SlotHandle<P>, slot: Slot<P>): Promise<void> {\n if (handle.ended) return slot.closed ?? Promise.resolve();\n handle.end(\"released\");\n slot.holds.delete(handle);\n if (slot.state === \"open\" && slot.holds.size === 0 && slot.waiting === 0)\n this.close(slot, handle.id, \"released\", handle.holder, true);\n return slot.closed ?? Promise.resolve();\n }\n\n private startLoad(id: ProjectId, holder: ProjectHolder): Slot<P> {\n const startedAt = Date.now();\n const slot = new Slot<P>(async (s) => {\n let project: P;\n try {\n project = await this.deps.load(id, (p) => this.onGone(id, p));\n } catch (e: unknown) {\n // A load that failed because the project was deleted under it says so plainly.\n if (s.evicted !== undefined) throw evictionError(id, s.evicted);\n throw e;\n }\n if (s.evicted !== undefined) {\n await destroyQuietly(project, this.deps.logger);\n throw evictionError(id, s.evicted);\n }\n s.project = project;\n s.state = \"open\";\n this.publish();\n this.deps.logger.info(`project ${id}: loaded for ${holder} in ${Date.now() - startedAt} ms`);\n return project;\n });\n this.slots.set(id, slot);\n slot.load.catch((e: unknown) => {\n // A load that was evicted is removed by the eviction.\n if (slot.state !== \"loading\") return;\n this.remove(id, slot);\n this.deps.logger.info(\n `project ${id}: load for ${holder} failed: ${e instanceof Error ? e.message : String(e)}`,\n );\n });\n return slot;\n }\n\n private addHold(slot: Slot<P>, id: ProjectId, holder: ProjectHolder): SlotHandle<P> {\n if (slot.project === undefined) throw new Error(`Project ${id} is open but not loaded`);\n const handle = new SlotHandle(id, holder, slot.project, slot, this);\n slot.holds.add(handle);\n return handle;\n }\n\n /** Starts destroying an open slot. Everything before the first await happens synchronously. */\n private close(\n slot: Slot<P>,\n id: ProjectId,\n cause: ProjectHandleEnd,\n holder: ProjectHolder | undefined,\n snapshot: boolean,\n ): void {\n const project = slot.project;\n if (project === undefined) throw new Error(`Project ${id} is open but not loaded`);\n slot.state = \"closing\";\n this.publish();\n // The capture inside is synchronous and needs the tree alive, so it comes before destroy.\n if (snapshot) this.deps.trackSnapshotWrite(project.snapshotOnClose());\n slot.closed = (async () => {\n try {\n await destroyQuietly(project, this.deps.logger);\n } finally {\n this.remove(id, slot);\n }\n this.deps.logger.info(\n `project ${id}: destroyed (${cause}${holder === undefined ? \"\" : ` by ${holder}`})`,\n );\n })();\n }\n\n private onGone(id: ProjectId, project: P): void {\n const slot = this.slots.get(id);\n if (slot === undefined) return;\n if (slot.project !== project && slot.state !== \"loading\") return;\n this.deps.logger.info(`project ${id}: deleted elsewhere`);\n void this.evict(id, \"deleted\");\n }\n\n private remove(id: ProjectId, slot: Slot<P>): void {\n if (this.slots.get(id) === slot) this.slots.delete(id);\n }\n\n private publish(): void {\n const open: ProjectId[] = [];\n for (const [id, slot] of this.slots) if (slot.state === \"open\") open.push(id);\n this.deps.publish(open);\n }\n}\n\nfunction evictionError(id: ProjectId, reason: ProjectHandleEnd): Error {\n return reason === \"deleted\" ? notListedError(\"Project\", id) : new Error(\"Middle layer is closed\");\n}\n\nasync function destroyQuietly(project: SlotProject, logger: Pick<MiLogger, \"warn\">): Promise<void> {\n try {\n await project.destroy();\n } catch (e: unknown) {\n logger.warn(new Error(\"Project destroy failed\", { cause: e }));\n }\n}\n"],"mappings":";;;AAaA,SAAgB,gBAAgB,OAA8B;CAC5D,OAAO;AACT;;;;;AAkCA,IAAa,oBAAb,cAAuC,MAAM;CAIhC;CACA;CAJX,OAAgB;CAEhB,YACE,WACA,SACA;EACA,MAAM,WAAW,UAAU,gBAAgB,QAAQ,KAAK,IAAI,GAAG;EAHtD,KAAA,YAAA;EACA,KAAA,UAAA;CAGX;AACF;;AAGA,SAAgB,oBAAoB,OAA4C;CAC9E,OAAO,iBAAiB,SAAS,MAAM,SAAS;AAClD;;AAoBA,IAAM,OAAN,MAAc;CACZ,QAAwC;CACxC,UAAyB,KAAA;CACzB,wBAAiB,IAAI,IAAmB;;CAExC,UAAU;;CAEV,UAAwC,KAAA;;CAExC,SAAoC,KAAA;CACpC;CAEA,YAAY,KAAoC;EAC9C,KAAK,OAAO,IAAI,IAAI;CACtB;AACF;;AAGA,IAAa,aAAb,MAA2B;CAId;CACA;CACQ;CACA;CACA;CAPnB,aAA8B,IAAI,gBAAgB;CAElD,YACE,IACA,QACA,QACA,MACA,OACA;EALS,KAAA,KAAA;EACA,KAAA,SAAA;EACQ,KAAA,SAAA;EACA,KAAA,OAAA;EACA,KAAA,QAAA;CAChB;CAEH,IAAI,UAAa;EACf,IAAI,KAAK,OACP,MAAM,IAAI,MACR,eAAe,KAAK,OAAO,cAAc,KAAK,GAAG,cAAc,OAAO,KAAK,OAAO,MAAM,GAC1F;EACF,OAAO,KAAK;CACd;CAEA,IAAI,SAAsB;EACxB,OAAO,KAAK,WAAW;CACzB;CAEA,IAAI,QAAiB;EACnB,OAAO,KAAK,WAAW,OAAO;CAChC;;CAGA,IAAI,QAAg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