@fluidframework/task-manager 2.0.0-dev-rc.1.0.0.224419

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 (66) hide show
  1. package/.eslintrc.js +29 -0
  2. package/.mocharc.js +12 -0
  3. package/CHANGELOG.md +144 -0
  4. package/LICENSE +21 -0
  5. package/README.md +70 -0
  6. package/api-extractor-lint.json +4 -0
  7. package/api-extractor.json +4 -0
  8. package/api-report/task-manager.api.md +71 -0
  9. package/dist/index.cjs +10 -0
  10. package/dist/index.cjs.map +1 -0
  11. package/dist/index.d.ts +13 -0
  12. package/dist/index.d.ts.map +1 -0
  13. package/dist/interfaces.cjs +7 -0
  14. package/dist/interfaces.cjs.map +1 -0
  15. package/dist/interfaces.d.ts +178 -0
  16. package/dist/interfaces.d.ts.map +1 -0
  17. package/dist/packageVersion.cjs +12 -0
  18. package/dist/packageVersion.cjs.map +1 -0
  19. package/dist/packageVersion.d.ts +9 -0
  20. package/dist/packageVersion.d.ts.map +1 -0
  21. package/dist/task-manager-alpha.d.ts +27 -0
  22. package/dist/task-manager-beta.d.ts +27 -0
  23. package/dist/task-manager-public.d.ts +27 -0
  24. package/dist/task-manager-untrimmed.d.ts +335 -0
  25. package/dist/taskManager.cjs +621 -0
  26. package/dist/taskManager.cjs.map +1 -0
  27. package/dist/taskManager.d.ts +150 -0
  28. package/dist/taskManager.d.ts.map +1 -0
  29. package/dist/taskManagerFactory.cjs +41 -0
  30. package/dist/taskManagerFactory.cjs.map +1 -0
  31. package/dist/taskManagerFactory.d.ts +21 -0
  32. package/dist/taskManagerFactory.d.ts.map +1 -0
  33. package/dist/tsdoc-metadata.json +11 -0
  34. package/lib/index.d.mts +7 -0
  35. package/lib/index.d.mts.map +1 -0
  36. package/lib/index.mjs +6 -0
  37. package/lib/index.mjs.map +1 -0
  38. package/lib/interfaces.d.mts +178 -0
  39. package/lib/interfaces.d.mts.map +1 -0
  40. package/lib/interfaces.mjs +6 -0
  41. package/lib/interfaces.mjs.map +1 -0
  42. package/lib/packageVersion.d.mts +9 -0
  43. package/lib/packageVersion.d.mts.map +1 -0
  44. package/lib/packageVersion.mjs +9 -0
  45. package/lib/packageVersion.mjs.map +1 -0
  46. package/lib/task-manager-alpha.d.mts +27 -0
  47. package/lib/task-manager-beta.d.mts +27 -0
  48. package/lib/task-manager-public.d.mts +27 -0
  49. package/lib/task-manager-untrimmed.d.mts +335 -0
  50. package/lib/taskManager.d.mts +150 -0
  51. package/lib/taskManager.d.mts.map +1 -0
  52. package/lib/taskManager.mjs +617 -0
  53. package/lib/taskManager.mjs.map +1 -0
  54. package/lib/taskManagerFactory.d.mts +21 -0
  55. package/lib/taskManagerFactory.d.mts.map +1 -0
  56. package/lib/taskManagerFactory.mjs +37 -0
  57. package/lib/taskManagerFactory.mjs.map +1 -0
  58. package/package.json +137 -0
  59. package/prettier.config.cjs +8 -0
  60. package/src/index.ts +14 -0
  61. package/src/interfaces.ts +190 -0
  62. package/src/packageVersion.ts +9 -0
  63. package/src/taskManager.ts +776 -0
  64. package/src/taskManagerFactory.ts +55 -0
  65. package/tsc-multi.test.json +4 -0
  66. package/tsconfig.json +12 -0
