@fluidframework/container-runtime 2.0.0-internal.3.0.0 → 2.0.0-internal.3.1.0

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 (327) hide show
  1. package/.eslintrc.js +19 -19
  2. package/.mocharc.js +2 -2
  3. package/api-extractor.json +2 -2
  4. package/dist/batchTracker.d.ts.map +1 -1
  5. package/dist/batchTracker.js +2 -1
  6. package/dist/batchTracker.js.map +1 -1
  7. package/dist/blobManager.d.ts +9 -2
  8. package/dist/blobManager.d.ts.map +1 -1
  9. package/dist/blobManager.js +80 -33
  10. package/dist/blobManager.js.map +1 -1
  11. package/dist/connectionTelemetry.d.ts.map +1 -1
  12. package/dist/connectionTelemetry.js +11 -9
  13. package/dist/connectionTelemetry.js.map +1 -1
  14. package/dist/containerHandleContext.d.ts.map +1 -1
  15. package/dist/containerHandleContext.js +3 -1
  16. package/dist/containerHandleContext.js.map +1 -1
  17. package/dist/containerRuntime.d.ts +10 -0
  18. package/dist/containerRuntime.d.ts.map +1 -1
  19. package/dist/containerRuntime.js +140 -72
  20. package/dist/containerRuntime.js.map +1 -1
  21. package/dist/dataStore.d.ts.map +1 -1
  22. package/dist/dataStore.js +11 -9
  23. package/dist/dataStore.js.map +1 -1
  24. package/dist/dataStoreContext.d.ts +18 -1
  25. package/dist/dataStoreContext.d.ts.map +1 -1
  26. package/dist/dataStoreContext.js +66 -15
  27. package/dist/dataStoreContext.js.map +1 -1
  28. package/dist/dataStoreContexts.d.ts.map +1 -1
  29. package/dist/dataStoreContexts.js +7 -3
  30. package/dist/dataStoreContexts.js.map +1 -1
  31. package/dist/dataStoreRegistry.d.ts.map +1 -1
  32. package/dist/dataStoreRegistry.js +3 -1
  33. package/dist/dataStoreRegistry.js.map +1 -1
  34. package/dist/dataStores.d.ts +26 -1
  35. package/dist/dataStores.d.ts.map +1 -1
  36. package/dist/dataStores.js +103 -18
  37. package/dist/dataStores.js.map +1 -1
  38. package/dist/deltaScheduler.d.ts.map +1 -1
  39. package/dist/deltaScheduler.js +8 -3
  40. package/dist/deltaScheduler.js.map +1 -1
  41. package/dist/garbageCollection.d.ts +34 -14
  42. package/dist/garbageCollection.d.ts.map +1 -1
  43. package/dist/garbageCollection.js +188 -93
  44. package/dist/garbageCollection.js.map +1 -1
  45. package/dist/garbageCollectionConstants.d.ts +3 -0
  46. package/dist/garbageCollectionConstants.d.ts.map +1 -1
  47. package/dist/garbageCollectionConstants.js +6 -1
  48. package/dist/garbageCollectionConstants.js.map +1 -1
  49. package/dist/garbageCollectionHelpers.d.ts +26 -0
  50. package/dist/garbageCollectionHelpers.d.ts.map +1 -0
  51. package/dist/garbageCollectionHelpers.js +45 -0
  52. package/dist/garbageCollectionHelpers.js.map +1 -0
  53. package/dist/gcSweepReadyUsageDetection.d.ts +5 -5
  54. package/dist/gcSweepReadyUsageDetection.d.ts.map +1 -1
  55. package/dist/gcSweepReadyUsageDetection.js +14 -10
  56. package/dist/gcSweepReadyUsageDetection.js.map +1 -1
  57. package/dist/index.d.ts +2 -2
  58. package/dist/index.d.ts.map +1 -1
  59. package/dist/index.js.map +1 -1
  60. package/dist/opLifecycle/batchManager.d.ts +5 -5
  61. package/dist/opLifecycle/batchManager.d.ts.map +1 -1
  62. package/dist/opLifecycle/batchManager.js +19 -12
  63. package/dist/opLifecycle/batchManager.js.map +1 -1
  64. package/dist/opLifecycle/definitions.d.ts.map +1 -1
  65. package/dist/opLifecycle/definitions.js.map +1 -1
  66. package/dist/opLifecycle/index.d.ts.map +1 -1
  67. package/dist/opLifecycle/index.js.map +1 -1
  68. package/dist/opLifecycle/opCompressor.d.ts.map +1 -1
  69. package/dist/opLifecycle/opCompressor.js.map +1 -1
  70. package/dist/opLifecycle/opDecompressor.d.ts.map +1 -1
  71. package/dist/opLifecycle/opDecompressor.js +5 -2
  72. package/dist/opLifecycle/opDecompressor.js.map +1 -1
  73. package/dist/opLifecycle/opSplitter.d.ts.map +1 -1
  74. package/dist/opLifecycle/opSplitter.js +4 -1
  75. package/dist/opLifecycle/opSplitter.js.map +1 -1
  76. package/dist/opLifecycle/outbox.d.ts.map +1 -1
  77. package/dist/opLifecycle/outbox.js +19 -17
  78. package/dist/opLifecycle/outbox.js.map +1 -1
  79. package/dist/opLifecycle/remoteMessageProcessor.d.ts.map +1 -1
  80. package/dist/opLifecycle/remoteMessageProcessor.js.map +1 -1
  81. package/dist/opProperties.d.ts.map +1 -1
  82. package/dist/opProperties.js +1 -3
  83. package/dist/opProperties.js.map +1 -1
  84. package/dist/orderedClientElection.d.ts.map +1 -1
  85. package/dist/orderedClientElection.js +10 -4
  86. package/dist/orderedClientElection.js.map +1 -1
  87. package/dist/packageVersion.d.ts +1 -1
  88. package/dist/packageVersion.js +1 -1
  89. package/dist/packageVersion.js.map +1 -1
  90. package/dist/pendingStateManager.d.ts +7 -0
  91. package/dist/pendingStateManager.d.ts.map +1 -1
  92. package/dist/pendingStateManager.js +7 -4
  93. package/dist/pendingStateManager.js.map +1 -1
  94. package/dist/runWhileConnectedCoordinator.d.ts.map +1 -1
  95. package/dist/runWhileConnectedCoordinator.js.map +1 -1
  96. package/dist/runningSummarizer.d.ts.map +1 -1
  97. package/dist/runningSummarizer.js +34 -21
  98. package/dist/runningSummarizer.js.map +1 -1
  99. package/dist/scheduleManager.d.ts.map +1 -1
  100. package/dist/scheduleManager.js +3 -2
  101. package/dist/scheduleManager.js.map +1 -1
  102. package/dist/serializedSnapshotStorage.d.ts +2 -2
  103. package/dist/serializedSnapshotStorage.d.ts.map +1 -1
  104. package/dist/serializedSnapshotStorage.js +5 -3
  105. package/dist/serializedSnapshotStorage.js.map +1 -1
  106. package/dist/summarizer.d.ts +2 -2
  107. package/dist/summarizer.d.ts.map +1 -1
  108. package/dist/summarizer.js +37 -17
  109. package/dist/summarizer.js.map +1 -1
  110. package/dist/summarizerClientElection.d.ts.map +1 -1
  111. package/dist/summarizerClientElection.js.map +1 -1
  112. package/dist/summarizerHandle.d.ts.map +1 -1
  113. package/dist/summarizerHandle.js.map +1 -1
  114. package/dist/summarizerHeuristics.d.ts.map +1 -1
  115. package/dist/summarizerHeuristics.js +6 -9
  116. package/dist/summarizerHeuristics.js.map +1 -1
  117. package/dist/summarizerTypes.d.ts +21 -21
  118. package/dist/summarizerTypes.d.ts.map +1 -1
  119. package/dist/summarizerTypes.js.map +1 -1
  120. package/dist/summaryCollection.d.ts.map +1 -1
  121. package/dist/summaryCollection.js +18 -8
  122. package/dist/summaryCollection.js.map +1 -1
  123. package/dist/summaryFormat.d.ts +22 -0
  124. package/dist/summaryFormat.d.ts.map +1 -1
  125. package/dist/summaryFormat.js +18 -10
  126. package/dist/summaryFormat.js.map +1 -1
  127. package/dist/summaryGenerator.d.ts.map +1 -1
  128. package/dist/summaryGenerator.js +34 -15
  129. package/dist/summaryGenerator.js.map +1 -1
  130. package/dist/summaryManager.d.ts.map +1 -1
  131. package/dist/summaryManager.js +21 -9
  132. package/dist/summaryManager.js.map +1 -1
  133. package/dist/throttler.d.ts +2 -2
  134. package/dist/throttler.d.ts.map +1 -1
  135. package/dist/throttler.js +4 -4
  136. package/dist/throttler.js.map +1 -1
  137. package/garbageCollection.md +15 -2
  138. package/lib/batchTracker.d.ts.map +1 -1
  139. package/lib/batchTracker.js +2 -1
  140. package/lib/batchTracker.js.map +1 -1
  141. package/lib/blobManager.d.ts +9 -2
  142. package/lib/blobManager.d.ts.map +1 -1
  143. package/lib/blobManager.js +82 -35
  144. package/lib/blobManager.js.map +1 -1
  145. package/lib/connectionTelemetry.d.ts.map +1 -1
  146. package/lib/connectionTelemetry.js +11 -9
  147. package/lib/connectionTelemetry.js.map +1 -1
  148. package/lib/containerHandleContext.d.ts.map +1 -1
  149. package/lib/containerHandleContext.js +3 -1
  150. package/lib/containerHandleContext.js.map +1 -1
  151. package/lib/containerRuntime.d.ts +10 -0
  152. package/lib/containerRuntime.d.ts.map +1 -1
  153. package/lib/containerRuntime.js +146 -78
  154. package/lib/containerRuntime.js.map +1 -1
  155. package/lib/dataStore.d.ts.map +1 -1
  156. package/lib/dataStore.js +11 -9
  157. package/lib/dataStore.js.map +1 -1
  158. package/lib/dataStoreContext.d.ts +18 -1
  159. package/lib/dataStoreContext.d.ts.map +1 -1
  160. package/lib/dataStoreContext.js +68 -17
  161. package/lib/dataStoreContext.js.map +1 -1
  162. package/lib/dataStoreContexts.d.ts.map +1 -1
  163. package/lib/dataStoreContexts.js +7 -3
  164. package/lib/dataStoreContexts.js.map +1 -1
  165. package/lib/dataStoreRegistry.d.ts.map +1 -1
  166. package/lib/dataStoreRegistry.js +3 -1
  167. package/lib/dataStoreRegistry.js.map +1 -1
  168. package/lib/dataStores.d.ts +26 -1
  169. package/lib/dataStores.d.ts.map +1 -1
  170. package/lib/dataStores.js +109 -24
  171. package/lib/dataStores.js.map +1 -1
  172. package/lib/deltaScheduler.d.ts.map +1 -1
  173. package/lib/deltaScheduler.js +9 -4
  174. package/lib/deltaScheduler.js.map +1 -1
  175. package/lib/garbageCollection.d.ts +34 -14
  176. package/lib/garbageCollection.d.ts.map +1 -1
  177. package/lib/garbageCollection.js +190 -95
  178. package/lib/garbageCollection.js.map +1 -1
  179. package/lib/garbageCollectionConstants.d.ts +3 -0
  180. package/lib/garbageCollectionConstants.d.ts.map +1 -1
  181. package/lib/garbageCollectionConstants.js +5 -0
  182. package/lib/garbageCollectionConstants.js.map +1 -1
  183. package/lib/garbageCollectionHelpers.d.ts +26 -0
  184. package/lib/garbageCollectionHelpers.d.ts.map +1 -0
  185. package/lib/garbageCollectionHelpers.js +40 -0
  186. package/lib/garbageCollectionHelpers.js.map +1 -0
  187. package/lib/gcSweepReadyUsageDetection.d.ts +5 -5
  188. package/lib/gcSweepReadyUsageDetection.d.ts.map +1 -1
  189. package/lib/gcSweepReadyUsageDetection.js +14 -10
  190. package/lib/gcSweepReadyUsageDetection.js.map +1 -1
  191. package/lib/index.d.ts +2 -2
  192. package/lib/index.d.ts.map +1 -1
  193. package/lib/index.js +1 -1
  194. package/lib/index.js.map +1 -1
  195. package/lib/opLifecycle/batchManager.d.ts +5 -5
  196. package/lib/opLifecycle/batchManager.d.ts.map +1 -1
  197. package/lib/opLifecycle/batchManager.js +19 -12
  198. package/lib/opLifecycle/batchManager.js.map +1 -1
  199. package/lib/opLifecycle/definitions.d.ts.map +1 -1
  200. package/lib/opLifecycle/definitions.js.map +1 -1
  201. package/lib/opLifecycle/index.d.ts.map +1 -1
  202. package/lib/opLifecycle/index.js.map +1 -1
  203. package/lib/opLifecycle/opCompressor.d.ts.map +1 -1
  204. package/lib/opLifecycle/opCompressor.js.map +1 -1
  205. package/lib/opLifecycle/opDecompressor.d.ts.map +1 -1
  206. package/lib/opLifecycle/opDecompressor.js +5 -2
  207. package/lib/opLifecycle/opDecompressor.js.map +1 -1
  208. package/lib/opLifecycle/opSplitter.d.ts.map +1 -1
  209. package/lib/opLifecycle/opSplitter.js +5 -2
  210. package/lib/opLifecycle/opSplitter.js.map +1 -1
  211. package/lib/opLifecycle/outbox.d.ts.map +1 -1
  212. package/lib/opLifecycle/outbox.js +19 -17
  213. package/lib/opLifecycle/outbox.js.map +1 -1
  214. package/lib/opLifecycle/remoteMessageProcessor.d.ts.map +1 -1
  215. package/lib/opLifecycle/remoteMessageProcessor.js.map +1 -1
  216. package/lib/opProperties.d.ts.map +1 -1
  217. package/lib/opProperties.js +1 -3
  218. package/lib/opProperties.js.map +1 -1
  219. package/lib/orderedClientElection.d.ts.map +1 -1
  220. package/lib/orderedClientElection.js +10 -4
  221. package/lib/orderedClientElection.js.map +1 -1
  222. package/lib/packageVersion.d.ts +1 -1
  223. package/lib/packageVersion.js +1 -1
  224. package/lib/packageVersion.js.map +1 -1
  225. package/lib/pendingStateManager.d.ts +7 -0
  226. package/lib/pendingStateManager.d.ts.map +1 -1
  227. package/lib/pendingStateManager.js +7 -4
  228. package/lib/pendingStateManager.js.map +1 -1
  229. package/lib/runWhileConnectedCoordinator.d.ts.map +1 -1
  230. package/lib/runWhileConnectedCoordinator.js.map +1 -1
  231. package/lib/runningSummarizer.d.ts.map +1 -1
  232. package/lib/runningSummarizer.js +35 -22
  233. package/lib/runningSummarizer.js.map +1 -1
  234. package/lib/scheduleManager.d.ts.map +1 -1
  235. package/lib/scheduleManager.js +3 -2
  236. package/lib/scheduleManager.js.map +1 -1
  237. package/lib/serializedSnapshotStorage.d.ts +2 -2
  238. package/lib/serializedSnapshotStorage.d.ts.map +1 -1
  239. package/lib/serializedSnapshotStorage.js +5 -3
  240. package/lib/serializedSnapshotStorage.js.map +1 -1
  241. package/lib/summarizer.d.ts +2 -2
  242. package/lib/summarizer.d.ts.map +1 -1
  243. package/lib/summarizer.js +37 -17
  244. package/lib/summarizer.js.map +1 -1
  245. package/lib/summarizerClientElection.d.ts.map +1 -1
  246. package/lib/summarizerClientElection.js.map +1 -1
  247. package/lib/summarizerHandle.d.ts.map +1 -1
  248. package/lib/summarizerHandle.js.map +1 -1
  249. package/lib/summarizerHeuristics.d.ts.map +1 -1
  250. package/lib/summarizerHeuristics.js +6 -9
  251. package/lib/summarizerHeuristics.js.map +1 -1
  252. package/lib/summarizerTypes.d.ts +21 -21
  253. package/lib/summarizerTypes.d.ts.map +1 -1
  254. package/lib/summarizerTypes.js.map +1 -1
  255. package/lib/summaryCollection.d.ts.map +1 -1
  256. package/lib/summaryCollection.js +18 -8
  257. package/lib/summaryCollection.js.map +1 -1
  258. package/lib/summaryFormat.d.ts +22 -0
  259. package/lib/summaryFormat.d.ts.map +1 -1
  260. package/lib/summaryFormat.js +20 -12
  261. package/lib/summaryFormat.js.map +1 -1
  262. package/lib/summaryGenerator.d.ts.map +1 -1
  263. package/lib/summaryGenerator.js +34 -15
  264. package/lib/summaryGenerator.js.map +1 -1
  265. package/lib/summaryManager.d.ts.map +1 -1
  266. package/lib/summaryManager.js +21 -9
  267. package/lib/summaryManager.js.map +1 -1
  268. package/lib/throttler.d.ts +2 -2
  269. package/lib/throttler.d.ts.map +1 -1
  270. package/lib/throttler.js +4 -4
  271. package/lib/throttler.js.map +1 -1
  272. package/package.json +121 -149
  273. package/prettier.config.cjs +1 -1
  274. package/src/batchTracker.ts +54 -49
  275. package/src/blobManager.ts +793 -672
  276. package/src/connectionTelemetry.ts +280 -249
  277. package/src/containerHandleContext.ts +27 -29
  278. package/src/containerRuntime.ts +3168 -2940
  279. package/src/dataStore.ts +172 -159
  280. package/src/dataStoreContext.ts +1098 -996
  281. package/src/dataStoreContexts.ts +178 -161
  282. package/src/dataStoreRegistry.ts +25 -20
  283. package/src/dataStores.ts +884 -728
  284. package/src/deltaScheduler.ts +158 -150
  285. package/src/garbageCollection.ts +1883 -1692
  286. package/src/garbageCollectionConstants.ts +6 -0
  287. package/src/garbageCollectionHelpers.ts +61 -0
  288. package/src/gcSweepReadyUsageDetection.ts +89 -83
  289. package/src/index.ts +67 -66
  290. package/src/opLifecycle/README.md +152 -0
  291. package/src/opLifecycle/batchManager.ts +145 -141
  292. package/src/opLifecycle/definitions.ts +29 -29
  293. package/src/opLifecycle/index.ts +5 -5
  294. package/src/opLifecycle/opCompressor.ts +54 -53
  295. package/src/opLifecycle/opDecompressor.ts +100 -81
  296. package/src/opLifecycle/opSplitter.ts +214 -188
  297. package/src/opLifecycle/outbox.ts +204 -194
  298. package/src/opLifecycle/remoteMessageProcessor.ts +62 -62
  299. package/src/opProperties.ts +11 -9
  300. package/src/orderedClientElection.ts +489 -457
  301. package/src/packageVersion.ts +1 -1
  302. package/src/pendingStateManager.ts +384 -338
  303. package/src/runWhileConnectedCoordinator.ts +78 -71
  304. package/src/runningSummarizer.ts +619 -581
  305. package/src/scheduleManager.ts +299 -269
  306. package/src/serializedSnapshotStorage.ts +126 -112
  307. package/src/summarizer.ts +417 -381
  308. package/src/summarizerClientElection.ts +107 -100
  309. package/src/summarizerHandle.ts +11 -9
  310. package/src/summarizerHeuristics.ts +183 -186
  311. package/src/summarizerTypes.ts +344 -330
  312. package/src/summaryCollection.ts +378 -349
  313. package/src/summaryFormat.ts +170 -126
  314. package/src/summaryGenerator.ts +465 -406
  315. package/src/summaryManager.ts +377 -348
  316. package/src/throttler.ts +131 -122
  317. package/tsconfig.esnext.json +6 -6
  318. package/tsconfig.json +9 -13
  319. package/dist/garbageCollectionTombstoneUtils.d.ts +0 -14
  320. package/dist/garbageCollectionTombstoneUtils.d.ts.map +0 -1
  321. package/dist/garbageCollectionTombstoneUtils.js +0 -23
  322. package/dist/garbageCollectionTombstoneUtils.js.map +0 -1
  323. package/lib/garbageCollectionTombstoneUtils.d.ts +0 -14
  324. package/lib/garbageCollectionTombstoneUtils.d.ts.map +0 -1
  325. package/lib/garbageCollectionTombstoneUtils.js +0 -19
  326. package/lib/garbageCollectionTombstoneUtils.js.map +0 -1
  327. package/src/garbageCollectionTombstoneUtils.ts +0 -28
