@fluidframework/container-runtime 1.2.6 → 2.0.0-dev.1.3.0.96595

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 (221) hide show
  1. package/.mocharc.js +12 -0
  2. package/dist/batchManager.d.ts +37 -0
  3. package/dist/batchManager.d.ts.map +1 -0
  4. package/dist/batchManager.js +73 -0
  5. package/dist/batchManager.js.map +1 -0
  6. package/dist/batchTracker.d.ts +1 -2
  7. package/dist/batchTracker.d.ts.map +1 -1
  8. package/dist/batchTracker.js +2 -3
  9. package/dist/batchTracker.js.map +1 -1
  10. package/dist/blobManager.d.ts +87 -25
  11. package/dist/blobManager.d.ts.map +1 -1
  12. package/dist/blobManager.js +317 -99
  13. package/dist/blobManager.js.map +1 -1
  14. package/dist/containerRuntime.d.ts +109 -124
  15. package/dist/containerRuntime.d.ts.map +1 -1
  16. package/dist/containerRuntime.js +349 -542
  17. package/dist/containerRuntime.js.map +1 -1
  18. package/dist/dataStore.js +29 -24
  19. package/dist/dataStore.js.map +1 -1
  20. package/dist/dataStoreContext.d.ts +20 -14
  21. package/dist/dataStoreContext.d.ts.map +1 -1
  22. package/dist/dataStoreContext.js +49 -58
  23. package/dist/dataStoreContext.js.map +1 -1
  24. package/dist/dataStores.d.ts +12 -5
  25. package/dist/dataStores.d.ts.map +1 -1
  26. package/dist/dataStores.js +21 -20
  27. package/dist/dataStores.js.map +1 -1
  28. package/dist/deltaScheduler.d.ts +6 -4
  29. package/dist/deltaScheduler.d.ts.map +1 -1
  30. package/dist/deltaScheduler.js +6 -4
  31. package/dist/deltaScheduler.js.map +1 -1
  32. package/dist/garbageCollection.d.ts +74 -14
  33. package/dist/garbageCollection.d.ts.map +1 -1
  34. package/dist/garbageCollection.js +249 -170
  35. package/dist/garbageCollection.js.map +1 -1
  36. package/dist/gcSweepReadyUsageDetection.d.ts +53 -0
  37. package/dist/gcSweepReadyUsageDetection.d.ts.map +1 -0
  38. package/dist/gcSweepReadyUsageDetection.js +126 -0
  39. package/dist/gcSweepReadyUsageDetection.js.map +1 -0
  40. package/dist/index.d.ts +2 -1
  41. package/dist/index.d.ts.map +1 -1
  42. package/dist/index.js +3 -2
  43. package/dist/index.js.map +1 -1
  44. package/dist/opProperties.d.ts +7 -0
  45. package/dist/opProperties.d.ts.map +1 -0
  46. package/dist/opProperties.js +20 -0
  47. package/dist/opProperties.js.map +1 -0
  48. package/dist/orderedClientElection.d.ts +28 -10
  49. package/dist/orderedClientElection.d.ts.map +1 -1
  50. package/dist/orderedClientElection.js +14 -4
  51. package/dist/orderedClientElection.js.map +1 -1
  52. package/dist/packageVersion.d.ts +1 -1
  53. package/dist/packageVersion.d.ts.map +1 -1
  54. package/dist/packageVersion.js +1 -1
  55. package/dist/packageVersion.js.map +1 -1
  56. package/dist/pendingStateManager.d.ts +0 -11
  57. package/dist/pendingStateManager.d.ts.map +1 -1
  58. package/dist/pendingStateManager.js +24 -46
  59. package/dist/pendingStateManager.js.map +1 -1
  60. package/dist/runningSummarizer.d.ts +14 -4
  61. package/dist/runningSummarizer.d.ts.map +1 -1
  62. package/dist/runningSummarizer.js +68 -26
  63. package/dist/runningSummarizer.js.map +1 -1
  64. package/dist/scheduleManager.d.ts +31 -0
  65. package/dist/scheduleManager.d.ts.map +1 -0
  66. package/dist/scheduleManager.js +243 -0
  67. package/dist/scheduleManager.js.map +1 -0
  68. package/dist/summarizer.d.ts +0 -2
  69. package/dist/summarizer.d.ts.map +1 -1
  70. package/dist/summarizer.js +1 -12
  71. package/dist/summarizer.js.map +1 -1
  72. package/dist/summarizerHeuristics.d.ts +26 -4
  73. package/dist/summarizerHeuristics.d.ts.map +1 -1
  74. package/dist/summarizerHeuristics.js +95 -18
  75. package/dist/summarizerHeuristics.js.map +1 -1
  76. package/dist/summarizerTypes.d.ts +45 -18
  77. package/dist/summarizerTypes.d.ts.map +1 -1
  78. package/dist/summarizerTypes.js +1 -1
  79. package/dist/summarizerTypes.js.map +1 -1
  80. package/dist/summaryCollection.d.ts +1 -0
  81. package/dist/summaryCollection.d.ts.map +1 -1
  82. package/dist/summaryCollection.js +31 -15
  83. package/dist/summaryCollection.js.map +1 -1
  84. package/dist/summaryFormat.d.ts +0 -5
  85. package/dist/summaryFormat.d.ts.map +1 -1
  86. package/dist/summaryFormat.js.map +1 -1
  87. package/dist/summaryGenerator.d.ts +1 -0
  88. package/dist/summaryGenerator.d.ts.map +1 -1
  89. package/dist/summaryGenerator.js +11 -9
  90. package/dist/summaryGenerator.js.map +1 -1
  91. package/dist/summaryManager.d.ts +2 -2
  92. package/dist/summaryManager.d.ts.map +1 -1
  93. package/dist/summaryManager.js +22 -7
  94. package/dist/summaryManager.js.map +1 -1
  95. package/lib/batchManager.d.ts +37 -0
  96. package/lib/batchManager.d.ts.map +1 -0
  97. package/lib/batchManager.js +69 -0
  98. package/lib/batchManager.js.map +1 -0
  99. package/lib/batchTracker.d.ts +1 -2
  100. package/lib/batchTracker.d.ts.map +1 -1
  101. package/lib/batchTracker.js +2 -3
  102. package/lib/batchTracker.js.map +1 -1
  103. package/lib/blobManager.d.ts +87 -25
  104. package/lib/blobManager.d.ts.map +1 -1
  105. package/lib/blobManager.js +319 -101
  106. package/lib/blobManager.js.map +1 -1
  107. package/lib/containerRuntime.d.ts +109 -124
  108. package/lib/containerRuntime.d.ts.map +1 -1
  109. package/lib/containerRuntime.js +355 -547
  110. package/lib/containerRuntime.js.map +1 -1
  111. package/lib/dataStore.js +29 -24
  112. package/lib/dataStore.js.map +1 -1
  113. package/lib/dataStoreContext.d.ts +20 -14
  114. package/lib/dataStoreContext.d.ts.map +1 -1
  115. package/lib/dataStoreContext.js +46 -55
  116. package/lib/dataStoreContext.js.map +1 -1
  117. package/lib/dataStores.d.ts +12 -5
  118. package/lib/dataStores.d.ts.map +1 -1
  119. package/lib/dataStores.js +21 -20
  120. package/lib/dataStores.js.map +1 -1
  121. package/lib/deltaScheduler.d.ts +6 -4
  122. package/lib/deltaScheduler.d.ts.map +1 -1
  123. package/lib/deltaScheduler.js +6 -4
  124. package/lib/deltaScheduler.js.map +1 -1
  125. package/lib/garbageCollection.d.ts +74 -14
  126. package/lib/garbageCollection.d.ts.map +1 -1
  127. package/lib/garbageCollection.js +238 -160
  128. package/lib/garbageCollection.js.map +1 -1
  129. package/lib/gcSweepReadyUsageDetection.d.ts +53 -0
  130. package/lib/gcSweepReadyUsageDetection.d.ts.map +1 -0
  131. package/lib/gcSweepReadyUsageDetection.js +121 -0
  132. package/lib/gcSweepReadyUsageDetection.js.map +1 -0
  133. package/lib/index.d.ts +2 -1
  134. package/lib/index.d.ts.map +1 -1
  135. package/lib/index.js +2 -1
  136. package/lib/index.js.map +1 -1
  137. package/lib/opProperties.d.ts +7 -0
  138. package/lib/opProperties.d.ts.map +1 -0
  139. package/lib/opProperties.js +16 -0
  140. package/lib/opProperties.js.map +1 -0
  141. package/lib/orderedClientElection.d.ts +28 -10
  142. package/lib/orderedClientElection.d.ts.map +1 -1
  143. package/lib/orderedClientElection.js +14 -4
  144. package/lib/orderedClientElection.js.map +1 -1
  145. package/lib/packageVersion.d.ts +1 -1
  146. package/lib/packageVersion.d.ts.map +1 -1
  147. package/lib/packageVersion.js +1 -1
  148. package/lib/packageVersion.js.map +1 -1
  149. package/lib/pendingStateManager.d.ts +0 -11
  150. package/lib/pendingStateManager.d.ts.map +1 -1
  151. package/lib/pendingStateManager.js +24 -46
  152. package/lib/pendingStateManager.js.map +1 -1
  153. package/lib/runningSummarizer.d.ts +14 -4
  154. package/lib/runningSummarizer.d.ts.map +1 -1
  155. package/lib/runningSummarizer.js +68 -26
  156. package/lib/runningSummarizer.js.map +1 -1
  157. package/lib/scheduleManager.d.ts +31 -0
  158. package/lib/scheduleManager.d.ts.map +1 -0
  159. package/lib/scheduleManager.js +239 -0
  160. package/lib/scheduleManager.js.map +1 -0
  161. package/lib/summarizer.d.ts +0 -2
  162. package/lib/summarizer.d.ts.map +1 -1
  163. package/lib/summarizer.js +1 -12
  164. package/lib/summarizer.js.map +1 -1
  165. package/lib/summarizerHeuristics.d.ts +26 -4
  166. package/lib/summarizerHeuristics.d.ts.map +1 -1
  167. package/lib/summarizerHeuristics.js +95 -18
  168. package/lib/summarizerHeuristics.js.map +1 -1
  169. package/lib/summarizerTypes.d.ts +45 -18
  170. package/lib/summarizerTypes.d.ts.map +1 -1
  171. package/lib/summarizerTypes.js +1 -1
  172. package/lib/summarizerTypes.js.map +1 -1
  173. package/lib/summaryCollection.d.ts +1 -0
  174. package/lib/summaryCollection.d.ts.map +1 -1
  175. package/lib/summaryCollection.js +31 -15
  176. package/lib/summaryCollection.js.map +1 -1
  177. package/lib/summaryFormat.d.ts +0 -5
  178. package/lib/summaryFormat.d.ts.map +1 -1
  179. package/lib/summaryFormat.js.map +1 -1
  180. package/lib/summaryGenerator.d.ts +1 -0
  181. package/lib/summaryGenerator.d.ts.map +1 -1
  182. package/lib/summaryGenerator.js +11 -9
  183. package/lib/summaryGenerator.js.map +1 -1
  184. package/lib/summaryManager.d.ts +2 -2
  185. package/lib/summaryManager.d.ts.map +1 -1
  186. package/lib/summaryManager.js +22 -7
  187. package/lib/summaryManager.js.map +1 -1
  188. package/package.json +65 -24
  189. package/src/batchManager.ts +91 -0
  190. package/src/batchTracker.ts +2 -3
  191. package/src/blobManager.ts +385 -118
  192. package/src/containerRuntime.ts +529 -740
  193. package/src/dataStore.ts +49 -37
  194. package/src/dataStoreContext.ts +44 -56
  195. package/src/dataStores.ts +34 -30
  196. package/src/deltaScheduler.ts +6 -4
  197. package/src/garbageCollection.ts +297 -206
  198. package/src/gcSweepReadyUsageDetection.ts +139 -0
  199. package/src/index.ts +1 -2
  200. package/src/opProperties.ts +19 -0
  201. package/src/orderedClientElection.ts +31 -10
  202. package/src/packageVersion.ts +1 -1
  203. package/src/pendingStateManager.ts +27 -59
  204. package/src/runningSummarizer.ts +75 -22
  205. package/src/scheduleManager.ts +314 -0
  206. package/src/summarizer.ts +1 -18
  207. package/src/summarizerHeuristics.ts +133 -19
  208. package/src/summarizerTypes.ts +53 -18
  209. package/src/summaryCollection.ts +33 -18
  210. package/src/summaryFormat.ts +0 -6
  211. package/src/summaryGenerator.ts +40 -22
  212. package/src/summaryManager.ts +22 -7
  213. package/dist/opTelemetry.d.ts +0 -22
  214. package/dist/opTelemetry.d.ts.map +0 -1
  215. package/dist/opTelemetry.js +0 -59
  216. package/dist/opTelemetry.js.map +0 -1
  217. package/lib/opTelemetry.d.ts +0 -22
  218. package/lib/opTelemetry.d.ts.map +0 -1
  219. package/lib/opTelemetry.js +0 -55
  220. package/lib/opTelemetry.js.map +0 -1
  221. package/src/opTelemetry.ts +0 -71