@@ -0,0 +1,617 @@
1
+ /*!
2
+ * Copyright (c) Microsoft Corporation and contributors. All rights reserved.
3
+ * Licensed under the MIT License.
4
+ */
5
+ import { EventEmitter } from "events";
6
+ import { assert } from "@fluidframework/core-utils";
7
+ import { MessageType } from "@fluidframework/protocol-definitions";
8
+ import { readAndParse } from "@fluidframework/driver-utils";
9
+ import { createSingleBlobSummary, SharedObject, } from "@fluidframework/shared-object-base";
10
+ import { TaskManagerFactory } from "./taskManagerFactory.mjs";
11
+ const snapshotFileName = "header";
12
+ /**
13
+ * Placeholder clientId for detached scenarios.
14
+ */
15
+ const placeholderClientId = "placeholder";
16
+ /**
17
+ * {@inheritDoc ITaskManager}
18
+ *
19
+ * @sealed
20
+ * @internal
21
+ */
22
+ export class TaskManager extends SharedObject {
23
+ /**
24
+ * Create a new TaskManager
25
+ *
26
+ * @param runtime - data store runtime the new task queue belongs to
27
+ * @param id - optional name of the task queue
28
+ * @returns newly create task queue (but not attached yet)
29
+ */
30
+ static create(runtime, id) {
31
+ return runtime.createChannel(id, TaskManagerFactory.Type);
32
+ }
33
+ /**
34
+ * Get a factory for TaskManager to register with the data store.
35
+ *
36
+ * @returns a factory that creates and load TaskManager
37
+ */
38
+ static getFactory() {
39
+ return new TaskManagerFactory();
40
+ }
41
+ /**
42
+ * Returns the clientId. Will return a placeholder if the runtime is detached and not yet assigned a clientId.
43
+ */
44
+ get clientId() {
45
+ return this.isAttached() ? this.runtime.clientId : placeholderClientId;
46
+ }
47
+ /**
48
+ * Returns a ReadOnlyInfo object to determine current read/write permissions.
49
+ */
50
+ get readOnlyInfo() {
51
+ return this.runtime.deltaManager.readOnlyInfo;
52
+ }
53
+ /**
54
+ * Constructs a new task manager. If the object is non-local an id and service interfaces will
55
+ * be provided
56
+ *
57
+ * @param runtime - data store runtime the task queue belongs to
58
+ * @param id - optional name of the task queue
59
+ */
60
+ constructor(id, runtime, attributes) {
61
+ super(id, runtime, attributes, "fluid_taskManager_");
62
+ /**
63
+ * Mapping of taskId to a queue of clientIds that are waiting on the task. Maintains the consensus state of the
64
+ * queue, even if we know we've submitted an op that should eventually modify the queue.
65
+ */
66
+ this.taskQueues = new Map();
67
+ // opWatcher emits for every op on this data store. This is just a repackaging of processCore into events.
68
+ this.opWatcher = new EventEmitter();
69
+ // queueWatcher emits an event whenever the consensus state of the task queues changes
70
+ this.queueWatcher = new EventEmitter();
71
+ // abandonWatcher emits an event whenever the local client calls abandon() on a task.
72
+ this.abandonWatcher = new EventEmitter();
73
+ // connectionWatcher emits an event whenever we get connected or disconnected.
74
+ this.connectionWatcher = new EventEmitter();
75
+ // completedWatcher emits an event whenever the local client receives a completed op.
76
+ this.completedWatcher = new EventEmitter();
77
+ this.messageId = -1;
78
+ /**
79
+ * Tracks the most recent pending op for a given task
80
+ */
81
+ this.latestPendingOps = new Map();
82
+ /**
83
+ * Tracks tasks that are this client is currently subscribed to.
84
+ */
85
+ this.subscribedTasks = new Set();
86
+ /**
87
+ * Map to track tasks that have pending complete ops.
88
+ */
89
+ this.pendingCompletedTasks = new Map();
90
+ this.opWatcher.on("volunteer", (taskId, clientId, local, messageId) => {
91
+ // We're tracking local ops from this connection. Filter out local ops during "connecting"
92
+ // state since these were sent on the prior connection and were already cleared from the latestPendingOps.
93
+ if (runtime.connected && local) {
94
+ const pendingOp = this.latestPendingOps.get(taskId);
95
+ assert(pendingOp !== undefined, 0x07b /* "Unexpected op" */);
96
+ // Need to check the id, since it's possible to volunteer and abandon multiple times before the acks
97
+ if (messageId === pendingOp.messageId) {
98
+ assert(pendingOp.type === "volunteer", 0x07c /* "Unexpected op type" */);
99
+ // Delete the pending, because we no longer have an outstanding op
100
+ this.latestPendingOps.delete(taskId);
101
+ }
102
+ }
103
+ this.addClientToQueue(taskId, clientId);
104
+ });
105
+ this.opWatcher.on("abandon", (taskId, clientId, local, messageId) => {
106
+ if (runtime.connected && local) {
107
+ const pendingOp = this.latestPendingOps.get(taskId);
108
+ assert(pendingOp !== undefined, 0x07d /* "Unexpected op" */);
109
+ // Need to check the id, since it's possible to abandon and volunteer multiple times before the acks
110
+ if (messageId === pendingOp.messageId) {
111
+ assert(pendingOp.type === "abandon", 0x07e /* "Unexpected op type" */);
112
+ // Delete the pending, because we no longer have an outstanding op
113
+ this.latestPendingOps.delete(taskId);
114
+ }
115
+ }
116
+ this.removeClientFromQueue(taskId, clientId);
117
+ });
118
+ this.opWatcher.on("complete", (taskId, clientId, local, messageId) => {
119
+ if (runtime.connected && local) {
120
+ const pendingOp = this.latestPendingOps.get(taskId);
121
+ assert(pendingOp !== undefined, 0x400 /* Unexpected op */);
122
+ // Need to check the id, since it's possible to complete multiple times before the acks
123
+ if (messageId === pendingOp.messageId) {
124
+ assert(pendingOp.type === "complete", 0x401 /* Unexpected op type */);
125
+ // Delete the pending, because we no longer have an outstanding op
126
+ this.latestPendingOps.delete(taskId);
127
+ }
128
+ // Remove complete op from this.pendingCompletedTasks
129
+ const pendingIds = this.pendingCompletedTasks.get(taskId);
130
+ assert(pendingIds !== undefined && pendingIds.length > 0, 0x402 /* pendingIds is empty */);
131
+ const removed = pendingIds.shift();
132
+ assert(removed === messageId, 0x403 /* Removed complete op id does not match */);
133
+ }
134
+ // For clients in queue, we need to remove them from the queue and raise the proper events.
135
+ if (!local) {
136
+ this.taskQueues.delete(taskId);
137
+ this.completedWatcher.emit("completed", taskId);
138
+ this.emit("completed", taskId);
139
+ }
140
+ });
141
+ runtime.getQuorum().on("removeMember", (clientId) => {
142
+ this.removeClientFromAllQueues(clientId);
143
+ });
144
+ this.queueWatcher.on("queueChange", (taskId, oldLockHolder, newLockHolder) => {
145
+ // If oldLockHolder is placeholderClientId we need to emit the task was lost during the attach process
146
+ if (oldLockHolder === placeholderClientId) {
147
+ this.emit("lost", taskId);
148
+ return;
149
+ }
150
+ // Exit early if we are still catching up on reconnect -- we can't be the leader yet anyway.
151
+ if (this.clientId === undefined) {
152
+ return;
153
+ }
154
+ if (oldLockHolder !== this.clientId && newLockHolder === this.clientId) {
155
+ this.emit("assigned", taskId);
156
+ }
157
+ else if (oldLockHolder === this.clientId && newLockHolder !== this.clientId) {
158
+ this.emit("lost", taskId);
159
+ }
160
+ });
161
+ this.connectionWatcher.on("disconnect", () => {
162
+ assert(this.clientId !== undefined, 0x1d3 /* "Missing client id on disconnect" */);
163
+ // We don't modify the taskQueues on disconnect (they still reflect the latest known consensus state).
164
+ // After reconnect these will get cleaned up by observing the clientLeaves.
165
+ // However we do need to recognize that we lost the lock if we had it. Calls to .queued() and
166
+ // .assigned() are also connection-state-aware to be consistent.
167
+ for (const [taskId, clientQueue] of this.taskQueues.entries()) {
168
+ if (this.isAttached() && clientQueue[0] === this.clientId) {
169
+ this.emit("lost", taskId);
170
+ }
171
+ }
172
+ // All of our outstanding ops will be for the old clientId even if they get ack'd
173
+ this.latestPendingOps.clear();
174
+ });
175
+ }
176
+ submitVolunteerOp(taskId) {
177
+ const op = {
178
+ type: "volunteer",
179
+ taskId,
180
+ };
181
+ const pendingOp = {
182
+ type: "volunteer",
183
+ messageId: ++this.messageId,
184
+ };
185
+ this.submitLocalMessage(op, pendingOp.messageId);
186
+ this.latestPendingOps.set(taskId, pendingOp);
187
+ }
188
+ submitAbandonOp(taskId) {
189
+ const op = {
190
+ type: "abandon",
191
+ taskId,
192
+ };
193
+ const pendingOp = {
194
+ type: "abandon",
195
+ messageId: ++this.messageId,
196
+ };
197
+ this.submitLocalMessage(op, pendingOp.messageId);
198
+ this.latestPendingOps.set(taskId, pendingOp);
199
+ }
200
+ submitCompleteOp(taskId) {
201
+ const op = {
202
+ type: "complete",
203
+ taskId,
204
+ };
205
+ const pendingOp = {
206
+ type: "complete",
207
+ messageId: ++this.messageId,
208
+ };
209
+ if (this.pendingCompletedTasks.has(taskId)) {
210
+ this.pendingCompletedTasks.get(taskId)?.push(pendingOp.messageId);
211
+ }
212
+ else {
213
+ this.pendingCompletedTasks.set(taskId, [pendingOp.messageId]);
214
+ }
215
+ this.submitLocalMessage(op, pendingOp.messageId);
216
+ this.latestPendingOps.set(taskId, pendingOp);
217
+ }
218
+ /**
219
+ * {@inheritDoc ITaskManager.volunteerForTask}
220
+ */
221
+ async volunteerForTask(taskId) {
222
+ // If we have the lock, resolve immediately
223
+ if (this.assigned(taskId)) {
224
+ return true;
225
+ }
226
+ if (this.readOnlyInfo.readonly === true) {
227
+ const error = this.readOnlyInfo.permissions === true
228
+ ? new Error("Attempted to volunteer with read-only permissions")
229
+ : new Error("Attempted to volunteer in read-only state");
230
+ throw error;
231
+ }
232
+ if (!this.isAttached()) {
233
+ // Simulate auto-ack in detached scenario
234
+ assert(this.clientId !== undefined, 0x472 /* clientId should not be undefined */);
235
+ this.addClientToQueue(taskId, this.clientId);
236
+ return true;
237
+ }
238
+ if (!this.connected) {
239
+ throw new Error("Attempted to volunteer in disconnected state");
240
+ }
241
+ // This promise works even if we already have an outstanding volunteer op.
242
+ const lockAcquireP = new Promise((resolve, reject) => {
243
+ const checkIfAcquiredLock = (eventTaskId) => {
244
+ if (eventTaskId !== taskId) {
245
+ return;
246
+ }
247
+ // Also check pending ops here because it's possible we are currently in the queue from a previous
248
+ // lock attempt, but have an outstanding abandon AND the outstanding volunteer for this lock attempt.
249
+ // If we reach the head of the queue based on the previous lock attempt, we don't want to resolve.
250
+ if (this.assigned(taskId) && !this.latestPendingOps.has(taskId)) {
251
+ this.queueWatcher.off("queueChange", checkIfAcquiredLock);
252
+ this.abandonWatcher.off("abandon", checkIfAbandoned);
253
+ this.connectionWatcher.off("disconnect", rejectOnDisconnect);
254
+ this.completedWatcher.off("completed", checkIfCompleted);
255
+ resolve(true);
256
+ }
257
+ };
258
+ const checkIfAbandoned = (eventTaskId) => {
259
+ if (eventTaskId !== taskId) {
260
+ return;
261
+ }
262
+ this.queueWatcher.off("queueChange", checkIfAcquiredLock);
263
+ this.abandonWatcher.off("abandon", checkIfAbandoned);
264
+ this.connectionWatcher.off("disconnect", rejectOnDisconnect);
265
+ this.completedWatcher.off("completed", checkIfCompleted);
266
+ reject(new Error("Abandoned before acquiring task assignment"));
267
+ };
268
+ const rejectOnDisconnect = () => {
269
+ this.queueWatcher.off("queueChange", checkIfAcquiredLock);
270
+ this.abandonWatcher.off("abandon", checkIfAbandoned);
271
+ this.connectionWatcher.off("disconnect", rejectOnDisconnect);
272
+ this.completedWatcher.off("completed", checkIfCompleted);
273
+ reject(new Error("Disconnected before acquiring task assignment"));
274
+ };
275
+ const checkIfCompleted = (eventTaskId) => {
276
+ if (eventTaskId !== taskId) {
277
+ return;
278
+ }
279
+ this.queueWatcher.off("queueChange", checkIfAcquiredLock);
280
+ this.abandonWatcher.off("abandon", checkIfAbandoned);
281
+ this.connectionWatcher.off("disconnect", rejectOnDisconnect);
282
+ this.completedWatcher.off("completed", checkIfCompleted);
283
+ resolve(false);
284
+ };
285
+ this.queueWatcher.on("queueChange", checkIfAcquiredLock);
286
+ this.abandonWatcher.on("abandon", checkIfAbandoned);
287
+ this.connectionWatcher.on("disconnect", rejectOnDisconnect);
288
+ this.completedWatcher.on("completed", checkIfCompleted);
289
+ });
290
+ if (!this.queued(taskId)) {
291
+ this.submitVolunteerOp(taskId);
292
+ }
293
+ return lockAcquireP;
294
+ }
295
+ /**
296
+ * {@inheritDoc ITaskManager.subscribeToTask}
297
+ */
298
+ subscribeToTask(taskId) {
299
+ if (this.subscribed(taskId)) {
300
+ return;
301
+ }
302
+ if (this.readOnlyInfo.readonly === true && this.readOnlyInfo.permissions === true) {
303
+ throw new Error("Attempted to subscribe with read-only permissions");
304
+ }
305
+ const submitVolunteerOp = () => {
306
+ this.submitVolunteerOp(taskId);
307
+ };
308
+ const disconnectHandler = () => {
309
+ // Wait to be connected again and then re-submit volunteer op
310
+ this.connectionWatcher.once("connect", submitVolunteerOp);
311
+ };
312
+ const checkIfAbandoned = (eventTaskId) => {
313
+ if (eventTaskId !== taskId) {
314
+ return;
315
+ }
316
+ this.abandonWatcher.off("abandon", checkIfAbandoned);
317
+ this.connectionWatcher.off("disconnect", disconnectHandler);
318
+ this.connectionWatcher.off("connect", submitVolunteerOp);
319
+ this.completedWatcher.off("completed", checkIfCompleted);
320
+ this.subscribedTasks.delete(taskId);
321
+ };
322
+ const checkIfCompleted = (eventTaskId) => {
323
+ if (eventTaskId !== taskId) {
324
+ return;
325
+ }
326
+ this.abandonWatcher.off("abandon", checkIfAbandoned);
327
+ this.connectionWatcher.off("disconnect", disconnectHandler);
328
+ this.connectionWatcher.off("connect", submitVolunteerOp);
329
+ this.completedWatcher.off("completed", checkIfCompleted);
330
+ this.subscribedTasks.delete(taskId);
331
+ };
332
+ this.abandonWatcher.on("abandon", checkIfAbandoned);
333
+ this.connectionWatcher.on("disconnect", disconnectHandler);
334
+ this.completedWatcher.on("completed", checkIfCompleted);
335
+ if (!this.isAttached()) {
336
+ // Simulate auto-ack in detached scenario
337
+ assert(this.clientId !== undefined, 0x473 /* clientId should not be undefined */);
338
+ this.addClientToQueue(taskId, this.clientId);
339
+ // Because we volunteered with placeholderClientId, we need to wait for when we attach and are assigned
340
+ // a real clientId. At that point we should re-enter the queue with a real volunteer op (assuming we are
341
+ // connected).
342
+ this.runtime.once("attached", () => {
343
+ if (this.queued(taskId)) {
344
+ // If we are already queued, then we were able to replace the placeholderClientId with our real
345
+ // clientId and no action is required.
346
+ return;
347
+ }
348
+ else if (this.connected) {
349
+ submitVolunteerOp();
350
+ }
351
+ else {
352
+ this.connectionWatcher.once("connect", () => {
353
+ submitVolunteerOp();
354
+ });
355
+ }
356
+ });
357
+ }
358
+ else if (!this.connected) {
359
+ // If we are disconnected (and attached), wait to be connected and submit volunteer op
360
+ disconnectHandler();
361
+ }
362
+ else if (!this.assigned(taskId) && !this.queued(taskId)) {
363
+ submitVolunteerOp();
364
+ }
365
+ this.subscribedTasks.add(taskId);
366
+ }
367
+ /**
368
+ * {@inheritDoc ITaskManager.abandon}
369
+ */
370
+ abandon(taskId) {
371
+ // Always allow abandon if the client is subscribed to allow clients to unsubscribe while disconnected.
372
+ // Otherwise, we should check to make sure the client is both connected queued for the task before sending an
373
+ // abandon op.
374
+ if (!this.subscribed(taskId) && !this.queued(taskId)) {
375
+ // Nothing to do
376
+ return;
377
+ }
378
+ if (!this.isAttached()) {
379
+ // Simulate auto-ack in detached scenario
380
+ assert(this.clientId !== undefined, 0x474 /* clientId is undefined */);
381
+ this.removeClientFromQueue(taskId, this.clientId);
382
+ this.abandonWatcher.emit("abandon", taskId);
383
+ return;
384
+ }
385
+ // If we're subscribed but not queued, we don't need to submit an abandon op (probably offline)
386
+ if (this.queued(taskId)) {
387
+ this.submitAbandonOp(taskId);
388
+ }
389
+ this.abandonWatcher.emit("abandon", taskId);
390
+ }
391
+ /**
392
+ * {@inheritDoc ITaskManager.assigned}
393
+ */
394
+ assigned(taskId) {
395
+ if (this.isAttached() && !this.connected) {
396
+ return false;
397
+ }
398
+ const currentAssignee = this.taskQueues.get(taskId)?.[0];
399
+ return (currentAssignee !== undefined &&
400
+ currentAssignee === this.clientId &&
401
+ !this.latestPendingOps.has(taskId));
402
+ }
403
+ /**
404
+ * {@inheritDoc ITaskManager.queued}
405
+ */
406
+ queued(taskId) {
407
+ if (this.isAttached() && !this.connected) {
408
+ return false;
409
+ }
410
+ assert(this.clientId !== undefined, 0x07f /* "clientId undefined" */);
411
+ const clientQueue = this.taskQueues.get(taskId);
412
+ // If we have no queue for the taskId, then no one has signed up for it.
413
+ return (((clientQueue?.includes(this.clientId) ?? false) &&
414
+ !this.latestPendingOps.has(taskId)) ||
415
+ this.latestPendingOps.get(taskId)?.type === "volunteer");
416
+ }
417
+ /**
418
+ * {@inheritDoc ITaskManager.subscribed}
419
+ */
420
+ subscribed(taskId) {
421
+ return this.subscribedTasks.has(taskId);
422
+ }
423
+ /**
424
+ * {@inheritDoc ITaskManager.complete}
425
+ */
426
+ complete(taskId) {
427
+ if (!this.assigned(taskId)) {
428
+ throw new Error("Attempted to mark task as complete while not being assigned");
429
+ }
430
+ // If we are detached we will simulate auto-ack for the complete op. Therefore we only need to send the op if
431
+ // we are attached. Additionally, we don't need to check if we are connected while detached.
432
+ if (this.isAttached()) {
433
+ if (!this.connected) {
434
+ throw new Error("Attempted to complete task in disconnected state");
435
+ }
436
+ this.submitCompleteOp(taskId);
437
+ }
438
+ this.taskQueues.delete(taskId);
439
+ this.completedWatcher.emit("completed", taskId);
440
+ this.emit("completed", taskId);
441
+ }
442
+ /**
443
+ * {@inheritDoc ITaskManager.canVolunteer}
444
+ */
445
+ canVolunteer() {
446
+ // A client can volunteer for a task if it's both connected to the delta stream and in write mode.
447
+ // this.connected reflects that condition, but is unintuitive and may be changed in the future. This API allows
448
+ // us to make changes to this.connected without affecting our guidance on how to check if a client is eligible
449
+ // to volunteer for a task.
450
+ return this.connected;
451
+ }
452
+ /**
453
+ * Create a summary for the task manager
454
+ *
455
+ * @returns the summary of the current state of the task manager
456
+ */
457
+ summarizeCore(serializer) {
458
+ if (this.runtime.clientId !== undefined) {
459
+ // If the runtime has been assigned an actual clientId by now, we can replace the placeholder clientIds
460
+ // and maintain the task assignment.
461
+ this.replacePlaceholderInAllQueues();
462
+ }
463
+ else {
464
+ // If the runtime has still not been assigned a clientId, we should not summarize with the placeholder
465
+ // clientIds and instead remove them from the queues and require the client to re-volunteer when assigned
466
+ // a new clientId.
467
+ this.removeClientFromAllQueues(placeholderClientId);
468
+ }
469
+ // Only include tasks if there are clients in the queue.
470
+ const filteredMap = new Map();
471
+ this.taskQueues.forEach((queue, taskId) => {
472
+ if (queue.length > 0) {
473
+ filteredMap.set(taskId, queue);
474
+ }
475
+ });
476
+ const content = [...filteredMap.entries()];
477
+ return createSingleBlobSummary(snapshotFileName, JSON.stringify(content));
478
+ }
479
+ /**
480
+ * {@inheritDoc @fluidframework/shared-object-base#SharedObject.loadCore}
481
+ */
482
+ async loadCore(storage) {
483
+ const content = await readAndParse(storage, snapshotFileName);
484
+ content.forEach(([taskId, clientIdQueue]) => {
485
+ this.taskQueues.set(taskId, clientIdQueue);
486
+ });
487
+ this.scrubClientsNotInQuorum();
488
+ }
489
+ /***/
490
+ initializeLocalCore() { }
491
+ /**
492
+ * {@inheritDoc @fluidframework/shared-object-base#SharedObject.onDisconnect}
493
+ */
494
+ onDisconnect() {
495
+ this.connectionWatcher.emit("disconnect");
496
+ }
497
+ /**
498
+ * {@inheritDoc @fluidframework/shared-object-base#SharedObject.onConnect}
499
+ */
500
+ onConnect() {
501
+ this.connectionWatcher.emit("connect");
502
+ }
503
+ //
504
+ /**
505
+ * Override resubmit core to avoid resubmission on reconnect. On disconnect we accept our removal from the
506
+ * queues, and leave it up to the user to decide whether they want to attempt to re-enter a queue on reconnect.
507
+ */
508
+ reSubmitCore() { }
509
+ /**
510
+ * Process a task manager operation
511
+ *
512
+ * @param message - the message to prepare
513
+ * @param local - whether the message was sent by the local client
514
+ * @param localOpMetadata - For local client messages, this is the metadata that was submitted with the message.
515
+ * For messages from a remote client, this will be undefined.
516
+ */
517
+ processCore(message, local, localOpMetadata) {
518
+ if (message.type === MessageType.Operation) {
519
+ const op = message.contents;
520
+ const messageId = localOpMetadata;
521
+ switch (op.type) {
522
+ case "volunteer":
523
+ this.opWatcher.emit("volunteer", op.taskId, message.clientId, local, messageId);
524
+ break;
525
+ case "abandon":
526
+ this.opWatcher.emit("abandon", op.taskId, message.clientId, local, messageId);
527
+ break;
528
+ case "complete":
529
+ this.opWatcher.emit("complete", op.taskId, message.clientId, local, messageId);
530
+ break;
531
+ default:
532
+ throw new Error("Unknown operation");
533
+ }
534
+ }
535
+ }
536
+ addClientToQueue(taskId, clientId) {
537
+ const pendingIds = this.pendingCompletedTasks.get(taskId);
538
+ if (pendingIds !== undefined && pendingIds.length > 0) {
539
+ // Ignore the volunteer op if we know this task is about to be completed
540
+ return;
541
+ }
542
+ // Ensure that the clientId exists in the quorum, or it is placeholderClientId (detached scenario)
543
+ if (this.runtime.getQuorum().getMembers().has(clientId) ||
544
+ this.clientId === placeholderClientId) {
545
+ // Create the queue if it doesn't exist, and push the client on the back.
546
+ let clientQueue = this.taskQueues.get(taskId);
547
+ if (clientQueue === undefined) {
548
+ clientQueue = [];
549
+ this.taskQueues.set(taskId, clientQueue);
550
+ }
551
+ const oldLockHolder = clientQueue[0];
552
+ clientQueue.push(clientId);
553
+ const newLockHolder = clientQueue[0];
554
+ if (newLockHolder !== oldLockHolder) {
555
+ this.queueWatcher.emit("queueChange", taskId, oldLockHolder, newLockHolder);
556
+ }
557
+ }
558
+ }
559
+ removeClientFromQueue(taskId, clientId) {
560
+ const clientQueue = this.taskQueues.get(taskId);
561
+ if (clientQueue === undefined) {
562
+ return;
563
+ }
564
+ const oldLockHolder = clientId === placeholderClientId ? placeholderClientId : clientQueue[0];
565
+ const clientIdIndex = clientQueue.indexOf(clientId);
566
+ if (clientIdIndex !== -1) {
567
+ clientQueue.splice(clientIdIndex, 1);
568
+ // Clean up the queue if there are no more clients in it.
569
+ if (clientQueue.length === 0) {
570
+ this.taskQueues.delete(taskId);
571
+ }
572
+ }
573
+ const newLockHolder = clientQueue[0];
574
+ if (newLockHolder !== oldLockHolder) {
575
+ this.queueWatcher.emit("queueChange", taskId, oldLockHolder, newLockHolder);
576
+ }
577
+ }
578
+ removeClientFromAllQueues(clientId) {
579
+ for (const taskId of this.taskQueues.keys()) {
580
+ this.removeClientFromQueue(taskId, clientId);
581
+ }
582
+ }
583
+ /**
584
+ * Will replace all instances of the placeholderClientId with the current clientId. This should only be called when
585
+ * transitioning from detached to attached and this.runtime.clientId is defined.
586
+ */
587
+ replacePlaceholderInAllQueues() {
588
+ assert(this.runtime.clientId !== undefined, 0x475 /* this.runtime.clientId should be defined */);
589
+ for (const clientQueue of this.taskQueues.values()) {
590
+ const clientIdIndex = clientQueue.indexOf(placeholderClientId);
591
+ if (clientIdIndex !== -1) {
592
+ clientQueue[clientIdIndex] = this.runtime.clientId;
593
+ }
594
+ }
595
+ }
596
+ // This seems like it should be unnecessary if we can trust to receive the join/leave messages and
597
+ // also have an accurate snapshot.
598
+ scrubClientsNotInQuorum() {
599
+ const quorum = this.runtime.getQuorum();
600
+ for (const [taskId, clientQueue] of this.taskQueues) {
601
+ const filteredClientQueue = clientQueue.filter((clientId) => quorum.getMember(clientId) !== undefined);
602
+ if (clientQueue.length !== filteredClientQueue.length) {
603
+ if (filteredClientQueue.length === 0) {
604
+ this.taskQueues.delete(taskId);
605
+ }
606
+ else {
607
+ this.taskQueues.set(taskId, filteredClientQueue);
608
+ }
609
+ this.queueWatcher.emit("queueChange", taskId);
610
+ }
611
+ }
612
+ }
613
+ applyStashedOp() {
614
+ // do nothing...
615
+ }
616
+ }
617
+ //# sourceMappingURL=taskManager.mjs.map