@casual-simulation/aux-records 3.2.6 → 3.2.7-alpha.6227012901

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 (93) hide show
  1. package/AIController.d.ts +1 -1
  2. package/AIGenerateSkyboxInterface.d.ts +1 -1
  3. package/AuthController.d.ts +53 -1
  4. package/AuthController.js +117 -1
  5. package/AuthController.js.map +1 -1
  6. package/AuthMessenger.d.ts +1 -1
  7. package/AuthStore.d.ts +5 -1
  8. package/AuthUtils.d.ts +55 -1
  9. package/AuthUtils.js +130 -2
  10. package/AuthUtils.js.map +1 -1
  11. package/DataRecordsController.d.ts +1 -1
  12. package/DataRecordsStore.d.ts +1 -1
  13. package/EventRecordsController.d.ts +1 -1
  14. package/EventRecordsController.js.map +1 -1
  15. package/EventRecordsStore.d.ts +1 -1
  16. package/FileRecordsController.d.ts +1 -1
  17. package/FileRecordsStore.d.ts +2 -2
  18. package/LivekitEvents.d.ts +1 -1
  19. package/MemoryRateLimiter.js +1 -1
  20. package/MemoryRateLimiter.js.map +1 -1
  21. package/MemoryStore.d.ts +2 -2
  22. package/MemoryStore.js +2 -0
  23. package/MemoryStore.js.map +1 -1
  24. package/PolicyController.d.ts +1 -1
  25. package/PolicyController.js.map +1 -1
  26. package/PolicyPermissions.d.ts +212 -1
  27. package/PolicyPermissions.js +67 -0
  28. package/PolicyPermissions.js.map +1 -1
  29. package/PolicyStore.d.ts +1 -1
  30. package/RateLimitController.d.ts +3 -1
  31. package/RateLimitController.js +2 -0
  32. package/RateLimitController.js.map +1 -1
  33. package/RecordsController.d.ts +30 -2
  34. package/RecordsController.js +12 -8
  35. package/RecordsController.js.map +1 -1
  36. package/{RecordsHttpServer.d.ts → RecordsServer.d.ts} +35 -5
  37. package/{RecordsHttpServer.js → RecordsServer.js} +153 -6
  38. package/RecordsServer.js.map +1 -0
  39. package/RecordsStore.d.ts +12 -6
  40. package/SubscriptionConfiguration.d.ts +479 -74
  41. package/SubscriptionConfiguration.js +34 -1
  42. package/SubscriptionConfiguration.js.map +1 -1
  43. package/SubscriptionController.d.ts +1 -1
  44. package/TestUtils.d.ts +2 -0
  45. package/TestUtils.js +5 -0
  46. package/TestUtils.js.map +1 -1
  47. package/Utils.d.ts +0 -10
  48. package/Utils.js +0 -19
  49. package/Utils.js.map +1 -1
  50. package/index.d.ts +2 -1
  51. package/index.js +2 -1
  52. package/index.js.map +1 -1
  53. package/package.json +6 -3
  54. package/websockets/InstRecordsStore.d.ts +186 -0
  55. package/websockets/InstRecordsStore.js +2 -0
  56. package/websockets/InstRecordsStore.js.map +1 -0
  57. package/websockets/MemoryInstRecordsStore.d.ts +31 -0
  58. package/websockets/MemoryInstRecordsStore.js +310 -0
  59. package/websockets/MemoryInstRecordsStore.js.map +1 -0
  60. package/websockets/MemoryTempInstRecordsStore.d.ts +31 -0
  61. package/websockets/MemoryTempInstRecordsStore.js +169 -0
  62. package/websockets/MemoryTempInstRecordsStore.js.map +1 -0
  63. package/websockets/MemoryWebsocketConnectionStore.d.ts +33 -0
  64. package/websockets/MemoryWebsocketConnectionStore.js +169 -0
  65. package/websockets/MemoryWebsocketConnectionStore.js.map +1 -0
  66. package/websockets/MemoryWebsocketMessenger.d.ts +21 -0
  67. package/websockets/MemoryWebsocketMessenger.js +94 -0
  68. package/websockets/MemoryWebsocketMessenger.js.map +1 -0
  69. package/websockets/SplitInstRecordsStore.d.ts +21 -0
  70. package/websockets/SplitInstRecordsStore.js +186 -0
  71. package/websockets/SplitInstRecordsStore.js.map +1 -0
  72. package/websockets/TemporaryInstRecordsStore.d.ts +130 -0
  73. package/websockets/TemporaryInstRecordsStore.js +2 -0
  74. package/websockets/TemporaryInstRecordsStore.js.map +1 -0
  75. package/websockets/Utils.d.ts +16 -0
  76. package/websockets/Utils.js +26 -0
  77. package/websockets/Utils.js.map +1 -0
  78. package/websockets/WebsocketConnectionStore.d.ts +141 -0
  79. package/websockets/WebsocketConnectionStore.js +2 -0
  80. package/websockets/WebsocketConnectionStore.js.map +1 -0
  81. package/websockets/WebsocketController.d.ts +97 -0
  82. package/websockets/WebsocketController.js +707 -0
  83. package/websockets/WebsocketController.js.map +1 -0
  84. package/websockets/WebsocketMessenger.d.ts +42 -0
  85. package/websockets/WebsocketMessenger.js +2 -0
  86. package/websockets/WebsocketMessenger.js.map +1 -0
  87. package/websockets/index.d.ts +12 -0
  88. package/websockets/index.js +12 -0
  89. package/websockets/index.js.map +1 -0
  90. package/Errors.d.ts +0 -29
  91. package/Errors.js +0 -2
  92. package/Errors.js.map +0 -1
  93. package/RecordsHttpServer.js.map +0 -1