@@ -5,10 +5,12 @@
5
5
  */
6
6
  Object.defineProperty(exports, "__esModule", { value: true });
7
7
  exports.BlobManager = exports.BlobHandle = void 0;
8
+ const uuid_1 = require("uuid");
8
9
  const runtime_utils_1 = require("@fluidframework/runtime-utils");
9
10
  const common_utils_1 = require("@fluidframework/common-utils");
10
11
  const container_definitions_1 = require("@fluidframework/container-definitions");
11
12
  const telemetry_utils_1 = require("@fluidframework/telemetry-utils");
13
+ const throttler_1 = require("./throttler");
12
14
  /**
13
15
  * This class represents blob (long string)
14
16
  * This object is used only when creating (writing) new blob and serialization purposes.
@@ -36,33 +38,111 @@ class BlobHandle {
36
38
  }
37
39
  }
38
40
  exports.BlobHandle = BlobHandle;
41
+ class CancellableThrottler {
42
+ constructor(throttler) {
43
+ this.throttler = throttler;
44
+ this.cancelP = new common_utils_1.Deferred();
45
+ }
46
+ async getDelay() {
47
+ return Promise.race([
48
+ this.cancelP.promise,
49
+ new Promise((resolve) => setTimeout(resolve, this.throttler.getDelay())),
50
+ ]);
51
+ }
52
+ cancel() {
53
+ this.cancelP.resolve();
54
+ this.cancelP = new common_utils_1.Deferred();
55
+ }
56
+ }
57
+ // Note that while offline we "submit" an op before uploading the blob, but we always
58
+ // expect blobs to be uploaded before we actually see the op round-trip
59
+ var PendingBlobStatus;
60
+ (function (PendingBlobStatus) {
61
+ PendingBlobStatus[PendingBlobStatus["OnlinePendingUpload"] = 0] = "OnlinePendingUpload";
62
+ PendingBlobStatus[PendingBlobStatus["OnlinePendingOp"] = 1] = "OnlinePendingOp";
63
+ PendingBlobStatus[PendingBlobStatus["OfflinePendingUpload"] = 2] = "OfflinePendingUpload";
64
+ PendingBlobStatus[PendingBlobStatus["OfflinePendingOp"] = 3] = "OfflinePendingOp";
65
+ })(PendingBlobStatus || (PendingBlobStatus = {}));
39
66
  class BlobManager {
40
- constructor(routeContext, snapshot, getStorage, attachBlobCallback,
67
+ constructor(routeContext, snapshot, getStorage,
68
+ /**
69
+ * Submit a BlobAttach op. When a blob is uploaded, there is a short grace period before which
70
+ * the blob is deleted. The BlobAttach op notifies the server that blob is in use. The server
71
+ * will then not delete the blob as long as it is listed as referenced in future summaries.
72
+ * The summarizing client will know to include the storage ID in the summary when it sees the op.
73
+ *
74
+ * The op may also include a local ID to inform all clients of the relation to the storage
75
+ * ID, without knowledge of which they cannot request the blob from storage. This is also
76
+ * included in the redirect table in the summary.
77
+ */
78
+ sendBlobAttachOp,
41
79
  // To be called when a blob node is requested. blobPath is the path of the blob's node in GC's graph. It's
