@verdant-web/server 1.7.8

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 (165) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +5 -0
  3. package/dist/cjs/Baselines.d.ts +14 -0
  4. package/dist/cjs/Baselines.js +101 -0
  5. package/dist/cjs/Baselines.js.map +1 -0
  6. package/dist/cjs/ClientConnection.d.ts +18 -0
  7. package/dist/cjs/ClientConnection.js +106 -0
  8. package/dist/cjs/ClientConnection.js.map +1 -0
  9. package/dist/cjs/MessageSender.d.ts +5 -0
  10. package/dist/cjs/MessageSender.js +3 -0
  11. package/dist/cjs/MessageSender.js.map +1 -0
  12. package/dist/cjs/OperationHistory.d.ts +34 -0
  13. package/dist/cjs/OperationHistory.js +147 -0
  14. package/dist/cjs/OperationHistory.js.map +1 -0
  15. package/dist/cjs/Presence.d.ts +15 -0
  16. package/dist/cjs/Presence.js +60 -0
  17. package/dist/cjs/Presence.js.map +1 -0
  18. package/dist/cjs/Profiles.d.ts +10 -0
  19. package/dist/cjs/Profiles.js +20 -0
  20. package/dist/cjs/Profiles.js.map +1 -0
  21. package/dist/cjs/ReplicaKeepaliveTimers.d.ts +17 -0
  22. package/dist/cjs/ReplicaKeepaliveTimers.js +31 -0
  23. package/dist/cjs/ReplicaKeepaliveTimers.js.map +1 -0
  24. package/dist/cjs/Replicas.d.ts +23 -0
  25. package/dist/cjs/Replicas.js +174 -0
  26. package/dist/cjs/Replicas.js.map +1 -0
  27. package/dist/cjs/Server.d.ts +121 -0
  28. package/dist/cjs/Server.js +378 -0
  29. package/dist/cjs/Server.js.map +1 -0
  30. package/dist/cjs/ServerLibrary.d.ts +63 -0
  31. package/dist/cjs/ServerLibrary.js +468 -0
  32. package/dist/cjs/ServerLibrary.js.map +1 -0
  33. package/dist/cjs/ServerStorage.d.ts +35 -0
  34. package/dist/cjs/ServerStorage.js +60 -0
  35. package/dist/cjs/ServerStorage.js.map +1 -0
  36. package/dist/cjs/TokenProvider.d.ts +16 -0
  37. package/dist/cjs/TokenProvider.js +27 -0
  38. package/dist/cjs/TokenProvider.js.map +1 -0
  39. package/dist/cjs/TokenVerifier.d.ts +16 -0
  40. package/dist/cjs/TokenVerifier.js +29 -0
  41. package/dist/cjs/TokenVerifier.js.map +1 -0
  42. package/dist/cjs/files/FileMetadata.d.ts +28 -0
  43. package/dist/cjs/files/FileMetadata.js +69 -0
  44. package/dist/cjs/files/FileMetadata.js.map +1 -0
  45. package/dist/cjs/files/FileStorage.d.ts +35 -0
  46. package/dist/cjs/files/FileStorage.js +72 -0
  47. package/dist/cjs/files/FileStorage.js.map +1 -0
  48. package/dist/cjs/index.d.ts +9 -0
  49. package/dist/cjs/index.js +12 -0
  50. package/dist/cjs/index.js.map +1 -0
  51. package/dist/cjs/migrations/v0.sql.d.ts +2 -0
  52. package/dist/cjs/migrations/v0.sql.js +29 -0
  53. package/dist/cjs/migrations/v0.sql.js.map +1 -0
  54. package/dist/cjs/migrations/v1.sql.d.ts +2 -0
  55. package/dist/cjs/migrations/v1.sql.js +31 -0
  56. package/dist/cjs/migrations/v1.sql.js.map +1 -0
  57. package/dist/cjs/migrations/v2.sql.d.ts +2 -0
  58. package/dist/cjs/migrations/v2.sql.js +28 -0
  59. package/dist/cjs/migrations/v2.sql.js.map +1 -0
  60. package/dist/cjs/migrations/v3.sql.d.ts +2 -0
  61. package/dist/cjs/migrations/v3.sql.js +14 -0
  62. package/dist/cjs/migrations/v3.sql.js.map +1 -0
  63. package/dist/cjs/migrations/v4.sql.d.ts +2 -0
  64. package/dist/cjs/migrations/v4.sql.js +8 -0
  65. package/dist/cjs/migrations/v4.sql.js.map +1 -0
  66. package/dist/cjs/migrations.d.ts +2 -0
  67. package/dist/cjs/migrations.js +41 -0
  68. package/dist/cjs/migrations.js.map +1 -0
  69. package/dist/cjs/types.d.ts +22 -0
  70. package/dist/cjs/types.js +3 -0
  71. package/dist/cjs/types.js.map +1 -0
  72. package/dist/esm/Baselines.d.ts +14 -0
  73. package/dist/esm/Baselines.js +97 -0
  74. package/dist/esm/Baselines.js.map +1 -0
  75. package/dist/esm/ClientConnection.d.ts +18 -0
  76. package/dist/esm/ClientConnection.js +102 -0
  77. package/dist/esm/ClientConnection.js.map +1 -0
  78. package/dist/esm/MessageSender.d.ts +5 -0
  79. package/dist/esm/MessageSender.js +2 -0
  80. package/dist/esm/MessageSender.js.map +1 -0
  81. package/dist/esm/OperationHistory.d.ts +34 -0
  82. package/dist/esm/OperationHistory.js +143 -0
  83. package/dist/esm/OperationHistory.js.map +1 -0
  84. package/dist/esm/Presence.d.ts +15 -0
  85. package/dist/esm/Presence.js +53 -0
  86. package/dist/esm/Presence.js.map +1 -0
  87. package/dist/esm/Profiles.d.ts +10 -0
  88. package/dist/esm/Profiles.js +16 -0
  89. package/dist/esm/Profiles.js.map +1 -0
  90. package/dist/esm/ReplicaKeepaliveTimers.d.ts +17 -0
  91. package/dist/esm/ReplicaKeepaliveTimers.js +27 -0
  92. package/dist/esm/ReplicaKeepaliveTimers.js.map +1 -0
  93. package/dist/esm/Replicas.d.ts +23 -0
  94. package/dist/esm/Replicas.js +170 -0
  95. package/dist/esm/Replicas.js.map +1 -0
  96. package/dist/esm/Server.d.ts +121 -0
  97. package/dist/esm/Server.js +371 -0
  98. package/dist/esm/Server.js.map +1 -0
  99. package/dist/esm/ServerLibrary.d.ts +63 -0
  100. package/dist/esm/ServerLibrary.js +464 -0
  101. package/dist/esm/ServerLibrary.js.map +1 -0
  102. package/dist/esm/ServerStorage.d.ts +44 -0
  103. package/dist/esm/ServerStorage.js +58 -0
  104. package/dist/esm/ServerStorage.js.map +1 -0
  105. package/dist/esm/TokenProvider.d.ts +16 -0
  106. package/dist/esm/TokenProvider.js +20 -0
  107. package/dist/esm/TokenProvider.js.map +1 -0
  108. package/dist/esm/TokenVerifier.d.ts +16 -0
  109. package/dist/esm/TokenVerifier.js +22 -0
  110. package/dist/esm/TokenVerifier.js.map +1 -0
  111. package/dist/esm/files/FileMetadata.d.ts +28 -0
  112. package/dist/esm/files/FileMetadata.js +65 -0
  113. package/dist/esm/files/FileMetadata.js.map +1 -0
  114. package/dist/esm/files/FileStorage.d.ts +35 -0
  115. package/dist/esm/files/FileStorage.js +45 -0
  116. package/dist/esm/files/FileStorage.js.map +1 -0
  117. package/dist/esm/index.d.ts +9 -0
  118. package/dist/esm/index.js +5 -0
  119. package/dist/esm/index.js.map +1 -0
  120. package/dist/esm/migrations/v0.sql.d.ts +2 -0
  121. package/dist/esm/migrations/v0.sql.js +27 -0
  122. package/dist/esm/migrations/v0.sql.js.map +1 -0
  123. package/dist/esm/migrations/v1.sql.d.ts +2 -0
  124. package/dist/esm/migrations/v1.sql.js +29 -0
  125. package/dist/esm/migrations/v1.sql.js.map +1 -0
  126. package/dist/esm/migrations/v2.sql.d.ts +2 -0
  127. package/dist/esm/migrations/v2.sql.js +26 -0
  128. package/dist/esm/migrations/v2.sql.js.map +1 -0
  129. package/dist/esm/migrations/v3.sql.d.ts +2 -0
  130. package/dist/esm/migrations/v3.sql.js +12 -0
  131. package/dist/esm/migrations/v3.sql.js.map +1 -0
  132. package/dist/esm/migrations/v4.sql.d.ts +2 -0
  133. package/dist/esm/migrations/v4.sql.js +6 -0
  134. package/dist/esm/migrations/v4.sql.js.map +1 -0
  135. package/dist/esm/migrations.d.ts +2 -0
  136. package/dist/esm/migrations.js +34 -0
  137. package/dist/esm/migrations.js.map +1 -0
  138. package/dist/esm/types.d.ts +22 -0
  139. package/dist/esm/types.js +2 -0
  140. package/dist/esm/types.js.map +1 -0
  141. package/dist/tsconfig-cjs.tsbuildinfo +1 -0
  142. package/dist/tsconfig.tsbuildinfo +1 -0
  143. package/package.json +43 -0
  144. package/src/Baselines.ts +158 -0
  145. package/src/ClientConnection.ts +150 -0
  146. package/src/MessageSender.ts +10 -0
  147. package/src/OperationHistory.ts +206 -0
  148. package/src/Presence.ts +63 -0
  149. package/src/Profiles.ts +21 -0
  150. package/src/ReplicaKeepaliveTimers.ts +34 -0
  151. package/src/Replicas.ts +238 -0
  152. package/src/Server.ts +553 -0
  153. package/src/ServerLibrary.ts +727 -0
  154. package/src/TokenProvider.ts +39 -0
  155. package/src/TokenVerifier.ts +30 -0
  156. package/src/files/FileMetadata.ts +112 -0
  157. package/src/files/FileStorage.ts +87 -0
  158. package/src/index.ts +9 -0
  159. package/src/migrations/v0.sql.ts +26 -0
  160. package/src/migrations/v1.sql.ts +28 -0
  161. package/src/migrations/v2.sql.ts +26 -0
  162. package/src/migrations/v3.sql.ts +12 -0
  163. package/src/migrations/v4.sql.ts +6 -0
  164. package/src/migrations.ts +51 -0
  165. package/src/types.ts +35 -0
