document-drive 1.0.0-alpha.9 → 1.0.0-alpha.91

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/LICENSE CHANGED
@@ -56,6 +56,7 @@ this license.
56
56
  The precise terms and conditions for copying, distribution and
57
57
  modification follow.
58
58
 
59
+
59
60
  TERMS AND CONDITIONS
60
61
 
61
62
  0. Definitions.
package/README.md ADDED
@@ -0,0 +1 @@
1
+ # Document Drive
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "document-drive",
3
- "version": "1.0.0-alpha.9",
3
+ "version": "1.0.0-alpha.91",
4
4
  "license": "AGPL-3.0-only",
5
5
  "type": "module",
6
6
  "module": "./src/index.ts",
@@ -13,8 +13,14 @@
13
13
  "./storage/filesystem": "./src/storage/filesystem.ts",
14
14
  "./storage/memory": "./src/storage/memory.ts",
15
15
  "./storage/prisma": "./src/storage/prisma.ts",
16
+ "./cache/redis": "./src/cache/redis.ts",
17
+ "./cache/memory": "./src/cache/memory.ts",
18
+ "./queue/redis": "./src/queue/redis.ts",
19
+ "./queue/base": "./src/queue/base.ts",
16
20
  "./utils": "./src/utils/index.ts",
17
- "./utils/graphql": "./src/utils/graphql.ts"
21
+ "./utils/graphql": "./src/utils/graphql.ts",
22
+ "./utils/migrations": "./src/utils/migrations.ts",
23
+ "./logger": "./src/utils/logger.ts"
18
24
  },
19
25
  "files": [
20
26
  "./src"
@@ -25,48 +31,56 @@
25
31
  "lint:fix": "eslint src --ext .js,.jsx,.ts,.tsx --fix",
26
32
  "format": "prettier . --write",
27
33
  "release": "semantic-release",
28
- "test": "vitest run --coverage",
34
+ "test": "vitest run --coverage --exclude \"test/flaky/**\"",
29
35
  "test:watch": "vitest watch"
30
36
  },
31
37
  "peerDependencies": {
32
- "@prisma/client": "5.8.1",
33
- "document-model": "^1.0.29",
34
- "document-model-libs": "^1.1.44",
38
+ "document-model": "^1.7.0",
39
+ "document-model-libs": "^1.57.0"
40
+ },
41
+ "optionalDependencies": {
42
+ "@prisma/client": "^5.18.0",
35
43
  "localforage": "^1.10.0",
36
- "sequelize": "^6.35.2",
44
+ "redis": "^4.6.15",
45
+ "sequelize": "^6.37.3",
37
46
  "sqlite3": "^5.1.7"
38
47
  },
39
48
  "dependencies": {
40
- "graphql": "^16.8.1",
49
+ "exponential-backoff": "^3.1.1",
50
+ "graphql": "^16.9.0",
41
51
  "graphql-request": "^6.1.0",
42
52
  "json-stringify-deterministic": "^1.0.12",
43
53
  "nanoevents": "^9.0.0",
44
- "sanitize-filename": "^1.6.3"
54
+ "sanitize-filename": "^1.6.3",
55
+ "uuid": "^9.0.1"
45
56
  },
