@procedures/mongo 0.15.0 → 0.16.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/CHANGELOG.md +22 -0
- package/README.md +8 -0
- package/dist/.tsbuildinfo +1 -1
- package/dist/index.d.ts +2 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +2 -0
- package/dist/index.js.map +1 -1
- package/dist/storage/index.d.ts +2 -0
- package/dist/storage/index.d.ts.map +1 -1
- package/dist/storage/index.js +2 -0
- package/dist/storage/index.js.map +1 -1
- package/dist/storage/view-storage.d.ts +99 -0
- package/dist/storage/view-storage.d.ts.map +1 -0
- package/dist/storage/view-storage.js +189 -0
- package/dist/storage/view-storage.js.map +1 -0
- package/package.json +3 -3
- package/src/index.ts +3 -0
- package/src/storage/index.ts +3 -0
- package/src/storage/view-storage.ts +243 -0
|
@@ -0,0 +1,243 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `MongoViewStorage`: the rows of one materialized view as a read-only `CollectionStorage`
|
|
3
|
+
* (roadmap CLI-38). The collection procedures can then serve a view, and each reader of them gets
|
|
4
|
+
* one whole generation.
|
|
5
|
+
*
|
|
6
|
+
* A `ViewMaterializer` writes a big rebuild as a new generation in groups. Then it changes the
|
|
7
|
+
* generation in the status of the view. During the rebuild, the target has the rows of two
|
|
8
|
+
* generations, and a plain query reads both. This storage reads the status of the view one time
|
|
9
|
+
* for each operation, and reads only the rows of that generation (`viewFilter`). Thus `get`,
|
|
10
|
+
* `getAll`, `find`, `changes` and the other reads of the procedures do not mix two generations.
|
|
11
|
+
*
|
|
12
|
+
* - The key of a row is the `_id` of the row in the result of the pipeline. It must be a text.
|
|
13
|
+
* - The value of a row is the row of the result: its `_id` and its fields, without the fields of
|
|
14
|
+
* the materializer (the partition, `_viewGen` and `_viewHash`).
|
|
15
|
+
* - The storage has no change log. The procedure `changes` thus gives all the rows of the current
|
|
16
|
+
* generation.
|
|
17
|
+
* - A read that starts before a change of generation ends on the previous generation. The
|
|
18
|
+
* materializer keeps its rows for `generationGrace`, so a read must end in that time.
|
|
19
|
+
* - Before the first pass of the view, and without the view document, the storage has no row.
|
|
20
|
+
* - Only the materializer writes a target. Each write of this storage rejects with `FORBIDDEN`.
|
|
21
|
+
*/
|
|
22
|
+
|
|
23
|
+
import type { Collection, Db, Document, ObjectId } from "mongodb";
|
|
24
|
+
import type { CollectionStorage, StorageMetadata } from "@procedures/collections";
|
|
25
|
+
import { ensureConnection } from "../connection.js";
|
|
26
|
+
import { partitionTargetId, viewFilter, VIEW_GENERATION_FIELD, VIEW_HASH_FIELD, type MaterializedView, type MaterializedViewStatus, type ViewTargetId } from "./materializer.js";
|
|
27
|
+
|
|
28
|
+
/** The options of a `MongoViewStorage`. Give the same names as to the `ViewMaterializer` of the view. */
|
|
29
|
+
export interface MongoViewStorageOptions {
|
|
30
|
+
/** The `_id` of the document of the view. The document names the partition and the target. */
|
|
31
|
+
view: string;
|
|
32
|
+
/** The database of the views and of the target. The default is the database of the default connection, for each operation. */
|
|
33
|
+
db?: (() => Db | Promise<Db>) | undefined;
|
|
34
|
+
/** The collection of the view documents (default `_aggregations`). */
|
|
35
|
+
views?: string | undefined;
|
|
36
|
+
/** The field of a document that names its partition (default `_part`). */
|
|
37
|
+
partitionField?: string | undefined;
|
|
38
|
+
/** The field of a view document that keeps its status (default `_materializerStatus`). */
|
|
39
|
+
statusField?: string | undefined;
|
|
40
|
+
/**
|
|
41
|
+
* The stored `_id` of a row from its key, the partition and the generation (default
|
|
42
|
+
* `partitionTargetId`). It is the option `targetId` of the materializer. `get`, `has` and
|
|
43
|
+
* `getBatch` find a row with it.
|
|
44
|
+
*/
|
|
45
|
+
targetId?: ViewTargetId | undefined;
|
|
46
|
+
/**
|
|
47
|
+
* The `_id` of the row in the result, from its stored `_id`. It reverses `targetId`. The default
|
|
48
|
+
* reads the field `id` of the form of `partitionTargetId`.
|
|
49
|
+
*/
|
|
50
|
+
rowIdOf?: ((storedId: unknown) => unknown) | undefined;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/** The current generation of a view: its target, and the filter of its rows. */
|
|
54
|
+
interface Generation {
|
|
55
|
+
readonly target: Collection<Document>;
|
|
56
|
+
readonly filter: Document;
|
|
57
|
+
readonly partition: string;
|
|
58
|
+
readonly generation: ObjectId;
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/** The `_id` of a row in the result, from the stored `_id` of `partitionTargetId`. */
|
|
62
|
+
function defaultRowId(storedId: unknown): unknown {
|
|
63
|
+
return typeof storedId === "object" && storedId !== null && "id" in storedId ? (storedId as { id: unknown }).id : storedId;
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/**
|
|
67
|
+
* A read-only `CollectionStorage` over the target of one materialized view (roadmap CLI-38). Each
|
|
68
|
+
* read gives the rows of the current generation of the view only.
|
|
69
|
+
*
|
|
70
|
+
* @example
|
|
71
|
+
* ```typescript
|
|
72
|
+
* const server = new ProcedureServer({ collections: { totals: new MongoViewStorage({ view: "totals", db: () => db }) } });
|
|
73
|
+
* server.registerCollectionProcedures("totals");
|
|
74
|
+
* ```
|
|
75
|
+
*/
|
|
76
|
+
export class MongoViewStorage<T = Document> implements CollectionStorage<T> {
|
|
77
|
+
private readonly options: MongoViewStorageOptions;
|
|
78
|
+
private readonly viewsName: string;
|
|
79
|
+
private readonly partitionField: string;
|
|
80
|
+
private readonly statusField: string;
|
|
81
|
+
private readonly targetId: ViewTargetId;
|
|
82
|
+
private readonly rowIdOf: (storedId: unknown) => unknown;
|
|
83
|
+
private closed = false;
|
|
84
|
+
|
|
85
|
+
constructor(options: MongoViewStorageOptions) {
|
|
86
|
+
if (typeof options.view !== "string" || options.view === "") throw new Error("A MongoViewStorage needs the _id of its view");
|
|
87
|
+
this.options = options;
|
|
88
|
+
this.viewsName = options.views ?? "_aggregations";
|
|
89
|
+
this.partitionField = options.partitionField ?? "_part";
|
|
90
|
+
this.statusField = options.statusField ?? "_materializerStatus";
|
|
91
|
+
this.targetId = options.targetId ?? partitionTargetId;
|
|
92
|
+
this.rowIdOf = options.rowIdOf ?? defaultRowId;
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
// ===========================================================================
|
|
96
|
+
// The generation of a read
|
|
97
|
+
// ===========================================================================
|
|
98
|
+
|
|
99
|
+
/**
|
|
100
|
+
* The current generation of the view: one read of the view document. Each read of the storage
|
|
101
|
+
* uses one generation, so it gives the rows of one generation only. The result is undefined
|
|
102
|
+
* before the first pass of the view, or without the view document.
|
|
103
|
+
*/
|
|
104
|
+
private async current(): Promise<Generation | undefined> {
|
|
105
|
+
this.checkOpen();
|
|
106
|
+
const db = this.options.db ? await this.options.db() : (await ensureConnection()).getDb();
|
|
107
|
+
const view = (await db.collection(this.viewsName).findOne({ _id: this.options.view } as Document)) as unknown as MaterializedView | null;
|
|
108
|
+
if (!view || typeof view.targetCollection !== "string") return undefined;
|
|
109
|
+
const partition = view[this.partitionField];
|
|
110
|
+
const generation = (view[this.statusField] as Partial<MaterializedViewStatus> | undefined)?.generation;
|
|
111
|
+
if (typeof partition !== "string" || !generation) return undefined;
|
|
112
|
+
return {
|
|
113
|
+
target: db.collection(view.targetCollection),
|
|
114
|
+
filter: viewFilter(view, { partitionField: this.partitionField, statusField: this.statusField }),
|
|
115
|
+
partition,
|
|
116
|
+
generation,
|
|
117
|
+
};
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
/** The stored `_id` of a key in a generation. */
|
|
121
|
+
private storedId(id: string, generation: Generation): unknown {
|
|
122
|
+
return this.targetId(id, generation.partition, generation.generation);
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
/** The key and the value of a stored row. A row whose `_id` is not a text cannot have a key. */
|
|
126
|
+
private decode(doc: Document): [string, T] {
|
|
127
|
+
const { _id: storedId, [this.partitionField]: _partition, [VIEW_GENERATION_FIELD]: _generation, [VIEW_HASH_FIELD]: _hash, ...content } = doc;
|
|
128
|
+
const id = this.rowIdOf(storedId);
|
|
129
|
+
if (typeof id !== "string") {
|
|
130
|
+
throw new Error(`A row of the view ${this.options.view} has an _id that is not a text: give each row of its result a text _id`);
|
|
131
|
+
}
|
|
132
|
+
const value: Record<string, unknown> = { _id: id, ...content };
|
|
133
|
+
return [id, value as T];
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
/** The rows of the current generation, in the order of their stored `_id`. */
|
|
137
|
+
private async entriesOf(extra?: Document): Promise<Array<[string, T]>> {
|
|
138
|
+
const generation = await this.current();
|
|
139
|
+
if (!generation) return [];
|
|
140
|
+
const docs = await generation.target
|
|
141
|
+
.find({ ...generation.filter, ...extra } as Document)
|
|
142
|
+
.sort({ _id: 1 })
|
|
143
|
+
.toArray();
|
|
144
|
+
return docs.map((doc) => this.decode(doc));
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
// ===========================================================================
|
|
148
|
+
// Reads
|
|
149
|
+
// ===========================================================================
|
|
150
|
+
|
|
151
|
+
async get(id: string): Promise<T | undefined> {
|
|
152
|
+
const generation = await this.current();
|
|
153
|
+
if (!generation) return undefined;
|
|
154
|
+
const doc = await generation.target.findOne({ ...generation.filter, _id: this.storedId(id, generation) } as Document);
|
|
155
|
+
return doc ? this.decode(doc)[1] : undefined;
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
async getAll(): Promise<T[]> {
|
|
159
|
+
return (await this.entriesOf()).map(([, value]) => value);
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
async getEntries(): Promise<Array<[string, T]>> {
|
|
163
|
+
return this.entriesOf();
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
async getIds(): Promise<string[]> {
|
|
167
|
+
return (await this.entriesOf()).map(([id]) => id);
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
async find(predicate: (item: T) => boolean): Promise<T[]> {
|
|
171
|
+
return (await this.getAll()).filter(predicate);
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
async has(id: string): Promise<boolean> {
|
|
175
|
+
const generation = await this.current();
|
|
176
|
+
if (!generation) return false;
|
|
177
|
+
return (await generation.target.countDocuments({ ...generation.filter, _id: this.storedId(id, generation) } as Document, { limit: 1 })) > 0;
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
async size(): Promise<number> {
|
|
181
|
+
const generation = await this.current();
|
|
182
|
+
if (!generation) return 0;
|
|
183
|
+
return generation.target.countDocuments(generation.filter);
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
async getBatch(ids: string[]): Promise<Map<string, T>> {
|
|
187
|
+
const result = new Map<string, T>();
|
|
188
|
+
const generation = await this.current();
|
|
189
|
+
if (!generation || ids.length === 0) return result;
|
|
190
|
+
const byId = new Map(await this.entriesOf({ _id: { $in: ids.map((id) => this.storedId(id, generation)) } }));
|
|
191
|
+
// The order of the ids of the call
|
|
192
|
+
for (const id of ids) if (byId.has(id)) result.set(id, byId.get(id)!);
|
|
193
|
+
return result;
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
// ===========================================================================
|
|
197
|
+
// Writes: only the materializer writes a target
|
|
198
|
+
// ===========================================================================
|
|
199
|
+
|
|
200
|
+
private readOnly(): Promise<never> {
|
|
201
|
+
this.checkOpen();
|
|
202
|
+
return Promise.reject(
|
|
203
|
+
Object.assign(new Error(`The view ${this.options.view} is read-only: only its materializer writes its target`), { code: "FORBIDDEN", retryable: false }),
|
|
204
|
+
);
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
async set(_id: string, _value: T): Promise<void> {
|
|
208
|
+
return this.readOnly();
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
async setBatch(_items: Array<[string, T]>): Promise<void> {
|
|
212
|
+
return this.readOnly();
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
async delete(_id: string): Promise<boolean> {
|
|
216
|
+
return this.readOnly();
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
async deleteBatch(_ids: string[]): Promise<number> {
|
|
220
|
+
return this.readOnly();
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
async clear(): Promise<void> {
|
|
224
|
+
return this.readOnly();
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
// ===========================================================================
|
|
228
|
+
// The life of the storage
|
|
229
|
+
// ===========================================================================
|
|
230
|
+
|
|
231
|
+
/** This method closes the storage. After it, each operation rejects, and a second `close()` does nothing. */
|
|
232
|
+
async close(): Promise<void> {
|
|
233
|
+
this.closed = true;
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
private checkOpen(): void {
|
|
237
|
+
if (this.closed) throw new Error(`The MongoViewStorage of the view ${this.options.view} is closed`);
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
async getMetadata(): Promise<StorageMetadata> {
|
|
241
|
+
return { type: "custom", size: await this.size(), stats: { view: this.options.view } };
|
|
242
|
+
}
|
|
243
|
+
}
|