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