46
57
  "devDependencies": {
47
58
  "@commitlint/cli": "^18.6.1",
48
- "@commitlint/config-conventional": "^18.6.2",
49
- "@prisma/client": "5.8.1",
59
+ "@commitlint/config-conventional": "^18.6.3",
60
+ "@prisma/client": "5.17.0",
50
61
  "@semantic-release/changelog": "^6.0.3",
51
62
  "@semantic-release/git": "^10.0.1",
52
63
  "@total-typescript/ts-reset": "^0.5.1",
53
- "@types/node": "^20.11.16",
54
- "@typescript-eslint/eslint-plugin": "^6.18.1",
55
- "@typescript-eslint/parser": "^6.18.1",
56
- "@vitest/coverage-v8": "^0.34.6",
57
- "document-model": "^1.0.30",
58
- "document-model-libs": "^1.1.51",
59
- "eslint": "^8.56.0",
64
+ "@types/node": "^20.14.11",
65
+ "@types/uuid": "^9.0.8",
66
+ "@typescript-eslint/eslint-plugin": "^6.21.0",
67
+ "@typescript-eslint/parser": "^6.21.0",
68
+ "@vitest/coverage-v8": "^2.0.5",
69
+ "document-model": "^1.7.0",
70
+ "document-model-libs": "^1.70.0",
71
+ "eslint": "^8.57.0",
60
72
  "eslint-config-prettier": "^9.1.0",
61
- "fake-indexeddb": "^5.0.1",
73
+ "fake-indexeddb": "^5.0.2",
62
74
  "localforage": "^1.10.0",
63
- "msw": "^2.1.2",
64
- "prettier": "^3.1.1",
75
+ "msw": "^2.3.1",
76
+ "prettier": "^3.3.3",
65
77
  "prettier-plugin-organize-imports": "^3.2.4",
66
- "semantic-release": "^23.0.2",
67
- "sequelize": "^6.35.2",
78
+ "prisma": "^5.18.0",
79
+ "semantic-release": "^23.1.1",
80
+ "sequelize": "^6.37.2",
68
81
  "sqlite3": "^5.1.7",
69
- "typescript": "^5.3.2",
70
- "vitest": "^1.2.2"
71
- }
82
+ "typescript": "^5.5.3",
83
+ "vitest": "^2.0.5"
84
+ },
85
+ "packageManager": "pnpm@9.1.4+sha256.30a1801ac4e723779efed13a21f4c39f9eb6c9fbb4ced101bce06b422593d7c9"
72
86
  }
@@ -0,0 +1,2 @@
1
+ export * from './memory';
2
+ export * from './types';
@@ -0,0 +1,33 @@
1
+ import { Document } from 'document-model/document';
2
+ import { ICache } from './types';
3
+
4
+ class InMemoryCache implements ICache {
5
+ private cache = new Map<string, Map<string, Document>>();
6
+
7
+ async setDocument(drive: string, id: string, document: Document) {
8
+ const global = document.operations.global.map(e => {
9
+ delete e.resultingState;
10
+ return e;
11
+ });
12
+ const local = document.operations.local.map(e => {
13
+ delete e.resultingState;
14
+ return e;
15
+ });
16
+ const doc = { ...document, operations: { global, local } };
17
+ if (!this.cache.has(drive)) {
18
+ this.cache.set(drive, new Map());
19
+ }
20
+ this.cache.get(drive)?.set(id, doc);
21
+ return true;
22
+ }
23
+
24
+ async deleteDocument(drive: string, id: string) {
25
+ return this.cache.get(drive)?.delete(id) ?? false;
26
+ }
27
+
28
+ async getDocument(drive: string, id: string) {
29
+ return this.cache.get(drive)?.get(id);
30
+ }
31
+ }
32
+
33
+ export default InMemoryCache;
@@ -0,0 +1,56 @@
1
+ import { Document } from 'document-model/document';
2
+ import type { RedisClientType } from 'redis';
3
+ import { ICache } from './types';
4
+
5
+ class RedisCache implements ICache {
6
+ private redis: RedisClientType;
7
+ private timeoutInSeconds: number;
8
+
9
+ constructor(
10
+ redis: RedisClientType,
11
+ timeoutInSeconds: number | undefined = 5 * 60
12
+ ) {
13
+ this.redis = redis;
14
+ this.timeoutInSeconds = timeoutInSeconds;
15
+ }
16
+
17
+ private static _getId(drive: string, id: string) {
18
+ return `cache:${drive}:${id}`;
19
+ }
20
+
21
+ async setDocument(drive: string, id: string, document: Document) {
22
+ const global = document.operations.global.map(e => {
23
+ delete e.resultingState;
24
+ return e;
25
+ });
26
+ const local = document.operations.local.map(e => {
27
+ delete e.resultingState;
28
+ return e;
29
+ });
30
+ const doc = { ...document, operations: { global, local } };
31
+ const redisId = RedisCache._getId(drive, id);
32
+ const result = await this.redis.set(redisId, JSON.stringify(doc), {
33
+ EX: this.timeoutInSeconds ? this.timeoutInSeconds : undefined
34
+ });
35
+
36
+ if (result === 'OK') {
37
+ return true;
38
+ }
39
+
40
+ return false;
41
+ }
42
+
43
+ async getDocument(drive: string, id: string) {
44
+ const redisId = RedisCache._getId(drive, id);
45
+ const doc = await this.redis.get(redisId);
46
+
47
+ return doc ? (JSON.parse(doc) as Document) : undefined;
48
+ }
49
+
50
+ async deleteDocument(drive: string, id: string) {
51
+ const redisId = RedisCache._getId(drive, id);
52
+ return (await this.redis.del(redisId)) > 0;
53
+ }
54
+ }
55
+
56
+ export default RedisCache;
@@ -0,0 +1,13 @@
1
+ import type { Document } from 'document-model/document';
2
+
3
+ export interface ICache {
4
+ setDocument(
5
+ drive: string,
6
+ id: string,
7
+ document: Document
8
+ ): Promise<boolean>;
9
+ getDocument(drive: string, id: string): Promise<Document | undefined>;
10
+
11
+ // @returns — true if a document existed and has been removed, or false if the document is not cached.
12
+ deleteDocument(drive: string, id: string): Promise<boolean>;
13
+ }
package/src/index.ts CHANGED
@@ -1,3 +1,4 @@
1
1
  export * from './server';