@@ -0,0 +1,707 @@
1
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
2
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
3
+ return new (P || (P = Promise))(function (resolve, reject) {
4
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
5
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
6
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
7
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
8
+ });
9
+ };
10
+ var __rest = (this && this.__rest) || function (s, e) {
11
+ var t = {};
12
+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
13
+ t[p] = s[p];
14
+ if (s != null && typeof Object.getOwnPropertySymbols === "function")
15
+ for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
16
+ if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
17
+ t[p[i]] = s[p[i]];
18
+ }
19
+ return t;
20
+ };
21
+ import { action, ON_WEBHOOK_ACTION_NAME, } from '@casual-simulation/aux-common/bots';
22
+ import { YjsPartitionImpl } from '@casual-simulation/aux-common/partitions';
23
+ import { device, deviceError, deviceResult, } from '@casual-simulation/aux-common/common/RemoteActions';
24
+ import { toByteArray } from 'base64-js';
25
+ import { applyUpdate } from 'yjs';
26
+ import { WebsocketEventTypes, } from '@casual-simulation/aux-common/websockets/WebsocketEvents';
27
+ import { sumBy } from 'lodash';
28
+ import { PUBLIC_WRITE_MARKER } from '../PolicyPermissions';
29
+ /**
30
+ * Defines a class that is able to serve causal repos in realtime.
31
+ */
32
+ export class WebsocketController {
33
+ get messenger() {
34
+ return this._messenger;
35
+ }
36
+ constructor(connectionStore, messenger, instStore, temporaryInstStore, auth) {
37
+ this.mergeUpdatesOnMaxSizeExceeded = false;
38
+ this._connectionStore = connectionStore;
39
+ this._messenger = messenger;
40
+ this._instStore = instStore;
41
+ this._temporaryStore = temporaryInstStore;
42
+ this._auth = auth;
43
+ }
44
+ /**
45
+ * Attempts to log the given connection in.
46
+ * @param connectionId The ID of the connection.
47
+ * @param requestId The ID of the request.
48
+ * @param message The login message.
49
+ */
50
+ login(connectionId, requestId, message) {
51
+ return __awaiter(this, void 0, void 0, function* () {
52
+ try {
53
+ let userId = null;
54
+ let sessionId = null;
55
+ let clientConnectionId;
56
+ if (!message.connectionToken) {
57
+ if (!message.connectionId) {
58
+ yield this._messenger.sendEvent(connectionId, [
59
+ WebsocketEventTypes.Error,
60
+ requestId,
61
+ 'unacceptable_connection_id',
62
+ 'A connection ID must be specified when logging in without a connection token.',
63
+ null,
64
+ ]);
65
+ return;
66
+ }
67
+ yield this._connectionStore.saveConnection({
68
+ serverConnectionId: connectionId,
69
+ clientConnectionId: message.connectionId,
70
+ userId: null,
71
+ sessionId: null,
72
+ token: null,
73
+ });
74
+ clientConnectionId = message.connectionId;
75
+ }
76
+ else {
77
+ const validationResult = yield this._auth.validateConnectionToken(message.connectionToken);
78
+ if (validationResult.success === false) {
79
+ yield this._messenger.sendEvent(connectionId, [
80
+ WebsocketEventTypes.Error,
81
+ requestId,
82
+ validationResult.errorCode,
83
+ validationResult.errorMessage,
84
+ undefined,
85
+ ]);
86
+ return;
87
+ }
88
+ yield this._connectionStore.saveConnection({
89
+ serverConnectionId: connectionId,
90
+ userId: validationResult.userId,
91
+ sessionId: validationResult.sessionId,
92
+ clientConnectionId: validationResult.connectionId,
93
+ token: message.connectionToken,
94
+ });
95
+ userId = validationResult.userId;
96
+ sessionId = validationResult.sessionId;
97
+ clientConnectionId = validationResult.connectionId;
98
+ }
99
+ yield this._messenger.sendMessage([connectionId], {
100
+ type: 'login_result',
101
+ info: {
102
+ userId,
103
+ sessionId,
104
+ connectionId: clientConnectionId,
105
+ },
106
+ });
107
+ }
108
+ catch (err) {
109
+ console.error('[WebsocketController] [login] Error while logging in.', err);
110
+ yield this.sendError(connectionId, {
111
+ requestId: requestId,
112
+ errorCode: 'server_error',
113
+ errorMessage: 'A server error occurred while logging in.',
114
+ });
115
+ }
116
+ });
117
+ }
118
+ disconnect(connectionId) {
119
+ return __awaiter(this, void 0, void 0, function* () {
120
+ const loadedConnections = yield this._connectionStore.getConnections(connectionId);
121
+ yield this._connectionStore.clearConnection(connectionId);
122
+ for (let connection of loadedConnections) {
123
+ if (connection.mode === 'branch') {
124
+ if (connection.temporary) {
125
+ const count = yield this._connectionStore.countConnectionsByBranch(connection.mode, connection.recordName, connection.inst, connection.branch);
126
+ if (count <= 0) {
127
+ const branch = yield this._instStore.getBranchByName(connection.recordName, connection.inst, connection.branch);
128
+ if (branch.temporary) {
129
+ yield this._temporaryStore.deleteBranch(connection.recordName, connection.inst, connection.branch);
130
+ yield this._instStore.deleteBranch(connection.recordName, connection.inst, connection.branch);
131
+ }
132
+ }
133
+ }
134
+ const watchingDevices = yield this._connectionStore.getConnectionsByBranch('watch_branch', connection.recordName, connection.inst, connection.branch);
135
+ yield this._messenger.sendMessage(watchingDevices.map((d) => d.serverConnectionId), {
136
+ type: 'repo/disconnected_from_branch',
137
+ broadcast: false,
138
+ recordName: connection.recordName,
139
+ inst: connection.inst,
140
+ branch: connection.branch,
141
+ connection: connectionInfo(connection),
142
+ });
143
+ }
144
+ }
145
+ });
146
+ }
147
+ watchBranch(connectionId, event) {
148
+ return __awaiter(this, void 0, void 0, function* () {
149
+ if (!event) {
150
+ console.warn('[CasualRepoServer] Trying to watch branch with a null event!');
151
+ return;
152
+ }
153
+ console.log(`[CausalRepoServer] [namespace: ${event.recordName}/${event.inst}/${event.branch}, ${connectionId}] Watch`);
154
+ const connection = yield this._connectionStore.getConnection(connectionId);
155
+ if (!connection) {
156
+ throw new Error('Unable to watch_branch. The connection was not found!');
157
+ }
158
+ yield this._connectionStore.saveBranchConnection(Object.assign(Object.assign({}, connection), { serverConnectionId: connectionId, mode: 'branch', recordName: event.recordName, inst: event.inst, branch: event.branch, temporary: event.temporary || false }));
159
+ const inst = yield this._getOrCreateInst(event.recordName, event.inst);
160
+ const branch = yield this._getOrCreateBranch(event.recordName, event.inst, event.branch, event.temporary, inst);
161
+ let updates;
162
+ if (branch.temporary) {
163
+ // Temporary branches use a temporary inst data store.
164
+ // This is because temporary branches are never persisted to disk.
165
+ updates = yield this._temporaryStore.getUpdates(event.recordName, event.inst, event.branch);
166
+ }
167
+ else {
168
+ updates = yield this._instStore.getCurrentUpdates(event.recordName, event.inst, event.branch);
169
+ }
170
+ if (!updates) {
171
+ // branch info exists, but no updates for them exist yet.
172
+ updates = {
173
+ updates: [],
174
+ timestamps: [],
175
+ instSizeInBytes: 0,
176
+ };
177
+ }
178
+ const watchingDevices = yield this._connectionStore.getConnectionsByBranch('watch_branch', event.recordName, event.inst, event.branch);
179
+ console.log(`[CausalRepoServer] [namespace: ${event.recordName}/${event.inst}/${event.branch}, ${connectionId}] Connected.`);
180
+ const promises = [
181
+ this._messenger.sendMessage(watchingDevices.map((d) => d.serverConnectionId), {
182
+ type: 'repo/connected_to_branch',
183
+ broadcast: false,
184
+ branch: event,
185
+ connection: connectionInfo(connection),
186
+ }),
187
+ this._messenger.sendMessage([connection.serverConnectionId], {
188
+ type: 'repo/add_updates',
189
+ recordName: event.recordName,
190
+ inst: event.inst,
191
+ branch: event.branch,
192
+ updates: updates.updates,
193
+ initial: true,
194
+ }),
195
+ ];
196
+ yield Promise.all(promises);
197
+ });
198
+ }
199
+ _getOrCreateInst(recordName, instName) {
200
+ return __awaiter(this, void 0, void 0, function* () {
201
+ let inst = null;
202
+ if (recordName) {
203
+ let inst = yield this._instStore.getInstByName(recordName, instName);
204
+ if (!inst) {
205
+ // Create the inst
206
+ inst = {
207
+ recordName: recordName,
208
+ inst: instName,
209
+ // TODO: Choose a better default marker for auto-created insts
210
+ markers: [PUBLIC_WRITE_MARKER],
211
+ };
212
+ yield this._instStore.saveInst(inst);
213
+ }
214
+ }
215
+ return inst;
216
+ });
217
+ }
218
+ _getOrCreateBranch(recordName, inst, branch, temporary, linkedInst) {
219
+ return __awaiter(this, void 0, void 0, function* () {
220
+ let b = yield this._instStore.getBranchByName(recordName, inst, branch);
221
+ if (!b) {
222
+ if (temporary) {
223
+ // Save the branch to the temp store
224
+ yield this._temporaryStore.saveBranchInfo({
225
+ recordName: recordName,
226
+ inst: inst,
227
+ branch: branch,
228
+ temporary: true,
229
+ linkedInst: linkedInst,
230
+ });
231
+ }
232
+ // Save the branch to the inst store
233
+ yield this._instStore.saveBranch({
234
+ branch: branch,
235
+ inst: inst,
236
+ recordName: recordName,
237
+ temporary: temporary || false,
238
+ });
239
+ b = yield this._instStore.getBranchByName(recordName, inst, branch);
240
+ }
241
+ return b;
242
+ });
243
+ }
244
+ unwatchBranch(connectionId, recordName, inst, branch) {
245
+ return __awaiter(this, void 0, void 0, function* () {
246
+ if (!branch) {
247
+ console.warn('[CasualRepoServer] Trying to unwatch branch with a null event!');
248
+ return;
249
+ }
250
+ console.log(`[CausalRepoServer] [namespace: ${recordName}/${inst}/${branch}, ${connectionId}] Unwatch`);
251
+ const connection = yield this._connectionStore.getBranchConnection(connectionId, 'branch', recordName, inst, branch);
252
+ if (connection) {
253
+ yield this._connectionStore.deleteBranchConnection(connectionId, 'branch', recordName, inst, branch);
254
+ if (connection.temporary) {
255
+ const count = yield this._connectionStore.countConnectionsByBranch('branch', recordName, inst, branch);
256
+ if (count <= 0) {
257
+ const branch = yield this._instStore.getBranchByName(connection.recordName, connection.inst, connection.branch);
258
+ if (branch.temporary) {
259
+ yield this._temporaryStore.deleteBranch(connection.recordName, connection.inst, connection.branch);
260
+ yield this._instStore.deleteBranch(connection.recordName, connection.inst, connection.branch);
261
+ }
262
+ }
263
+ }
264
+ const watchingDevices = yield this._connectionStore.getConnectionsByBranch('watch_branch', recordName, inst, branch);
265
+ yield this._messenger.sendMessage(watchingDevices.map((d) => d.serverConnectionId), {
266
+ type: 'repo/disconnected_from_branch',
267
+ broadcast: false,
268
+ recordName,
269
+ inst,
270
+ branch: branch,
271
+ connection: connectionInfo(connection),
272
+ });
273
+ }
274
+ });
275
+ }
276
+ addUpdates(connectionId, event) {
277
+ return __awaiter(this, void 0, void 0, function* () {
278
+ if (!event) {
279
+ console.warn('[CasualRepoServer] Trying to add atoms with a null event!');
280
+ return;
281
+ }
282
+ console.log(`[CausalRepoServer] [namespace: ${event.recordName}/${event.inst}/${event.branch}, connectionId: ${connectionId}] Add Updates`);
283
+ if (event.updates) {
284
+ let branch = yield this._instStore.getBranchByName(event.recordName, event.inst, event.branch);
285
+ if (!branch) {
286
+ console.log(`[CausalRepoServer] [namespace: ${event.recordName}/${event.inst}/${event.branch}, connectionId: ${connectionId}] Branch not found!`);
287
+ yield this._getOrCreateInst(event.recordName, event.inst);
288
+ yield this._instStore.saveBranch({
289
+ branch: event.branch,
290
+ inst: event.inst,
291
+ recordName: event.recordName,
292
+ temporary: false,
293
+ });
294
+ branch = yield this._instStore.getBranchByName(event.recordName, event.inst, event.branch);
295
+ }
296
+ if (branch.temporary) {
297
+ // Temporary branches use a temporary inst data store.
298
+ // This is because temporary branches are never persisted to disk.
299
+ yield this._temporaryStore.addUpdates(event.recordName, event.inst, event.branch, event.updates, sumBy(event.updates, (u) => u.length));
300
+ }
301
+ else {
302
+ const result = yield this._instStore.addUpdates(event.recordName, event.inst, event.branch, event.updates, sumBy(event.updates, (u) => u.length));
303
+ if (result.success === false) {
304
+ console.log(`[CausalRepoServer] [namespace: ${event.recordName}/${event.inst}/${event.branch}, connectionId: ${connectionId}] Failed to add updates`, result);
305
+ if (result.errorCode === 'max_size_reached') {
306
+ // if (this.mergeUpdatesOnMaxSizeExceeded) {
307
+ // try {
308
+ // console.log(
309
+ // `[CausalRepoServer] [namespace: ${event.recordName}/${event.inst}/${event.branch}, connectionId: ${connectionId}] Merging branch updates.`
310
+ // );
311
+ // const updates = await this._instStore.getUpdates(
312
+ // namespace
313
+ // );
314
+ // const mergedUpdates = mergeUpdates([
315
+ // ...updates.updates.map((u) => toByteArray(u)),
316
+ // ...event.updates.map((u) => toByteArray(u)),
317
+ // ]);
318
+ // result = await this._updatesStore.replaceUpdates(
319
+ // namespace,
320
+ // updates,
321
+ // [fromByteArray(mergedUpdates)]
322
+ // );
323
+ // if (result.success === false) {
324
+ // console.log(
325
+ // `[CausalRepoServer] [${namespace}] [${connectionId}] Failed to merge branch updates`,
326
+ // result
327
+ // );
328
+ // }
329
+ // } catch (err) {
330
+ // console.error(
331
+ // '[CausalRepoServer] Unable to merge branch updates!',
332
+ // err
333
+ // );
334
+ // }
335
+ // }
336
+ if (result.success === false) {
337
+ if ('updateId' in event) {
338
+ let { success, branch } = result, rest = __rest(result, ["success", "branch"]);
339
+ yield this._messenger.sendMessage([connectionId], Object.assign({ type: 'repo/updates_received', recordName: event.recordName, inst: event.inst, branch: event.branch, updateId: event.updateId }, rest));
340
+ }
341
+ return;
342
+ }
343
+ }
344
+ }
345
+ }
346
+ }
347
+ const hasUpdates = event.updates && event.updates.length > 0;
348
+ if (hasUpdates) {
349
+ const connectedDevices = yield this._connectionStore.getConnectionsByBranch('branch', event.recordName, event.inst, event.branch);
350
+ let ret = {
351
+ type: 'repo/add_updates',
352
+ recordName: event.recordName,
353
+ inst: event.inst,
354
+ branch: event.branch,
355
+ updates: event.updates,
356
+ };
357
+ yield this._messenger.sendMessage(connectedDevices.map((c) => c.serverConnectionId), ret, connectionId);
358
+ }
359
+ if ('updateId' in event) {
360
+ yield this._messenger.sendMessage([connectionId], {
361
+ type: 'repo/updates_received',
362
+ recordName: event.recordName,
363
+ inst: event.inst,
364
+ branch: event.branch,
365
+ updateId: event.updateId,
366
+ });
367
+ }
368
+ });
369
+ }
370
+ sendAction(connectionId, event) {
371
+ return __awaiter(this, void 0, void 0, function* () {
372
+ if (!event) {
373
+ console.warn('[CasualRepoServer] Trying to send event with a null event!');
374
+ return;
375
+ }
376
+ // const namespace = branchNamespace(event.recordName, event.inst, event.branch);
377
+ const connectedDevices = yield this._connectionStore.getConnectionsByBranch('branch', event.recordName, event.inst, event.branch);
378
+ if (event.action.type === 'remote') {
379
+ const action = event.action.event;
380
+ }
381
+ let finalAction;
382
+ if (event.action.sessionId ||
383
+ event.action.connectionId ||
384
+ event.action.userId ||
385
+ (typeof event.action.broadcast !== 'undefined' &&
386
+ event.action.broadcast !== null)) {
387
+ finalAction = event.action;
388
+ }
389
+ else {
390
+ // TODO: Replace with system that selects target devices with better uniformity
391
+ // than Math.random().
392
+ const randomDeviceIndex = Math.min(connectedDevices.length - 1, Math.max(Math.floor(Math.random() * connectedDevices.length), 0));
393
+ const randomDevice = connectedDevices[randomDeviceIndex];
394
+ if (randomDevice) {
395
+ finalAction = Object.assign(Object.assign({}, event.action), { connectionId: randomDevice.clientConnectionId });
396
+ }
397
+ }
398
+ if (!finalAction) {
399
+ return;
400
+ }
401
+ const currentConnection = yield this._connectionStore.getConnection(connectionId);
402
+ const targetedDevices = connectedDevices.filter((d) => isEventForDevice(finalAction, d));
403
+ const dEvent = finalAction.type === 'remote'
404
+ ? device(connectionInfo(currentConnection), finalAction.event, finalAction.taskId)
405
+ : finalAction.type === 'remote_result'
406
+ ? deviceResult(connectionInfo(currentConnection), finalAction.result, finalAction.taskId)
407
+ : deviceError(connectionInfo(currentConnection), finalAction.error, finalAction.taskId);
408
+ yield this._messenger.sendMessage(targetedDevices.map((c) => c.serverConnectionId), {
409
+ type: 'repo/receive_action',
410
+ recordName: event.recordName,
411
+ inst: event.inst,
412
+ branch: event.branch,
413
+ action: dEvent,
414
+ });
415
+ });
416
+ }
417
+ watchBranchDevices(connectionId, recordName, inst, branch) {
418
+ return __awaiter(this, void 0, void 0, function* () {
419
+ console.log(`[CausalRepoServer] [namespace: ${recordName}/${inst}/${branch}, connectionId: ${connectionId}] Watch devices for branch`);
420
+ const connection = yield this._connectionStore.getConnection(connectionId);
421
+ if (!connection) {
422
+ throw new Error('Unable to watch_branch_devices. The connection was not found!');
423
+ }
424
+ yield this._connectionStore.saveBranchConnection(Object.assign(Object.assign({}, connection), { mode: 'watch_branch', serverConnectionId: connectionId, recordName,
425
+ inst,
426
+ branch, temporary: true }));
427
+ const currentDevices = yield this._connectionStore.getConnectionsByBranch('branch', recordName, inst, branch);
428
+ const promises = currentDevices.map((device) => this._messenger.sendMessage([connectionId], {
429
+ type: 'repo/connected_to_branch',
430
+ broadcast: false,
431
+ connection: connectionInfo(device),
432
+ branch: {
433
+ type: 'repo/watch_branch',
434
+ recordName: recordName,
435
+ inst: inst,
436
+ branch: branch,
437
+ temporary: device.temporary,
438
+ },
439
+ }));
440
+ yield Promise.all(promises);
441
+ });
442
+ }
443
+ unwatchBranchDevices(connectionId, recordName, inst, branch) {
444
+ return __awaiter(this, void 0, void 0, function* () {
445
+ yield this._connectionStore.deleteBranchConnection(connectionId, 'watch_branch', recordName, inst, branch);
446
+ });
447
+ }
448
+ deviceCount(connectionId, recordName, inst, branch) {
449
+ return __awaiter(this, void 0, void 0, function* () {
450
+ const count = typeof branch !== 'undefined' && branch !== null
451
+ ? yield this._connectionStore.countConnectionsByBranch('branch', recordName, inst, branch)
452
+ : yield this._connectionStore.countConnections();
453
+ yield this._messenger.sendMessage([connectionId], {
454
+ type: 'repo/connection_count',
455
+ recordName,
456
+ inst,
457
+ branch,
458
+ count: count,
459
+ });
460
+ });
461
+ }
462
+ getBranchData(recordName, inst, branch) {
463
+ var _a;
464
+ return __awaiter(this, void 0, void 0, function* () {
465
+ console.log(`[CausalRepoServer] [namespace: ${recordName}/${inst}/${branch}] Get Data`);
466
+ const updates = (_a = (yield this._instStore.getCurrentUpdates(recordName, inst, branch))) !== null && _a !== void 0 ? _a : {
467
+ updates: [],
468
+ timestamps: [],
469
+ instSizeInBytes: 0,
470
+ };
471
+ const partition = new YjsPartitionImpl({ type: 'yjs' });
472
+ for (let updateBase64 of updates.updates) {
473
+ const update = toByteArray(updateBase64);
474
+ applyUpdate(partition.doc, update);
475
+ }
476
+ return {
477
+ version: 1,
478
+ state: partition.state,
479
+ };
480
+ });
481
+ }
482
+ getUpdates(connectionId, recordName, inst, branch) {
483
+ var _a;
484
+ return __awaiter(this, void 0, void 0, function* () {
485
+ if (!branch) {
486
+ console.warn('[CasualRepoServer] Trying to get branch with a null branch!');
487
+ return;
488
+ }
489
+ const connection = yield this._connectionStore.getConnection(connectionId);
490
+ if (!connection) {
491
+ throw new Error('Unable to get_updates. The connection was not found!');
492
+ }
493
+ // const namespace = branchNamespace(recordName, inst, branch);
494
+ console.log(`[CausalRepoServer] [namespace: ${recordName}/${inst}/${branch}, connectionId: ${connectionId}] Get Updates`);
495
+ const updates = (_a = (yield this._instStore.getAllUpdates(recordName, inst, branch))) !== null && _a !== void 0 ? _a : {
496
+ updates: [],
497
+ timestamps: [],
498
+ };
499
+ this._messenger.sendMessage([connection.serverConnectionId], {
500
+ type: 'repo/add_updates',
501
+ recordName,
502
+ inst,
503
+ branch: branch,
504
+ updates: updates.updates,
505
+ timestamps: updates.timestamps,
506
+ });
507
+ });
508
+ }
509
+ /**
510
+ * Processes a webhook and returns the status code that should be returned.
511
+ * @param branch The branch that the webhook is for.
512
+ * @param method The HTTP method that was used for the webhook.
513
+ * @param url The URL that was requested.
514
+ * @param headers The headers that were included in the request.
515
+ * @param data The data included in the request.
516
+ */
517
+ webhook(recordName, inst, branch, method, url, headers, data) {
518
+ return __awaiter(this, void 0, void 0, function* () {
519
+ // const namespace = branchNamespace(recordName, inst, branch);
520
+ const b = yield this._instStore.getBranchByName(recordName, inst, branch);
521
+ if (!b) {
522
+ return 404;
523
+ }
524
+ const connectedDevices = yield this._connectionStore.getConnectionsByBranch('branch', recordName, inst, branch);
525
+ if (connectedDevices.some((d) => !d)) {
526
+ return 500;
527
+ }
528
+ if (connectedDevices.length <= 0) {
529
+ return 404;
530
+ }
531
+ // TODO: Replace with system that selects target devices with better uniformity
532
+ // than Math.random().
533
+ const randomDeviceIndex = Math.min(connectedDevices.length - 1, Math.max(Math.floor(Math.random() * connectedDevices.length), 0));
534
+ const randomDevice = connectedDevices[randomDeviceIndex];
535
+ if (!randomDevice) {
536
+ return 500;
537
+ }
538
+ const a = action(ON_WEBHOOK_ACTION_NAME, null, null, {
539
+ method,
540
+ url,
541
+ headers,
542
+ data,
543
+ });
544
+ yield this._messenger.sendMessage([randomDevice.serverConnectionId], {
545
+ type: 'repo/receive_action',
546
+ recordName,
547
+ inst,
548
+ branch,
549
+ action: a,
550
+ });
551
+ return 200;
552
+ });
553
+ }
554
+ syncTime(connectionId, event, requestTime) {
555
+ return __awaiter(this, void 0, void 0, function* () {
556
+ yield this._messenger.sendMessage([connectionId], {
557
+ type: 'sync/time/response',
558
+ id: event.id,
559
+ clientRequestTime: event.clientRequestTime,
560
+ serverReceiveTime: requestTime,
561
+ serverTransmitTime: Date.now(),
562
+ });
563
+ });
564
+ }
565
+ /**
566
+ * Handles when the rate limit has been exceeded by the given connection.
567
+ * @param connectionId The ID of the connection.
568
+ * @param retryAfter The Retry-After header value.
569
+ * @param totalHits The total number of hits by the connection.
570
+ * @param timeMs The current time in unix time in miliseconds.
571
+ */
572
+ rateLimitExceeded(connectionId, retryAfter, totalHits, timeMs) {
573
+ var _a;
574
+ return __awaiter(this, void 0, void 0, function* () {
575
+ const lastHit = (_a = (yield this._connectionStore.getConnectionRateLimitExceededTime(connectionId))) !== null && _a !== void 0 ? _a : -Infinity;
576
+ const difference = timeMs - lastHit;
577
+ yield this._connectionStore.setConnectionRateLimitExceededTime(connectionId, timeMs);
578
+ if (difference >= 1000) {
579
+ yield this._messenger.sendMessage([connectionId], {
580
+ type: 'rate_limit_exceeded',
581
+ retryAfter,
582
+ totalHits,
583
+ });
584
+ }
585
+ });
586
+ }
587
+ /**
588
+ * Processes the given upload request.
589
+ * @param connectionId The ID of the connection that is requesting the upload.
590
+ * @param requestId The ID of the request.
591
+ */
592
+ uploadRequest(connectionId, requestId) {
593
+ return __awaiter(this, void 0, void 0, function* () {
594
+ try {
595
+ const result = yield this._messenger.presignMessageUpload();
596
+ if (result.success === false) {
597
+ console.log(`[WebsocketController] [uploadRequest] Upload requests are not supported!`);
598
+ yield this.sendError(connectionId, {
599
+ requestId,
600
+ errorCode: 'not_supported',
601
+ errorMessage: 'Upload requests are not supported.',
602
+ });
603
+ return;
604
+ }
605
+ yield this.sendEvent(connectionId, [
606
+ WebsocketEventTypes.UploadResponse,
607
+ requestId,
608
+ result.uploadUrl,
609
+ result.uploadMethod,
610
+ result.uploadHeaders,
611
+ ]);
612
+ }
613
+ catch (err) {
614
+ console.error('[WebsocketController] [uploadRequest] Error while processing upload request.', err);
615
+ yield this.sendError(connectionId, {
616
+ requestId,
617
+ errorCode: 'server_error',
618
+ errorMessage: 'Error while processing upload request.',
619
+ });
620
+ }
621
+ });
622
+ }
623
+ downloadRequest(connectionId, requestId, url, method, headers) {
624
+ return __awaiter(this, void 0, void 0, function* () {
625
+ try {
626
+ const message = yield this._messenger.downloadMessage(url, method, headers);
627
+ if (message === undefined) {
628
+ console.log(`[WebsocketController] [downloadRequest] Download requests are not supported!`);
629
+ return {
630
+ success: false,
631
+ requestId,
632
+ errorCode: 'not_supported',
633
+ errorMessage: 'Download requests are not supported.',
634
+ };
635
+ }
636
+ else if (message === null) {
637
+ return {
638
+ success: false,
639
+ requestId,
640
+ errorCode: 'message_not_found',
641
+ errorMessage: 'Message not found.',
642
+ };
643
+ }
644
+ else {
645
+ return {
646
+ success: true,
647
+ requestId,
648
+ message,
649
+ };
650
+ }
651
+ }
652
+ catch (err) {
653
+ console.error('[WebsocketController] [downloadRequest] Error while processing download request.', err);
654
+ return {
655
+ success: false,
656
+ requestId,
657
+ errorCode: 'server_error',
658
+ errorMessage: 'Error while processing download request.',
659
+ };
660
+ }
661
+ });
662
+ }
663
+ sendError(connectionId, error) {
664
+ return __awaiter(this, void 0, void 0, function* () {
665
+ yield this.sendEvent(connectionId, [
666
+ WebsocketEventTypes.Error,
667
+ error.requestId,
668
+ error.errorCode,
669
+ error.errorMessage,
670
+ error.issues,
671
+ ]);
672
+ });
673
+ }
674
+ sendEvent(connectionId, event) {
675
+ return __awaiter(this, void 0, void 0, function* () {
676
+ yield this._messenger.sendEvent(connectionId, event);
677
+ });
678
+ }
679
+ }
680
+ export function connectionInfo(device) {
681
+ return {
682
+ connectionId: device.clientConnectionId,
683
+ sessionId: device.sessionId,
684
+ userId: device.userId,
685
+ };
686
+ }
687
+ /**
688
+ * Determines if the given event targets the given device connection.
689
+ * @param event The event to check.
690
+ * @param device The device to check.
691
+ */
692
+ export function isEventForDevice(event, device) {
693
+ if (event.broadcast === true) {
694
+ return true;
695
+ }
696
+ if (event.userId === device.userId) {
697
+ return true;
698
+ }
699
+ else if (event.connectionId === device.clientConnectionId) {
700
+ return true;
701
+ }
702
+ else if (event.sessionId === device.sessionId) {
703
+ return true;
704
+ }
705
+ return false;
706
+ }
707
+ //# sourceMappingURL=WebsocketController.js.map