42
80
  // of the format `/<BlobManager.basePath>/<blobId>`.
43
- gcNodeUpdated, runtime, logger) {
81
+ gcNodeUpdated, runtime, stashedBlobs = {}) {
44
82
  this.routeContext = routeContext;
45
83
  this.getStorage = getStorage;
46
- this.attachBlobCallback = attachBlobCallback;
84
+ this.sendBlobAttachOp = sendBlobAttachOp;
47
85
  this.gcNodeUpdated = gcNodeUpdated;
48
86
  this.runtime = runtime;
49
- this.logger = logger;
50
- // uploaded blob IDs
51
- this.blobIds = new Set();
52
- // blobs for which upload is pending. maps to a promise that will resolve once the blob has been uploaded and a
53
- // BlobAttach op has round-tripped.
54
- this.pendingBlobIds = new Map();
55
- // blobs uploaded while detached; cleared upon attach
56
- this.detachedBlobIds = new Set();
57
- this.runtime.once("dispose", () => {
58
- for (const promise of this.pendingBlobIds.values()) {
59
- promise.reject(new Error("runtime disposed while blobAttach op in flight"));
60
- }
87
+ /**
88
+ * Blobs which have not been uploaded or for which we have not yet seen a BlobAttach op round-trip.
89
+ * Until we see the op round-trip, there is a possibility we may need to re-upload the blob, so
90
+ * we must save it. This is true for both the online and offline flow.
91
+ */
92
+ this.pendingBlobs = new Map();
93
+ /**
94
+ * Track ops in flight for online flow. Used to avoid searching pendingBlobs since BlobAttach ops
95
+ * don't include local ID in online flow.
96
+ */
97
+ this.opsInFlight = new Map();
98
+ this.retryThrottler = new CancellableThrottler(new throttler_1.Throttler(60 * 1000, // 60 sec delay window
99
+ 30 * 1000, // 30 sec max delay
100
+ // throttling function increases exponentially (0ms, 40ms, 80ms, 160ms, etc)
101
+ (0, throttler_1.formExponentialFn)({ coefficient: 20, initialDelay: 0 })));
102
+ this.logger = telemetry_utils_1.ChildLogger.create(this.runtime.logger, "BlobManager");
103
+ this.runtime.on("disconnected", () => this.onDisconnected());
104
+ this.redirectTable = this.load(snapshot);
105
+ // Begin uploading stashed blobs from previous container instance
106
+ Object.entries(stashedBlobs).forEach(([localId, entry]) => {
107
+ const blob = (0, common_utils_1.stringToBuffer)(entry.blob, "base64");
108
+ this.pendingBlobs.set(localId, {
109
+ blob,
110
+ status: PendingBlobStatus.OfflinePendingUpload,
111
+ handleP: new common_utils_1.Deferred(),
112
+ uploadP: this.uploadBlob(localId, blob),
113
+ });
61
114
  });
62
- this.load(snapshot);
63
115
  }
64
- hasBlob(id) {
65
- return this.blobIds.has(id) || this.detachedBlobIds.has(id);
116
+ get pendingOfflineUploads() {
117
+ return Array.from(this.pendingBlobs.values())
118
+ .filter((e) => e.status === PendingBlobStatus.OfflinePendingUpload);
119
+ }
120
+ get hasPendingOfflineUploads() {
121
+ return this.pendingOfflineUploads.length > 0;
122
+ }
123
+ /**
124
+ * Upload blobs added while offline. This must be completed before connecting and resubmitting ops.
125
+ */
126
+ async onConnected() {
127
+ this.retryThrottler.cancel();
128
+ const pendingUploads = this.pendingOfflineUploads.map(async (e) => e.uploadP);
129
+ await telemetry_utils_1.PerformanceEvent.timedExecAsync(this.logger, {
130
+ eventName: "BlobUploadOnConnected",
131
+ count: pendingUploads.length,
132
+ }, async () => Promise.all(pendingUploads), { start: true, end: true });
133
+ }
134
+ /**
135
+ * Transition online blobs waiting for BlobAttach op round-trip since we will not see the op until we are connected
136
+ * again
137
+ */
138
+ onDisconnected() {
139
+ for (const [localId, entry] of this.pendingBlobs) {
140
+ if (entry.status === PendingBlobStatus.OnlinePendingOp) {
141
+ // This will submit another BlobAttach op for this blob. This is necessary because the one we sent
142
+ // already didn't have the local ID.
143
+ this.transitionToOffline(localId);
144
+ }
145
+ }
66
146
  }
67
147
  /**
68
148
  * For a blobId, returns its path in GC's graph. The node path is of the format `/<BlobManager.basePath>/<blobId>`
@@ -72,61 +152,200 @@ class BlobManager {
72
152
  getBlobGCNodePath(blobId) {
73
153
  return `/${BlobManager.basePath}/${blobId}`;
74
154
  }
155
+ /**
156
+ * Set of actual storage IDs (i.e., IDs that can be requested from storage). This will be empty if the container is
157
+ * detached or there are no (non-pending) attachment blobs in the document
158
+ */
159
+ get storageIds() {
160
+ const ids = new Set(this.redirectTable.values());
161
+ // If we are detached, we will not have storage IDs, only undefined
162
+ const undefinedValueInTable = ids.delete(undefined);
163
+ // For a detached container, entries are inserted into the redirect table with an undefined storage ID.
164
+ // For an attached container, entries are inserted w/storage ID after the BlobAttach op round-trips.
165
+ (0, common_utils_1.assert)(!undefinedValueInTable || this.runtime.attachState === container_definitions_1.AttachState.Detached && ids.size === 0, 0x382 /* 'redirectTable' must contain only undefined while detached / defined values while attached */);
166
+ return ids;
167
+ }
75
168
  async getBlob(blobId) {
76
- var _a, _b;
77
- const storageId = (_b = (_a = this.redirectTable) === null || _a === void 0 ? void 0 : _a.get(blobId)) !== null && _b !== void 0 ? _b : blobId;
78
- (0, common_utils_1.assert)(this.hasBlob(storageId), 0x11f /* "requesting unknown blobs" */);
79
- // When this blob is retrieved, let the container runtime know that the corresponding GC node got updated.
169
+ const pending = this.pendingBlobs.get(blobId);
170
+ if (pending) {
171
+ return pending.blob;
172
+ }
173
+ let storageId;
174
+ if (this.runtime.attachState === container_definitions_1.AttachState.Detached) {
175
+ (0, common_utils_1.assert)(this.redirectTable.has(blobId), 0x383 /* requesting unknown blobs */);
176
+ // Blobs created while the container is detached are stored in IDetachedBlobStorage.
177
+ // The 'IDocumentStorageService.readBlob()' call below will retrieve these via localId.
178
+ storageId = blobId;
179
+ }
180
+ else {
181
+ storageId = this.redirectTable.get(blobId);
182
+ (0, common_utils_1.assert)(!!storageId, 0x11f /* "requesting unknown blobs" */);
183
+ }
184
+ // When a GC-able (not pending) blob is retrieved, let runtime know that the corresponding GC node got updated.
80
185
  this.gcNodeUpdated(this.getBlobGCNodePath(blobId));
81
- return new BlobHandle(`${BlobManager.basePath}/${storageId}`, this.routeContext, async () => telemetry_utils_1.PerformanceEvent.timedExecAsync(this.logger, { eventName: "AttachmentReadBlob", id: storageId }, async () => {
186
+ return telemetry_utils_1.PerformanceEvent.timedExecAsync(this.logger, { eventName: "AttachmentReadBlob", id: storageId }, async () => {
82
187
  return this.getStorage().readBlob(storageId);
83
- }, { end: true, cancel: "error" }));
188
+ }, { end: true, cancel: "error" });
189
+ }
190
+ getBlobHandle(id) {
191
+ (0, common_utils_1.assert)(this.redirectTable.has(id) || this.pendingBlobs.has(id), 0x384 /* requesting handle for unknown blob */);
192
+ return new BlobHandle(`${BlobManager.basePath}/${id}`, this.routeContext, async () => this.getBlob(id));
193
+ }
194
+ async createBlobDetached(blob) {
195
+ // Blobs created while the container is detached are stored in IDetachedBlobStorage.
196
+ // The 'IDocumentStorageService.createBlob()' call below will respond with a localId.
197
+ const response = await this.getStorage().createBlob(blob);
198
+ this.redirectTable.set(response.id, undefined);
199
+ return this.getBlobHandle(response.id);
84
200
  }
85
201
  async createBlob(blob) {
86
- var _a, _b;
202
+ if (this.runtime.attachState === container_definitions_1.AttachState.Detached) {
203
+ return this.createBlobDetached(blob);
204
+ }
87
205
  if (this.runtime.attachState === container_definitions_1.AttachState.Attaching) {
88
206
  // blob upload is not supported in "Attaching" state
89
207
  this.logger.sendTelemetryEvent({ eventName: "CreateBlobWhileAttaching" });
90
208
  await new Promise((resolve) => this.runtime.once("attached", resolve));
91
209
  }
92
- if (!this.runtime.connected && this.runtime.attachState === container_definitions_1.AttachState.Attached) {
93
- // see https://github.com/microsoft/FluidFramework/issues/8246
94
- // Avoid getting storage if we are offline since it might be undefined. In the future we will return
95
- // handles immediately while offline
96
- await new Promise((resolve) => this.runtime.once("connected", resolve));
97
- }
98
- const response = await telemetry_utils_1.PerformanceEvent.timedExecAsync(this.logger, { eventName: "createBlob" }, async () => this.getStorage().createBlob(blob), { end: true, cancel: "error" });
99
- const handle = new BlobHandle(`${BlobManager.basePath}/${response.id}`, this.routeContext,
100
- // get() should go through BlobManager.getBlob() so handles created while detached can be redirected
101
- // to the correct storage id after they are uploaded
102
- async () => this.getBlob(response.id).then(async (h) => h.get()));
103
- if (this.runtime.attachState === container_definitions_1.AttachState.Detached) {
104
- this.detachedBlobIds.add(response.id);
105
- return handle;
210
+ (0, common_utils_1.assert)(this.runtime.attachState === container_definitions_1.AttachState.Attached, 0x385 /* For clarity and paranoid defense against adding future attachment states */);
211
+ // Create a local ID for each blob. This is used to support blobs if/when the client goes
212
+ // offline since we don't have the ID from storage yet. If online flow succeeds this won't be used.
213
+ const localId = (0, uuid_1.v4)();
214
+ const pendingEntry = {
215
+ blob,
216
+ status: PendingBlobStatus.OnlinePendingUpload,
217
+ handleP: new common_utils_1.Deferred(),
218
+ uploadP: this.uploadBlob(localId, blob),
219
+ };
220
+ this.pendingBlobs.set(localId, pendingEntry);
221
+ return pendingEntry.handleP.promise;
222
+ }
223
+ async uploadBlob(localId, blob) {
224
+ return telemetry_utils_1.PerformanceEvent.timedExecAsync(this.logger, { eventName: "createBlob" }, async () => this.getStorage().createBlob(blob), { end: true, cancel: this.runtime.connected ? "error" : "generic" }).then((response) => this.onUploadResolve(localId, response), async (err) => this.onUploadReject(localId, err));
225
+ }
226
+ onUploadResolve(localId, response) {
227
+ var _a;
228
+ const entry = this.pendingBlobs.get(localId);
229
+ (0, common_utils_1.assert)((entry === null || entry === void 0 ? void 0 : entry.status) === PendingBlobStatus.OnlinePendingUpload ||
230
+ (entry === null || entry === void 0 ? void 0 : entry.status) === PendingBlobStatus.OfflinePendingUpload, 0x386 /* Must have pending blob entry for uploaded blob */);
231
+ entry.storageId = response.id;
232
+ if (this.runtime.connected) {
233
+ if (entry.status === PendingBlobStatus.OnlinePendingUpload) {
234
+ if (this.storageIds.has(response.id)) {
235
+ // Storage may dedupe blobs and give us an ID we already know
236
+ // no need to submit BlobAttach op in this case
237
+ entry.handleP.resolve(this.getBlobHandle(response.id));
238
+ this.pendingBlobs.delete(localId);
239
+ }
240
+ else {
241
+ // Check for still-pending duplicates too; if an op is already in flight we can wait for that one
242
+ if (!this.opsInFlight.has(response.id)) {
243
+ this.sendBlobAttachOp(response.id);
244
+ }
245
+ this.opsInFlight.set(response.id, ((_a = this.opsInFlight.get(response.id)) !== null && _a !== void 0 ? _a : []).concat(localId));
246
+ entry.status = PendingBlobStatus.OnlinePendingOp;
247
+ }
248
+ }
249
+ else if (entry.status === PendingBlobStatus.OfflinePendingUpload) {
250
+ // We already submitted a BlobAttach op for this blob when it was transitioned to offline flow
251
+ entry.status = PendingBlobStatus.OfflinePendingOp;
252
+ }
106
253
  }
107
- // Note - server will de-dup blobs, so we might get existing blobId!
108
- if (this.pendingBlobIds.has(response.id)) {
109
- await ((_a = this.pendingBlobIds.get(response.id)) === null || _a === void 0 ? void 0 : _a.promise);
254
+ else {
255
+ // connected to storage but not ordering service?
256
+ this.logger.sendTelemetryEvent({ eventName: "BlobUploadSuccessWhileDisconnected" });
257
+ if (entry.status === PendingBlobStatus.OnlinePendingUpload) {
258
+ this.transitionToOffline(localId);
259
+ }
260
+ entry.status = PendingBlobStatus.OfflinePendingOp;
110
261
  }
111
- else if (!this.blobIds.has(response.id)) {
112
- this.pendingBlobIds.set(response.id, new common_utils_1.Deferred());
113
- // send blob attach op and wait until we see it to return the handle
114
- this.attachBlobCallback(response.id);
115
- await ((_b = this.pendingBlobIds.get(response.id)) === null || _b === void 0 ? void 0 : _b.promise);
262
+ return response;
263
+ }
264
+ async onUploadReject(localId, error) {
265
+ const entry = this.pendingBlobs.get(localId);
266
+ (0, common_utils_1.assert)(!!entry, 0x387 /* Must have pending blob entry for blob which failed to upload */);
267
+ if (!this.runtime.connected) {
268
+ if (entry.status === PendingBlobStatus.OnlinePendingUpload) {
269
+ this.transitionToOffline(localId);
270
+ }
271
+ // we are probably not connected to storage but start another upload request in case we are
272
+ entry.uploadP = this.retryThrottler.getDelay().then(async () => this.uploadBlob(localId, entry.blob));
273
+ return entry.uploadP;
116
274
  }
117
- return handle;
275
+ else {
276
+ entry.handleP.reject(error);
277
+ throw error;
278
+ }
279
+ }
280
+ transitionToOffline(localId) {
281
+ (0, common_utils_1.assert)(!this.runtime.connected, 0x388 /* Must only transition to offline flow while runtime is disconnected */);
282
+ const entry = this.pendingBlobs.get(localId);
283
+ (0, common_utils_1.assert)(!!entry, 0x389 /* No pending blob entry */);
284
+ (0, common_utils_1.assert)([PendingBlobStatus.OnlinePendingUpload, PendingBlobStatus.OnlinePendingOp].includes(entry.status), 0x38a /* Blob must be in online flow to transition to offline flow */);
285
+ entry.status = entry.status === PendingBlobStatus.OnlinePendingUpload
286
+ ? PendingBlobStatus.OfflinePendingUpload
287
+ : PendingBlobStatus.OfflinePendingOp;
288
+ // Submit a BlobAttach op. It's important we submit this op now before returning the blob handle so the
289
+ // BlobAttach op is sequenced prior to any ops referencing the handle. Otherwise an invalid handle could be
290
+ // added to the document if the ops are not all successfully submitted upon reconnection.
291
+ // storageId may be undefined but since we are not connected we will have a chance to add it when reSubmit()
292
+ // is called
293
+ this.sendBlobAttachOp(entry.storageId, localId);
294
+ entry.handleP.resolve(this.getBlobHandle(localId));
295
+ }
296
+ /**
297
+ * Resubmit a BlobAttach op. Used to add storage IDs to ops that were
298
+ * submitted to runtime while disconnected.
299
+ * @param metadata - op metadata containing storage and/or local IDs
300
+ */
301
+ reSubmit(metadata) {
302
+ (0, common_utils_1.assert)(!!metadata, 0x38b /* Resubmitted ops must have metadata */);
303
+ const { blobId, localId } = metadata;
304
+ if (!blobId) {
305
+ (0, common_utils_1.assert)(!!localId, 0x38c /* Submitted BlobAttach ops must have a blobId or localId */);
306
+ // We submitted this op while offline. The blob should have been uploaded by now.
307
+ const pendingEntry = this.pendingBlobs.get(localId);
308
+ (0, common_utils_1.assert)((pendingEntry === null || pendingEntry === void 0 ? void 0 : pendingEntry.status) === PendingBlobStatus.OfflinePendingOp &&
309
+ !!(pendingEntry === null || pendingEntry === void 0 ? void 0 : pendingEntry.storageId), 0x38d /* blob must be uploaded before resubmitting BlobAttach op */);
310
+ return this.sendBlobAttachOp(pendingEntry.storageId, localId);
311
+ }
312
+ return this.sendBlobAttachOp(blobId, localId);
118
313
  }
119
- processBlobAttachOp(blobId, local) {
314
+ processBlobAttachOp(message, local) {
315
+ var _a, _b;
316
+ (0, common_utils_1.assert)((_a = message === null || message === void 0 ? void 0 : message.metadata) === null || _a === void 0 ? void 0 : _a.blobId, 0x12a /* "Missing blob id on metadata" */);
317
+ if (message.metadata.localId !== undefined) {
318
+ this.redirectTable.set(message.metadata.localId, message.metadata.blobId);
319
+ }
320
+ // set identity (id -> id) entry
321
+ this.redirectTable.set(message.metadata.blobId, message.metadata.blobId);
120
322
  if (local) {
121
- const pendingBlobP = this.pendingBlobIds.get(blobId);
122
- (0, common_utils_1.assert)(pendingBlobP !== undefined, 0x1f8 /* "local BlobAttach op with no pending blob" */);
123
- pendingBlobP.resolve();
124
- this.pendingBlobIds.delete(blobId);
323
+ if (message.metadata.localId === undefined) {
324
+ // Since there is no local ID, we know this op was submitted while online.
325
+ const waitingBlobs = this.opsInFlight.get(message.metadata.blobId);
326
+ (0, common_utils_1.assert)(!!waitingBlobs, 0x38e /* local online BlobAttach op with no pending blob */);
327
+ waitingBlobs.forEach((localId) => {
328
+ const pendingBlobEntry = this.pendingBlobs.get(localId);
329
+ (0, common_utils_1.assert)(pendingBlobEntry !== undefined, 0x38f);
330
+ // It's possible we transitioned to offline flow while waiting for this op.
331
+ if (pendingBlobEntry.status === PendingBlobStatus.OnlinePendingOp) {
332
+ pendingBlobEntry.handleP.resolve(this.getBlobHandle(message.metadata.blobId));
333
+ this.pendingBlobs.delete(localId);
334
+ }
335
+ });
336
+ }
337
+ else {
338
+ // Each local ID is unique; get the pending blob entry and delete it
339
+ (0, common_utils_1.assert)(((_b = this.pendingBlobs.get(message.metadata.localId)) === null || _b === void 0 ? void 0 : _b.status) === PendingBlobStatus.OfflinePendingOp, 0x1f8 /* "local BlobAttach op with no pending blob" */);
340
+ this.pendingBlobs.delete(message.metadata.localId);
341
+ }
125
342
  }
126
- this.blobIds.add(blobId);
127
343
  }
128
344
  /**
129
345
  * Reads blobs needed to load BlobManager from storage.
346
+ * @param blobsTree - Tree containing IDs of previously attached blobs. We
347
+ * look for the IDs in the blob entries of the tree since the both the r11s
348
+ * and SPO drivers replace the attachment types returned in snapshot() with blobs.
130
349
  */
131
350
  static async load(blobsTree, tryFetchBlob) {
132
351
  if (!blobsTree) {
@@ -142,33 +361,23 @@ class BlobManager {
142
361
  return { ids, redirectTable };
143
362
  }
144
363
  /**
145
- * Load a set of previously attached blob IDs from a previous snapshot. Note
146
- * that BlobManager tracking and reporting attached blobs is a temporary
147
- * solution since storage expects attached blobs to be reported and any that
148
- * are not reported as attached may be GCed. In the future attached blob
149
- * IDs will be collected at summarization time, and runtime will not care
150
- * about the existence or specific formatting of this tree in returned
151
- * snapshots.
152
- *
153
- * @param blobsTree - Tree containing IDs of previously attached blobs. This
154
- * corresponds to snapshot() below. We look for the IDs in the blob entries
155
- * of the tree since the both the r11s and SPO drivers replace the
156
- * attachment types returned in snapshot() with blobs.
364
+ * Load a set of previously attached blob IDs and redirect table from a previous snapshot.
157
365
  */
158
366
  load(snapshot) {
159
367
  var _a, _b, _c;
160
- if (snapshot.ids) {
161
- const detached = this.runtime.attachState === container_definitions_1.AttachState.Detached;
162
- snapshot.ids.map((entry) => detached ? this.detachedBlobIds.add(entry) : this.blobIds.add(entry));
163
- }
164
- if (snapshot.redirectTable) {
165
- this.redirectTable = new Map(snapshot.redirectTable);
166
- }
167
368
  this.logger.sendTelemetryEvent({
168
369
  eventName: "AttachmentBlobsLoaded",
169
370
  count: (_b = (_a = snapshot.ids) === null || _a === void 0 ? void 0 : _a.length) !== null && _b !== void 0 ? _b : 0,
170
371
  redirectTable: (_c = snapshot.redirectTable) === null || _c === void 0 ? void 0 : _c.length,
171
372
  });
373
+ const table = new Map(snapshot.redirectTable);
374
+ if (snapshot.ids) {
375
+ const detached = this.runtime.attachState === container_definitions_1.AttachState.Detached;
376
+ // If we are detached, we don't have storage IDs yet, so set to undefined
377
+ // Otherwise, set identity (id -> id) entries
378
+ snapshot.ids.forEach((entry) => table.set(entry, detached ? undefined : entry));
379
+ }
380
+ return table;
172
381
  }
173
382
  /**
174
383
  * Generates data used for garbage collection. Each blob uploaded represents a node in the GC graph as it can be
@@ -178,22 +387,23 @@ class BlobManager {
178
387
  */
179
388
  getGCData(fullGC = false) {
180
389
  const gcData = { gcNodes: {} };
181
- this.blobIds.forEach((blobId) => {
390
+ /**
391
+ * The node path is of the format `/_blobs/blobId`. This path must match the path of the blob handle returned
392
+ * by the createBlob API because blobs are marked referenced by storing these handles in a referenced DDS.
393
+ */
394
+ this.storageIds.forEach((blobId) => {
182
395
  gcData.gcNodes[this.getBlobGCNodePath(blobId)] = [];
183
396
  });
184
- /**
185
- * For all blobs in the redirect table, the handle returned on creation is based off of the localId. So, these
186
- * nodes can be referenced by storing the localId handle. When that happens, the corresponding storageId node
187
- * must also be marked referenced. So, we add a route from the localId node to the storageId node.
188
- * Note that because of de-duping, there can be multiple localIds that all redirect to the same storageId or
189
- * a blob may be referenced via its storageId handle.
190
- */
191
- if (this.redirectTable !== undefined) {
192
- for (const [localId, storageId] of this.redirectTable) {
193
- // Add node for the localId and add a route to the storageId node. The storageId node will have been
194
- // added above when adding nodes for this.blobIds.
195
- gcData.gcNodes[this.getBlobGCNodePath(localId)] = [this.getBlobGCNodePath(storageId)];
196
- }
397
+ // For some blobs, the handle returned on creation is based off of the localId. So, these
398
+ // nodes can be referenced by storing the localId handle. When that happens, the corresponding storageId node
399
+ // must also be marked referenced. So, we add a route from the localId node to the storageId node.
400
+ // Note that because of de-duping, there can be multiple localIds that all redirect to the same storageId or
401
+ // a blob may be referenced via its storageId handle.
402
+ for (const [localId, storageId] of this.redirectTable) {
403
+ (0, common_utils_1.assert)(!!storageId, 0x390 /* Must be attached to get GC data */);
404
+ // Add node for the localId and add a route to the storageId node. The storageId node will have been
405
+ // added above when adding nodes for this.blobIds.
406
+ gcData.gcNodes[this.getBlobGCNodePath(localId)] = [this.getBlobGCNodePath(storageId)];
197
407
  }
198
408
  return gcData;
199
409
  }
@@ -215,32 +425,40 @@ class BlobManager {
215
425
  this.redirectTable.delete(blobId);
216
426
  continue;
217
427
  }
218
- this.blobIds.delete(blobId);
219
428
  }
220
429
  }
221
430
  summarize(telemetryContext) {
222
- // If we have a redirect table it means the container is about to transition to "Attaching" state, so we need
223
- // to return an actual snapshot containing all the real storage IDs we know about.
224
- const attachingOrAttached = !!this.redirectTable || this.runtime.attachState !== container_definitions_1.AttachState.Detached;
225
- const blobIds = attachingOrAttached ? this.blobIds : this.detachedBlobIds;
431
+ // if storageIds is empty, it means we are detached and have only local IDs, or that there are no blobs attached
432
+ const blobIds = this.storageIds.size > 0 ? Array.from(this.storageIds) : Array.from(this.redirectTable.keys());
226
433
  const builder = new runtime_utils_1.SummaryTreeBuilder();
227
434
  blobIds.forEach((blobId) => {
228
435
  builder.addAttachment(blobId);
229
436
  });
230
- if (this.redirectTable && this.redirectTable.size > 0) {
231
- builder.addBlob(BlobManager.redirectTableBlobName, JSON.stringify(Array.from(this.redirectTable.entries())));
437
+ // Any non-identity entries in the table need to be saved in the summary
438
+ if (this.redirectTable.size > blobIds.length) {
439
+ builder.addBlob(BlobManager.redirectTableBlobName,
440
+ // filter out identity entries
441
+ JSON.stringify(Array.from(this.redirectTable.entries())
442
+ .filter(([localId, storageId]) => localId !== storageId)));
232
443
  }
233
444
  return builder.getSummaryTree();
234
445
  }
235
446
  setRedirectTable(table) {
236
447
  (0, common_utils_1.assert)(this.runtime.attachState === container_definitions_1.AttachState.Detached, 0x252 /* "redirect table can only be set in detached container" */);
237
- (0, common_utils_1.assert)(!this.redirectTable, 0x253 /* "redirect table already exists" */);
448
+ (0, common_utils_1.assert)(this.redirectTable.size === table.size, 0x391 /* Redirect table size must match BlobManager's local ID count */);
238
449
  for (const [localId, storageId] of table) {
239
- (0, common_utils_1.assert)(this.detachedBlobIds.delete(localId), 0x254 /* "unrecognized id in redirect table" */);
240
- this.blobIds.add(storageId);
450
+ (0, common_utils_1.assert)(this.redirectTable.has(localId), 0x254 /* "unrecognized id in redirect table" */);
451
+ this.redirectTable.set(localId, storageId);
452
+ // set identity (id -> id) entry
453
+ this.redirectTable.set(storageId, storageId);
454
+ }
455
+ }
456
+ getPendingBlobs() {
457
+ const blobs = {};
458
+ for (const [key, entry] of this.pendingBlobs) {
459
+ blobs[key] = { blob: (0, common_utils_1.bufferToString)(entry.blob, "base64") };
241
460
  }
242
- (0, common_utils_1.assert)(this.detachedBlobIds.size === 0, 0x255 /* "detached blob id absent in redirect table" */);
243
- this.redirectTable = table;
461
+ return blobs;
244
462
  }
245
463
  }
246
464
  exports.BlobManager = BlobManager;