2
+ export * from './server/error';
2
3
  export * from './storage';
3
4
  export * from './utils';
@@ -0,0 +1,328 @@
1
+ import {
2
+ AddFileInput,
3
+ DeleteNodeInput
4
+ } from 'document-model-libs/document-drive';
5
+ import { Action } from 'document-model/document';
6
+ import { Unsubscribe, createNanoEvents } from 'nanoevents';
7
+ import { generateUUID } from '../utils';
8
+ import { logger } from '../utils/logger';
9
+ import {
10
+ IJob,
11
+ IJobQueue,
12
+ IQueue,
13
+ IQueueManager,
14
+ IServerDelegate,
15
+ Job,
16
+ JobId,
17
+ QueueEvents,
18
+ isOperationJob
19
+ } from './types';
20
+
21
+ export class MemoryQueue<T, R> implements IQueue<T, R> {
22
+ private id: string;
23
+ private blocked = false;
24
+ private deleted = false;
25
+ private items: IJob<T>[] = [];
26
+ private dependencies = new Array<IJob<Job>>();
27
+
28
+ constructor(id: string) {
29
+ this.id = id;
30
+ }
31
+
32
+ async setDeleted(deleted: boolean) {
33
+ this.deleted = deleted;
34
+ }
35
+
36
+ async isDeleted() {
37
+ return this.deleted;
38
+ }
39
+
40
+ async addJob(data: IJob<T>) {
41
+ this.items.push(data);
42
+ return Promise.resolve();
43
+ }
44
+
45
+ async getNextJob() {
46
+ const job = this.items.shift();
47
+ return Promise.resolve(job);
48
+ }
49
+
50
+ async amountOfJobs() {
51
+ return Promise.resolve(this.items.length);
52
+ }
53
+
54
+ getId() {
55
+ return this.id;
56
+ }
57
+
58
+ async setBlocked(blocked: boolean) {
59
+ this.blocked = blocked;
60
+ }
61
+
62
+ async isBlocked() {
63
+ return this.blocked;
64
+ }
65
+
66
+ async getJobs() {
67
+ return this.items;
68
+ }
69
+
70
+ async addDependencies(job: IJob<Job>) {
71
+ if (!this.dependencies.find(j => j.jobId === job.jobId)) {
72
+ this.dependencies.push(job);
73
+ }
74
+ if (!this.isBlocked()) {
75
+ this.setBlocked(true);
76
+ }
77
+ }
78
+
79
+ async removeDependencies(job: IJob<Job>) {
80
+ this.dependencies = this.dependencies.filter(
81
+ j => j.jobId !== job.jobId && j.driveId !== job.driveId
82
+ );
83
+ if (this.dependencies.length === 0) {
84
+ await this.setBlocked(false);
85
+ }
86
+ }
87
+ }
88
+
89
+ export class BaseQueueManager implements IQueueManager {
90
+ protected emitter = createNanoEvents<QueueEvents>();
91
+ protected ticker = 0;
92
+ protected queues: IJobQueue[] = [];
93
+ protected workers: number;
94
+ protected timeout: number;
95
+ private delegate: IServerDelegate | undefined;
96
+
97
+ constructor(workers = 3, timeout = 0) {
98
+ this.workers = workers;
99
+ this.timeout = timeout;
100
+ }
101
+
102
+ async init(
103
+ delegate: IServerDelegate,
104
+ onError: (error: Error) => void
105
+ ): Promise<void> {
106
+ this.delegate = delegate;
107
+ for (let i = 0; i < this.workers; i++) {
108
+ setTimeout(
109
+ () => this.processNextJob.bind(this)().catch(onError),
110
+ 100 * i
111
+ );
112
+ }
113
+ return Promise.resolve();
114
+ }
115
+
116
+ async addJob(job: Job): Promise<JobId> {
117
+ if (!this.delegate) {
118
+ throw new Error('No server delegate defined');
119
+ }
120
+
121
+ const jobId = generateUUID();
122
+ const queue = this.getQueue(job.driveId, job.documentId);
123
+
124
+ if (await queue.isDeleted()) {
125
+ throw new Error('Queue is deleted');
126
+ }
127
+
128
+ // checks if the job is for a document that doesn't exist in storage yet
129
+ const newDocument =
130
+ job.documentId &&
131
+ !(await this.delegate.checkDocumentExists(
132
+ job.driveId,
133
+ job.documentId
134
+ ));
135
+ // if it is a new document and queue is not yet blocked then
136
+ // blocks it so the jobs are not processed until it's ready
137
+ if (newDocument && !(await queue.isBlocked())) {
138
+ await queue.setBlocked(true);
139
+
140
+ // checks if there any job in the queue adding the file and adds as dependency
141
+ const driveQueue = this.getQueue(job.driveId);
142
+ const jobs = await driveQueue.getJobs();
143
+ for (const driveJob of jobs) {
144
+ const actions = isOperationJob(driveJob)
145
+ ? driveJob.operations
146
+ : driveJob.actions;
147
+ const op = actions.find((j: Action) => {
148
+ const input = j.input as AddFileInput;
149
+ return j.type === 'ADD_FILE' && input.id === job.documentId;
150
+ });
151
+ if (op) {
152
+ await queue.addDependencies(driveJob);
153
+ }
154
+ }
155
+ }
156
+
157
+ // if it has ADD_FILE operations then adds the job as
158
+ // a dependency to the corresponding document queues
159
+ const actions = isOperationJob(job) ? job.operations : job.actions;
160
+ const addFileOps = actions.filter((j: Action) => j.type === 'ADD_FILE');
161
+ for (const addFileOp of addFileOps) {
162
+ const input = addFileOp.input as AddFileInput;
163
+ const q = this.getQueue(job.driveId, input.id);
164
+ await q.addDependencies({ jobId, ...job });
165
+ }
166
+
167
+ // remove document if operations contains delete_node
168
+ const removeFileOps = actions.filter(
169
+ (j: Action) => j.type === 'DELETE_NODE'
170
+ );
171
+ for (const removeFileOp of removeFileOps) {
172
+ const input = removeFileOp.input as DeleteNodeInput;
173
+ const queue = this.getQueue(job.driveId, input.id);
174
+ await queue.setDeleted(true);
175
+ }
176
+ await queue.addJob({ jobId, ...job });
177
+
178
+ return jobId;
179
+ }
180
+
181
+ getQueue(driveId: string, documentId?: string) {
182
+ const queueId = this.getQueueId(driveId, documentId);
183
+ let queue = this.queues.find(q => q.getId() === queueId);
184
+
185
+ if (!queue) {
186
+ queue = new MemoryQueue(queueId);
187
+ this.queues.push(queue);
188
+ }
189
+
190
+ return queue;
191
+ }
192
+
193
+ removeQueue(driveId: string, documentId?: string) {
194
+ const queueId = this.getQueueId(driveId, documentId);
195
+ this.queues = this.queues.filter(q => q.getId() !== queueId);
196
+ this.emit('queueRemoved', queueId);
197
+ }
198
+
199
+ getQueueByIndex(index: number) {
200
+ const queue = this.queues[index];
201
+ if (queue) {
202
+ return queue;
203
+ }
204
+
205
+ return null;
206
+ }
207
+
208
+ getQueues() {
209
+ return this.queues.map(q => q.getId());
210
+ }
211
+
212
+ private retryNextJob(timeout?: number) {
213
+ const _timeout = timeout !== undefined ? timeout : this.timeout;
214
+ const retry =
215
+ _timeout === 0 && typeof setImmediate !== 'undefined'
216
+ ? setImmediate
217
+ : (fn: () => void) => setTimeout(fn, _timeout);
218
+ return retry(() => this.processNextJob());
219
+ }
220
+
221
+ private async findFirstNonEmptyQueue(
222
+ ticker: number
223
+ ): Promise<number | null> {
224
+ const numQueues = this.queues.length;
225
+
226
+ for (let i = 0; i < numQueues; i++) {
227
+ const index = (ticker + i) % numQueues;
228
+ const queue = this.queues[index];
229
+ if (queue && (await queue.amountOfJobs()) > 0) {
230
+ return index;
231
+ }
232
+ }
233
+ return null;
234
+ }
235
+
236
+ private async processNextJob() {
237
+ if (!this.delegate) {
238
+ throw new Error('No server delegate defined');
239
+ }
240
+
241
+ if (this.queues.length === 0) {
242
+ this.retryNextJob();
243
+ return;
244
+ }
245
+
246
+ const queue = this.queues[this.ticker];
247
+ if (!queue) {
248
+ this.ticker = 0;
249
+ this.retryNextJob();
250
+ return;
251
+ }
252
+
253
+ // if no jobs in the current queue then looks for the
254
+ // next queue with jobs. If no jobs in any queue then
255
+ // retries after a timeout
256
+ const amountOfJobs = await queue.amountOfJobs();
257
+ if (amountOfJobs === 0) {
258
+ const nextTicker = await this.findFirstNonEmptyQueue(this.ticker);
259
+ if (nextTicker !== null) {
260
+ this.ticker = nextTicker;
261
+ this.retryNextJob(0);
262
+ } else {
263
+ this.retryNextJob();
264
+ }
265
+ return;
266
+ }
267
+
268
+ this.ticker =
269
+ this.ticker === this.queues.length - 1 ? 0 : this.ticker + 1;
270
+
271
+ const isBlocked = await queue.isBlocked();
272
+ if (isBlocked) {
273
+ this.retryNextJob();
274
+ return;
275
+ }
276
+
277
+ await queue.setBlocked(true);
278
+ const nextJob = await queue.getNextJob();
279
+ if (!nextJob) {
280
+ this.retryNextJob();
281
+ return;
282
+ }
283
+
284
+ try {
285
+ const result = await this.delegate.processJob(nextJob);
286
+
287
+ // unblock the document queues of each add_file operation
288
+ const actions = isOperationJob(nextJob)
289
+ ? nextJob.operations
290
+ : nextJob.actions;
291
+ const addFileActions = actions.filter(op => op.type === 'ADD_FILE');
292
+ if (addFileActions.length > 0) {
293
+ for (const addFile of addFileActions) {
294
+ const documentQueue = this.getQueue(
295
+ nextJob.driveId,
296
+ (addFile.input as AddFileInput).id
297
+ );
298
+ await documentQueue.removeDependencies(nextJob);
299
+ }
300
+ }
301
+ this.emit('jobCompleted', nextJob, result);
302
+ } catch (e) {
303
+ logger.error(`job failed`, e);
304
+ this.emit('jobFailed', nextJob, e as Error);
305
+ } finally {
306
+ await queue.setBlocked(false);
307
+ this.retryNextJob(0);
308
+ }
309
+ }
310
+
311
+ protected emit<K extends keyof QueueEvents>(
312
+ event: K,
313
+ ...args: Parameters<QueueEvents[K]>
314
+ ) {
315
+ this.emitter.emit(event, ...args);
316
+ }
317
+ on<K extends keyof QueueEvents>(
318
+ this: this,
319
+ event: K,
320
+ cb: QueueEvents[K]
321
+ ): Unsubscribe {
322
+ return this.emitter.on(event, cb);
323
+ }
324
+
325
+ protected getQueueId(driveId: string, documentId?: string) {
326
+ return `queue:${driveId}${documentId ? `:${documentId}` : ''}`;
327
+ }
328
+ }
@@ -0,0 +1,2 @@
1
+ export * from './base';
2
+ export * from './types';