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