@@ -1 +1 @@
1
- {"version":3,"file":"summaryGenerator.js","sourceRoot":"","sources":["../src/summaryGenerator.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAGH,OAAO,EACH,MAAM,EACN,QAAQ,EAGR,KAAK,GACR,MAAM,8BAA8B,CAAC;AACtC,OAAO,EAAE,WAAW,EAAE,MAAM,sCAAsC,CAAC;AACnE,OAAO,EAAE,gBAAgB,EAAE,YAAY,EAAE,WAAW,EAAE,MAAM,iCAAiC,CAAC;AAC9F,OAAO,EAAE,6BAA6B,EAAE,MAAM,8BAA8B,CAAC;AAC7E,OAAO,EAAE,eAAe,EAAE,MAAM,oCAAoC,CAAC;AAsBrE,uEAAuE;AACvE,MAAM,CAAC,KAAK,UAAU,SAAS,CAC3B,OAAmB,EACnB,KAAmC,EACnC,iBAA6C;IAE7C,MAAM,QAAQ,GAAkC;QAC5C,OAAO,CAAC,IAAI,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,CAAC,EAAE,MAAM,EAAE,MAAM,EAAE,KAAK,EAAY,CAAA,CAAC;QAC7D,KAAK,CAAC,IAAI,CAAC,CAAC,EAAE,WAAW,EAAE,MAAM,EAAE,EAAE,EAAE,CAAC,CAAC,EAAE,MAAM,EAAY,CAAA,CAAC;KACjE,CA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AAC,IAAY,EAAE,KAAa;QACrD,IAAI,CAAC,MAAM,CAAC,oBAAoB,CAAC;YAC7B,SAAS,EAAE,kBAAkB;YAC7B,WAAW,EAAE,IAAI;YACjB,YAAY,EAAE,KAAK;SACtB,CAAC,CAAC;QACH,IAAI,KAAK,GAAG,wBAAwB,EAAE;YAClC,+BAA+B;YAC/B,MAAM,QAAQ,GAAG,IAAI,GAAG,CAAC,CAAC;YAC1B,IAAI,CAAC,cAAc,CAAC,KAAK,CAAC,QAAQ,EAAE,GAAG,EAAE,CAAC,IAAI,CAAC,qBAAqB,CAAC,QAAQ,EAAE,KAAK,GAAG,CAAC,CAAC,CAAC,CAAC;SAC9F;IACL,CAAC;IAEM,OAAO;QACV,IAAI,CAAC,cAAc,CAAC,KAAK,EAAE,CAAC;IAChC,CAAC;CACJ","sourcesContent":["/*!\n * Copyright (c) Microsoft Corporation and contributors. All rights reserved.\n * Licensed under the MIT License.\n */\n\nimport { ITelemetryLogger } from \"@fluidframework/common-definitions\";\nimport {\n assert,\n Deferred,\n IPromiseTimer,\n IPromiseTimerResult,\n Timer,\n} from \"@fluidframework/common-utils\";\nimport { MessageType } from \"@fluidframework/protocol-definitions\";\nimport { PerformanceEvent, LoggingError, ChildLogger } from \"@fluidframework/telemetry-utils\";\nimport { getRetryDelaySecondsFromError } from \"@fluidframework/driver-utils\";\nimport { DriverErrorType } from \"@fluidframework/driver-definitions\";\nimport {\n IAckSummaryResult,\n INackSummaryResult,\n ISummarizeOptions,\n IBroadcastSummaryResult,\n ISummarizeResults,\n ISummarizeHeuristicData,\n ISubmitSummaryOptions,\n SubmitSummaryResult,\n SummarizeResultPart,\n ISummaryCancellationToken,\n ISummarizeTelemetryProperties,\n SummaryGeneratorTelemetry,\n} from \"./summarizerTypes\";\nimport { IClientSummaryWatcher } from \"./summaryCollection\";\n\nexport type raceTimerResult<T> =\n { result: \"done\"; value: T; } |\n { result: IPromiseTimerResult[\"timerResult\"]; } |\n { result: \"cancelled\"; };\n\n/** Helper function to wait for a promise or PromiseTimer to elapse. */\nexport async function raceTimer<T>(\n promise: Promise<T>,\n timer: Promise<IPromiseTimerResult>,\n cancellationToken?: ISummaryCancellationToken,\n): Promise<raceTimerResult<T>> {\n const promises: Promise<raceTimerResult<T>>[] = [\n promise.then((value) => ({ result: \"done\", value } as const)),\n timer.then(({ timerResult: result }) => ({ result } as const)),\n ];\n if (cancellationToken !== undefined) {\n promises.push(cancellationToken.waitCancelled.then(() => ({ result: \"cancelled\" } as const)));\n }\n return Promise.race(promises);\n}\n\n// Send some telemetry if generate summary takes too long\nconst maxSummarizeTimeoutTime = 20000; // 20 sec\nconst maxSummarizeTimeoutCount = 5; // Double and resend 5 times\n\nexport type SummarizeReason =\n /**\n * Attempt to summarize after idle timeout has elapsed.\n * Idle timer restarts whenever an op is received. So this\n * triggers only after some amount of time has passed with\n * no ops being received.\n */\n | \"idle\"\n /**\n * Attempt to summarize after a maximum time since last\n * successful summary has passed. This measures time since\n * last summary ack op was processed.\n */\n | \"maxTime\"\n /**\n * Attempt to summarize after a maximum number of ops have\n * passed since the last successful summary. This compares\n * op sequence numbers with the reference sequence number\n * of the summarize op corresponding to the last summary\n * ack op.\n */\n | \"maxOps\"\n /**\n * Special case to attempt to summarize one last time before the\n * summarizer client closes itself. This is to prevent cases where\n * the summarizer client never gets a chance to summarize, because\n * there are too many outstanding ops and/or parent client cannot\n * stay connected long enough for summarizer client to catch up.\n */\n | \"lastSummary\"\n /** On-demand summary requested with specified reason. */\n | `onDemand;${string}`\n /** Enqueue summarize attempt with specified reason. */\n | `enqueue;${string}`;\n\nconst summarizeErrors = {\n /**\n * Error encountered while generating the summary tree, uploading\n * it to storage, or submitting the op. It could be a result of\n * the client becoming disconnected while generating or an actual error.\n */\n submitSummaryFailure: \"Error while generating, uploading, or submitting summary\",\n /**\n * The summaryAckWaitTimeout time has elapsed before receiving the summarize op\n * sent by this summarize attempt. It is expected to be broadcast quickly.\n */\n summaryOpWaitTimeout: \"Timeout while waiting for summarize op broadcast\",\n /**\n * The summaryAckWaitTimeout time has elapsed before receiving either a\n * summaryAck or summaryNack op from the server in response to this\n * summarize attempt. It is expected that the server should respond.\n */\n summaryAckWaitTimeout: \"Timeout while waiting for summaryAck/summaryNack op\",\n /**\n * The server responded with a summaryNack op, thus rejecting this\n * summarize attempt.\n */\n summaryNack: \"Server rejected summary via summaryNack op\",\n\n disconnect: \"Summary cancelled due to summarizer or main client disconnect\",\n} as const;\n\nexport class SummarizeResultBuilder {\n public readonly summarySubmitted = new Deferred<SummarizeResultPart<SubmitSummaryResult>>();\n public readonly summaryOpBroadcasted = new Deferred<SummarizeResultPart<IBroadcastSummaryResult>>();\n public readonly receivedSummaryAckOrNack =\n new Deferred<SummarizeResultPart<IAckSummaryResult, INackSummaryResult>>();\n\n public fail(message: string, error: any, nackSummaryResult?: INackSummaryResult, retryAfterSeconds?: number) {\n assert(!this.receivedSummaryAckOrNack.isCompleted,\n 0x25e /* \"no reason to call fail if all promises have been completed\" */);\n\n const result: SummarizeResultPart<undefined> =\n { success: false, message, data: undefined, error, retryAfterSeconds } as const;\n this.summarySubmitted.resolve(result);\n this.summaryOpBroadcasted.resolve(result);\n this.receivedSummaryAckOrNack.resolve({ ...result, data: nackSummaryResult });\n }\n public build(): ISummarizeResults {\n return {\n summarySubmitted: this.summarySubmitted.promise,\n summaryOpBroadcasted: this.summaryOpBroadcasted.promise,\n receivedSummaryAckOrNack: this.receivedSummaryAckOrNack.promise,\n } as const;\n }\n}\n\n/**\n * This class generates and tracks a summary attempt.\n */\nexport class SummaryGenerator {\n private readonly summarizeTimer: Timer;\n constructor(\n private readonly pendingAckTimer: IPromiseTimer,\n private readonly heuristicData: ISummarizeHeuristicData,\n private readonly submitSummaryCallback: (options: ISubmitSummaryOptions) => Promise<SubmitSummaryResult>,\n private readonly raiseSummarizingError: (errorMessage: string) => void,\n private readonly successfulSummaryCallback: () => void,\n private readonly summaryWatcher: Pick<IClientSummaryWatcher, \"watchSummary\">,\n private readonly logger: ITelemetryLogger,\n ) {\n this.summarizeTimer = new Timer(\n maxSummarizeTimeoutTime,\n () => this.summarizeTimerHandler(maxSummarizeTimeoutTime, 1),\n );\n }\n\n /**\n * Generates summary and listens for broadcast and ack/nack.\n * Returns true for ack, false for nack, and undefined for failure or timeout.\n * @param reason - reason for summarizing\n * @param options - refreshLatestAck to fetch summary ack info from server,\n * fullTree to generate tree without any summary handles even if unchanged\n */\n public summarize(\n summarizeProps: ISummarizeTelemetryProperties,\n options: ISummarizeOptions,\n cancellationToken: ISummaryCancellationToken,\n resultsBuilder = new SummarizeResultBuilder(),\n ): ISummarizeResults {\n this.summarizeCore(summarizeProps, options, resultsBuilder, cancellationToken)\n .catch((error) => {\n const message = \"UnexpectedSummarizeError\";\n this.logger.sendErrorEvent({ eventName: message, ...summarizeProps }, error);\n resultsBuilder.fail(message, error);\n });\n\n return resultsBuilder.build();\n }\n\n private async summarizeCore(\n summarizeProps: ISummarizeTelemetryProperties,\n options: ISummarizeOptions,\n resultsBuilder: SummarizeResultBuilder,\n cancellationToken: ISummaryCancellationToken,\n ): Promise<void> {\n const { refreshLatestAck, fullTree } = options;\n const logger = ChildLogger.create(this.logger, undefined, { all: summarizeProps });\n\n // Note: timeSinceLastAttempt and timeSinceLastSummary for the\n // first summary are basically the time since the summarizer was loaded.\n const timeSinceLastAttempt = Date.now() - this.heuristicData.lastAttempt.summaryTime;\n const timeSinceLastSummary = Date.now() - this.heuristicData.lastSuccessfulSummary.summaryTime;\n let summarizeTelemetryProps: SummaryGeneratorTelemetry = {\n fullTree,\n timeSinceLastAttempt,\n timeSinceLastSummary,\n };\n\n const summarizeEvent = PerformanceEvent.start(logger, {\n eventName: \"Summarize\",\n refreshLatestAck,\n ...summarizeTelemetryProps,\n });\n\n // Helper functions to report failures and return.\n const getFailMessage =\n (errorCode: keyof typeof summarizeErrors) => `${errorCode}: ${summarizeErrors[errorCode]}`;\n const fail = (\n errorCode: keyof typeof summarizeErrors,\n error?: any,\n properties?: SummaryGeneratorTelemetry,\n nackSummaryResult?: INackSummaryResult,\n ) => {\n this.raiseSummarizingError(summarizeErrors[errorCode]);\n // UploadSummary may fail with 429 and retryAfter - respect that\n // Summary Nack also can have retryAfter, it's parsed below and comes as a property.\n const retryAfterSeconds = getRetryDelaySecondsFromError(error);\n\n // Report any failure as an error unless it was due to cancellation (like \"disconnected\" error)\n // If failure happened on upload, we may not yet realized that socket disconnected, so check\n // offlineError too.\n const category = cancellationToken.cancelled || error?.errorType === DriverErrorType.offlineError ?\n \"generic\" : \"error\";\n\n const message = getFailMessage(errorCode);\n summarizeEvent.cancel({\n ...properties,\n reason: errorCode,\n category,\n retryAfterSeconds,\n }, error ?? message); // disconnect & summaryAckTimeout do not have proper error.\n resultsBuilder.fail(message, error, nackSummaryResult, retryAfterSeconds);\n };\n\n // Wait to generate and send summary\n this.summarizeTimer.start();\n\n // Use record type to prevent unexpected value types\n let summaryData: SubmitSummaryResult | undefined;\n try {\n summaryData = await this.submitSummaryCallback({\n fullTree,\n refreshLatestAck,\n summaryLogger: logger,\n cancellationToken,\n });\n\n // Cumulatively add telemetry properties based on how far generateSummary went.\n const referenceSequenceNumber = summaryData.referenceSequenceNumber;\n const opsSinceLastSummary =\n referenceSequenceNumber - this.heuristicData.lastSuccessfulSummary.refSequenceNumber;\n summarizeTelemetryProps = {\n ...summarizeTelemetryProps,\n referenceSequenceNumber,\n minimumSequenceNumber: summaryData.minimumSequenceNumber,\n opsSinceLastAttempt: referenceSequenceNumber - this.heuristicData.lastAttempt.refSequenceNumber,\n opsSinceLastSummary,\n };\n summarizeTelemetryProps = this.addSummaryDataToTelemetryProps(summaryData, summarizeTelemetryProps);\n\n if (summaryData.stage !== \"submit\") {\n return fail(\"submitSummaryFailure\", summaryData.error, summarizeTelemetryProps);\n }\n\n /**\n * With incremental summaries, if the full tree was not summarized, only data stores that changed should\n * be summarized. A data store is considered changed if either or both of the following is true:\n * - It has received an op.\n * - Its reference state changed, i.e., it went from referenced to unreferenced or vice-versa.\n *\n * In the extreme case, every op can be for a different data store and each op can result in the reference\n * state change of multiple data stores. So, the total number of data stores that are summarized should not\n * exceed the number of ops since last summary + number of data store whose reference state changed.\n */\n if (!fullTree && !summaryData.forcedFullTree) {\n const { summarizedDataStoreCount, gcStateUpdatedDataStoreCount = 0 } = summaryData.summaryStats;\n if (summarizedDataStoreCount > gcStateUpdatedDataStoreCount + opsSinceLastSummary) {\n logger.sendErrorEvent({\n eventName: \"IncrementalSummaryViolation\",\n summarizedDataStoreCount,\n gcStateUpdatedDataStoreCount,\n opsSinceLastSummary,\n });\n }\n }\n\n // Log event here on summary success only, as Summarize_cancel duplicates failure logging.\n summarizeEvent.reportEvent(\"generate\", { ...summarizeTelemetryProps });\n resultsBuilder.summarySubmitted.resolve({ success: true, data: summaryData });\n } catch (error) {\n return fail(\"submitSummaryFailure\", error);\n } finally {\n this.heuristicData.recordAttempt(summaryData?.referenceSequenceNumber);\n this.summarizeTimer.clear();\n }\n\n try {\n const pendingTimeoutP = this.pendingAckTimer.start();\n const summary = this.summaryWatcher.watchSummary(summaryData.clientSequenceNumber);\n\n // Wait for broadcast\n const waitBroadcastResult = await raceTimer(summary.waitBroadcast(), pendingTimeoutP, cancellationToken);\n if (waitBroadcastResult.result === \"cancelled\") {\n return fail(\"disconnect\");\n }\n if (waitBroadcastResult.result !== \"done\") {\n return fail(\"summaryOpWaitTimeout\");\n }\n const summarizeOp = waitBroadcastResult.value;\n\n const broadcastDuration = Date.now() - this.heuristicData.lastAttempt.summaryTime;\n resultsBuilder.summaryOpBroadcasted.resolve({\n success: true,\n data: { summarizeOp, broadcastDuration },\n });\n\n this.heuristicData.lastAttempt.summarySequenceNumber = summarizeOp.sequenceNumber;\n logger.sendTelemetryEvent({\n eventName: \"Summarize_Op\",\n duration: broadcastDuration,\n referenceSequenceNumber: summarizeOp.referenceSequenceNumber,\n summarySequenceNumber: summarizeOp.sequenceNumber,\n handle: summarizeOp.contents.handle,\n });\n\n // Wait for ack/nack\n const waitAckNackResult = await raceTimer(summary.waitAckNack(), pendingTimeoutP, cancellationToken);\n if (waitAckNackResult.result === \"cancelled\") {\n return fail(\"disconnect\");\n }\n if (waitAckNackResult.result !== \"done\") {\n return fail(\"summaryAckWaitTimeout\");\n }\n const ackNackOp = waitAckNackResult.value;\n this.pendingAckTimer.clear();\n\n // Update for success/failure\n const ackNackDuration = Date.now() - this.heuristicData.lastAttempt.summaryTime;\n\n // adding new properties\n summarizeTelemetryProps = {\n ackWaitDuration: ackNackDuration,\n ackNackSequenceNumber: ackNackOp.sequenceNumber,\n summarySequenceNumber: ackNackOp.contents.summaryProposal.summarySequenceNumber,\n ...summarizeTelemetryProps,\n };\n if (ackNackOp.type === MessageType.SummaryAck) {\n this.heuristicData.markLastAttemptAsSuccessful();\n this.successfulSummaryCallback();\n summarizeEvent.end({\n ...summarizeTelemetryProps,\n handle: ackNackOp.contents.handle,\n });\n resultsBuilder.receivedSummaryAckOrNack.resolve({ success: true, data: {\n summaryAckOp: ackNackOp,\n ackNackDuration,\n } });\n } else {\n // Check for retryDelay in summaryNack response.\n assert(ackNackOp.type === MessageType.SummaryNack, 0x274 /* \"type check\" */);\n const summaryNack = ackNackOp.contents;\n const message = summaryNack?.message;\n const retryAfterSeconds = summaryNack?.retryAfter;\n\n // pre-0.58 error message prefix: summaryNack\n const error = new LoggingError(`Received summaryNack: ${message}`, { retryAfterSeconds });\n\n assert(getRetryDelaySecondsFromError(error) === retryAfterSeconds, 0x25f /* \"retryAfterSeconds\" */);\n // This will only set resultsBuilder.receivedSummaryAckOrNack, as other promises are already set.\n return fail(\n \"summaryNack\",\n error,\n { ...summarizeTelemetryProps, nackRetryAfter: retryAfterSeconds },\n { summaryNackOp: ackNackOp, ackNackDuration },\n );\n }\n } finally {\n this.pendingAckTimer.clear();\n }\n }\n\n private addSummaryDataToTelemetryProps(\n summaryData: SubmitSummaryResult,\n initialProps: SummaryGeneratorTelemetry,\n ): SummaryGeneratorTelemetry {\n switch (summaryData.stage) {\n case \"base\": return initialProps;\n\n case \"generate\": return {\n ...initialProps,\n ...summaryData.summaryStats,\n generateDuration: summaryData.generateDuration,\n };\n\n case \"upload\": return {\n ...initialProps,\n ...summaryData.summaryStats,\n generateDuration: summaryData.generateDuration,\n handle: summaryData.handle,\n uploadDuration: summaryData.uploadDuration,\n };\n\n case \"submit\": return {\n ...initialProps,\n ...summaryData.summaryStats,\n generateDuration: summaryData.generateDuration,\n handle: summaryData.handle,\n uploadDuration: summaryData.uploadDuration,\n clientSequenceNumber: summaryData.clientSequenceNumber,\n hasMissingOpData: this.heuristicData.hasMissingOpData,\n opsSizesSinceLastSummary: this.heuristicData.totalOpsSize,\n nonRuntimeOpsSinceLastSummary: this.heuristicData.numNonRuntimeOps,\n };\n\n default: assert(true, 0x397 /* Unexpected summary stage */);\n }\n\n return initialProps;\n }\n\n private summarizeTimerHandler(time: number, count: number) {\n this.logger.sendPerformanceEvent({\n eventName: \"SummarizeTimeout\",\n timeoutTime: time,\n timeoutCount: count,\n });\n if (count < maxSummarizeTimeoutCount) {\n // Double and start a new timer\n const nextTime = time * 2;\n this.summarizeTimer.start(nextTime, () => this.summarizeTimerHandler(nextTime, count + 1));\n }\n }\n\n public dispose() {\n this.summarizeTimer.clear();\n }\n}\n"]}
1
+ {"version":3,"file":"summaryGenerator.js","sourceRoot":"","sources":["../src/summaryGenerator.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAGH,OAAO,EACN,MAAM,EACN,QAAQ,EAGR,KAAK,GACL,MAAM,8BAA8B,CAAC;AACtC,OAAO,EAAE,WAAW,EAAE,MAAM,sCAAsC,CAAC;AACnE,OAAO,EAAE,gBAAgB,EAAE,YAAY,EAAE,WAAW,EAAE,MAAM,iCAAiC,CAAC;AAC9F,OAAO,EAAE,6BAA6B,EAAE,MAAM,8BAA8B,CAAC;AAC7E,OAAO,EAAE,eAAe,EAAE,MAAM,oCAAoC,CAAC;AAsBrE,uEAAuE;AACvE,MAAM,CAAC,KAAK,UAAU,SAAS,CAC9B,OAAmB,EACn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AAE,WAAW,CAAC,cAAc,EAC1C,oBAAoB,EAAE,WAAW,CAAC,oBAAoB,EACtD,gBAAgB,EAAE,IAAI,CAAC,aAAa,CAAC,gBAAgB,EACrD,wBAAwB,EAAE,IAAI,CAAC,aAAa,CAAC,YAAY,EACzD,6BAA6B,EAAE,IAAI,CAAC,aAAa,CAAC,gBAAgB,IACjE;YAEH;gBACC,MAAM,CAAC,IAAI,EAAE,KAAK,CAAC,8BAA8B,CAAC,CAAC;SACpD;QAED,OAAO,YAAY,CAAC;IACrB,CAAC;IAEO,qBAAqB,CAAC,IAAY,EAAE,KAAa;QACxD,IAAI,CAAC,MAAM,CAAC,oBAAoB,CAAC;YAChC,SAAS,EAAE,kBAAkB;YAC7B,WAAW,EAAE,IAAI;YACjB,YAAY,EAAE,KAAK;SACnB,CAAC,CAAC;QACH,IAAI,KAAK,GAAG,wBAAwB,EAAE;YACrC,+BAA+B;YAC/B,MAAM,QAAQ,GAAG,IAAI,GAAG,CAAC,CAAC;YAC1B,IAAI,CAAC,cAAc,CAAC,KAAK,CAAC,QAAQ,EAAE,GAAG,EAAE,CACxC,IAAI,CAAC,qBAAqB,CAAC,QAAQ,EAAE,KAAK,GAAG,CAAC,CAAC,CAC/C,CAAC;SACF;IACF,CAAC;IAEM,OAAO;QACb,IAAI,CAAC,cAAc,CAAC,KAAK,EAAE,CAAC;IAC7B,CAAC;CACD","sourcesContent":["/*!\n * Copyright (c) Microsoft Corporation and contributors. All rights reserved.\n * Licensed under the MIT License.\n */\n\nimport { ITelemetryLogger } from \"@fluidframework/common-definitions\";\nimport {\n\tassert,\n\tDeferred,\n\tIPromiseTimer,\n\tIPromiseTimerResult,\n\tTimer,\n} from \"@fluidframework/common-utils\";\nimport { MessageType } from \"@fluidframework/protocol-definitions\";\nimport { PerformanceEvent, LoggingError, ChildLogger } from \"@fluidframework/telemetry-utils\";\nimport { getRetryDelaySecondsFromError } from \"@fluidframework/driver-utils\";\nimport { DriverErrorType } from \"@fluidframework/driver-definitions\";\nimport {\n\tIAckSummaryResult,\n\tINackSummaryResult,\n\tISummarizeOptions,\n\tIBroadcastSummaryResult,\n\tISummarizeResults,\n\tISummarizeHeuristicData,\n\tISubmitSummaryOptions,\n\tSubmitSummaryResult,\n\tSummarizeResultPart,\n\tISummaryCancellationToken,\n\tISummarizeTelemetryProperties,\n\tSummaryGeneratorTelemetry,\n} from \"./summarizerTypes\";\nimport { IClientSummaryWatcher } from \"./summaryCollection\";\n\nexport type raceTimerResult<T> =\n\t| { result: \"done\"; value: T }\n\t| { result: IPromiseTimerResult[\"timerResult\"] }\n\t| { result: \"cancelled\" };\n\n/** Helper function to wait for a promise or PromiseTimer to elapse. */\nexport async function raceTimer<T>(\n\tpromise: Promise<T>,\n\ttimer: Promise<IPromiseTimerResult>,\n\tcancellationToken?: ISummaryCancellationToken,\n): Promise<raceTimerResult<T>> {\n\tconst promises: Promise<raceTimerResult<T>>[] = [\n\t\tpromise.then((value) => ({ result: \"done\", value } as const)),\n\t\ttimer.then(({ timerResult: result }) => ({ result } as const)),\n\t];\n\tif (cancellationToken !== undefined) {\n\t\tpromises.push(\n\t\t\tcancellationToken.waitCancelled.then(() => ({ result: \"cancelled\" } as const)),\n\t\t);\n\t}\n\treturn Promise.race(promises);\n}\n\n// Send some telemetry if generate summary takes too long\nconst maxSummarizeTimeoutTime = 20000; // 20 sec\nconst maxSummarizeTimeoutCount = 5; // Double and resend 5 times\n\nexport type SummarizeReason =\n\t/**\n\t * Attempt to summarize after idle timeout has elapsed.\n\t * Idle timer restarts whenever an op is received. So this\n\t * triggers only after some amount of time has passed with\n\t * no ops being received.\n\t */\n\t| \"idle\"\n\t/**\n\t * Attempt to summarize after a maximum time since last\n\t * successful summary has passed. This measures time since\n\t * last summary ack op was processed.\n\t */\n\t| \"maxTime\"\n\t/**\n\t * Attempt to summarize after a maximum number of ops have\n\t * passed since the last successful summary. This compares\n\t * op sequence numbers with the reference sequence number\n\t * of the summarize op corresponding to the last summary\n\t * ack op.\n\t */\n\t| \"maxOps\"\n\t/**\n\t * Special case to attempt to summarize one last time before the\n\t * summarizer client closes itself. This is to prevent cases where\n\t * the summarizer client never gets a chance to summarize, because\n\t * there are too many outstanding ops and/or parent client cannot\n\t * stay connected long enough for summarizer client to catch up.\n\t */\n\t| \"lastSummary\"\n\t/** On-demand summary requested with specified reason. */\n\t| `onDemand;${string}`\n\t/** Enqueue summarize attempt with specified reason. */\n\t| `enqueue;${string}`;\n\nconst summarizeErrors = {\n\t/**\n\t * Error encountered while generating the summary tree, uploading\n\t * it to storage, or submitting the op. It could be a result of\n\t * the client becoming disconnected while generating or an actual error.\n\t */\n\tsubmitSummaryFailure: \"Error while generating, uploading, or submitting summary\",\n\t/**\n\t * The summaryAckWaitTimeout time has elapsed before receiving the summarize op\n\t * sent by this summarize attempt. It is expected to be broadcast quickly.\n\t */\n\tsummaryOpWaitTimeout: \"Timeout while waiting for summarize op broadcast\",\n\t/**\n\t * The summaryAckWaitTimeout time has elapsed before receiving either a\n\t * summaryAck or summaryNack op from the server in response to this\n\t * summarize attempt. It is expected that the server should respond.\n\t */\n\tsummaryAckWaitTimeout: \"Timeout while waiting for summaryAck/summaryNack op\",\n\t/**\n\t * The server responded with a summaryNack op, thus rejecting this\n\t * summarize attempt.\n\t */\n\tsummaryNack: \"Server rejected summary via summaryNack op\",\n\n\tdisconnect: \"Summary cancelled due to summarizer or main client disconnect\",\n} as const;\n\nexport class SummarizeResultBuilder {\n\tpublic readonly summarySubmitted = new Deferred<SummarizeResultPart<SubmitSummaryResult>>();\n\tpublic readonly summaryOpBroadcasted = new Deferred<\n\t\tSummarizeResultPart<IBroadcastSummaryResult>\n\t>();\n\tpublic readonly receivedSummaryAckOrNack = new Deferred<\n\t\tSummarizeResultPart<IAckSummaryResult, INackSummaryResult>\n\t>();\n\n\tpublic fail(\n\t\tmessage: string,\n\t\terror: any,\n\t\tnackSummaryResult?: INackSummaryResult,\n\t\tretryAfterSeconds?: number,\n\t) {\n\t\tassert(\n\t\t\t!this.receivedSummaryAckOrNack.isCompleted,\n\t\t\t0x25e /* \"no reason to call fail if all promises have been completed\" */,\n\t\t);\n\n\t\tconst result: SummarizeResultPart<undefined> = {\n\t\t\tsuccess: false,\n\t\t\tmessage,\n\t\t\tdata: undefined,\n\t\t\terror,\n\t\t\tretryAfterSeconds,\n\t\t} as const;\n\t\tthis.summarySubmitted.resolve(result);\n\t\tthis.summaryOpBroadcasted.resolve(result);\n\t\tthis.receivedSummaryAckOrNack.resolve({ ...result, data: nackSummaryResult });\n\t}\n\tpublic build(): ISummarizeResults {\n\t\treturn {\n\t\t\tsummarySubmitted: this.summarySubmitted.promise,\n\t\t\tsummaryOpBroadcasted: this.summaryOpBroadcasted.promise,\n\t\t\treceivedSummaryAckOrNack: this.receivedSummaryAckOrNack.promise,\n\t\t} as const;\n\t}\n}\n\n/**\n * This class generates and tracks a summary attempt.\n */\nexport class SummaryGenerator {\n\tprivate readonly summarizeTimer: Timer;\n\tconstructor(\n\t\tprivate readonly pendingAckTimer: IPromiseTimer,\n\t\tprivate readonly heuristicData: ISummarizeHeuristicData,\n\t\tprivate readonly submitSummaryCallback: (\n\t\t\toptions: ISubmitSummaryOptions,\n\t\t) => Promise<SubmitSummaryResult>,\n\t\tprivate readonly raiseSummarizingError: (errorMessage: string) => void,\n\t\tprivate readonly successfulSummaryCallback: () => void,\n\t\tprivate readonly summaryWatcher: Pick<IClientSummaryWatcher, \"watchSummary\">,\n\t\tprivate readonly logger: ITelemetryLogger,\n\t) {\n\t\tthis.summarizeTimer = new Timer(maxSummarizeTimeoutTime, () =>\n\t\t\tthis.summarizeTimerHandler(maxSummarizeTimeoutTime, 1),\n\t\t);\n\t}\n\n\t/**\n\t * Generates summary and listens for broadcast and ack/nack.\n\t * Returns true for ack, false for nack, and undefined for failure or timeout.\n\t * @param reason - reason for summarizing\n\t * @param options - refreshLatestAck to fetch summary ack info from server,\n\t * fullTree to generate tree without any summary handles even if unchanged\n\t */\n\tpublic summarize(\n\t\tsummarizeProps: ISummarizeTelemetryProperties,\n\t\toptions: ISummarizeOptions,\n\t\tcancellationToken: ISummaryCancellationToken,\n\t\tresultsBuilder = new SummarizeResultBuilder(),\n\t): ISummarizeResults {\n\t\tthis.logger.sendTelemetryEvent({\n\t\t\teventName: \"Summarize_start\",\n\t\t\t...summarizeProps,\n\t\t});\n\t\tthis.summarizeCore(summarizeProps, options, resultsBuilder, cancellationToken).catch(\n\t\t\t(error) => {\n\t\t\t\tconst message = \"UnexpectedSummarizeError\";\n\t\t\t\tthis.logger.sendErrorEvent({ eventName: message, ...summarizeProps }, error);\n\t\t\t\tresultsBuilder.fail(message, error);\n\t\t\t},\n\t\t);\n\n\t\treturn resultsBuilder.build();\n\t}\n\n\tprivate async summarizeCore(\n\t\tsummarizeProps: ISummarizeTelemetryProperties,\n\t\toptions: ISummarizeOptions,\n\t\tresultsBuilder: SummarizeResultBuilder,\n\t\tcancellationToken: ISummaryCancellationToken,\n\t): Promise<void> {\n\t\tconst { refreshLatestAck, fullTree } = options;\n\t\tconst logger = ChildLogger.create(this.logger, undefined, { all: summarizeProps });\n\n\t\t// Note: timeSinceLastAttempt and timeSinceLastSummary for the\n\t\t// first summary are basically the time since the summarizer was loaded.\n\t\tconst timeSinceLastAttempt = Date.now() - this.heuristicData.lastAttempt.summaryTime;\n\t\tconst timeSinceLastSummary =\n\t\t\tDate.now() - this.heuristicData.lastSuccessfulSummary.summaryTime;\n\t\tlet summarizeTelemetryProps: SummaryGeneratorTelemetry = {\n\t\t\tfullTree,\n\t\t\ttimeSinceLastAttempt,\n\t\t\ttimeSinceLastSummary,\n\t\t};\n\n\t\tconst summarizeEvent = PerformanceEvent.start(logger, {\n\t\t\teventName: \"Summarize\",\n\t\t\trefreshLatestAck,\n\t\t\t...summarizeTelemetryProps,\n\t\t});\n\n\t\t// Helper functions to report failures and return.\n\t\tconst getFailMessage = (errorCode: keyof typeof summarizeErrors) =>\n\t\t\t`${errorCode}: ${summarizeErrors[errorCode]}`;\n\t\tconst fail = (\n\t\t\terrorCode: keyof typeof summarizeErrors,\n\t\t\terror?: any,\n\t\t\tproperties?: SummaryGeneratorTelemetry,\n\t\t\tnackSummaryResult?: INackSummaryResult,\n\t\t) => {\n\t\t\tthis.raiseSummarizingError(summarizeErrors[errorCode]);\n\t\t\t// UploadSummary may fail with 429 and retryAfter - respect that\n\t\t\t// Summary Nack also can have retryAfter, it's parsed below and comes as a property.\n\t\t\tconst retryAfterSeconds = getRetryDelaySecondsFromError(error);\n\n\t\t\t// Report any failure as an error unless it was due to cancellation (like \"disconnected\" error)\n\t\t\t// If failure happened on upload, we may not yet realized that socket disconnected, so check\n\t\t\t// offlineError too.\n\t\t\tconst category =\n\t\t\t\tcancellationToken.cancelled || error?.errorType === DriverErrorType.offlineError\n\t\t\t\t\t? \"generic\"\n\t\t\t\t\t: \"error\";\n\n\t\t\tconst message = getFailMessage(errorCode);\n\t\t\tsummarizeEvent.cancel(\n\t\t\t\t{\n\t\t\t\t\t...properties,\n\t\t\t\t\treason: errorCode,\n\t\t\t\t\tcategory,\n\t\t\t\t\tretryAfterSeconds,\n\t\t\t\t},\n\t\t\t\terror ?? message,\n\t\t\t); // disconnect & summaryAckTimeout do not have proper error.\n\t\t\tresultsBuilder.fail(message, error, nackSummaryResult, retryAfterSeconds);\n\t\t};\n\n\t\t// Wait to generate and send summary\n\t\tthis.summarizeTimer.start();\n\n\t\t// Use record type to prevent unexpected value types\n\t\tlet summaryData: SubmitSummaryResult | undefined;\n\t\ttry {\n\t\t\tsummaryData = await this.submitSummaryCallback({\n\t\t\t\tfullTree,\n\t\t\t\trefreshLatestAck,\n\t\t\t\tsummaryLogger: logger,\n\t\t\t\tcancellationToken,\n\t\t\t});\n\n\t\t\t// Cumulatively add telemetry properties based on how far generateSummary went.\n\t\t\tconst referenceSequenceNumber = summaryData.referenceSequenceNumber;\n\t\t\tconst opsSinceLastSummary =\n\t\t\t\treferenceSequenceNumber -\n\t\t\t\tthis.heuristicData.lastSuccessfulSummary.refSequenceNumber;\n\t\t\tsummarizeTelemetryProps = {\n\t\t\t\t...summarizeTelemetryProps,\n\t\t\t\treferenceSequenceNumber,\n\t\t\t\tminimumSequenceNumber: summaryData.minimumSequenceNumber,\n\t\t\t\topsSinceLastAttempt:\n\t\t\t\t\treferenceSequenceNumber - this.heuristicData.lastAttempt.refSequenceNumber,\n\t\t\t\topsSinceLastSummary,\n\t\t\t};\n\t\t\tsummarizeTelemetryProps = this.addSummaryDataToTelemetryProps(\n\t\t\t\tsummaryData,\n\t\t\t\tsummarizeTelemetryProps,\n\t\t\t);\n\n\t\t\tif (summaryData.stage !== \"submit\") {\n\t\t\t\treturn fail(\"submitSummaryFailure\", summaryData.error, summarizeTelemetryProps);\n\t\t\t}\n\n\t\t\t/**\n\t\t\t * With incremental summaries, if the full tree was not summarized, only data stores that changed should\n\t\t\t * be summarized. A data store is considered changed if either or both of the following is true:\n\t\t\t * - It has received an op.\n\t\t\t * - Its reference state changed, i.e., it went from referenced to unreferenced or vice-versa.\n\t\t\t *\n\t\t\t * In the extreme case, every op can be for a different data store and each op can result in the reference\n\t\t\t * state change of multiple data stores. So, the total number of data stores that are summarized should not\n\t\t\t * exceed the number of ops since last summary + number of data store whose reference state changed.\n\t\t\t */\n\t\t\tif (!fullTree && !summaryData.forcedFullTree) {\n\t\t\t\tconst { summarizedDataStoreCount, gcStateUpdatedDataStoreCount = 0 } =\n\t\t\t\t\tsummaryData.summaryStats;\n\t\t\t\tif (summarizedDataStoreCount > gcStateUpdatedDataStoreCount + opsSinceLastSummary) {\n\t\t\t\t\tlogger.sendErrorEvent({\n\t\t\t\t\t\teventName: \"IncrementalSummaryViolation\",\n\t\t\t\t\t\tsummarizedDataStoreCount,\n\t\t\t\t\t\tgcStateUpdatedDataStoreCount,\n\t\t\t\t\t\topsSinceLastSummary,\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Log event here on summary success only, as Summarize_cancel duplicates failure logging.\n\t\t\tsummarizeEvent.reportEvent(\"generate\", { ...summarizeTelemetryProps });\n\t\t\tresultsBuilder.summarySubmitted.resolve({ success: true, data: summaryData });\n\t\t} catch (error) {\n\t\t\treturn fail(\"submitSummaryFailure\", error);\n\t\t} finally {\n\t\t\tthis.heuristicData.recordAttempt(summaryData?.referenceSequenceNumber);\n\t\t\tthis.summarizeTimer.clear();\n\t\t}\n\n\t\ttry {\n\t\t\tconst pendingTimeoutP = this.pendingAckTimer.start();\n\t\t\tconst summary = this.summaryWatcher.watchSummary(summaryData.clientSequenceNumber);\n\n\t\t\t// Wait for broadcast\n\t\t\tconst waitBroadcastResult = await raceTimer(\n\t\t\t\tsummary.waitBroadcast(),\n\t\t\t\tpendingTimeoutP,\n\t\t\t\tcancellationToken,\n\t\t\t);\n\t\t\tif (waitBroadcastResult.result === \"cancelled\") {\n\t\t\t\treturn fail(\"disconnect\");\n\t\t\t}\n\t\t\tif (waitBroadcastResult.result !== \"done\") {\n\t\t\t\treturn fail(\"summaryOpWaitTimeout\");\n\t\t\t}\n\t\t\tconst summarizeOp = waitBroadcastResult.value;\n\n\t\t\tconst broadcastDuration = Date.now() - this.heuristicData.lastAttempt.summaryTime;\n\t\t\tresultsBuilder.summaryOpBroadcasted.resolve({\n\t\t\t\tsuccess: true,\n\t\t\t\tdata: { summarizeOp, broadcastDuration },\n\t\t\t});\n\n\t\t\tthis.heuristicData.lastAttempt.summarySequenceNumber = summarizeOp.sequenceNumber;\n\t\t\tlogger.sendTelemetryEvent({\n\t\t\t\teventName: \"Summarize_Op\",\n\t\t\t\tduration: broadcastDuration,\n\t\t\t\treferenceSequenceNumber: summarizeOp.referenceSequenceNumber,\n\t\t\t\tsummarySequenceNumber: summarizeOp.sequenceNumber,\n\t\t\t\thandle: summarizeOp.contents.handle,\n\t\t\t});\n\n\t\t\t// Wait for ack/nack\n\t\t\tconst waitAckNackResult = await raceTimer(\n\t\t\t\tsummary.waitAckNack(),\n\t\t\t\tpendingTimeoutP,\n\t\t\t\tcancellationToken,\n\t\t\t);\n\t\t\tif (waitAckNackResult.result === \"cancelled\") {\n\t\t\t\treturn fail(\"disconnect\");\n\t\t\t}\n\t\t\tif (waitAckNackResult.result !== \"done\") {\n\t\t\t\treturn fail(\"summaryAckWaitTimeout\");\n\t\t\t}\n\t\t\tconst ackNackOp = waitAckNackResult.value;\n\t\t\tthis.pendingAckTimer.clear();\n\n\t\t\t// Update for success/failure\n\t\t\tconst ackNackDuration = Date.now() - this.heuristicData.lastAttempt.summaryTime;\n\n\t\t\t// adding new properties\n\t\t\tsummarizeTelemetryProps = {\n\t\t\t\tackWaitDuration: ackNackDuration,\n\t\t\t\tackNackSequenceNumber: ackNackOp.sequenceNumber,\n\t\t\t\tsummarySequenceNumber: ackNackOp.contents.summaryProposal.summarySequenceNumber,\n\t\t\t\t...summarizeTelemetryProps,\n\t\t\t};\n\t\t\tif (ackNackOp.type === MessageType.SummaryAck) {\n\t\t\t\tthis.heuristicData.markLastAttemptAsSuccessful();\n\t\t\t\tthis.successfulSummaryCallback();\n\t\t\t\tsummarizeEvent.end({\n\t\t\t\t\t...summarizeTelemetryProps,\n\t\t\t\t\thandle: ackNackOp.contents.handle,\n\t\t\t\t});\n\t\t\t\tresultsBuilder.receivedSummaryAckOrNack.resolve({\n\t\t\t\t\tsuccess: true,\n\t\t\t\t\tdata: {\n\t\t\t\t\t\tsummaryAckOp: ackNackOp,\n\t\t\t\t\t\tackNackDuration,\n\t\t\t\t\t},\n\t\t\t\t});\n\t\t\t} else {\n\t\t\t\t// Check for retryDelay in summaryNack response.\n\t\t\t\tassert(ackNackOp.type === MessageType.SummaryNack, 0x274 /* \"type check\" */);\n\t\t\t\tconst summaryNack = ackNackOp.contents;\n\t\t\t\tconst errorMessage = summaryNack?.message;\n\t\t\t\tconst retryAfterSeconds = summaryNack?.retryAfter;\n\n\t\t\t\t// pre-0.58 error message prefix: summaryNack\n\t\t\t\tconst error = new LoggingError(`Received summaryNack`, {\n\t\t\t\t\tretryAfterSeconds,\n\t\t\t\t\terrorMessage,\n\t\t\t\t});\n\n\t\t\t\tassert(\n\t\t\t\t\tgetRetryDelaySecondsFromError(error) === retryAfterSeconds,\n\t\t\t\t\t0x25f /* \"retryAfterSeconds\" */,\n\t\t\t\t);\n\t\t\t\t// This will only set resultsBuilder.receivedSummaryAckOrNack, as other promises are already set.\n\t\t\t\treturn fail(\n\t\t\t\t\t\"summaryNack\",\n\t\t\t\t\terror,\n\t\t\t\t\t{ ...summarizeTelemetryProps, nackRetryAfter: retryAfterSeconds },\n\t\t\t\t\t{ summaryNackOp: ackNackOp, ackNackDuration },\n\t\t\t\t);\n\t\t\t}\n\t\t} finally {\n\t\t\tthis.pendingAckTimer.clear();\n\t\t}\n\t}\n\n\tprivate addSummaryDataToTelemetryProps(\n\t\tsummaryData: SubmitSummaryResult,\n\t\tinitialProps: SummaryGeneratorTelemetry,\n\t): SummaryGeneratorTelemetry {\n\t\tswitch (summaryData.stage) {\n\t\t\tcase \"base\":\n\t\t\t\treturn initialProps;\n\n\t\t\tcase \"generate\":\n\t\t\t\treturn {\n\t\t\t\t\t...initialProps,\n\t\t\t\t\t...summaryData.summaryStats,\n\t\t\t\t\tgenerateDuration: summaryData.generateDuration,\n\t\t\t\t};\n\n\t\t\tcase \"upload\":\n\t\t\t\treturn {\n\t\t\t\t\t...initialProps,\n\t\t\t\t\t...summaryData.summaryStats,\n\t\t\t\t\tgenerateDuration: summaryData.generateDuration,\n\t\t\t\t\thandle: summaryData.handle,\n\t\t\t\t\tuploadDuration: summaryData.uploadDuration,\n\t\t\t\t};\n\n\t\t\tcase \"submit\":\n\t\t\t\treturn {\n\t\t\t\t\t...initialProps,\n\t\t\t\t\t...summaryData.summaryStats,\n\t\t\t\t\tgenerateDuration: summaryData.generateDuration,\n\t\t\t\t\thandle: summaryData.handle,\n\t\t\t\t\tuploadDuration: summaryData.uploadDuration,\n\t\t\t\t\tclientSequenceNumber: summaryData.clientSequenceNumber,\n\t\t\t\t\thasMissingOpData: this.heuristicData.hasMissingOpData,\n\t\t\t\t\topsSizesSinceLastSummary: this.heuristicData.totalOpsSize,\n\t\t\t\t\tnonRuntimeOpsSinceLastSummary: this.heuristicData.numNonRuntimeOps,\n\t\t\t\t};\n\n\t\t\tdefault:\n\t\t\t\tassert(true, 0x397 /* Unexpected summary stage */);\n\t\t}\n\n\t\treturn initialProps;\n\t}\n\n\tprivate summarizeTimerHandler(time: number, count: number) {\n\t\tthis.logger.sendPerformanceEvent({\n\t\t\teventName: \"SummarizeTimeout\",\n\t\t\ttimeoutTime: time,\n\t\t\ttimeoutCount: count,\n\t\t});\n\t\tif (count < maxSummarizeTimeoutCount) {\n\t\t\t// Double and start a new timer\n\t\t\tconst nextTime = time * 2;\n\t\t\tthis.summarizeTimer.start(nextTime, () =>\n\t\t\t\tthis.summarizeTimerHandler(nextTime, count + 1),\n\t\t\t);\n\t\t}\n\t}\n\n\tpublic dispose() {\n\t\tthis.summarizeTimer.clear();\n\t}\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"summaryManager.d.ts","sourceRoot":"","sources":["../src/summaryManager.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,OAAO,EAAE,WAAW,EAAE,MAAM,EAAE,cAAc,EAAE,gBAAgB,EAAE,MAAM,oCAAoC,CAAC;AAI3G,OAAO,EAAE,yBAAyB,EAAE,MAAM,4BAA4B,CAAC;AACvE,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AACzC,OAAO,EACH,WAAW,EAEd,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EAAE,iBAAiB,EAAE,MAAM,qBAAqB,CAAC;AAMxD,oBAAY,mBAAmB;IAC3B,GAAG,IAAI;IACP,QAAQ,IAAI;IACZ,OAAO,IAAI;IACX,QAAQ,IAAI;CACf;AAWD,MAAM,WAAW,gBAAiB,SAAQ,MAAM;IAC5C,CAAC,KAAK,EAAE,WAAW,EAAE,QAAQ,EAAE,CAAC,QAAQ,EAAE,MAAM,KAAK,IAAI,OAAE;IAC3D,CAAC,KAAK,EAAE,cAA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EAC3C,EACC,cAAsC,EACtC,uBAAwD,GACxD,GAAE,QAAQ,CAAC,OAAO,CAAC,qBAAqB,CAAC,CAAM,EAC/B,iBAAiB,CAAC,qBAAS;IAc7C;;;OAGG;IACI,KAAK,IAAI,IAAI;IAKpB,OAAO,CAAC,QAAQ,CAAC,eAAe,CAM9B;IAEF,OAAO,CAAC,QAAQ,CAAC,kBAAkB,CAEjC;IAEF,OAAO,CAAC,MAAM,CAAC,QAAQ,CAAC,mBAAmB,CACsC;IAEjF,OAAO,CAAC,uBAAuB;IA8B/B,OAAO,CAAC,QAAQ,CAAC,iBAAiB,CA+BhC;IAEF,OAAO,CAAC,kBAAkB;IAwH1B,OAAO,CAAC,IAAI;IAWZ;;;;OAIG;YACW,6BAA6B;IAuD3C,SAAgB,iBAAiB,EAAE,WAAW,CAAC,mBAAmB,CAAC,CAMjE;IAEF,SAAgB,gBAAgB,EAAE,WAAW,CAAC,kBAAkB,CAAC,CAM/D;IAEK,OAAO;CAMd"}
@@ -89,7 +89,9 @@ export class SummaryManager {
89
89
  }
90
90
  return this.summarizer.enqueueSummarize(...args);
91
91
  };
92
- this.logger = ChildLogger.create(parentLogger, "SummaryManager", { all: { clientId: () => this.latestClientId } });
92
+ this.logger = ChildLogger.create(parentLogger, "SummaryManager", {
93
+ all: { clientId: () => this.latestClientId },
94
+ });
93
95
  this.connectedState.on("connected", this.handleConnected);
94
96
  this.connectedState.on("disconnected", this.handleDisconnected);
95
97
  this.latestClientId = this.connectedState.clientId;
@@ -99,7 +101,9 @@ export class SummaryManager {
99
101
  get disposed() {
100
102
  return this._disposed;
101
103
  }
102
- get currentState() { return this.state; }
104
+ get currentState() {
105
+ return this.state;
106
+ }
103
107
  /**
104
108
  * Until start is called, the SummaryManager won't begin attempting to start summarization. This ensures there's
105
109
  * a window between construction and starting where the caller can attach listeners.
@@ -136,7 +140,8 @@ export class SummaryManager {
136
140
  assert(this.state === SummaryManagerState.Off, 0x261 /* "Expected: off" */);
137
141
  this.state = SummaryManagerState.Starting;
138
142
  assert(this.summarizer === undefined, 0x262 /* "Old summarizer is still working!" */);
139
- this.delayBeforeCreatingSummarizer().then(async (startWithInitialDelay) => {
143
+ this.delayBeforeCreatingSummarizer()
144
+ .then(async (startWithInitialDelay) => {
140
145
  // Re-validate that it need to be running. Due to asynchrony, it may be not the case anymore
141
146
  // but only if creation was delayed. If it was not, then we want to ensure we always create
142
147
  // a summarizer to kick off lastSummary. Without that, we would not be able to summarize and get
@@ -165,7 +170,8 @@ export class SummaryManager {
165
170
  // In order to allow the last summary to run, we not only need a stop reason that would
166
171
  // allow it but also, startWithInitialDelay to be false (start the summarization immediately),
167
172
  // which would happen when we have a high enough number of unsummarized ops.
168
- if (startWithInitialDelay || !Summarizer.stopReasonCanRunLastSummary(shouldSummarizeState.stopReason)) {
173
+ if (startWithInitialDelay ||
174
+ !Summarizer.stopReasonCanRunLastSummary(shouldSummarizeState.stopReason)) {
169
175
  this.state = SummaryManagerState.Starting;
170
176
  summarizer.stop(shouldSummarizeState.stopReason);
171
177
  return `early exit after starting summarizer ${shouldSummarizeState.stopReason}`;
@@ -177,12 +183,14 @@ export class SummaryManager {
177
183
  // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
178
184
  const clientId = this.latestClientId;
179
185
  return PerformanceEvent.timedExecAsync(this.logger, { eventName: "RunningSummarizer", attempt: this.startThrottler.numAttempts }, async () => summarizer.run(clientId, this.disableHeuristics));
180
- }).then((reason) => {
186
+ })
187
+ .then((reason) => {
181
188
  this.logger.sendTelemetryEvent({
182
189
  eventName: "EndingSummarizer",
183
190
  reason,
184
191
  });
185
- }).catch((error) => {
192
+ })
193
+ .catch((error) => {
186
194
  this.logger.sendTelemetryEvent({
187
195
  eventName: "EndingSummarizer",
188
196
  reason: "exception",
@@ -195,7 +203,8 @@ export class SummaryManager {
195
203
  // means it also lost connection), and error happened on load (we do not have summarizer).
196
204
  // We could annotate the error raised in Container.load where the container closed during load with no error
197
205
  // and check for that case here, but that does not seem to be necessary.
198
- if (this.getShouldSummarizeState().shouldSummarize || this.summarizer !== undefined) {
206
+ if (this.getShouldSummarizeState().shouldSummarize ||
207
+ this.summarizer !== undefined) {
199
208
  // Report any failure as an error unless it was due to cancellation (like "disconnected" error)
200
209
  // If failure happened on container load, we may not yet realized that socket disconnected, so check
201
210
  // offlineError.
@@ -205,7 +214,8 @@ export class SummaryManager {
205
214
  category,
206
215
  }, error);
207
216
  }
208
- }).finally(() => {
217
+ })
218
+ .finally(() => {
209
219
  var _a;
210
220
  assert(this.state !== SummaryManagerState.Off, 0x264 /* "Expected: Not Off" */);
211
221
  this.state = SummaryManagerState.Off;
@@ -273,7 +283,9 @@ export class SummaryManager {
273
283
  timer = setTimeout(() => resolve(), delayMs);
274
284
  });
275
285
  // Create a Promise that will resolve if the ops count passes the threshold.
276
- const opPromise = new Promise((resolve) => { resolveOpPromiseFn = resolve; });
286
+ const opPromise = new Promise((resolve) => {
287
+ resolveOpPromiseFn = resolve;
288
+ });
277
289
  this.summaryCollection.addOpListener(opsListenerFn);
278
290
  await Promise.race([delayPromise, opPromise]);
279
291
  this.summaryCollection.removeOpListener(opsListenerFn);
@@ -1 +1 @@
1
- {"version":3,"file":"summaryManager.js","sourceRoot":"","sources":["../src/summaryManager.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAGH,OAAO,EAAE,MAAM,EAAE,MAAM,8BAA8B,CAAC;AACtD,OAAO,EAAE,WAAW,EAAE,gBAAgB,EAAE,MAAM,iCAAiC,CAAC;AAChF,OAAO,EAAE,eAAe,EAAE,MAAM,oCAAoC,CAAC;AAQrE,OAAO,EAAE,UAAU,EAAE,MAAM,cAAc,CAAC;AAE1C,MAAM,qBAAqB,GAAG,IAAI,CAAC;AACnC,MAAM,8BAA8B,GAAG,IAAI,CAAC;AAE5C,MAAM,CAAN,IAAY,mBAKX;AALD,WAAY,mBAAmB;IAC3B,2DAAO,CAAA;IACP,qEAAY,CAAA;IACZ,mEAAW,CAAA;IACX,qEAAY,CAAA;AAChB,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,kBAAkB,GAAG,OAAO,CAAC,CAAC,CAAC,CAAC,CAAC;YACpF,IAAI,CAAC,iBAAiB,CAAC,aAAa,CAAC,aAAa,CAAC,CAAC;YACpD,MAAM,OAAO,CAAC,IAAI,CAAC,CAAC,YAAY,EAAE,SAAS,CAAC,CAAC,CAAC;YAC9C,IAAI,CAAC,iBAAiB,CAAC,gBAAgB,CAAC,aAAa,CAAC,CAAC;SAC1D;QACD,OAAO,qBAAqB,CAAC;IACjC,CAAC;IAkBM,OAAO;QACV,IAAI,CAAC,cAAc,CAAC,GAAG,CAAC,0BAA0B,EAAE,IAAI,CAAC,iBAAiB,CAAC,CAAC;QAC5E,IAAI,CAAC,cAAc,CAAC,GAAG,CAAC,WAAW,EAAE,IAAI,CAAC,eAAe,CAAC,CAAC;QAC3D,IAAI,CAAC,cAAc,CAAC,GAAG,CAAC,cAAc,EAAE,IAAI,CAAC,kBAAkB,CAAC,CAAC;QACjE,IAAI,CAAC,SAAS,GAAG,IAAI,CAAC;IAC1B,CAAC;;AAhQuB,kCAAmB,GAAG,CAAC,KAA0B,EAAE,EAAE,CACzE,KAAK,KAAK,mBAAmB,CAAC,QAAQ,IAAI,KAAK,KAAK,mBAAmB,CAAC,OAAO,CAAC","sourcesContent":["/*!\n * Copyright (c) Microsoft Corporation and contributors. All rights reserved.\n * Licensed under the MIT License.\n */\n\nimport { IDisposable, IEvent, IEventProvider, ITelemetryLogger } from \"@fluidframework/common-definitions\";\nimport { assert } from \"@fluidframework/common-utils\";\nimport { ChildLogger, PerformanceEvent } from \"@fluidframework/telemetry-utils\";\nimport { DriverErrorType } from \"@fluidframework/driver-definitions\";\nimport { ISummarizerClientElection } from \"./summarizerClientElection\";\nimport { IThrottler } from \"./throttler\";\nimport {\n ISummarizer,\n SummarizerStopReason,\n} from \"./summarizerTypes\";\nimport { SummaryCollection } from \"./summaryCollection\";\nimport { Summarizer } from \"./summarizer\";\n\nconst defaultInitialDelayMs = 5000;\nconst defaultOpsToBypassInitialDelay = 4000;\n\nexport enum SummaryManagerState {\n Off = 0,\n Starting = 1,\n Running = 2,\n Stopping = 3,\n}\n\n// Please note that all reasons in this list are not errors,\n// and thus they are not raised today to parent container as error.\n// If this needs to be changed in future, we should re-evaluate what and how we raise to summarizer\ntype StopReason = Extract<SummarizerStopReason,\n \"parentNotConnected\" | \"notElectedParent\" | \"notElectedClient\">;\ntype ShouldSummarizeState =\n | { shouldSummarize: true; }\n | { shouldSummarize: false; stopReason: StopReason; };\n\nexport interface IConnectedEvents extends IEvent {\n (event: \"connected\", listener: (clientId: string) => void);\n (event: \"disconnected\", listener: () => void);\n}\n\n/**\n * IConnectedState describes an object that SummaryManager can watch to observe connection/disconnection.\n *\n * Under current implementation, its role will be fulfilled by the ContainerRuntime, but this could be replaced\n * with anything else that fulfills the contract if we want to shift the layer that the SummaryManager lives at.\n */\nexport interface IConnectedState extends IEventProvider<IConnectedEvents> {\n readonly connected: boolean;\n\n /**\n * Under current implementation this is undefined if we've never connected, otherwise it's the clientId from our\n * latest connection (even if we've since disconnected!). Although this happens to be the behavior we want in\n * SummaryManager, I suspect that globally we may eventually want to modify this behavior (e.g. make clientId\n * undefined while disconnected). To protect against this, let's assume this field can't be trusted while\n * disconnected and instead separately track \"latest clientId\" in SummaryManager.\n */\n readonly clientId: string | undefined;\n}\n\nexport interface ISummaryManagerConfig {\n initialDelayMs: number;\n opsToBypassInitialDelay: number;\n}\n\n/**\n * SummaryManager is created by parent container (i.e. interactive container with clientType !== \"summarizer\") only.\n * It observes changes in calculated summarizer and reacts to changes by either creating summarizer client or\n * stopping existing summarizer client.\n */\nexport class SummaryManager implements IDisposable {\n private readonly logger: ITelemetryLogger;\n private readonly opsToBypassInitialDelay: number;\n private readonly initialDelayMs: number;\n private latestClientId: string | undefined;\n private state = SummaryManagerState.Off;\n private summarizer?: ISummarizer;\n private _disposed = false;\n\n public get disposed() {\n return this._disposed;\n }\n\n public get currentState() { return this.state; }\n\n constructor(\n private readonly clientElection: ISummarizerClientElection,\n private readonly connectedState: IConnectedState,\n private readonly summaryCollection:\n Pick<SummaryCollection, \"opsSinceLastAck\" | \"addOpListener\" | \"removeOpListener\">,\n parentLogger: ITelemetryLogger,\n /** Creates summarizer by asking interactive container to spawn summarizing container and\n * get back its Summarizer instance. */\n private readonly requestSummarizerFn: () => Promise<ISummarizer>,\n private readonly startThrottler: IThrottler,\n {\n initialDelayMs = defaultInitialDelayMs,\n opsToBypassInitialDelay = defaultOpsToBypassInitialDelay,\n }: Readonly<Partial<ISummaryManagerConfig>> = {},\n private readonly disableHeuristics?: boolean,\n ) {\n this.logger = ChildLogger.create(\n parentLogger,\n \"SummaryManager\",\n { all: { clientId: () => this.latestClientId } });\n\n this.connectedState.on(\"connected\", this.handleConnected);\n this.connectedState.on(\"disconnected\", this.handleDisconnected);\n this.latestClientId = this.connectedState.clientId;\n\n this.opsToBypassInitialDelay = opsToBypassInitialDelay;\n this.initialDelayMs = initialDelayMs;\n }\n\n /**\n * Until start is called, the SummaryManager won't begin attempting to start summarization. This ensures there's\n * a window between construction and starting where the caller can attach listeners.\n */\n public start(): void {\n this.clientElection.on(\"electedSummarizerChanged\", this.refreshSummarizer);\n this.refreshSummarizer();\n }\n\n private readonly handleConnected = (clientId: string) => {\n this.latestClientId = clientId;\n // If we have a summarizer, it should have been either cancelled on disconnected by now.\n // But because of lastSummary process, it can still hang around, so there is not much we can\n // check or assert.\n this.refreshSummarizer();\n };\n\n private readonly handleDisconnected = () => {\n this.refreshSummarizer();\n };\n\n private static readonly isStartingOrRunning = (state: SummaryManagerState) =>\n state === SummaryManagerState.Starting || state === SummaryManagerState.Running;\n\n private getShouldSummarizeState(): ShouldSummarizeState {\n // Note that if we're in the Running state, the electedClient may be a summarizer client, so we can't\n // enforce connectedState.clientId === clientElection.electedClientId. But once we're Running, we should\n // only transition to Stopping when the electedParentId changes. Stopping the summarizer without\n // changing the electedParent will just cause us to transition to Starting again.\n\n // New Parent has been elected and it is not the current client, or\n if (this.connectedState.clientId !== this.clientElection.electedParentId) {\n return { shouldSummarize: false, stopReason: \"notElectedParent\" };\n }\n\n // We are not already running the summarizer and we are not the current elected client id.\n if (this.state !== SummaryManagerState.Running &&\n this.connectedState.clientId !== this.clientElection.electedClientId) {\n return { shouldSummarize: false, stopReason: \"notElectedClient\" };\n }\n\n if (!this.connectedState.connected) {\n return { shouldSummarize: false, stopReason: \"parentNotConnected\" };\n }\n\n if (this.disposed) {\n assert(false, 0x260 /* \"Disposed should mean disconnected!\" */);\n } else {\n return { shouldSummarize: true };\n }\n }\n\n private readonly refreshSummarizer = () => {\n // Transition states depending on shouldSummarize, which is a calculated property\n // that is only true if this client is connected and is the elected summarizer.\n const shouldSummarizeState = this.getShouldSummarizeState();\n switch (this.state) {\n case SummaryManagerState.Off: {\n if (shouldSummarizeState.shouldSummarize) {\n this.startSummarization();\n }\n return;\n }\n case SummaryManagerState.Starting: {\n // Cannot take any action until summarizer is created\n // state transition will occur after creation\n return;\n }\n case SummaryManagerState.Running: {\n if (shouldSummarizeState.shouldSummarize === false) {\n this.stop(shouldSummarizeState.stopReason);\n }\n return;\n }\n case SummaryManagerState.Stopping: {\n // Cannot take any action until running summarizer finishes\n // state transition will occur after it stops\n return;\n }\n default: {\n return;\n }\n }\n };\n\n private startSummarization() {\n assert(this.state === SummaryManagerState.Off, 0x261 /* \"Expected: off\" */);\n this.state = SummaryManagerState.Starting;\n\n assert(this.summarizer === undefined, 0x262 /* \"Old summarizer is still working!\" */);\n\n this.delayBeforeCreatingSummarizer().then(async (startWithInitialDelay: boolean) => {\n // Re-validate that it need to be running. Due to asynchrony, it may be not the case anymore\n // but only if creation was delayed. If it was not, then we want to ensure we always create\n // a summarizer to kick off lastSummary. Without that, we would not be able to summarize and get\n // document out of broken state if it has too many ops and ordering service keeps nacking main\n // container (and thus it goes into cycle of reconnects)\n // If we can't run the LastSummary, simply return as to avoid paying the cost of launching\n // the summarizer at all.\n const shouldSummarizeStateEarlyStage = this.getShouldSummarizeState();\n if (startWithInitialDelay &&\n shouldSummarizeStateEarlyStage.shouldSummarize === false) {\n return `early exit ${shouldSummarizeStateEarlyStage.stopReason}`;\n }\n\n // We transition to Running before requesting the summarizer, because after requesting we can't predict\n // when the electedClient will be replaced with the new summarizer client.\n // The alternative would be to let connectedState.clientId !== clientElection.electedClientId when\n // state === Starting || state === Running.\n assert(this.state === SummaryManagerState.Starting, 0x263 /* \"Expected: starting\" */);\n this.state = SummaryManagerState.Running;\n\n const summarizer = await this.requestSummarizerFn();\n this.summarizer = summarizer;\n\n // Re-validate that it need to be running. Due to asynchrony, it may be not the case anymore\n // If we can't run the LastSummary, simply return as to avoid paying the cost of launching\n // the summarizer at all.\n const shouldSummarizeState = this.getShouldSummarizeState();\n if (shouldSummarizeState.shouldSummarize === false) {\n // In order to allow the last summary to run, we not only need a stop reason that would\n // allow it but also, startWithInitialDelay to be false (start the summarization immediately),\n // which would happen when we have a high enough number of unsummarized ops.\n if (startWithInitialDelay || !Summarizer.stopReasonCanRunLastSummary(shouldSummarizeState.stopReason)) {\n this.state = SummaryManagerState.Starting;\n summarizer.stop(shouldSummarizeState.stopReason);\n return `early exit after starting summarizer ${shouldSummarizeState.stopReason}`;\n }\n this.logger.sendTelemetryEvent({\n eventName: \"LastAttemptToSummarize\",\n });\n }\n\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n const clientId = this.latestClientId!;\n\n return PerformanceEvent.timedExecAsync(\n this.logger,\n { eventName: \"RunningSummarizer\", attempt: this.startThrottler.numAttempts },\n async () => summarizer.run(clientId, this.disableHeuristics),\n );\n }).then((reason: string) => {\n this.logger.sendTelemetryEvent({\n eventName: \"EndingSummarizer\",\n reason,\n });\n }).catch((error) => {\n this.logger.sendTelemetryEvent(\n {\n eventName: \"EndingSummarizer\",\n reason: \"exception\",\n },\n error);\n\n // Most of exceptions happen due to container being closed while loading it, due to\n // summarizer container loosing connection while load.\n // Not worth reporting such errors as errors. That said, we might miss some real errors if\n // we ignore blindly, so try to narrow signature we are looking for - skip logging\n // error only if this client should no longer be a summarizer (which in practice\n // means it also lost connection), and error happened on load (we do not have summarizer).\n // We could annotate the error raised in Container.load where the container closed during load with no error\n // and check for that case here, but that does not seem to be necessary.\n if (this.getShouldSummarizeState().shouldSummarize || this.summarizer !== undefined) {\n // Report any failure as an error unless it was due to cancellation (like \"disconnected\" error)\n // If failure happened on container load, we may not yet realized that socket disconnected, so check\n // offlineError.\n const category = error?.errorType === DriverErrorType.offlineError ? \"generic\" : \"error\";\n this.logger.sendTelemetryEvent(\n {\n eventName: \"SummarizerException\",\n category,\n },\n error);\n }\n }).finally(() => {\n assert(this.state !== SummaryManagerState.Off, 0x264 /* \"Expected: Not Off\" */);\n this.state = SummaryManagerState.Off;\n\n this.summarizer?.close();\n this.summarizer = undefined;\n\n if (this.getShouldSummarizeState().shouldSummarize) {\n this.startSummarization();\n }\n });\n }\n\n private stop(reason: SummarizerStopReason) {\n if (!SummaryManager.isStartingOrRunning(this.state)) {\n return;\n }\n this.state = SummaryManagerState.Stopping;\n\n // Stopping the running summarizer client should trigger a change\n // in states when the running summarizer closes\n this.summarizer?.stop(reason);\n }\n\n /**\n * Implements initial delay before creating summarizer\n * @returns `true`, if creation is delayed due to heuristics (not many ops to summarize).\n * `false` if summarizer should start immediately due to too many unsummarized ops.\n */\n private async delayBeforeCreatingSummarizer(): Promise<boolean> {\n // throttle creation of new summarizer containers to prevent spamming the server with websocket connections\n let delayMs = this.startThrottler.getDelay();\n\n // We have been elected the summarizer. Some day we may be able to summarize with a live document but for\n // now we play it safe and launch a second copy.\n this.logger.sendTelemetryEvent({\n eventName: \"CreatingSummarizer\",\n throttlerDelay: delayMs,\n initialDelay: this.initialDelayMs,\n startThrottlerMaxDelayMs: this.startThrottler.maxDelayMs,\n opsSinceLastAck: this.summaryCollection.opsSinceLastAck,\n opsToBypassInitialDelay: this.opsToBypassInitialDelay,\n });\n\n // This delay helps ensure that last summarizer that might be left from previous client\n // has enough time to complete its last summary and thus new summarizer not conflict with previous one.\n // If, however, there are too many unsummarized ops, try to resolve it as quickly as possible, with\n // understanding that we may see nacks because of such quick action.\n // A better design would be for summarizer election logic to always select current summarizer as\n // summarizing client (i.e. clientType === \"summarizer\" can be elected) to ensure that nobody else can\n // summarizer while it finishes its work and moves to exit.\n // It also helps with pure boot scenario (single client) to offset expensive work a bit out from\n // critical boot sequence.\n let startWithInitialDelay = false;\n if (this.summaryCollection.opsSinceLastAck < this.opsToBypassInitialDelay) {\n startWithInitialDelay = true;\n delayMs = Math.max(delayMs, this.initialDelayMs);\n }\n\n if (delayMs > 0) {\n let timer;\n let resolveOpPromiseFn;\n // Create a listener that will break the delay if we've exceeded the initial delay ops count.\n const opsListenerFn = () => {\n if (this.summaryCollection.opsSinceLastAck >= this.opsToBypassInitialDelay) {\n clearTimeout(timer);\n resolveOpPromiseFn();\n }\n };\n // Create a Promise that will resolve when the delay expires.\n const delayPromise = new Promise<void>((resolve) => {\n timer = setTimeout(() => resolve(), delayMs);\n });\n // Create a Promise that will resolve if the ops count passes the threshold.\n const opPromise = new Promise<void>((resolve) => { resolveOpPromiseFn = resolve; });\n this.summaryCollection.addOpListener(opsListenerFn);\n await Promise.race([delayPromise, opPromise]);\n this.summaryCollection.removeOpListener(opsListenerFn);\n }\n return startWithInitialDelay;\n }\n\n public readonly summarizeOnDemand: ISummarizer[\"summarizeOnDemand\"] = (...args) => {\n if (this.summarizer === undefined) {\n throw Error(\"No running summarizer client\");\n // TODO: could spawn a summarizer client temporarily.\n }\n return this.summarizer.summarizeOnDemand(...args);\n };\n\n public readonly enqueueSummarize: ISummarizer[\"enqueueSummarize\"] = (...args) => {\n if (this.summarizer === undefined) {\n throw Error(\"No running summarizer client\");\n // TODO: could spawn a summarizer client temporarily.\n }\n return this.summarizer.enqueueSummarize(...args);\n };\n\n public dispose() {\n this.clientElection.off(\"electedSummarizerChanged\", this.refreshSummarizer);\n this.connectedState.off(\"connected\", this.handleConnected);\n this.connectedState.off(\"disconnected\", this.handleDisconnected);\n this._disposed = true;\n }\n}\n"]}
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AK,KAAK,mBAAmB,CAAC,OAAO,CAAC","sourcesContent":["/*!\n * Copyright (c) Microsoft Corporation and contributors. All rights reserved.\n * Licensed under the MIT License.\n */\n\nimport {\n\tIDisposable,\n\tIEvent,\n\tIEventProvider,\n\tITelemetryLogger,\n} from \"@fluidframework/common-definitions\";\nimport { assert } from \"@fluidframework/common-utils\";\nimport { ChildLogger, PerformanceEvent } from \"@fluidframework/telemetry-utils\";\nimport { DriverErrorType } from \"@fluidframework/driver-definitions\";\nimport { ISummarizerClientElection } from \"./summarizerClientElection\";\nimport { IThrottler } from \"./throttler\";\nimport { ISummarizer, SummarizerStopReason } from \"./summarizerTypes\";\nimport { SummaryCollection } from \"./summaryCollection\";\nimport { Summarizer } from \"./summarizer\";\n\nconst defaultInitialDelayMs = 5000;\nconst defaultOpsToBypassInitialDelay = 4000;\n\nexport enum SummaryManagerState {\n\tOff = 0,\n\tStarting = 1,\n\tRunning = 2,\n\tStopping = 3,\n}\n\n// Please note that all reasons in this list are not errors,\n// and thus they are not raised today to parent container as error.\n// If this needs to be changed in future, we should re-evaluate what and how we raise to summarizer\ntype StopReason = Extract<\n\tSummarizerStopReason,\n\t\"parentNotConnected\" | \"notElectedParent\" | \"notElectedClient\"\n>;\ntype ShouldSummarizeState =\n\t| { shouldSummarize: true }\n\t| { shouldSummarize: false; stopReason: StopReason };\n\nexport interface IConnectedEvents extends IEvent {\n\t(event: \"connected\", listener: (clientId: string) => void);\n\t(event: \"disconnected\", listener: () => void);\n}\n\n/**\n * IConnectedState describes an object that SummaryManager can watch to observe connection/disconnection.\n *\n * Under current implementation, its role will be fulfilled by the ContainerRuntime, but this could be replaced\n * with anything else that fulfills the contract if we want to shift the layer that the SummaryManager lives at.\n */\nexport interface IConnectedState extends IEventProvider<IConnectedEvents> {\n\treadonly connected: boolean;\n\n\t/**\n\t * Under current implementation this is undefined if we've never connected, otherwise it's the clientId from our\n\t * latest connection (even if we've since disconnected!). Although this happens to be the behavior we want in\n\t * SummaryManager, I suspect that globally we may eventually want to modify this behavior (e.g. make clientId\n\t * undefined while disconnected). To protect against this, let's assume this field can't be trusted while\n\t * disconnected and instead separately track \"latest clientId\" in SummaryManager.\n\t */\n\treadonly clientId: string | undefined;\n}\n\nexport interface ISummaryManagerConfig {\n\tinitialDelayMs: number;\n\topsToBypassInitialDelay: number;\n}\n\n/**\n * SummaryManager is created by parent container (i.e. interactive container with clientType !== \"summarizer\") only.\n * It observes changes in calculated summarizer and reacts to changes by either creating summarizer client or\n * stopping existing summarizer client.\n */\nexport class SummaryManager implements IDisposable {\n\tprivate readonly logger: ITelemetryLogger;\n\tprivate readonly opsToBypassInitialDelay: number;\n\tprivate readonly initialDelayMs: number;\n\tprivate latestClientId: string | undefined;\n\tprivate state = SummaryManagerState.Off;\n\tprivate summarizer?: ISummarizer;\n\tprivate _disposed = false;\n\n\tpublic get disposed() {\n\t\treturn this._disposed;\n\t}\n\n\tpublic get currentState() {\n\t\treturn this.state;\n\t}\n\n\tconstructor(\n\t\tprivate readonly clientElection: ISummarizerClientElection,\n\t\tprivate readonly connectedState: IConnectedState,\n\t\tprivate readonly summaryCollection: Pick<\n\t\t\tSummaryCollection,\n\t\t\t\"opsSinceLastAck\" | \"addOpListener\" | \"removeOpListener\"\n\t\t>,\n\t\tparentLogger: ITelemetryLogger,\n\t\t/** Creates summarizer by asking interactive container to spawn summarizing container and\n\t\t * get back its Summarizer instance. */\n\t\tprivate readonly requestSummarizerFn: () => Promise<ISummarizer>,\n\t\tprivate readonly startThrottler: IThrottler,\n\t\t{\n\t\t\tinitialDelayMs = defaultInitialDelayMs,\n\t\t\topsToBypassInitialDelay = defaultOpsToBypassInitialDelay,\n\t\t}: Readonly<Partial<ISummaryManagerConfig>> = {},\n\t\tprivate readonly disableHeuristics?: boolean,\n\t) {\n\t\tthis.logger = ChildLogger.create(parentLogger, \"SummaryManager\", {\n\t\t\tall: { clientId: () => this.latestClientId },\n\t\t});\n\n\t\tthis.connectedState.on(\"connected\", this.handleConnected);\n\t\tthis.connectedState.on(\"disconnected\", this.handleDisconnected);\n\t\tthis.latestClientId = this.connectedState.clientId;\n\n\t\tthis.opsToBypassInitialDelay = opsToBypassInitialDelay;\n\t\tthis.initialDelayMs = initialDelayMs;\n\t}\n\n\t/**\n\t * Until start is called, the SummaryManager won't begin attempting to start summarization. This ensures there's\n\t * a window between construction and starting where the caller can attach listeners.\n\t */\n\tpublic start(): void {\n\t\tthis.clientElection.on(\"electedSummarizerChanged\", this.refreshSummarizer);\n\t\tthis.refreshSummarizer();\n\t}\n\n\tprivate readonly handleConnected = (clientId: string) => {\n\t\tthis.latestClientId = clientId;\n\t\t// If we have a summarizer, it should have been either cancelled on disconnected by now.\n\t\t// But because of lastSummary process, it can still hang around, so there is not much we can\n\t\t// check or assert.\n\t\tthis.refreshSummarizer();\n\t};\n\n\tprivate readonly handleDisconnected = () => {\n\t\tthis.refreshSummarizer();\n\t};\n\n\tprivate static readonly isStartingOrRunning = (state: SummaryManagerState) =>\n\t\tstate === SummaryManagerState.Starting || state === SummaryManagerState.Running;\n\n\tprivate getShouldSummarizeState(): ShouldSummarizeState {\n\t\t// Note that if we're in the Running state, the electedClient may be a summarizer client, so we can't\n\t\t// enforce connectedState.clientId === clientElection.electedClientId. But once we're Running, we should\n\t\t// only transition to Stopping when the electedParentId changes. Stopping the summarizer without\n\t\t// changing the electedParent will just cause us to transition to Starting again.\n\n\t\t// New Parent has been elected and it is not the current client, or\n\t\tif (this.connectedState.clientId !== this.clientElection.electedParentId) {\n\t\t\treturn { shouldSummarize: false, stopReason: \"notElectedParent\" };\n\t\t}\n\n\t\t// We are not already running the summarizer and we are not the current elected client id.\n\t\tif (\n\t\t\tthis.state !== SummaryManagerState.Running &&\n\t\t\tthis.connectedState.clientId !== this.clientElection.electedClientId\n\t\t) {\n\t\t\treturn { shouldSummarize: false, stopReason: \"notElectedClient\" };\n\t\t}\n\n\t\tif (!this.connectedState.connected) {\n\t\t\treturn { shouldSummarize: false, stopReason: \"parentNotConnected\" };\n\t\t}\n\n\t\tif (this.disposed) {\n\t\t\tassert(false, 0x260 /* \"Disposed should mean disconnected!\" */);\n\t\t} else {\n\t\t\treturn { shouldSummarize: true };\n\t\t}\n\t}\n\n\tprivate readonly refreshSummarizer = () => {\n\t\t// Transition states depending on shouldSummarize, which is a calculated property\n\t\t// that is only true if this client is connected and is the elected summarizer.\n\t\tconst shouldSummarizeState = this.getShouldSummarizeState();\n\t\tswitch (this.state) {\n\t\t\tcase SummaryManagerState.Off: {\n\t\t\t\tif (shouldSummarizeState.shouldSummarize) {\n\t\t\t\t\tthis.startSummarization();\n\t\t\t\t}\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tcase SummaryManagerState.Starting: {\n\t\t\t\t// Cannot take any action until summarizer is created\n\t\t\t\t// state transition will occur after creation\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tcase SummaryManagerState.Running: {\n\t\t\t\tif (shouldSummarizeState.shouldSummarize === false) {\n\t\t\t\t\tthis.stop(shouldSummarizeState.stopReason);\n\t\t\t\t}\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tcase SummaryManagerState.Stopping: {\n\t\t\t\t// Cannot take any action until running summarizer finishes\n\t\t\t\t// state transition will occur after it stops\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tdefault: {\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\t};\n\n\tprivate startSummarization() {\n\t\tassert(this.state === SummaryManagerState.Off, 0x261 /* \"Expected: off\" */);\n\t\tthis.state = SummaryManagerState.Starting;\n\n\t\tassert(this.summarizer === undefined, 0x262 /* \"Old summarizer is still working!\" */);\n\n\t\tthis.delayBeforeCreatingSummarizer()\n\t\t\t.then(async (startWithInitialDelay: boolean) => {\n\t\t\t\t// Re-validate that it need to be running. Due to asynchrony, it may be not the case anymore\n\t\t\t\t// but only if creation was delayed. If it was not, then we want to ensure we always create\n\t\t\t\t// a summarizer to kick off lastSummary. Without that, we would not be able to summarize and get\n\t\t\t\t// document out of broken state if it has too many ops and ordering service keeps nacking main\n\t\t\t\t// container (and thus it goes into cycle of reconnects)\n\t\t\t\t// If we can't run the LastSummary, simply return as to avoid paying the cost of launching\n\t\t\t\t// the summarizer at all.\n\t\t\t\tconst shouldSummarizeStateEarlyStage = this.getShouldSummarizeState();\n\t\t\t\tif (\n\t\t\t\t\tstartWithInitialDelay &&\n\t\t\t\t\tshouldSummarizeStateEarlyStage.shouldSummarize === false\n\t\t\t\t) {\n\t\t\t\t\treturn `early exit ${shouldSummarizeStateEarlyStage.stopReason}`;\n\t\t\t\t}\n\n\t\t\t\t// We transition to Running before requesting the summarizer, because after requesting we can't predict\n\t\t\t\t// when the electedClient will be replaced with the new summarizer client.\n\t\t\t\t// The alternative would be to let connectedState.clientId !== clientElection.electedClientId when\n\t\t\t\t// state === Starting || state === Running.\n\t\t\t\tassert(\n\t\t\t\t\tthis.state === SummaryManagerState.Starting,\n\t\t\t\t\t0x263 /* \"Expected: starting\" */,\n\t\t\t\t);\n\t\t\t\tthis.state = SummaryManagerState.Running;\n\n\t\t\t\tconst summarizer = await this.requestSummarizerFn();\n\t\t\t\tthis.summarizer = summarizer;\n\n\t\t\t\t// Re-validate that it need to be running. Due to asynchrony, it may be not the case anymore\n\t\t\t\t// If we can't run the LastSummary, simply return as to avoid paying the cost of launching\n\t\t\t\t// the summarizer at all.\n\t\t\t\tconst shouldSummarizeState = this.getShouldSummarizeState();\n\t\t\t\tif (shouldSummarizeState.shouldSummarize === false) {\n\t\t\t\t\t// In order to allow the last summary to run, we not only need a stop reason that would\n\t\t\t\t\t// allow it but also, startWithInitialDelay to be false (start the summarization immediately),\n\t\t\t\t\t// which would happen when we have a high enough number of unsummarized ops.\n\t\t\t\t\tif (\n\t\t\t\t\t\tstartWithInitialDelay ||\n\t\t\t\t\t\t!Summarizer.stopReasonCanRunLastSummary(shouldSummarizeState.stopReason)\n\t\t\t\t\t) {\n\t\t\t\t\t\tthis.state = SummaryManagerState.Starting;\n\t\t\t\t\t\tsummarizer.stop(shouldSummarizeState.stopReason);\n\t\t\t\t\t\treturn `early exit after starting summarizer ${shouldSummarizeState.stopReason}`;\n\t\t\t\t\t}\n\t\t\t\t\tthis.logger.sendTelemetryEvent({\n\t\t\t\t\t\teventName: \"LastAttemptToSummarize\",\n\t\t\t\t\t});\n\t\t\t\t}\n\n\t\t\t\t// eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n\t\t\t\tconst clientId = this.latestClientId!;\n\n\t\t\t\treturn PerformanceEvent.timedExecAsync(\n\t\t\t\t\tthis.logger,\n\t\t\t\t\t{ eventName: \"RunningSummarizer\", attempt: this.startThrottler.numAttempts },\n\t\t\t\t\tasync () => summarizer.run(clientId, this.disableHeuristics),\n\t\t\t\t);\n\t\t\t})\n\t\t\t.then((reason: string) => {\n\t\t\t\tthis.logger.sendTelemetryEvent({\n\t\t\t\t\teventName: \"EndingSummarizer\",\n\t\t\t\t\treason,\n\t\t\t\t});\n\t\t\t})\n\t\t\t.catch((error) => {\n\t\t\t\tthis.logger.sendTelemetryEvent(\n\t\t\t\t\t{\n\t\t\t\t\t\teventName: \"EndingSummarizer\",\n\t\t\t\t\t\treason: \"exception\",\n\t\t\t\t\t},\n\t\t\t\t\terror,\n\t\t\t\t);\n\n\t\t\t\t// Most of exceptions happen due to container being closed while loading it, due to\n\t\t\t\t// summarizer container loosing connection while load.\n\t\t\t\t// Not worth reporting such errors as errors. That said, we might miss some real errors if\n\t\t\t\t// we ignore blindly, so try to narrow signature we are looking for - skip logging\n\t\t\t\t// error only if this client should no longer be a summarizer (which in practice\n\t\t\t\t// means it also lost connection), and error happened on load (we do not have summarizer).\n\t\t\t\t// We could annotate the error raised in Container.load where the container closed during load with no error\n\t\t\t\t// and check for that case here, but that does not seem to be necessary.\n\t\t\t\tif (\n\t\t\t\t\tthis.getShouldSummarizeState().shouldSummarize ||\n\t\t\t\t\tthis.summarizer !== undefined\n\t\t\t\t) {\n\t\t\t\t\t// Report any failure as an error unless it was due to cancellation (like \"disconnected\" error)\n\t\t\t\t\t// If failure happened on container load, we may not yet realized that socket disconnected, so check\n\t\t\t\t\t// offlineError.\n\t\t\t\t\tconst category =\n\t\t\t\t\t\terror?.errorType === DriverErrorType.offlineError ? \"generic\" : \"error\";\n\t\t\t\t\tthis.logger.sendTelemetryEvent(\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\teventName: \"SummarizerException\",\n\t\t\t\t\t\t\tcategory,\n\t\t\t\t\t\t},\n\t\t\t\t\t\terror,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t})\n\t\t\t.finally(() => {\n\t\t\t\tassert(this.state !== SummaryManagerState.Off, 0x264 /* \"Expected: Not Off\" */);\n\t\t\t\tthis.state = SummaryManagerState.Off;\n\n\t\t\t\tthis.summarizer?.close();\n\t\t\t\tthis.summarizer = undefined;\n\n\t\t\t\tif (this.getShouldSummarizeState().shouldSummarize) {\n\t\t\t\t\tthis.startSummarization();\n\t\t\t\t}\n\t\t\t});\n\t}\n\n\tprivate stop(reason: SummarizerStopReason) {\n\t\tif (!SummaryManager.isStartingOrRunning(this.state)) {\n\t\t\treturn;\n\t\t}\n\t\tthis.state = SummaryManagerState.Stopping;\n\n\t\t// Stopping the running summarizer client should trigger a change\n\t\t// in states when the running summarizer closes\n\t\tthis.summarizer?.stop(reason);\n\t}\n\n\t/**\n\t * Implements initial delay before creating summarizer\n\t * @returns `true`, if creation is delayed due to heuristics (not many ops to summarize).\n\t * `false` if summarizer should start immediately due to too many unsummarized ops.\n\t */\n\tprivate async delayBeforeCreatingSummarizer(): Promise<boolean> {\n\t\t// throttle creation of new summarizer containers to prevent spamming the server with websocket connections\n\t\tlet delayMs = this.startThrottler.getDelay();\n\n\t\t// We have been elected the summarizer. Some day we may be able to summarize with a live document but for\n\t\t// now we play it safe and launch a second copy.\n\t\tthis.logger.sendTelemetryEvent({\n\t\t\teventName: \"CreatingSummarizer\",\n\t\t\tthrottlerDelay: delayMs,\n\t\t\tinitialDelay: this.initialDelayMs,\n\t\t\tstartThrottlerMaxDelayMs: this.startThrottler.maxDelayMs,\n\t\t\topsSinceLastAck: this.summaryCollection.opsSinceLastAck,\n\t\t\topsToBypassInitialDelay: this.opsToBypassInitialDelay,\n\t\t});\n\n\t\t// This delay helps ensure that last summarizer that might be left from previous client\n\t\t// has enough time to complete its last summary and thus new summarizer not conflict with previous one.\n\t\t// If, however, there are too many unsummarized ops, try to resolve it as quickly as possible, with\n\t\t// understanding that we may see nacks because of such quick action.\n\t\t// A better design would be for summarizer election logic to always select current summarizer as\n\t\t// summarizing client (i.e. clientType === \"summarizer\" can be elected) to ensure that nobody else can\n\t\t// summarizer while it finishes its work and moves to exit.\n\t\t// It also helps with pure boot scenario (single client) to offset expensive work a bit out from\n\t\t// critical boot sequence.\n\t\tlet startWithInitialDelay = false;\n\t\tif (this.summaryCollection.opsSinceLastAck < this.opsToBypassInitialDelay) {\n\t\t\tstartWithInitialDelay = true;\n\t\t\tdelayMs = Math.max(delayMs, this.initialDelayMs);\n\t\t}\n\n\t\tif (delayMs > 0) {\n\t\t\tlet timer;\n\t\t\tlet resolveOpPromiseFn;\n\t\t\t// Create a listener that will break the delay if we've exceeded the initial delay ops count.\n\t\t\tconst opsListenerFn = () => {\n\t\t\t\tif (this.summaryCollection.opsSinceLastAck >= this.opsToBypassInitialDelay) {\n\t\t\t\t\tclearTimeout(timer);\n\t\t\t\t\tresolveOpPromiseFn();\n\t\t\t\t}\n\t\t\t};\n\t\t\t// Create a Promise that will resolve when the delay expires.\n\t\t\tconst delayPromise = new Promise<void>((resolve) => {\n\t\t\t\ttimer = setTimeout(() => resolve(), delayMs);\n\t\t\t});\n\t\t\t// Create a Promise that will resolve if the ops count passes the threshold.\n\t\t\tconst opPromise = new Promise<void>((resolve) => {\n\t\t\t\tresolveOpPromiseFn = resolve;\n\t\t\t});\n\t\t\tthis.summaryCollection.addOpListener(opsListenerFn);\n\t\t\tawait Promise.race([delayPromise, opPromise]);\n\t\t\tthis.summaryCollection.removeOpListener(opsListenerFn);\n\t\t}\n\t\treturn startWithInitialDelay;\n\t}\n\n\tpublic readonly summarizeOnDemand: ISummarizer[\"summarizeOnDemand\"] = (...args) => {\n\t\tif (this.summarizer === undefined) {\n\t\t\tthrow Error(\"No running summarizer client\");\n\t\t\t// TODO: could spawn a summarizer client temporarily.\n\t\t}\n\t\treturn this.summarizer.summarizeOnDemand(...args);\n\t};\n\n\tpublic readonly enqueueSummarize: ISummarizer[\"enqueueSummarize\"] = (...args) => {\n\t\tif (this.summarizer === undefined) {\n\t\t\tthrow Error(\"No running summarizer client\");\n\t\t\t// TODO: could spawn a summarizer client temporarily.\n\t\t}\n\t\treturn this.summarizer.enqueueSummarize(...args);\n\t};\n\n\tpublic dispose() {\n\t\tthis.clientElection.off(\"electedSummarizerChanged\", this.refreshSummarizer);\n\t\tthis.connectedState.off(\"connected\", this.handleConnected);\n\t\tthis.connectedState.off(\"disconnected\", this.handleDisconnected);\n\t\tthis._disposed = true;\n\t}\n}\n"]}
@@ -95,12 +95,12 @@ export declare const formExponentialFnWithAttemptOffset: (attemptOffset: number,
95
95
  * If not provided, coefficient will default to 1, and offset to 0, yielding:
96
96
  * 0 ms, 1 ms, 2 ms, 3 ms, ..., n ms delays; a linear back-off.
97
97
  */
98
- export declare const formLinearFn: ({ coefficient, offset, }?: {
98
+ export declare const formLinearFn: ({ coefficient, offset }?: {
99
99
  coefficient?: number | undefined;
100
100
  offset?: number | undefined;
101
101
  }) => IThrottler["delayFn"];
102
102
  /** f(n) = C x (n+A) + F = C x n + (C x A + F) */
103
- export declare const formLinearFnWithAttemptOffset: (attemptOffset: number, { coefficient, offset, }?: {
103
+ export declare const formLinearFnWithAttemptOffset: (attemptOffset: number, { coefficient, offset }?: {
104
104
  coefficient?: number | undefined;
105
105
  offset?: number | undefined;
106
106
  }) => (numAttempts: number) => number;
@@ -1 +1 @@
1
- {"version":3,"file":"throttler.d.ts","sourceRoot":"","sources":["../src/throttler.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,MAAM,WAAW,UAAU;IACvB;;;OA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6IzC,CAAC"}
package/lib/throttler.js CHANGED
@@ -52,7 +52,7 @@ export class Throttler {
52
52
  }
53
53
  }
54
54
  // Remove all attempts that have already fallen out of the window.
55
- this.startTimes = this.startTimes.filter((t) => (now - t) < this.delayWindowMs);
55
+ this.startTimes = this.startTimes.filter((t) => now - t < this.delayWindowMs);
56
56
  // Compute delay, but do not exceed the specified max delay.
57
57
  const delayMs = Math.min(this.delayFn(this.startTimes.length), this.maxDelayMs);
58
58
  // Record this attempt start time.
@@ -80,7 +80,7 @@ export class Throttler {
80
80
  */
81
81
  export const formExponentialFn = ({ multiplier = 2, coefficient = 1, offset = 0, initialDelay = undefined, } = {}) => (numAttempts) => Math.max(0, numAttempts <= 0 && initialDelay !== undefined
82
82
  ? initialDelay
83
- : coefficient * (Math.pow(multiplier, numAttempts)) + offset);
83
+ : coefficient * Math.pow(multiplier, numAttempts) + offset);
84
84
  /** f(n) = C x (B^(n+A)) + F = (C x B^A) x B^n + F */
85
85
  export const formExponentialFnWithAttemptOffset = (attemptOffset, { multiplier = 2, coefficient = 1, offset = 0, initialDelay = undefined, } = {}) => formExponentialFn({
86
86
  multiplier,
@@ -95,9 +95,9 @@ export const formExponentialFnWithAttemptOffset = (attemptOffset, { multiplier =
95
95
  * If not provided, coefficient will default to 1, and offset to 0, yielding:
96
96
  * 0 ms, 1 ms, 2 ms, 3 ms, ..., n ms delays; a linear back-off.
97
97
  */
98
- export const formLinearFn = ({ coefficient = 1, offset = 0, } = {}) => (numAttempts) => Math.max(0, coefficient * numAttempts + offset);
98
+ export const formLinearFn = ({ coefficient = 1, offset = 0 } = {}) => (numAttempts) => Math.max(0, coefficient * numAttempts + offset);
99
99
  /** f(n) = C x (n+A) + F = C x n + (C x A + F) */
100
- export const formLinearFnWithAttemptOffset = (attemptOffset, { coefficient = 1, offset = 0, } = {}) => formLinearFn({
100
+ export const formLinearFnWithAttemptOffset = (attemptOffset, { coefficient = 1, offset = 0 } = {}) => formLinearFn({
101
101
  coefficient,
102
102
  offset: coefficient * attemptOffset + offset,
103
103
  });
@@ -1 +1 @@
1
- {"version":3,"file":"throttler.js","sourceRoot":"","sources":["../src/throttler.ts"],"names":[],"mappings":"AAAA;;;GAGG;AA2BH;;;GAGG;AACH,MAAM,OAAO,SAAS;IAuBlB;IACI,qDAAqD;IACrC,aAAqB;IACrC,6CAA6C;IAC7B,UAAkB;IAClC;;;;OAIG;IACa,OAAwC;QARxC,kBAAa,GAAb,aAAa,CAAQ;QAErB,eAAU,GAAV,UAAU,CAAQ;QAMlB,YAAO,GAAP,OAAO,CAAiC;QAhCpD,eAAU,GAAa,EAAE,CAAC;IAiC9B,CAAC;IA/BL,IAAW,WAAW;QAClB,OAAO,IAAI,CAAC,UAAU,CAAC,MAAM,CAAC;IAClC,CAAC;IAED;;;OAGG;IACI,WAAW;QACd,OAAO,CAAC,GAAG,IAAI,CAAC,UAAU,CAAC,CAAC;IAChC,CAAC;IAED;;;OAGG;IACH,IAAW,iBAAiB;QACxB,OAAO,IAAI,CAAC,UAAU,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,UAAU,CAAC,IAAI,CAAC,UAAU,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC,SAAS,CAAC;IAChG,CAAC;IAeM,QAAQ;QACX,MAAM,GAAG,GAAG,IAAI,CAAC,GAAG,EAAE,CAAC;QAEvB,MAAM,iBAAiB,GAAG,IAAI,CAAC,iBAAiB,CAAC;QACjD,IAAI,iBAAiB,KAAK,SAAS,EAAE;YACjC,4DAA4D;YAC5D,6DAA6D;YAC7D,MAAM,OAAO,GAAG,iBAAiB,GAAG,GAAG,CAAC;YACxC,IAAI,OAAO,GAAG,CAAC,EAAE;gBACb,IAAI,CAAC,UAAU,GAAG,IAAI,CAAC,UAAU,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,GAAG,OAAO,CAAC,CAAC;aAC7D;SACJ;QAED,kEAAkE;QAClE,IAAI,CAA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CAAC,EACd,WAAW,GAAG,CAAC,EACf,MAAM,GAAG,CAAC,EACV,YAAY,GAAG,SAA+B,MAC9C,EAAE,EAAE,EAAE,CAAC,iBAAiB,CAAC;IACzB,UAAU;IACV,WAAW,EAAE,WAAW,GAAG,IAAI,CAAC,GAAG,CAAC,UAAU,EAAE,aAAa,CAAC;IAC9D,MAAM;IACN,YAAY;CACf,CAAC,CAAC;AAEH;;;;;;GAMG;AACH,MAAM,CAAC,MAAM,YAAY,GAAG,CAAC,EACzB,WAAW,GAAG,CAAC,EACf,MAAM,GAAG,CAAC,GACb,GAAG,EAAE,EAAyB,EAAE,CAAC,CAAC,WAAW,EAAE,EAAE,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC,EACzD,WAAW,GAAG,WAAW,GAAG,MAAM,CAAC,CAAC;AAExC,iDAAiD;AACjD,MAAM,CAAC,MAAM,6BAA6B,GAAG,CAAC,aAAqB,EAAE,EACjE,WAAW,GAAG,CAAC,EACf,MAAM,GAAG,CAAC,GACb,GAAG,EAAE,EAAE,EAAE,CAAC,YAAY,CAAC;IACpB,WAAW;IACX,MAAM,EAAE,WAAW,GAAG,aAAa,GAAG,MAAM;CAC/C,CAAC,CAAC","sourcesContent":["/*!\n * Copyright (c) Microsoft Corporation and contributors. All rights reserved.\n * Licensed under the MIT License.\n */\n\nexport interface IThrottler {\n /**\n * Computes what the throttle delay should be, and records an attempt\n * which will be used for calculating future attempt delays.\n */\n getDelay(): number;\n\n /**\n * Number of attempts that occurred within the sliding window as of\n * the most recent delay computation.\n */\n readonly numAttempts: number;\n\n /** Width of sliding delay window in milliseconds. */\n readonly delayWindowMs: number;\n /** Maximum delay allowed in milliseconds. */\n readonly maxDelayMs: number;\n /**\n * Delay function used to calculate what the delay should be.\n * The input is the number of attempts that occurred within the sliding window.\n * The result is the calculated delay in milliseconds.\n */\n readonly delayFn: (numAttempts: number) => number;\n}\n\n/**\n * Used to give increasing delay times for throttling a single functionality.\n * Delay is based on previous attempts within specified time window, subtracting delay time.\n */\nexport class Throttler implements IThrottler {\n private startTimes: number[] = [];\n\n public get numAttempts() {\n return this.startTimes.length;\n }\n\n /**\n * Gets all attempt start times after compensating for the delay times\n * by adding the delay times to the actual times.\n */\n public getAttempts(): readonly number[] {\n return [...this.startTimes];\n }\n\n /**\n * Latest attempt time after compensating for the delay time itself\n * by adding the delay time to the actual time.\n */\n public get latestAttemptTime() {\n return this.startTimes.length > 0 ? this.startTimes[this.startTimes.length - 1] : undefined;\n }\n\n constructor(\n /** Width of sliding delay window in milliseconds. */\n public readonly delayWindowMs: number,\n /** Maximum delay allowed in milliseconds. */\n public readonly maxDelayMs: number,\n /**\n * Delay function used to calculate what the delay should be.\n * The input is the number of attempts that occurred within the sliding window.\n * The result is the calculated delay in milliseconds.\n */\n public readonly delayFn: (numAttempts: number) => number,\n ) { }\n\n public getDelay() {\n const now = Date.now();\n\n const latestAttemptTime = this.latestAttemptTime;\n if (latestAttemptTime !== undefined) {\n // If getDelay was called sooner than the most recent delay,\n // subtract the remaining time, since we previously added it.\n const earlyMs = latestAttemptTime - now;\n if (earlyMs > 0) {\n this.startTimes = this.startTimes.map((t) => t - earlyMs);\n }\n }\n\n // Remove all attempts that have already fallen out of the window.\n this.startTimes = this.startTimes.filter((t) => (now - t) < this.delayWindowMs);\n\n // Compute delay, but do not exceed the specified max delay.\n const delayMs = Math.min(this.delayFn(this.startTimes.length), this.maxDelayMs);\n\n // Record this attempt start time.\n this.startTimes.push(now);\n\n // Account for the delay time, by effectively removing it from the delay window.\n this.startTimes = this.startTimes.map((t) => t + delayMs);\n\n if (delayMs === this.maxDelayMs) {\n // We hit max delay, so adding more won't affect anything.\n // Shift off oldest time to stop this array from growing forever.\n this.startTimes.shift();\n }\n\n return delayMs;\n }\n}\n\n/**\n * Helper function to generate simple exponential throttle functions.\n * f(n) = [coefficient] x ([multiplier]^n) + [flatOffset]\n * where n = number of attempts, and f(n) = delay time in milliseconds.\n * If not provided, coefficient will default to 1, multiplier to 2,\n * minimum delay to 0, and the offset to 0, yielding:\n * 0 ms, 2 ms, 4 ms, 8 ms, ..., 2^n ms\n * where M = multiplier; an exponential back-off.\n * Use initialDelay to decide what should happen when numAttempts is 0,\n * leave it undefined to not special case.\n */\n export const formExponentialFn = ({\n multiplier = 2,\n coefficient = 1,\n offset = 0,\n initialDelay = undefined as number | undefined,\n} = {}): IThrottler[\"delayFn\"] => (numAttempts) => Math.max(0,\n numAttempts <= 0 && initialDelay !== undefined\n ? initialDelay\n : coefficient * (Math.pow(multiplier, numAttempts)) + offset);\n\n/** f(n) = C x (B^(n+A)) + F = (C x B^A) x B^n + F */\nexport const formExponentialFnWithAttemptOffset = (attemptOffset: number, {\n multiplier = 2,\n coefficient = 1,\n offset = 0,\n initialDelay = undefined as number | undefined,\n} = {}) => formExponentialFn({\n multiplier,\n coefficient: coefficient * Math.pow(multiplier, attemptOffset),\n offset,\n initialDelay,\n});\n\n/**\n * Helper function to generate simple linear throttle functions.\n * f(n) = [coefficient] x n + [flatOffset]\n * where n = number of attempts, and f(n) = delay time in milliseconds.\n * If not provided, coefficient will default to 1, and offset to 0, yielding:\n * 0 ms, 1 ms, 2 ms, 3 ms, ..., n ms delays; a linear back-off.\n */\nexport const formLinearFn = ({\n coefficient = 1,\n offset = 0,\n} = {}): IThrottler[\"delayFn\"] => (numAttempts) => Math.max(0,\n coefficient * numAttempts + offset);\n\n/** f(n) = C x (n+A) + F = C x n + (C x A + F) */\nexport const formLinearFnWithAttemptOffset = (attemptOffset: number, {\n coefficient = 1,\n offset = 0,\n} = {}) => formLinearFn({\n coefficient,\n offset: coefficient * attemptOffset + offset,\n});\n"]}
1
+ {"version":3,"file":"throttler.js","sourceRoot":"","sources":["../src/throttler.ts"],"names":[],"mappings":"AAAA;;;GAGG;AA2BH;;;GAGG;AACH,MAAM,OAAO,SAAS;IAuBrB;IACC,qDAAqD;IACrC,aAAqB;IACrC,6CAA6C;IAC7B,UAAkB;IAClC;;;;OAIG;IACa,OAAwC;QARxC,kBAAa,G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AY,GACxB,CAAC,EAAE,WAAW,GAAG,CAAC,EAAE,MAAM,GAAG,CAAC,EAAE,GAAG,EAAE,EAAyB,EAAE,CAChE,CAAC,WAAW,EAAE,EAAE,CACf,IAAI,CAAC,GAAG,CAAC,CAAC,EAAE,WAAW,GAAG,WAAW,GAAG,MAAM,CAAC,CAAC;AAElD,iDAAiD;AACjD,MAAM,CAAC,MAAM,6BAA6B,GAAG,CAC5C,aAAqB,EACrB,EAAE,WAAW,GAAG,CAAC,EAAE,MAAM,GAAG,CAAC,EAAE,GAAG,EAAE,EACnC,EAAE,CACH,YAAY,CAAC;IACZ,WAAW;IACX,MAAM,EAAE,WAAW,GAAG,aAAa,GAAG,MAAM;CAC5C,CAAC,CAAC","sourcesContent":["/*!\n * Copyright (c) Microsoft Corporation and contributors. All rights reserved.\n * Licensed under the MIT License.\n */\n\nexport interface IThrottler {\n\t/**\n\t * Computes what the throttle delay should be, and records an attempt\n\t * which will be used for calculating future attempt delays.\n\t */\n\tgetDelay(): number;\n\n\t/**\n\t * Number of attempts that occurred within the sliding window as of\n\t * the most recent delay computation.\n\t */\n\treadonly numAttempts: number;\n\n\t/** Width of sliding delay window in milliseconds. */\n\treadonly delayWindowMs: number;\n\t/** Maximum delay allowed in milliseconds. */\n\treadonly maxDelayMs: number;\n\t/**\n\t * Delay function used to calculate what the delay should be.\n\t * The input is the number of attempts that occurred within the sliding window.\n\t * The result is the calculated delay in milliseconds.\n\t */\n\treadonly delayFn: (numAttempts: number) => number;\n}\n\n/**\n * Used to give increasing delay times for throttling a single functionality.\n * Delay is based on previous attempts within specified time window, subtracting delay time.\n */\nexport class Throttler implements IThrottler {\n\tprivate startTimes: number[] = [];\n\n\tpublic get numAttempts() {\n\t\treturn this.startTimes.length;\n\t}\n\n\t/**\n\t * Gets all attempt start times after compensating for the delay times\n\t * by adding the delay times to the actual times.\n\t */\n\tpublic getAttempts(): readonly number[] {\n\t\treturn [...this.startTimes];\n\t}\n\n\t/**\n\t * Latest attempt time after compensating for the delay time itself\n\t * by adding the delay time to the actual time.\n\t */\n\tpublic get latestAttemptTime() {\n\t\treturn this.startTimes.length > 0 ? this.startTimes[this.startTimes.length - 1] : undefined;\n\t}\n\n\tconstructor(\n\t\t/** Width of sliding delay window in milliseconds. */\n\t\tpublic readonly delayWindowMs: number,\n\t\t/** Maximum delay allowed in milliseconds. */\n\t\tpublic readonly maxDelayMs: number,\n\t\t/**\n\t\t * Delay function used to calculate what the delay should be.\n\t\t * The input is the number of attempts that occurred within the sliding window.\n\t\t * The result is the calculated delay in milliseconds.\n\t\t */\n\t\tpublic readonly delayFn: (numAttempts: number) => number,\n\t) {}\n\n\tpublic getDelay() {\n\t\tconst now = Date.now();\n\n\t\tconst latestAttemptTime = this.latestAttemptTime;\n\t\tif (latestAttemptTime !== undefined) {\n\t\t\t// If getDelay was called sooner than the most recent delay,\n\t\t\t// subtract the remaining time, since we previously added it.\n\t\t\tconst earlyMs = latestAttemptTime - now;\n\t\t\tif (earlyMs > 0) {\n\t\t\t\tthis.startTimes = this.startTimes.map((t) => t - earlyMs);\n\t\t\t}\n\t\t}\n\n\t\t// Remove all attempts that have already fallen out of the window.\n\t\tthis.startTimes = this.startTimes.filter((t) => now - t < this.delayWindowMs);\n\n\t\t// Compute delay, but do not exceed the specified max delay.\n\t\tconst delayMs = Math.min(this.delayFn(this.startTimes.length), this.maxDelayMs);\n\n\t\t// Record this attempt start time.\n\t\tthis.startTimes.push(now);\n\n\t\t// Account for the delay time, by effectively removing it from the delay window.\n\t\tthis.startTimes = this.startTimes.map((t) => t + delayMs);\n\n\t\tif (delayMs === this.maxDelayMs) {\n\t\t\t// We hit max delay, so adding more won't affect anything.\n\t\t\t// Shift off oldest time to stop this array from growing forever.\n\t\t\tthis.startTimes.shift();\n\t\t}\n\n\t\treturn delayMs;\n\t}\n}\n\n/**\n * Helper function to generate simple exponential throttle functions.\n * f(n) = [coefficient] x ([multiplier]^n) + [flatOffset]\n * where n = number of attempts, and f(n) = delay time in milliseconds.\n * If not provided, coefficient will default to 1, multiplier to 2,\n * minimum delay to 0, and the offset to 0, yielding:\n * 0 ms, 2 ms, 4 ms, 8 ms, ..., 2^n ms\n * where M = multiplier; an exponential back-off.\n * Use initialDelay to decide what should happen when numAttempts is 0,\n * leave it undefined to not special case.\n */\nexport const formExponentialFn =\n\t({\n\t\tmultiplier = 2,\n\t\tcoefficient = 1,\n\t\toffset = 0,\n\t\tinitialDelay = undefined as number | undefined,\n\t} = {}): IThrottler[\"delayFn\"] =>\n\t(numAttempts) =>\n\t\tMath.max(\n\t\t\t0,\n\t\t\tnumAttempts <= 0 && initialDelay !== undefined\n\t\t\t\t? initialDelay\n\t\t\t\t: coefficient * Math.pow(multiplier, numAttempts) + offset,\n\t\t);\n\n/** f(n) = C x (B^(n+A)) + F = (C x B^A) x B^n + F */\nexport const formExponentialFnWithAttemptOffset = (\n\tattemptOffset: number,\n\t{\n\t\tmultiplier = 2,\n\t\tcoefficient = 1,\n\t\toffset = 0,\n\t\tinitialDelay = undefined as number | undefined,\n\t} = {},\n) =>\n\tformExponentialFn({\n\t\tmultiplier,\n\t\tcoefficient: coefficient * Math.pow(multiplier, attemptOffset),\n\t\toffset,\n\t\tinitialDelay,\n\t});\n\n/**\n * Helper function to generate simple linear throttle functions.\n * f(n) = [coefficient] x n + [flatOffset]\n * where n = number of attempts, and f(n) = delay time in milliseconds.\n * If not provided, coefficient will default to 1, and offset to 0, yielding:\n * 0 ms, 1 ms, 2 ms, 3 ms, ..., n ms delays; a linear back-off.\n */\nexport const formLinearFn =\n\t({ coefficient = 1, offset = 0 } = {}): IThrottler[\"delayFn\"] =>\n\t(numAttempts) =>\n\t\tMath.max(0, coefficient * numAttempts + offset);\n\n/** f(n) = C x (n+A) + F = C x n + (C x A + F) */\nexport const formLinearFnWithAttemptOffset = (\n\tattemptOffset: number,\n\t{ coefficient = 1, offset = 0 } = {},\n) =>\n\tformLinearFn({\n\t\tcoefficient,\n\t\toffset: coefficient * attemptOffset + offset,\n\t});\n"]}