package/src/Server.ts ADDED
@@ -0,0 +1,553 @@
1
+ import {
2
+ assert,
3
+ ClientMessage,
4
+ createOid,
5
+ DocumentBaseline,
6
+ FileData,
7
+ generateId,
8
+ Operation,
9
+ ServerMessage,
10
+ } from '@verdant-web/common';
11
+ import EventEmitter from 'events';
12
+ import { IncomingMessage, Server as HttpServer, ServerResponse } from 'http';
13
+ import { WebSocketServer, WebSocket } from 'ws';
14
+ import { UserProfileLoader, UserProfiles } from './Profiles.js';
15
+ import create from 'better-sqlite3';
16
+ import { MessageSender } from './MessageSender.js';
17
+ import { URL } from 'url';
18
+ import { ClientConnectionManager } from './ClientConnection.js';
19
+ import { ReplicaKeepaliveTimers } from './ReplicaKeepaliveTimers.js';
20
+ import { TokenInfo, TokenVerifier } from './TokenVerifier.js';
21
+ import busboy from 'busboy';
22
+ import { FileInfo, FileStorage } from './files/FileStorage.js';
23
+ import { Readable } from 'stream';
24
+ import { FileMetadata, FileMetadataConfig } from './files/FileMetadata.js';
25
+ import { ServerLibrary } from './ServerLibrary.js';
26
+ import { migrations } from './migrations.js';
27
+
28
+ export interface ServerOptions {
29
+ /**
30
+ * Attach to a pre-existing HTTP server. Provide this if you have another server,
31
+ * like an Express server, that you want to add lofi to. If provided, you don't
32
+ * need to call .listen()
33
+ */
34
+ httpServer?: HttpServer;
35
+ /**
36
+ * The secret value used to generate tokens from your authentication endpoint.
37
+ * Used to verify and decode user identity and library access on connection.
38
+ */
39
+ tokenSecret: string;
40
+ /**
41
+ * The path to your SQLite database.
42
+ */
43
+ databaseFile: string;
44
+ /**
45
+ * Optionally provide an implementation of the UserProfiles interface to look up
46
+ * static user profile data to use in persistence. This data is considered trusted
47
+ * and can be used to identify users with information like name or profile image.
48
+ */
49
+ profiles?: UserProfiles<any>;
50
+ /**
51
+ * How many minutes of inactivity before a replica is considered truant and
52
+ * removed from the library. Defaults to 30 days.
53
+ */
54
+ replicaTruancyMinutes?: number;
55
+ /**
56
+ * Supply a logging function to log debug messages.
57
+ */
58
+ log?: (...args: any[]) => void;
59
+ /**
60
+ * Disable history compaction. Storage usage will grow indefinitely. Not recommended.
61
+ */
62
+ disableRebasing?: boolean;
63
+ /**
64
+ * Provide a FileStorage backend to accept file uploads. Without a file backend,
65
+ * users will not be able to synchronize files, and all files added on peer replicas
66
+ * will be forever unavailable.
67
+ *
68
+ * A default, filesystem-backed FileStorage implementation is provided as an export
69
+ * of this library.
70
+ */
71
+ fileStorage?: FileStorage;
72
+ fileConfig?: FileMetadataConfig;
73
+ }
74
+
75
+ class DefaultProfiles implements UserProfiles<{ id: string }> {
76
+ get = async (userId: string) => {
77
+ return { id: userId };
78
+ };
79
+ }
80
+
81
+ export interface ServerEvents {
82
+ error: (err: any) => void;
83
+ warning: (msg: string, ...args: any[]) => void;
84
+ changes: (
85
+ info: Omit<TokenInfo, 'token'>,
86
+ operations: Operation[],
87
+ baselines: DocumentBaseline[],
88
+ ) => void;
89
+ request: (info: TokenInfo) => void;
90
+ 'socket-close': (info: TokenInfo) => void;
91
+ 'socket-connection': (info: TokenInfo) => void;
92
+ }
93
+
94
+ export declare interface Server {
95
+ on<Event extends keyof ServerEvents>(
96
+ ev: Event,
97
+ cb: ServerEvents[Event],
98
+ ): this;
99
+ off<Event extends keyof ServerEvents>(
100
+ ev: Event,
101
+ cb: ServerEvents[Event],
102
+ ): this;
103
+ emit<Event extends keyof ServerEvents>(
104
+ ev: Event,
105
+ ...args: Parameters<ServerEvents[Event]>
106
+ ): boolean;
107
+ }
108
+
109
+ export class Server extends EventEmitter implements MessageSender {
110
+ readonly httpServer: HttpServer;
111
+ private wss: WebSocketServer;
112
+ private fileStorage?: FileStorage;
113
+ private fileMetadata;
114
+ private library;
115
+
116
+ private clientConnections = new ClientConnectionManager();
117
+ private keepalives = new ReplicaKeepaliveTimers();
118
+
119
+ private tokenVerifier;
120
+
121
+ private connectionToReplicaIdMap = new WeakMap<WebSocket, string>();
122
+
123
+ private log: (...args: any[]) => void = () => {};
124
+
125
+ private __testMode = false;
126
+
127
+ constructor(options: ServerOptions) {
128
+ super();
129
+
130
+ this.__testMode =
131
+ process.env.NODE_ENV === 'test' && process.env.VITEST === 'true';
132
+
133
+ this.log = options.log || this.log;
134
+
135
+ this.tokenVerifier = new TokenVerifier({
136
+ secret: options.tokenSecret,
137
+ });
138
+
139
+ this.fileStorage = options.fileStorage;
140
+
141
+ const db = create(options.databaseFile);
142
+ migrations(db);
143
+
144
+ this.fileMetadata = new FileMetadata(db, options.fileConfig);
145
+
146
+ this.library = new ServerLibrary({
147
+ db,
148
+ sender: this,
149
+ profiles: new UserProfileLoader(
150
+ options.profiles || new DefaultProfiles(),
151
+ ),
152
+ log: this.log,
153
+ disableRebasing: options.disableRebasing,
154
+ fileMetadata: this.fileMetadata,
155
+ fileStorage: this.fileStorage,
156
+ replicaTruancyMinutes: options.replicaTruancyMinutes || 60 * 24 * 14,
157
+ });
158
+
159
+ this.library.subscribe(
160
+ 'changes',
161
+ ({ token, ...info }, operations, baselines) => {
162
+ this.emit('changes', info, operations, baselines);
163
+ },
164
+ );
165
+
166
+ this.wss = new WebSocketServer({
167
+ noServer: true,
168
+ });
169
+
170
+ this.wss.on('connection', this.handleConnection);
171
+
172
+ this.httpServer =
173
+ options.httpServer || new HttpServer(this.internalServerHandleRequest);
174
+
175
+ this.httpServer.on('upgrade', async (req, socket, head) => {
176
+ try {
177
+ const info = this.authorizeRequest(req);
178
+ this.wss.handleUpgrade(req, socket, head, (ws) => {
179
+ this.wss.emit('connection', ws, req, info);
180
+ });
181
+ } catch (e) {
182
+ this.emit('error', e);
183
+ socket.destroy();
184
+ }
185
+ });
186
+
187
+ this.keepalives.subscribe('lost', this.library.remove);
188
+ }
189
+
190
+ private authorizeRequest = (req: IncomingMessage) => {
191
+ return this.tokenVerifier.verifyToken(this.getRequestToken(req));
192
+ };
193
+
194
+ private getRequestToken = (req: IncomingMessage) => {
195
+ if (req.headers.authorization) {
196
+ const [type, token] = req.headers.authorization.split(' ');
197
+ if (type === 'Bearer') {
198
+ return token;
199
+ }
200
+ }
201
+
202
+ if (req.headers['sec-websocket-protocol']) {
203
+ // hack: read the token from the websocket protocol header
204
+ const [type, token] = req.headers['sec-websocket-protocol'].split(',');
205
+ if (type === 'Bearer') {
206
+ return token.trim();
207
+ }
208
+ }
209
+
210
+ assert(req.url, 'Request URL is required');
211
+ const url = new URL(req.url, 'http://localhost');
212
+ const token = url.searchParams.get('token');
213
+ assert(token, 'Token is required');
214
+ return token;
215
+ };
216
+
217
+ private internalServerHandleRequest = (
218
+ req: IncomingMessage,
219
+ res: ServerResponse,
220
+ ) => {
221
+ const url = new URL(req.url || '', 'http://localhost');
222
+ if (url.pathname.startsWith('lofi')) {
223
+ if (url.pathname === 'lofi') {
224
+ return this.handleRequest(req, res);
225
+ } else if (url.pathname.startsWith('/lofi/files/')) {
226
+ return this.handleFileRequest(req, res);
227
+ }
228
+ } else {
229
+ res.writeHead(404);
230
+ res.end();
231
+ }
232
+ };
233
+
234
+ handleRequest = async (req: IncomingMessage, res: ServerResponse) => {
235
+ try {
236
+ if (req.method === 'POST') {
237
+ const info = this.authorizeRequest(req);
238
+
239
+ const key = generateId();
240
+
241
+ const finish = this.clientConnections.addRequest(
242
+ info.libraryId,
243
+ key,
244
+ req,
245
+ res,
246
+ info,
247
+ );
248
+
249
+ // FIXME: extremely naive compatibility with connect-like
250
+ // servers...
251
+ const body: {
252
+ messages: ClientMessage[];
253
+ } =
254
+ (req as any).body ??
255
+ (await new Promise<string>((resolve, reject) => {
256
+ let body = '';
257
+ req.on('data', (chunk) => {
258
+ body += chunk;
259
+ });
260
+ req.on('end', () => {
261
+ resolve(JSON.parse(body));
262
+ });
263
+ req.on('error', (e) => {
264
+ reject(e);
265
+ });
266
+ }));
267
+
268
+ for (const message of body.messages) {
269
+ await this.handleMessage(key, info, message);
270
+ }
271
+
272
+ // update our keepalive timers for presence management
273
+ const firstMessage = body.messages[0];
274
+ if (firstMessage) {
275
+ this.keepalives.refresh(info.libraryId, firstMessage.replicaId);
276
+ }
277
+
278
+ finish();
279
+
280
+ this.emit('request', info);
281
+ }
282
+ } catch (e) {
283
+ this.emit('error', e);
284
+ res.writeHead(500);
285
+ res.end();
286
+ }
287
+ };
288
+
289
+ /**
290
+ * Handles a multipart upload of a file from a verdant client. The upload
291
+ * will include parameters for the file's ID, name, and type. The request
292
+ * must be authenticated with a token to tie it to a library.
293
+ */
294
+ handleFileRequest = async (req: IncomingMessage, res: ServerResponse) => {
295
+ const fs = this.fileStorage;
296
+ if (!fs) {
297
+ this.emit(
298
+ 'error',
299
+ new Error(
300
+ 'No file storage configured, but a client attempted to upload a file.',
301
+ ),
302
+ );
303
+ res.writeHead(500);
304
+ res.write('File storage is not configured');
305
+ res.end();
306
+ return;
307
+ }
308
+
309
+ // FIXME: rather than trying to support Express, I should
310
+ // just expose regular methods you call from whatever HTTP handler...
311
+ const url = new URL(
312
+ (req as any).originalUrl || (req as any).baseUrl || req.url || '',
313
+ 'http://localhost',
314
+ );
315
+
316
+ const id = url.pathname.split('/').pop();
317
+
318
+ if (!id || id === 'files') {
319
+ res.writeHead(400);
320
+ res.write(
321
+ 'File ID is required to be in the URL path as the last parameter',
322
+ );
323
+ res.end();
324
+ return;
325
+ }
326
+
327
+ try {
328
+ if (req.method === 'POST') {
329
+ const info = this.authorizeRequest(req);
330
+ await new Promise((resolve, reject) => {
331
+ const bb = busboy({ headers: req.headers });
332
+
333
+ bb.on('file', (fieldName, stream, fileInfo) => {
334
+ // too many 'info's....
335
+ const lofiFileInfo: FileInfo = {
336
+ id,
337
+ libraryId: info.libraryId,
338
+ fileName: fileInfo.filename,
339
+ type: fileInfo.mimeType,
340
+ };
341
+ // write metadata to storage
342
+ try {
343
+ this.fileMetadata.put(info.libraryId, lofiFileInfo);
344
+ fs.put(stream, lofiFileInfo);
345
+ } catch (e) {
346
+ reject(e);
347
+ }
348
+ });
349
+ bb.on('field', (fieldName, value) => {
350
+ if (fieldName === 'file') {
351
+ if (this.__testMode) {
352
+ // this isn't right in the real world, but in testing it's
353
+ // the only way we get file data.
354
+ // we create a stream from the data and pass it as if it
355
+ // were a file stream
356
+ const stream = new Readable();
357
+ stream.push(value);
358
+ stream.push(null);
359
+ const fileInfo = {
360
+ filename: 'test.txt',
361
+ mimeType: 'text/plain',
362
+ };
363
+ bb.emit('file', fieldName, stream, fileInfo);
364
+ } else {
365
+ throw new Error('Invalid file upload');
366
+ }
367
+ }
368
+ });
369
+
370
+ req.pipe(bb);
371
+ bb.on('finish', resolve);
372
+ bb.on('error', reject);
373
+ });
374
+ this.log('File upload complete');
375
+ res.writeHead(200);
376
+ res.write(JSON.stringify({ success: true }));
377
+ res.end();
378
+ } else if (req.method === 'GET') {
379
+ const info = this.authorizeRequest(req);
380
+
381
+ const fileInfo = this.fileMetadata.get(info.libraryId, id);
382
+ if (!fileInfo) {
383
+ res.writeHead(404);
384
+ res.end();
385
+ return;
386
+ }
387
+
388
+ const url = await fs.getUrl({
389
+ fileName: fileInfo.name,
390
+ id: fileInfo.fileId,
391
+ libraryId: info.libraryId,
392
+ type: fileInfo.type,
393
+ });
394
+ res.writeHead(200, {
395
+ 'Content-Type': 'application/json',
396
+ });
397
+ // we need to augment that data with the URL from the file backend.
398
+ // and generally enforce the FileData interface here...
399
+ const data: FileData = {
400
+ id: fileInfo.fileId,
401
+ url,
402
+ remote: true,
403
+ name: fileInfo.name,
404
+ type: fileInfo.type,
405
+ };
406
+ res.write(JSON.stringify(data));
407
+ res.end();
408
+ }
409
+ } catch (e) {
410
+ this.log('Error handling file request', e);
411
+ this.emit('error', e);
412
+ res.writeHead(500);
413
+ res.end();
414
+ }
415
+ };
416
+
417
+ broadcast = (
418
+ libraryId: string,
419
+ message: ServerMessage,
420
+ omitKeys: string[] = [],
421
+ ) => {
422
+ this.clientConnections.broadcast(libraryId, message, omitKeys);
423
+ };
424
+
425
+ send = (libraryId: string, key: string, message: ServerMessage) => {
426
+ this.clientConnections.respond(libraryId, key, message);
427
+ };
428
+
429
+ private handleMessage = (
430
+ clientKey: string,
431
+ info: TokenInfo,
432
+ message: ClientMessage,
433
+ ) => {
434
+ this.log(
435
+ 'Got message from user',
436
+ info.userId,
437
+ ', library',
438
+ info.libraryId,
439
+ JSON.stringify(message),
440
+ );
441
+ return this.library.receive(message, clientKey, info);
442
+ };
443
+
444
+ private handleConnection = (
445
+ ws: WebSocket,
446
+ req: IncomingMessage,
447
+ info: TokenInfo,
448
+ ) => {
449
+ const key = generateId();
450
+
451
+ this.clientConnections.addSocket(info.libraryId, key, ws, info);
452
+
453
+ ws.on('message', async (message: any) => {
454
+ const data = JSON.parse(message.toString()) as ClientMessage;
455
+
456
+ if (data.replicaId) {
457
+ this.connectionToReplicaIdMap.set(ws, data.replicaId);
458
+ this.keepalives.refresh(info.libraryId, data.replicaId);
459
+ }
460
+
461
+ await this.handleMessage(key, info, data);
462
+ });
463
+
464
+ ws.on('close', () => {
465
+ const replicaId = this.connectionToReplicaIdMap.get(ws);
466
+ if (!replicaId) {
467
+ this.emit('warning', 'Unknown replica disconnected', ws);
468
+ return;
469
+ }
470
+
471
+ this.library.remove(info.libraryId, replicaId);
472
+
473
+ this.emit('socket-close', info);
474
+ });
475
+
476
+ this.emit('socket-connection', info);
477
+ };
478
+
479
+ listen = (...params: Parameters<HttpServer['listen']>) => {
480
+ this.httpServer.listen(...params);
481
+ };
482
+
483
+ close = async () => {
484
+ await Promise.all([
485
+ new Promise<void>((resolve) => {
486
+ setTimeout(() => {
487
+ console.warn('HTTP server close timed out');
488
+ resolve();
489
+ }, 5 * 1000);
490
+ this.httpServer.close(() => {
491
+ resolve();
492
+ this.log('HTTP server closed');
493
+ });
494
+ }),
495
+ new Promise<void>((resolve) => {
496
+ setTimeout(() => {
497
+ console.warn('Socket server close timed out');
498
+ resolve();
499
+ }, 5 * 1000);
500
+ this.wss.close(() => {
501
+ resolve();
502
+ this.log('Socket server closed');
503
+ });
504
+ }),
505
+ ]);
506
+ this.library.close();
507
+ };
508
+
509
+ /**
510
+ * Completely remove a library from the server.
511
+ * This will remove all data associated with the library.
512
+ * Use it very carefully! Data will still be stored on user
513
+ * devices, so this is not as scary as it sounds - the next time
514
+ * any replica connects, it will repopulate the library. But
515
+ * you should still be careful.
516
+ */
517
+ evictLibrary = (libraryId: string) => {
518
+ // disconnect all clients
519
+ this.clientConnections.disconnectAll(libraryId);
520
+ this.library.destroy(libraryId);
521
+ this.log('Evicted library', libraryId);
522
+ };
523
+
524
+ getLibraryPresence = (libraryId: string) => {
525
+ return this.library.getPresence(libraryId);
526
+ };
527
+
528
+ /**
529
+ * Removes all replicas associated with a User ID from
530
+ * the server. Consistency algorithms will no longer wait on these
531
+ * replicas before confirming and squashing changes.
532
+ */
533
+ evictUser = (libraryId: string, userId: string) => {
534
+ this.library.evictUser(libraryId, userId);
535
+ this.log('Evicted user', userId, 'from library', libraryId);
536
+ };
537
+
538
+ /**
539
+ * Retrieves a snapshot of the full document contents at this time.
540
+ * Useful for capturing the shape of data for static usage outside
541
+ * of the live system.
542
+ */
543
+ getDocumentSnapshot = (
544
+ libraryId: string,
545
+ collection: string,
546
+ documentId: string,
547
+ ) => {
548
+ return this.library.getDocumentSnapshot(
549
+ libraryId,
550
+ createOid(collection, documentId, []),
551
+ );
552
+ };
553
+ }