@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.
- package/dist/index.cjs +4 -0
- package/dist/index.d.ts +2 -1
- package/dist/index.js +2 -1
- package/dist/middle_layer/build_stamp.cjs +1 -1
- package/dist/middle_layer/build_stamp.js +1 -1
- package/dist/middle_layer/index.cjs +4 -0
- package/dist/middle_layer/index.d.ts +2 -1
- package/dist/middle_layer/index.js +2 -1
- package/dist/middle_layer/middle_layer.cjs +96 -28
- package/dist/middle_layer/middle_layer.cjs.map +1 -1
- package/dist/middle_layer/middle_layer.d.ts +54 -8
- package/dist/middle_layer/middle_layer.d.ts.map +1 -1
- package/dist/middle_layer/middle_layer.js +96 -28
- package/dist/middle_layer/middle_layer.js.map +1 -1
- package/dist/middle_layer/project.cjs +39 -17
- package/dist/middle_layer/project.cjs.map +1 -1
- package/dist/middle_layer/project.d.ts +17 -2
- package/dist/middle_layer/project.d.ts.map +1 -1
- package/dist/middle_layer/project.js +39 -17
- package/dist/middle_layer/project.js.map +1 -1
- package/dist/middle_layer/project_holds.cjs +266 -0
- package/dist/middle_layer/project_holds.cjs.map +1 -0
- package/dist/middle_layer/project_holds.d.ts +50 -0
- package/dist/middle_layer/project_holds.d.ts.map +1 -0
- package/dist/middle_layer/project_holds.js +262 -0
- package/dist/middle_layer/project_holds.js.map +1 -0
- package/package.json +6 -6
- package/src/middle_layer/index.ts +2 -0
- package/src/middle_layer/middle_layer.ts +117 -38
- package/src/middle_layer/project.ts +40 -15
- package/src/middle_layer/project_close_during_write.test.ts +142 -0
- package/src/middle_layer/project_handles.test.ts +168 -0
- package/src/middle_layer/project_holds.ts +359 -0
- package/src/middle_layer/project_slots.test.ts +331 -0
- package/src/test/write_tx_hooks.ts +75 -0
|
@@ -0,0 +1,168 @@
|
|
|
1
|
+
import path from "node:path";
|
|
2
|
+
import * as tp from "node:timers/promises";
|
|
3
|
+
import { expect, test } from "vitest";
|
|
4
|
+
import type { BlockPackSpec } from "@milaboratories/pl-model-middle-layer";
|
|
5
|
+
import { withMl } from "../test/with_ml";
|
|
6
|
+
import { countWriteTx, onceAfterWriteTx } from "../test/write_tx_hooks";
|
|
7
|
+
import { asProjectHolder } from "./project_holds";
|
|
8
|
+
|
|
9
|
+
/**
|
|
10
|
+
* Shared project handles against a live backend: a project stays loaded while anyone holds it,
|
|
11
|
+
* one load serves every holder, a release never takes the project from another holder, and a
|
|
12
|
+
* deleted project is taken from all of them.
|
|
13
|
+
*/
|
|
14
|
+
|
|
15
|
+
const EnterNumbers: BlockPackSpec = {
|
|
16
|
+
type: "dev-v2",
|
|
17
|
+
folder: path.resolve(__dirname, "../../../../../etc/blocks/enter-numbers/block"),
|
|
18
|
+
};
|
|
19
|
+
|
|
20
|
+
/** Longer than two refresh intervals of the project maintenance loop (2 s by default). */
|
|
21
|
+
const QUIET_WINDOW_MS = 5_000;
|
|
22
|
+
|
|
23
|
+
test("T-ML2: concurrent acquires load the project once, and the last release stops its loop", async () => {
|
|
24
|
+
await withMl(async (ml) => {
|
|
25
|
+
const id = await ml.createProject({ label: "concurrent" });
|
|
26
|
+
const txs = countWriteTx(ml.pl);
|
|
27
|
+
try {
|
|
28
|
+
const handles = await Promise.all(
|
|
29
|
+
[1, 2, 3, 4, 5].map((n) => ml.acquireProject(id, asProjectHolder(`holder-${n}`))),
|
|
30
|
+
);
|
|
31
|
+
expect(txs.count("ProjectAction: init")).toBe(1);
|
|
32
|
+
expect(new Set(handles.map((h) => h.project)).size).toBe(1);
|
|
33
|
+
expect(ml.projectHolders(id)).toHaveLength(5);
|
|
34
|
+
|
|
35
|
+
await Promise.all(handles.map((h) => h.release()));
|
|
36
|
+
expect(ml.isProjectOpened(id)).toBe(false);
|
|
37
|
+
const refreshes = txs.count("ProjectAction: doRefresh");
|
|
38
|
+
await tp.setTimeout(QUIET_WINDOW_MS);
|
|
39
|
+
expect(txs.count("ProjectAction: doRefresh")).toBe(refreshes);
|
|
40
|
+
} finally {
|
|
41
|
+
txs.restore();
|
|
42
|
+
}
|
|
43
|
+
});
|
|
44
|
+
});
|
|
45
|
+
|
|
46
|
+
test("T-ML5: a write resolves when another holder, or the last one, releases during it", async () => {
|
|
47
|
+
await withMl(async (ml) => {
|
|
48
|
+
const id = await ml.createProject({ label: "release during write" });
|
|
49
|
+
|
|
50
|
+
// Another holder goes away right after the commit: the writer still holds the project.
|
|
51
|
+
const a = await ml.acquireProject(id, asProjectHolder("a"));
|
|
52
|
+
const b = await ml.acquireProject(id, asProjectHolder("b"));
|
|
53
|
+
const otherGoes = onceAfterWriteTx(ml.pl, "ProjectAction: addBlock", () => b.release());
|
|
54
|
+
let first: string;
|
|
55
|
+
try {
|
|
56
|
+
first = await a.project.addBlock("First", EnterNumbers);
|
|
57
|
+
} finally {
|
|
58
|
+
otherGoes.restore();
|
|
59
|
+
}
|
|
60
|
+
expect(otherGoes.fired()).toBe(true);
|
|
61
|
+
expect(ml.isProjectOpened(id)).toBe(true);
|
|
62
|
+
expect((await a.project.overview.awaitStableValue()).blocks.map((x) => x.id)).toEqual([first]);
|
|
63
|
+
|
|
64
|
+
// The writer's own hold is the last one and goes away right after the commit.
|
|
65
|
+
const writerGoes = onceAfterWriteTx(ml.pl, "ProjectAction: addBlock", () => a.release());
|
|
66
|
+
const project = a.project;
|
|
67
|
+
let second: string;
|
|
68
|
+
try {
|
|
69
|
+
second = await project.addBlock("Second", EnterNumbers);
|
|
70
|
+
} finally {
|
|
71
|
+
writerGoes.restore();
|
|
72
|
+
}
|
|
73
|
+
expect(writerGoes.fired()).toBe(true);
|
|
74
|
+
expect(ml.isProjectOpened(id)).toBe(false);
|
|
75
|
+
|
|
76
|
+
const c = await ml.acquireProject(id, asProjectHolder("c"));
|
|
77
|
+
const blocks = (await c.project.overview.awaitStableValue()).blocks.map((x) => x.id);
|
|
78
|
+
expect(blocks).toEqual([first, second]);
|
|
79
|
+
await c.release();
|
|
80
|
+
});
|
|
81
|
+
});
|
|
82
|
+
|
|
83
|
+
test("T-ML6: deleting a held project ends every hold and stops the project", async () => {
|
|
84
|
+
await withMl(async (ml) => {
|
|
85
|
+
const id = await ml.createProject({ label: "deleted while held" });
|
|
86
|
+
const a = await ml.acquireProject(id, asProjectHolder("a"));
|
|
87
|
+
const b = await ml.acquireProject(id, asProjectHolder("b"));
|
|
88
|
+
await a.project.overview.awaitStableValue();
|
|
89
|
+
|
|
90
|
+
await ml.deleteProject(id);
|
|
91
|
+
expect(a.signal.reason).toBe("deleted");
|
|
92
|
+
expect(b.signal.reason).toBe("deleted");
|
|
93
|
+
expect(ml.isProjectOpened(id)).toBe(false);
|
|
94
|
+
expect(ml.projectHolders(id)).toEqual([]);
|
|
95
|
+
await expect(a.release()).resolves.toBeUndefined();
|
|
96
|
+
|
|
97
|
+
const txs = countWriteTx(ml.pl);
|
|
98
|
+
try {
|
|
99
|
+
await tp.setTimeout(QUIET_WINDOW_MS);
|
|
100
|
+
expect(txs.count("ProjectAction: doRefresh")).toBe(0);
|
|
101
|
+
} finally {
|
|
102
|
+
txs.restore();
|
|
103
|
+
}
|
|
104
|
+
await expect(ml.acquireProject(id, asProjectHolder("c"))).rejects.toThrow(/not found/);
|
|
105
|
+
});
|
|
106
|
+
});
|
|
107
|
+
|
|
108
|
+
test("T-ML6: deleting the folder of a held project ends every hold", async () => {
|
|
109
|
+
await withMl(async (ml) => {
|
|
110
|
+
const folder = await ml.createFolder("Doomed");
|
|
111
|
+
const id = await ml.createProject({ label: "in a folder" }, folder);
|
|
112
|
+
const a = await ml.acquireProject(id, asProjectHolder("a"));
|
|
113
|
+
|
|
114
|
+
const planned = await ml.previewFolderDeletion(folder);
|
|
115
|
+
expect(planned.ok).toBe(true);
|
|
116
|
+
if (!planned.ok) return;
|
|
117
|
+
expect(planned.removal.projects).toContain(id);
|
|
118
|
+
expect((await ml.deleteFolder(folder, planned.removal)).ok).toBe(true);
|
|
119
|
+
|
|
120
|
+
expect(a.signal.reason).toBe("deleted");
|
|
121
|
+
expect(ml.isProjectOpened(id)).toBe(false);
|
|
122
|
+
});
|
|
123
|
+
});
|
|
124
|
+
|
|
125
|
+
test("T-ML8: the legacy open and close are a hold of their own", async () => {
|
|
126
|
+
await withMl(async (ml) => {
|
|
127
|
+
const id = await ml.createProject({ label: "legacy" });
|
|
128
|
+
await ml.openProject(id);
|
|
129
|
+
// A second open is a no-op, not an error.
|
|
130
|
+
await ml.openProject(id);
|
|
131
|
+
expect(ml.projectHolders(id)).toEqual(["legacy"]);
|
|
132
|
+
|
|
133
|
+
const agent = await ml.acquireProject(id, asProjectHolder("mcp:test"));
|
|
134
|
+
await ml.closeProject(id);
|
|
135
|
+
expect(ml.isProjectOpened(id)).toBe(true);
|
|
136
|
+
expect(ml.projectHolders(id)).toEqual(["mcp:test"]);
|
|
137
|
+
expect(ml.getOpenedProject(id)).toBe(agent.project);
|
|
138
|
+
|
|
139
|
+
// Nothing of the legacy API holds it any more; closing again changes nothing.
|
|
140
|
+
await ml.closeProject(id);
|
|
141
|
+
expect(ml.isProjectOpened(id)).toBe(true);
|
|
142
|
+
|
|
143
|
+
await agent.release();
|
|
144
|
+
expect(ml.isProjectOpened(id)).toBe(false);
|
|
145
|
+
expect(() => ml.getOpenedProject(id)).toThrow(/not found among opened projects/);
|
|
146
|
+
});
|
|
147
|
+
});
|
|
148
|
+
|
|
149
|
+
test("T-ML10: two concurrent legacy opens take one hold, and one close lets the project go", async () => {
|
|
150
|
+
await withMl(async (ml) => {
|
|
151
|
+
const id = await ml.createProject({ label: "opened twice at once" });
|
|
152
|
+
await Promise.all([ml.openProject(id), ml.openProject(id)]);
|
|
153
|
+
expect(ml.projectHolders(id)).toEqual(["legacy"]);
|
|
154
|
+
await ml.closeProject(id);
|
|
155
|
+
expect(ml.isProjectOpened(id)).toBe(false);
|
|
156
|
+
expect(ml.projectHolders(id)).toEqual([]);
|
|
157
|
+
});
|
|
158
|
+
});
|
|
159
|
+
|
|
160
|
+
test("T-ML12: a legacy hold taken by a delete is forgotten", async () => {
|
|
161
|
+
await withMl(async (ml) => {
|
|
162
|
+
const id = await ml.createProject({ label: "legacy deleted" });
|
|
163
|
+
await ml.openProject(id);
|
|
164
|
+
expect(ml["legacyHolds"].has(id)).toBe(true);
|
|
165
|
+
await ml.deleteProject(id);
|
|
166
|
+
expect(ml["legacyHolds"].has(id)).toBe(false);
|
|
167
|
+
});
|
|
168
|
+
});
|
|
@@ -0,0 +1,359 @@
|
|
|
1
|
+
import type { Branded } from "@milaboratories/pl-model-common";
|
|
2
|
+
import type { MiLogger } from "@milaboratories/ts-helpers";
|
|
3
|
+
import type { ProjectId } from "../model/project_model";
|
|
4
|
+
import { notListedError } from "../mutator/list";
|
|
5
|
+
import type { Project } from "./project";
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* Who holds a loaded project: a free-form label for diagnostics, logs and `refuseIfHeldBy`, e.g.
|
|
9
|
+
* `desktop` or `mcp:mcp-1a2b3c4d`. Not an identity: two holds with the same label are two holds.
|
|
10
|
+
*/
|
|
11
|
+
export type ProjectHolder = Branded<string, "ProjectHolder">;
|
|
12
|
+
|
|
13
|
+
/** Brands a label as a {@link ProjectHolder}; each holder makes its label once. */
|
|
14
|
+
export function asProjectHolder(label: string): ProjectHolder {
|
|
15
|
+
return label as ProjectHolder;
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
/** Why a {@link ProjectHandle} stopped holding its project. */
|
|
19
|
+
export type ProjectHandleEnd =
|
|
20
|
+
/** The holder gave the hold back. */
|
|
21
|
+
| "released"
|
|
22
|
+
/** The project was deleted, here or by another client. */
|
|
23
|
+
| "deleted"
|
|
24
|
+
/** The middle layer was closed. */
|
|
25
|
+
| "closed";
|
|
26
|
+
|
|
27
|
+
/**
|
|
28
|
+
* One holder's hold on a loaded project. A project stays loaded while anyone holds it, and is
|
|
29
|
+
* destroyed when the last hold is given back; nobody else's release can take it from under a
|
|
30
|
+
* holder. Every holder releases its own handle exactly when it is done with the project.
|
|
31
|
+
*/
|
|
32
|
+
export interface ProjectHandle extends AsyncDisposable {
|
|
33
|
+
readonly id: ProjectId;
|
|
34
|
+
/** Who holds the project; see {@link ProjectHolder}. */
|
|
35
|
+
readonly holder: ProjectHolder;
|
|
36
|
+
/** The loaded project. Throws once the handle has ended. */
|
|
37
|
+
readonly project: Project;
|
|
38
|
+
/** Aborted when this handle stops holding; `signal.reason` is a {@link ProjectHandleEnd}. */
|
|
39
|
+
readonly signal: AbortSignal;
|
|
40
|
+
/** Whether this handle no longer holds the project. */
|
|
41
|
+
readonly ended: boolean;
|
|
42
|
+
/** Gives the hold back. Idempotent; never throws; resolves when a destroy it caused has finished. */
|
|
43
|
+
release(): Promise<void>;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/**
|
|
47
|
+
* Thrown by a delete that was told to refuse while the project is held: the project is untouched.
|
|
48
|
+
* `holders` are the labels of the holds that caused the refusal.
|
|
49
|
+
*/
|
|
50
|
+
export class ProjectInUseError extends Error {
|
|
51
|
+
override name = "ProjectInUseError";
|
|
52
|
+
|
|
53
|
+
constructor(
|
|
54
|
+
readonly projectId: ProjectId,
|
|
55
|
+
readonly holders: ProjectHolder[],
|
|
56
|
+
) {
|
|
57
|
+
super(`Project ${projectId} is in use by ${holders.join(", ")}`);
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/** Whether `error` is a {@link ProjectInUseError}, also across copies of this package. */
|
|
62
|
+
export function isProjectInUseError(error: unknown): error is ProjectInUseError {
|
|
63
|
+
return error instanceof Error && error.name === "ProjectInUseError";
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/** What {@link ProjectSlots} needs from a loaded project. */
|
|
67
|
+
export interface SlotProject {
|
|
68
|
+
destroy(): Promise<void>;
|
|
69
|
+
snapshotOnClose(): Promise<void>;
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/** What {@link ProjectSlots} is built on. */
|
|
73
|
+
export interface ProjectSlotsDeps<P extends SlotProject> {
|
|
74
|
+
/** Loads a project. The loaded project calls `onGone` when it finds it was deleted elsewhere. */
|
|
75
|
+
load: (id: ProjectId, onGone: (project: P) => void) => Promise<P>;
|
|
76
|
+
/** Keeps a close-boundary snapshot write, so the middle layer's close can drain it. */
|
|
77
|
+
trackSnapshotWrite: (write: Promise<void>) => void;
|
|
78
|
+
/** Receives the ids of the open projects every time that set changes. */
|
|
79
|
+
publish: (open: ProjectId[]) => void;
|
|
80
|
+
logger: Pick<MiLogger, "info" | "warn">;
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
/** One project's place in {@link ProjectSlots}: loading, open, or being destroyed. */
|
|
84
|
+
class Slot<P> {
|
|
85
|
+
state: "loading" | "open" | "closing" = "loading";
|
|
86
|
+
project: P | undefined = undefined;
|
|
87
|
+
readonly holds = new Set<SlotHandle<P>>();
|
|
88
|
+
/** Acquires waiting for the load. The slot is not closed while any wait. */
|
|
89
|
+
waiting = 0;
|
|
90
|
+
/** Set when the slot was taken away from its holders rather than released. */
|
|
91
|
+
evicted: ProjectHandleEnd | undefined = undefined;
|
|
92
|
+
/** The destroy, once the slot is closing. */
|
|
93
|
+
closed: Promise<void> | undefined = undefined;
|
|
94
|
+
readonly load: Promise<P>;
|
|
95
|
+
|
|
96
|
+
constructor(run: (slot: Slot<P>) => Promise<P>) {
|
|
97
|
+
this.load = run(this);
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
/** A hold handed out by {@link ProjectSlots}. */
|
|
102
|
+
export class SlotHandle<P> {
|
|
103
|
+
private readonly controller = new AbortController();
|
|
104
|
+
|
|
105
|
+
constructor(
|
|
106
|
+
readonly id: ProjectId,
|
|
107
|
+
readonly holder: ProjectHolder,
|
|
108
|
+
private readonly loaded: P,
|
|
109
|
+
private readonly slot: Slot<P>,
|
|
110
|
+
private readonly owner: { release(handle: SlotHandle<P>, slot: Slot<P>): Promise<void> },
|
|
111
|
+
) {}
|
|
112
|
+
|
|
113
|
+
get project(): P {
|
|
114
|
+
if (this.ended)
|
|
115
|
+
throw new Error(
|
|
116
|
+
`The hold of ${this.holder} on project ${this.id} has ended: ${String(this.signal.reason)}`,
|
|
117
|
+
);
|
|
118
|
+
return this.loaded;
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
get signal(): AbortSignal {
|
|
122
|
+
return this.controller.signal;
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
get ended(): boolean {
|
|
126
|
+
return this.controller.signal.aborted;
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
/** Ends the hold without touching the slot; the caller does the bookkeeping. */
|
|
130
|
+
end(reason: ProjectHandleEnd): void {
|
|
131
|
+
this.controller.abort(reason);
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
release(): Promise<void> {
|
|
135
|
+
return this.owner.release(this, this.slot);
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
[Symbol.asyncDispose](): Promise<void> {
|
|
139
|
+
return this.release();
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
const noop = () => {};
|
|
144
|
+
|
|
145
|
+
/**
|
|
146
|
+
* The loaded projects of a middle layer and their holders.
|
|
147
|
+
*
|
|
148
|
+
* At most one project object exists per id: concurrent acquires share one load, and an acquire
|
|
149
|
+
* that comes while the project is being destroyed waits for the destroy and loads it anew. The
|
|
150
|
+
* project is destroyed when its last hold is released, when it is deleted, and when the middle
|
|
151
|
+
* layer closes. Every state change that matters to a release happens synchronously, so a release
|
|
152
|
+
* that is not awaited followed at once by an acquire is safe.
|
|
153
|
+
*/
|
|
154
|
+
export class ProjectSlots<P extends SlotProject> {
|
|
155
|
+
private readonly slots = new Map<ProjectId, Slot<P>>();
|
|
156
|
+
private closing = false;
|
|
157
|
+
|
|
158
|
+
constructor(private readonly deps: ProjectSlotsDeps<P>) {}
|
|
159
|
+
|
|
160
|
+
/** Takes a hold on the project, loading it when nobody holds it. */
|
|
161
|
+
async acquire(id: ProjectId, holder: ProjectHolder): Promise<SlotHandle<P>> {
|
|
162
|
+
for (;;) {
|
|
163
|
+
if (this.closing) throw new Error("Middle layer is closed");
|
|
164
|
+
const slot = this.slots.get(id) ?? this.startLoad(id, holder);
|
|
165
|
+
if (slot.state === "closing") {
|
|
166
|
+
await slot.closed;
|
|
167
|
+
continue;
|
|
168
|
+
}
|
|
169
|
+
if (slot.state === "loading") {
|
|
170
|
+
slot.waiting++;
|
|
171
|
+
try {
|
|
172
|
+
await slot.load;
|
|
173
|
+
} finally {
|
|
174
|
+
slot.waiting--;
|
|
175
|
+
}
|
|
176
|
+
// A finished load leaves the slot open unless it was evicted meanwhile.
|
|
177
|
+
if (slot.evicted !== undefined) throw evictionError(id, slot.evicted);
|
|
178
|
+
}
|
|
179
|
+
return this.addHold(slot, id, holder);
|
|
180
|
+
}
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
/** The loaded project, when the slot is open, whoever holds it. */
|
|
184
|
+
get(id: ProjectId): P | undefined {
|
|
185
|
+
const slot = this.slots.get(id);
|
|
186
|
+
return slot?.state === "open" ? slot.project : undefined;
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
/** Labels of the live holds on the project, one per hold; empty when nobody holds it. */
|
|
190
|
+
holders(id: ProjectId): ProjectHolder[] {
|
|
191
|
+
const slot = this.slots.get(id);
|
|
192
|
+
return slot === undefined ? [] : [...slot.holds].map((h) => h.holder);
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
/**
|
|
196
|
+
* Deletes the project with `remove` (the backend write) and takes it from every holder, as
|
|
197
|
+
* {@link evict} with `deleted` does: holds taken while `remove` runs end too, and a load in
|
|
198
|
+
* flight is discarded.
|
|
199
|
+
*
|
|
200
|
+
* With `refuseIfHeldBy`, the delete is refused with a {@link ProjectInUseError}, and `remove`
|
|
201
|
+
* not run, when any of the {@link holders} at the start is one it returns `true` for.
|
|
202
|
+
*/
|
|
203
|
+
async delete(
|
|
204
|
+
id: ProjectId,
|
|
205
|
+
remove: () => Promise<void>,
|
|
206
|
+
refuseIfHeldBy?: (holder: ProjectHolder) => boolean,
|
|
207
|
+
): Promise<void> {
|
|
208
|
+
if (refuseIfHeldBy !== undefined) {
|
|
209
|
+
const refused = this.holders(id).filter(refuseIfHeldBy);
|
|
210
|
+
if (refused.length > 0) throw new ProjectInUseError(id, refused);
|
|
211
|
+
}
|
|
212
|
+
await remove();
|
|
213
|
+
await this.evict(id, "deleted");
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
/**
|
|
217
|
+
* Takes the project away from all its holders: every hold ends with `reason`, a load in flight
|
|
218
|
+
* is discarded, and the loaded project is destroyed without a snapshot. Resolves when the destroy
|
|
219
|
+
* has finished. A load in flight is not waited for (the eviction may come from inside it): it
|
|
220
|
+
* destroys its project when it finishes, and the acquires waiting for it are rejected.
|
|
221
|
+
*/
|
|
222
|
+
evict(id: ProjectId, reason: ProjectHandleEnd): Promise<void> {
|
|
223
|
+
const slot = this.slots.get(id);
|
|
224
|
+
if (slot === undefined) return Promise.resolve();
|
|
225
|
+
if (slot.state === "loading") {
|
|
226
|
+
slot.evicted = reason;
|
|
227
|
+
slot.state = "closing";
|
|
228
|
+
// An acquire meanwhile waits for this, then loads anew.
|
|
229
|
+
slot.closed = slot.load.then(noop, noop).finally(() => this.remove(id, slot));
|
|
230
|
+
this.deps.logger.info(`project ${id}: load discarded (${reason})`);
|
|
231
|
+
return Promise.resolve();
|
|
232
|
+
}
|
|
233
|
+
if (slot.state === "open") {
|
|
234
|
+
slot.evicted = reason;
|
|
235
|
+
for (const hold of slot.holds) hold.end(reason);
|
|
236
|
+
slot.holds.clear();
|
|
237
|
+
this.close(slot, id, reason, undefined, false);
|
|
238
|
+
}
|
|
239
|
+
return slot.closed ?? Promise.resolve();
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
/**
|
|
243
|
+
* Ends every hold with `closed`, destroys every loaded project and refuses later acquires.
|
|
244
|
+
* Resolves when every project is destroyed, those of loads in flight included: such a load runs
|
|
245
|
+
* to its end, and its project is destroyed then.
|
|
246
|
+
*/
|
|
247
|
+
async closeAll(): Promise<void> {
|
|
248
|
+
this.closing = true;
|
|
249
|
+
const slots = [...this.slots.entries()];
|
|
250
|
+
await Promise.all(slots.map(([id]) => this.evict(id, "closed")));
|
|
251
|
+
await Promise.all(slots.map(([, slot]) => slot.closed));
|
|
252
|
+
}
|
|
253
|
+
|
|
254
|
+
/** @internal Called by {@link SlotHandle.release}. */
|
|
255
|
+
release(handle: SlotHandle<P>, slot: Slot<P>): Promise<void> {
|
|
256
|
+
if (handle.ended) return slot.closed ?? Promise.resolve();
|
|
257
|
+
handle.end("released");
|
|
258
|
+
slot.holds.delete(handle);
|
|
259
|
+
if (slot.state === "open" && slot.holds.size === 0 && slot.waiting === 0)
|
|
260
|
+
this.close(slot, handle.id, "released", handle.holder, true);
|
|
261
|
+
return slot.closed ?? Promise.resolve();
|
|
262
|
+
}
|
|
263
|
+
|
|
264
|
+
private startLoad(id: ProjectId, holder: ProjectHolder): Slot<P> {
|
|
265
|
+
const startedAt = Date.now();
|
|
266
|
+
const slot = new Slot<P>(async (s) => {
|
|
267
|
+
let project: P;
|
|
268
|
+
try {
|
|
269
|
+
project = await this.deps.load(id, (p) => this.onGone(id, p));
|
|
270
|
+
} catch (e: unknown) {
|
|
271
|
+
// A load that failed because the project was deleted under it says so plainly.
|
|
272
|
+
if (s.evicted !== undefined) throw evictionError(id, s.evicted);
|
|
273
|
+
throw e;
|
|
274
|
+
}
|
|
275
|
+
if (s.evicted !== undefined) {
|
|
276
|
+
await destroyQuietly(project, this.deps.logger);
|
|
277
|
+
throw evictionError(id, s.evicted);
|
|
278
|
+
}
|
|
279
|
+
s.project = project;
|
|
280
|
+
s.state = "open";
|
|
281
|
+
this.publish();
|
|
282
|
+
this.deps.logger.info(`project ${id}: loaded for ${holder} in ${Date.now() - startedAt} ms`);
|
|
283
|
+
return project;
|
|
284
|
+
});
|
|
285
|
+
this.slots.set(id, slot);
|
|
286
|
+
slot.load.catch((e: unknown) => {
|
|
287
|
+
// A load that was evicted is removed by the eviction.
|
|
288
|
+
if (slot.state !== "loading") return;
|
|
289
|
+
this.remove(id, slot);
|
|
290
|
+
this.deps.logger.info(
|
|
291
|
+
`project ${id}: load for ${holder} failed: ${e instanceof Error ? e.message : String(e)}`,
|
|
292
|
+
);
|
|
293
|
+
});
|
|
294
|
+
return slot;
|
|
295
|
+
}
|
|
296
|
+
|
|
297
|
+
private addHold(slot: Slot<P>, id: ProjectId, holder: ProjectHolder): SlotHandle<P> {
|
|
298
|
+
if (slot.project === undefined) throw new Error(`Project ${id} is open but not loaded`);
|
|
299
|
+
const handle = new SlotHandle(id, holder, slot.project, slot, this);
|
|
300
|
+
slot.holds.add(handle);
|
|
301
|
+
return handle;
|
|
302
|
+
}
|
|
303
|
+
|
|
304
|
+
/** Starts destroying an open slot. Everything before the first await happens synchronously. */
|
|
305
|
+
private close(
|
|
306
|
+
slot: Slot<P>,
|
|
307
|
+
id: ProjectId,
|
|
308
|
+
cause: ProjectHandleEnd,
|
|
309
|
+
holder: ProjectHolder | undefined,
|
|
310
|
+
snapshot: boolean,
|
|
311
|
+
): void {
|
|
312
|
+
const project = slot.project;
|
|
313
|
+
if (project === undefined) throw new Error(`Project ${id} is open but not loaded`);
|
|
314
|
+
slot.state = "closing";
|
|
315
|
+
this.publish();
|
|
316
|
+
// The capture inside is synchronous and needs the tree alive, so it comes before destroy.
|
|
317
|
+
if (snapshot) this.deps.trackSnapshotWrite(project.snapshotOnClose());
|
|
318
|
+
slot.closed = (async () => {
|
|
319
|
+
try {
|
|
320
|
+
await destroyQuietly(project, this.deps.logger);
|
|
321
|
+
} finally {
|
|
322
|
+
this.remove(id, slot);
|
|
323
|
+
}
|
|
324
|
+
this.deps.logger.info(
|
|
325
|
+
`project ${id}: destroyed (${cause}${holder === undefined ? "" : ` by ${holder}`})`,
|
|
326
|
+
);
|
|
327
|
+
})();
|
|
328
|
+
}
|
|
329
|
+
|
|
330
|
+
private onGone(id: ProjectId, project: P): void {
|
|
331
|
+
const slot = this.slots.get(id);
|
|
332
|
+
if (slot === undefined) return;
|
|
333
|
+
if (slot.project !== project && slot.state !== "loading") return;
|
|
334
|
+
this.deps.logger.info(`project ${id}: deleted elsewhere`);
|
|
335
|
+
void this.evict(id, "deleted");
|
|
336
|
+
}
|
|
337
|
+
|
|
338
|
+
private remove(id: ProjectId, slot: Slot<P>): void {
|
|
339
|
+
if (this.slots.get(id) === slot) this.slots.delete(id);
|
|
340
|
+
}
|
|
341
|
+
|
|
342
|
+
private publish(): void {
|
|
343
|
+
const open: ProjectId[] = [];
|
|
344
|
+
for (const [id, slot] of this.slots) if (slot.state === "open") open.push(id);
|
|
345
|
+
this.deps.publish(open);
|
|
346
|
+
}
|
|
347
|
+
}
|
|
348
|
+
|
|
349
|
+
function evictionError(id: ProjectId, reason: ProjectHandleEnd): Error {
|
|
350
|
+
return reason === "deleted" ? notListedError("Project", id) : new Error("Middle layer is closed");
|
|
351
|
+
}
|
|
352
|
+
|
|
353
|
+
async function destroyQuietly(project: SlotProject, logger: Pick<MiLogger, "warn">): Promise<void> {
|
|
354
|
+
try {
|
|
355
|
+
await project.destroy();
|
|
356
|
+
} catch (e: unknown) {
|
|
357
|
+
logger.warn(new Error("Project destroy failed", { cause: e }));
|
|
358
|
+
}
|
|
359
|
+
}
|