@cloudcare/browser-rum 3.3.6 → 3.3.7

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 (354) hide show
  1. package/README.md +24 -3
  2. package/README.zh.md +19 -3
  3. package/bundle/dataflux-rum.js +1 -1
  4. package/cjs/boot/buildEnv.js +1 -1
  5. package/cjs/boot/buildEnv.js.map +1 -1
  6. package/cjs/boot/perStartRum.js.map +1 -1
  7. package/cjs/boot/recorderApi.js +170 -200
  8. package/cjs/boot/recorderApi.js.map +1 -1
  9. package/cjs/boot/recorderApiStub.js +3 -29
  10. package/cjs/boot/recorderApiStub.js.map +1 -1
  11. package/cjs/boot/rum.entry.js.map +1 -1
  12. package/cjs/boot/rum.js.map +1 -1
  13. package/cjs/boot/rum.slim.entry.js.map +1 -1
  14. package/cjs/boot/rumEntryFactory.js.map +1 -1
  15. package/cjs/boot/rumPublicApi.js.map +1 -1
  16. package/cjs/boot/rumRecorderApiStub.js.map +1 -1
  17. package/cjs/boot/rumSlimConfiguration.js.map +1 -1
  18. package/cjs/boot/sessionReplayPublicApi.js +14 -27
  19. package/cjs/boot/sessionReplayPublicApi.js.map +1 -1
  20. package/cjs/boot/startRecording.js +333 -108
  21. package/cjs/boot/startRecording.js.map +1 -1
  22. package/cjs/constants.js.map +1 -1
  23. package/cjs/domain/assembly.js +1 -7
  24. package/cjs/domain/assembly.js.map +1 -1
  25. package/cjs/domain/configuration.js +31 -43
  26. package/cjs/domain/configuration.js.map +1 -1
  27. package/cjs/domain/contexts/commonContext.js.map +1 -1
  28. package/cjs/domain/contexts/displayContext.js.map +1 -1
  29. package/cjs/domain/contexts/foregroundContexts.js.map +1 -1
  30. package/cjs/domain/contexts/internalContext.js.map +1 -1
  31. package/cjs/domain/contexts/pageStateHistory.js.map +1 -1
  32. package/cjs/domain/contexts/urlContexts.js +10 -1
  33. package/cjs/domain/contexts/urlContexts.js.map +1 -1
  34. package/cjs/domain/contexts/viewContexts.js.map +1 -1
  35. package/cjs/domain/deflate/deflateEncoder.js +517 -39
  36. package/cjs/domain/deflate/deflateEncoder.js.map +1 -1
  37. package/cjs/domain/deflate/deflateWorker.js +194 -115
  38. package/cjs/domain/deflate/deflateWorker.js.map +1 -1
  39. package/cjs/domain/deflate/index.js.map +1 -1
  40. package/cjs/domain/domMutationObservable.js.map +1 -1
  41. package/cjs/domain/encoderStreamId.js.map +1 -1
  42. package/cjs/domain/firstInputPolyfill.js.map +1 -1
  43. package/cjs/domain/initViewportObservable.js.map +1 -1
  44. package/cjs/domain/locationChangeObservable.js.map +1 -1
  45. package/cjs/domain/performanceObservable.js.map +1 -1
  46. package/cjs/domain/performanceUtils.js.map +1 -1
  47. package/cjs/domain/plugins.js.map +1 -1
  48. package/cjs/domain/replay/record/canvasAutoSnapshot.js.map +1 -1
  49. package/cjs/domain/replay/record/canvasCommandCapture.js +968 -167
  50. package/cjs/domain/replay/record/canvasCommandCapture.js.map +1 -1
  51. package/cjs/domain/replay/record/canvasCommandObserver.js +1058 -119
  52. package/cjs/domain/replay/record/canvasCommandObserver.js.map +1 -1
  53. package/cjs/domain/replay/record/canvasCommandSerializeArgs.js +61 -37
  54. package/cjs/domain/replay/record/canvasCommandSerializeArgs.js.map +1 -1
  55. package/cjs/domain/replay/record/canvasContext.js +63 -0
  56. package/cjs/domain/replay/record/canvasContext.js.map +1 -0
  57. package/cjs/domain/replay/record/canvasContinuousScheduler.js +246 -118
  58. package/cjs/domain/replay/record/canvasContinuousScheduler.js.map +1 -1
  59. package/cjs/domain/replay/record/canvasEncodeBridge.js +539 -87
  60. package/cjs/domain/replay/record/canvasEncodeBridge.js.map +1 -1
  61. package/cjs/domain/replay/record/canvasEncodeWorker.js +50 -32
  62. package/cjs/domain/replay/record/canvasEncodeWorker.js.map +1 -1
  63. package/cjs/domain/replay/record/canvasFrameSignature.js +49 -17
  64. package/cjs/domain/replay/record/canvasFrameSignature.js.map +1 -1
  65. package/cjs/domain/replay/record/canvasMutationRecord.js.map +1 -1
  66. package/cjs/domain/replay/record/canvasObserver.js +295 -59
  67. package/cjs/domain/replay/record/canvasObserver.js.map +1 -1
  68. package/cjs/domain/replay/record/canvasSerializeArgs.js.map +1 -1
  69. package/cjs/domain/replay/record/canvasWebGLPluginHost.js +33 -0
  70. package/cjs/domain/replay/record/canvasWebGLPluginHost.js.map +1 -0
  71. package/cjs/domain/replay/record/elementsScrollPositions.js +3 -0
  72. package/cjs/domain/replay/record/elementsScrollPositions.js.map +1 -1
  73. package/cjs/domain/replay/record/index.js.map +1 -1
  74. package/cjs/domain/replay/record/mutationBatch.js +542 -25
  75. package/cjs/domain/replay/record/mutationBatch.js.map +1 -1
  76. package/cjs/domain/replay/record/mutationObserver.js +1900 -191
  77. package/cjs/domain/replay/record/mutationObserver.js.map +1 -1
  78. package/cjs/domain/replay/record/mutationResourceBudget.js +144 -0
  79. package/cjs/domain/replay/record/mutationResourceBudget.js.map +1 -0
  80. package/cjs/domain/replay/record/observers.js +222 -53
  81. package/cjs/domain/replay/record/observers.js.map +1 -1
  82. package/cjs/domain/replay/record/privacy.js +31 -8
  83. package/cjs/domain/replay/record/privacy.js.map +1 -1
  84. package/cjs/domain/replay/record/record.js +3083 -321
  85. package/cjs/domain/replay/record/record.js.map +1 -1
  86. package/cjs/domain/replay/record/serializationUtils.js +426 -26
  87. package/cjs/domain/replay/record/serializationUtils.js.map +1 -1
  88. package/cjs/domain/replay/record/serialize.js +259 -49
  89. package/cjs/domain/replay/record/serialize.js.map +1 -1
  90. package/cjs/domain/replay/record/shadowRootsController.js +875 -21
  91. package/cjs/domain/replay/record/shadowRootsController.js.map +1 -1
  92. package/cjs/domain/replay/record/utils.js.map +1 -1
  93. package/cjs/domain/replay/record/viewports.js.map +1 -1
  94. package/cjs/domain/replay/replayStats.js.map +1 -1
  95. package/cjs/domain/replay/segmentCollection/buildReplayPayload.js.map +1 -1
  96. package/cjs/domain/replay/segmentCollection/index.js.map +1 -1
  97. package/cjs/domain/replay/segmentCollection/segment.js +315 -11
  98. package/cjs/domain/replay/segmentCollection/segment.js.map +1 -1
  99. package/cjs/domain/replay/segmentCollection/segmentCollection.js +956 -71
  100. package/cjs/domain/replay/segmentCollection/segmentCollection.js.map +1 -1
  101. package/cjs/domain/replay/startRecordBridge.js.map +1 -1
  102. package/cjs/domain/requestCollection.js.map +1 -1
  103. package/cjs/domain/rumEventsCollection/actions/actionCollection.js.map +1 -1
  104. package/cjs/domain/rumEventsCollection/actions/clickChain.js.map +1 -1
  105. package/cjs/domain/rumEventsCollection/actions/computeFrustration.js.map +1 -1
  106. package/cjs/domain/rumEventsCollection/actions/getActionNameFromElement.js.map +1 -1
  107. package/cjs/domain/rumEventsCollection/actions/getSelectorsFromElement.js.map +1 -1
  108. package/cjs/domain/rumEventsCollection/actions/interactionSelectorCache.js.map +1 -1
  109. package/cjs/domain/rumEventsCollection/actions/listenActionEvents.js.map +1 -1
  110. package/cjs/domain/rumEventsCollection/actions/trackClickActions.js.map +1 -1
  111. package/cjs/domain/rumEventsCollection/error/errorCollection.js.map +1 -1
  112. package/cjs/domain/rumEventsCollection/error/trackConsoleError.js.map +1 -1
  113. package/cjs/domain/rumEventsCollection/error/trackReportError.js.map +1 -1
  114. package/cjs/domain/rumEventsCollection/longTask/longAnimationFrameCollection.js.map +1 -1
  115. package/cjs/domain/rumEventsCollection/longTask/longTaskCollection.js.map +1 -1
  116. package/cjs/domain/rumEventsCollection/resource/matchRequestResourceEntry.js.map +1 -1
  117. package/cjs/domain/rumEventsCollection/resource/resourceCollection.js.map +1 -1
  118. package/cjs/domain/rumEventsCollection/resource/resourceTrackerManager.js.map +1 -1
  119. package/cjs/domain/rumEventsCollection/resource/resourceUtils.js.map +1 -1
  120. package/cjs/domain/rumEventsCollection/resource/retrieveInitialDocumentResourceTiming.js.map +1 -1
  121. package/cjs/domain/rumEventsCollection/resource/webSocketCollection.js.map +1 -1
  122. package/cjs/domain/rumEventsCollection/view/interactionCountPolyfill.js.map +1 -1
  123. package/cjs/domain/rumEventsCollection/view/trackCommonViewMetrics.js.map +1 -1
  124. package/cjs/domain/rumEventsCollection/view/trackCumulativeLayoutShift.js.map +1 -1
  125. package/cjs/domain/rumEventsCollection/view/trackFirstContentfulPaint.js.map +1 -1
  126. package/cjs/domain/rumEventsCollection/view/trackFirstHidden.js.map +1 -1
  127. package/cjs/domain/rumEventsCollection/view/trackFirstInput.js.map +1 -1
  128. package/cjs/domain/rumEventsCollection/view/trackInitialViewTimings.js.map +1 -1
  129. package/cjs/domain/rumEventsCollection/view/trackInteractionToNextPaint.js.map +1 -1
  130. package/cjs/domain/rumEventsCollection/view/trackLargestContentfulPaint.js.map +1 -1
  131. package/cjs/domain/rumEventsCollection/view/trackLoadingTime.js.map +1 -1
  132. package/cjs/domain/rumEventsCollection/view/trackNavigationTimings.js.map +1 -1
  133. package/cjs/domain/rumEventsCollection/view/trackScrollMetrics.js.map +1 -1
  134. package/cjs/domain/rumEventsCollection/view/trackViewEventCounts.js.map +1 -1
  135. package/cjs/domain/rumEventsCollection/view/trackViews.js +29 -11
  136. package/cjs/domain/rumEventsCollection/view/trackViews.js.map +1 -1
  137. package/cjs/domain/rumEventsCollection/view/viewCollection.js.map +1 -1
  138. package/cjs/domain/rumSessionManager.js.map +1 -1
  139. package/cjs/domain/tracing/ddtraceTracer.js.map +1 -1
  140. package/cjs/domain/tracing/getDocumentTraceId.js.map +1 -1
  141. package/cjs/domain/tracing/jaegerTracer.js.map +1 -1
  142. package/cjs/domain/tracing/sampler.js.map +1 -1
  143. package/cjs/domain/tracing/skywalkingTracer.js.map +1 -1
  144. package/cjs/domain/tracing/traceIdentifier.js.map +1 -1
  145. package/cjs/domain/tracing/tracer.js +2 -2
  146. package/cjs/domain/tracing/tracer.js.map +1 -1
  147. package/cjs/domain/tracing/w3cTraceParentTracer.js.map +1 -1
  148. package/cjs/domain/tracing/zipkinMultiTracer.js.map +1 -1
  149. package/cjs/domain/tracing/zipkinSingleTracer.js.map +1 -1
  150. package/cjs/domain/trackEventCounts.js.map +1 -1
  151. package/cjs/domain/usr/index.js.map +1 -1
  152. package/cjs/domain/waitPageActivityEnd.js.map +1 -1
  153. package/cjs/index.js.map +1 -1
  154. package/cjs/transport/startRumBatch.js +3 -1
  155. package/cjs/transport/startRumBatch.js.map +1 -1
  156. package/cjs/transport/startRumEventBridge.js.map +1 -1
  157. package/cjs/types/index.js.map +1 -1
  158. package/cjs/types/sessionReplayConstants.js.map +1 -1
  159. package/esm/boot/buildEnv.js +1 -1
  160. package/esm/boot/buildEnv.js.map +1 -1
  161. package/esm/boot/perStartRum.js.map +1 -1
  162. package/esm/boot/recorderApi.js +172 -202
  163. package/esm/boot/recorderApi.js.map +1 -1
  164. package/esm/boot/recorderApiStub.js +3 -29
  165. package/esm/boot/recorderApiStub.js.map +1 -1
  166. package/esm/boot/rum.entry.js.map +1 -1
  167. package/esm/boot/rum.js.map +1 -1
  168. package/esm/boot/rum.slim.entry.js.map +1 -1
  169. package/esm/boot/rumEntryFactory.js.map +1 -1
  170. package/esm/boot/rumPublicApi.js.map +1 -1
  171. package/esm/boot/rumRecorderApiStub.js.map +1 -1
  172. package/esm/boot/rumSlimConfiguration.js.map +1 -1
  173. package/esm/boot/sessionReplayPublicApi.js +14 -27
  174. package/esm/boot/sessionReplayPublicApi.js.map +1 -1
  175. package/esm/boot/startRecording.js +334 -109
  176. package/esm/boot/startRecording.js.map +1 -1
  177. package/esm/constants.js.map +1 -1
  178. package/esm/domain/assembly.js +1 -7
  179. package/esm/domain/assembly.js.map +1 -1
  180. package/esm/domain/configuration.js +31 -43
  181. package/esm/domain/configuration.js.map +1 -1
  182. package/esm/domain/contexts/commonContext.js.map +1 -1
  183. package/esm/domain/contexts/displayContext.js.map +1 -1
  184. package/esm/domain/contexts/foregroundContexts.js.map +1 -1
  185. package/esm/domain/contexts/internalContext.js.map +1 -1
  186. package/esm/domain/contexts/pageStateHistory.js.map +1 -1
  187. package/esm/domain/contexts/urlContexts.js +11 -2
  188. package/esm/domain/contexts/urlContexts.js.map +1 -1
  189. package/esm/domain/contexts/viewContexts.js.map +1 -1
  190. package/esm/domain/deflate/deflateEncoder.js +517 -39
  191. package/esm/domain/deflate/deflateEncoder.js.map +1 -1
  192. package/esm/domain/deflate/deflateWorker.js +193 -116
  193. package/esm/domain/deflate/deflateWorker.js.map +1 -1
  194. package/esm/domain/deflate/index.js.map +1 -1
  195. package/esm/domain/domMutationObservable.js.map +1 -1
  196. package/esm/domain/encoderStreamId.js.map +1 -1
  197. package/esm/domain/firstInputPolyfill.js.map +1 -1
  198. package/esm/domain/initViewportObservable.js.map +1 -1
  199. package/esm/domain/locationChangeObservable.js.map +1 -1
  200. package/esm/domain/performanceObservable.js.map +1 -1
  201. package/esm/domain/performanceUtils.js.map +1 -1
  202. package/esm/domain/plugins.js.map +1 -1
  203. package/esm/domain/replay/record/canvasAutoSnapshot.js.map +1 -1
  204. package/esm/domain/replay/record/canvasCommandCapture.js +968 -168
  205. package/esm/domain/replay/record/canvasCommandCapture.js.map +1 -1
  206. package/esm/domain/replay/record/canvasCommandObserver.js +1058 -119
  207. package/esm/domain/replay/record/canvasCommandObserver.js.map +1 -1
  208. package/esm/domain/replay/record/canvasCommandSerializeArgs.js +60 -37
  209. package/esm/domain/replay/record/canvasCommandSerializeArgs.js.map +1 -1
  210. package/esm/domain/replay/record/canvasContext.js +50 -0
  211. package/esm/domain/replay/record/canvasContext.js.map +1 -0
  212. package/esm/domain/replay/record/canvasContinuousScheduler.js +246 -118
  213. package/esm/domain/replay/record/canvasContinuousScheduler.js.map +1 -1
  214. package/esm/domain/replay/record/canvasEncodeBridge.js +539 -87
  215. package/esm/domain/replay/record/canvasEncodeBridge.js.map +1 -1
  216. package/esm/domain/replay/record/canvasEncodeWorker.js +51 -33
  217. package/esm/domain/replay/record/canvasEncodeWorker.js.map +1 -1
  218. package/esm/domain/replay/record/canvasFrameSignature.js +50 -17
  219. package/esm/domain/replay/record/canvasFrameSignature.js.map +1 -1
  220. package/esm/domain/replay/record/canvasMutationRecord.js.map +1 -1
  221. package/esm/domain/replay/record/canvasObserver.js +295 -59
  222. package/esm/domain/replay/record/canvasObserver.js.map +1 -1
  223. package/esm/domain/replay/record/canvasSerializeArgs.js.map +1 -1
  224. package/esm/domain/replay/record/canvasWebGLPluginHost.js +26 -0
  225. package/esm/domain/replay/record/canvasWebGLPluginHost.js.map +1 -0
  226. package/esm/domain/replay/record/elementsScrollPositions.js +3 -0
  227. package/esm/domain/replay/record/elementsScrollPositions.js.map +1 -1
  228. package/esm/domain/replay/record/index.js.map +1 -1
  229. package/esm/domain/replay/record/mutationBatch.js +541 -25
  230. package/esm/domain/replay/record/mutationBatch.js.map +1 -1
  231. package/esm/domain/replay/record/mutationObserver.js +1892 -195
  232. package/esm/domain/replay/record/mutationObserver.js.map +1 -1
  233. package/esm/domain/replay/record/mutationResourceBudget.js +137 -0
  234. package/esm/domain/replay/record/mutationResourceBudget.js.map +1 -0
  235. package/esm/domain/replay/record/observers.js +224 -55
  236. package/esm/domain/replay/record/observers.js.map +1 -1
  237. package/esm/domain/replay/record/privacy.js +30 -7
  238. package/esm/domain/replay/record/privacy.js.map +1 -1
  239. package/esm/domain/replay/record/record.js +3086 -325
  240. package/esm/domain/replay/record/record.js.map +1 -1
  241. package/esm/domain/replay/record/serializationUtils.js +422 -25
  242. package/esm/domain/replay/record/serializationUtils.js.map +1 -1
  243. package/esm/domain/replay/record/serialize.js +258 -50
  244. package/esm/domain/replay/record/serialize.js.map +1 -1
  245. package/esm/domain/replay/record/shadowRootsController.js +875 -21
  246. package/esm/domain/replay/record/shadowRootsController.js.map +1 -1
  247. package/esm/domain/replay/record/utils.js.map +1 -1
  248. package/esm/domain/replay/record/viewports.js.map +1 -1
  249. package/esm/domain/replay/replayStats.js.map +1 -1
  250. package/esm/domain/replay/segmentCollection/buildReplayPayload.js.map +1 -1
  251. package/esm/domain/replay/segmentCollection/index.js.map +1 -1
  252. package/esm/domain/replay/segmentCollection/segment.js +315 -10
  253. package/esm/domain/replay/segmentCollection/segment.js.map +1 -1
  254. package/esm/domain/replay/segmentCollection/segmentCollection.js +957 -72
  255. package/esm/domain/replay/segmentCollection/segmentCollection.js.map +1 -1
  256. package/esm/domain/replay/startRecordBridge.js.map +1 -1
  257. package/esm/domain/requestCollection.js.map +1 -1
  258. package/esm/domain/rumEventsCollection/actions/actionCollection.js.map +1 -1
  259. package/esm/domain/rumEventsCollection/actions/clickChain.js.map +1 -1
  260. package/esm/domain/rumEventsCollection/actions/computeFrustration.js.map +1 -1
  261. package/esm/domain/rumEventsCollection/actions/getActionNameFromElement.js.map +1 -1
  262. package/esm/domain/rumEventsCollection/actions/getSelectorsFromElement.js.map +1 -1
  263. package/esm/domain/rumEventsCollection/actions/interactionSelectorCache.js.map +1 -1
  264. package/esm/domain/rumEventsCollection/actions/listenActionEvents.js.map +1 -1
  265. package/esm/domain/rumEventsCollection/actions/trackClickActions.js.map +1 -1
  266. package/esm/domain/rumEventsCollection/error/errorCollection.js.map +1 -1
  267. package/esm/domain/rumEventsCollection/error/trackConsoleError.js.map +1 -1
  268. package/esm/domain/rumEventsCollection/error/trackReportError.js.map +1 -1
  269. package/esm/domain/rumEventsCollection/longTask/longAnimationFrameCollection.js.map +1 -1
  270. package/esm/domain/rumEventsCollection/longTask/longTaskCollection.js.map +1 -1
  271. package/esm/domain/rumEventsCollection/resource/matchRequestResourceEntry.js.map +1 -1
  272. package/esm/domain/rumEventsCollection/resource/resourceCollection.js.map +1 -1
  273. package/esm/domain/rumEventsCollection/resource/resourceTrackerManager.js.map +1 -1
  274. package/esm/domain/rumEventsCollection/resource/resourceUtils.js.map +1 -1
  275. package/esm/domain/rumEventsCollection/resource/retrieveInitialDocumentResourceTiming.js.map +1 -1
  276. package/esm/domain/rumEventsCollection/resource/webSocketCollection.js.map +1 -1
  277. package/esm/domain/rumEventsCollection/view/interactionCountPolyfill.js.map +1 -1
  278. package/esm/domain/rumEventsCollection/view/trackCommonViewMetrics.js.map +1 -1
  279. package/esm/domain/rumEventsCollection/view/trackCumulativeLayoutShift.js.map +1 -1
  280. package/esm/domain/rumEventsCollection/view/trackFirstContentfulPaint.js.map +1 -1
  281. package/esm/domain/rumEventsCollection/view/trackFirstHidden.js.map +1 -1
  282. package/esm/domain/rumEventsCollection/view/trackFirstInput.js.map +1 -1
  283. package/esm/domain/rumEventsCollection/view/trackInitialViewTimings.js.map +1 -1
  284. package/esm/domain/rumEventsCollection/view/trackInteractionToNextPaint.js.map +1 -1
  285. package/esm/domain/rumEventsCollection/view/trackLargestContentfulPaint.js.map +1 -1
  286. package/esm/domain/rumEventsCollection/view/trackLoadingTime.js.map +1 -1
  287. package/esm/domain/rumEventsCollection/view/trackNavigationTimings.js.map +1 -1
  288. package/esm/domain/rumEventsCollection/view/trackScrollMetrics.js.map +1 -1
  289. package/esm/domain/rumEventsCollection/view/trackViewEventCounts.js.map +1 -1
  290. package/esm/domain/rumEventsCollection/view/trackViews.js +30 -12
  291. package/esm/domain/rumEventsCollection/view/trackViews.js.map +1 -1
  292. package/esm/domain/rumEventsCollection/view/viewCollection.js.map +1 -1
  293. package/esm/domain/rumSessionManager.js.map +1 -1
  294. package/esm/domain/tracing/ddtraceTracer.js.map +1 -1
  295. package/esm/domain/tracing/getDocumentTraceId.js.map +1 -1
  296. package/esm/domain/tracing/jaegerTracer.js.map +1 -1
  297. package/esm/domain/tracing/sampler.js.map +1 -1
  298. package/esm/domain/tracing/skywalkingTracer.js.map +1 -1
  299. package/esm/domain/tracing/traceIdentifier.js.map +1 -1
  300. package/esm/domain/tracing/tracer.js +2 -2
  301. package/esm/domain/tracing/tracer.js.map +1 -1
  302. package/esm/domain/tracing/w3cTraceParentTracer.js.map +1 -1
  303. package/esm/domain/tracing/zipkinMultiTracer.js.map +1 -1
  304. package/esm/domain/tracing/zipkinSingleTracer.js.map +1 -1
  305. package/esm/domain/trackEventCounts.js.map +1 -1
  306. package/esm/domain/usr/index.js.map +1 -1
  307. package/esm/domain/waitPageActivityEnd.js.map +1 -1
  308. package/esm/index.js.map +1 -1
  309. package/esm/transport/startRumBatch.js +4 -2
  310. package/esm/transport/startRumBatch.js.map +1 -1
  311. package/esm/transport/startRumEventBridge.js.map +1 -1
  312. package/esm/types/index.js.map +1 -1
  313. package/esm/types/sessionReplayConstants.js.map +1 -1
  314. package/package.json +12 -7
  315. package/src/boot/recorderApi.js +247 -220
  316. package/src/boot/recorderApiStub.js +3 -29
  317. package/src/boot/sessionReplayPublicApi.js +15 -28
  318. package/src/boot/startRecording.js +429 -146
  319. package/src/domain/assembly.js +5 -4
  320. package/src/domain/configuration.js +63 -100
  321. package/src/domain/contexts/urlContexts.js +16 -4
  322. package/src/domain/deflate/deflateEncoder.js +699 -43
  323. package/src/domain/deflate/deflateWorker.js +237 -136
  324. package/src/domain/replay/record/canvasCommandCapture.js +1374 -180
  325. package/src/domain/replay/record/canvasCommandObserver.js +1585 -150
  326. package/src/domain/replay/record/canvasCommandSerializeArgs.js +79 -42
  327. package/src/domain/replay/record/canvasContext.js +67 -0
  328. package/src/domain/replay/record/canvasContinuousScheduler.js +379 -143
  329. package/src/domain/replay/record/canvasEncodeBridge.js +691 -106
  330. package/src/domain/replay/record/canvasEncodeWorker.js +67 -43
  331. package/src/domain/replay/record/canvasFrameSignature.js +58 -24
  332. package/src/domain/replay/record/canvasObserver.js +461 -89
  333. package/src/domain/replay/record/canvasWebGLPluginHost.js +43 -0
  334. package/src/domain/replay/record/elementsScrollPositions.js +3 -0
  335. package/src/domain/replay/record/mutationBatch.js +761 -27
  336. package/src/domain/replay/record/mutationObserver.js +2992 -261
  337. package/src/domain/replay/record/mutationResourceBudget.js +191 -0
  338. package/src/domain/replay/record/observers.js +367 -97
  339. package/src/domain/replay/record/privacy.js +34 -12
  340. package/src/domain/replay/record/record.js +4284 -413
  341. package/src/domain/replay/record/serializationUtils.js +587 -28
  342. package/src/domain/replay/record/serialize.js +432 -66
  343. package/src/domain/replay/record/shadowRootsController.js +1108 -30
  344. package/src/domain/replay/segmentCollection/segment.js +441 -11
  345. package/src/domain/replay/segmentCollection/segmentCollection.js +1300 -77
  346. package/src/domain/rumEventsCollection/view/trackViews.js +36 -12
  347. package/src/domain/tracing/tracer.js +4 -5
  348. package/src/transport/startRumBatch.js +6 -1
  349. package/types/index.d.ts +15 -2
  350. package/cjs/domain/replay/record/canvasReplayFixtures.js +0 -105
  351. package/cjs/domain/replay/record/canvasReplayFixtures.js.map +0 -1
  352. package/esm/domain/replay/record/canvasReplayFixtures.js +0 -96
  353. package/esm/domain/replay/record/canvasReplayFixtures.js.map +0 -1
  354. package/src/domain/replay/record/canvasReplayFixtures.js +0 -113
@@ -1,4 +1,4 @@
1
- import { ONE_SECOND, LifeCycleEventType, isPageExitReason, assign, setTimeout, clearTimeout } from '@cloudcare/browser-core';
1
+ import { ONE_SECOND, LifeCycleEventType, isPageExitReason, PageExitReason, assign, addTelemetryDebug, dateNow, setTimeout, clearTimeout } from '@cloudcare/browser-core';
2
2
  import { IncrementalSource, RecordType } from '../../../types';
3
3
  import { buildReplayPayload } from './buildReplayPayload';
4
4
  import { createSegment } from './segment';
@@ -8,6 +8,15 @@ export var SEGMENT_DURATION_LIMIT = 5 * ONE_SECOND;
8
8
  * ensure that we leave room for logs, rum and potential other users
9
9
  */
10
10
  export var SEGMENT_BYTES_LIMIT = 60000;
11
+ // buildReplayPayload() exposes the compressed segment size, but sendBeacon
12
+ // accounts for the multipart boundaries, headers, and metadata fields too.
13
+ // Reserve a conservative envelope per segment so several small unload
14
+ // segments cannot collectively overrun the browser's exit delivery queue.
15
+ var SEGMENT_FORM_DATA_ESTIMATED_OVERHEAD = 2 * 1024;
16
+ var SEGMENT_PENDING_RAW_BYTES_LIMIT = 4 * 1024 * 1024;
17
+ var LOCKED_SEGMENTS_LIMIT = 12;
18
+ var CANVAS_FLUSH_MIN_INTERVAL = 250;
19
+ var MAX_CONSECUTIVE_FULL_SNAPSHOT_FAILURES = 3;
11
20
 
12
21
  // Segments are the main data structure for session replays. They contain context information used
13
22
  // for indexing or UI needs, and a list of records (RRWeb 'events', renamed to avoid confusing
@@ -41,6 +50,10 @@ export function startSegmentCollection(lifeCycle, configuration, sessionManager,
41
50
  return computeSegmentContext(configuration, sessionManager, viewContexts);
42
51
  }, httpRequest, encoder, isLocked, assign({
43
52
  flushCanvasImmediately: configuration.replayCanvasFlushImmediately,
53
+ pendingRawBytesLimit: SEGMENT_PENDING_RAW_BYTES_LIMIT,
54
+ beforePageExitFlush: undefined,
55
+ onReplayResetNeeded: undefined,
56
+ onReplayResetExhausted: undefined,
44
57
  onSegmentFlushed: undefined
45
58
  }, additionalOptions));
46
59
  }
@@ -53,115 +66,987 @@ export function doStartSegmentCollection(lifeCycle, getSegmentContext, httpReque
53
66
  if (options === undefined) {
54
67
  options = {};
55
68
  }
69
+ var pendingRawBytesLimit = typeof options.pendingRawBytesLimit === 'number' ? options.pendingRawBytesLimit : SEGMENT_PENDING_RAW_BYTES_LIMIT;
70
+ var lockedSegments = [];
71
+ var lockedBufferGeneration = 0;
72
+ var reportedDropReasons = {};
73
+ var lastCanvasFlushAt = -Infinity;
74
+ var canvasFlushTimeoutId;
75
+ var replayResetNeeded = false;
76
+ var replayResetReason;
77
+ var replayResetNotificationSent = false;
78
+ var replayResetNotificationTimeoutId;
79
+ var activeBaselineGeneration = 0;
80
+ var nextBaselineGeneration = 0;
81
+ var baselineGenerationStates = {};
82
+ var transportGenerationStates = {};
83
+ var baselineGenerationInFlightCounts = {};
84
+ var pendingSegmentResultsByGeneration = {};
85
+ var consecutiveFullSnapshotFailures = 0;
86
+ var replayRecoveryExhausted = false;
87
+ var lifecycleSubscriptionsStopped = false;
88
+ var nextSegmentFlushSequence = 0;
89
+ var inFlightSegmentFlushes = new Set();
90
+ var lastAddRecordWasBackpressured = false;
91
+ var backpressuredSerializedRecordData = new WeakMap();
92
+ var unloadingTransportLatched = false;
93
+ var unloadingDeliveryBytesRemaining;
94
+ var unloadingDeliveryBudgetExhausted = false;
95
+ var unloadingRetryPayloadsDrained = false;
96
+ var mandatoryRecoveryPending = false;
97
+ var bufferCheckoutPending = false;
98
+ var activeBaselineTransaction;
56
99
  var state = {
57
- status: SegmentCollectionStatus.WaitingForInitialRecord,
58
- nextSegmentCreationReason: 'init',
59
- isLocked: isLocked
100
+ $rStatus: SegmentCollectionStatus.WaitingForInitialRecord,
101
+ $rNextReason: 'init',
102
+ $rLocked: isLocked,
103
+ $rGeneration: activeBaselineGeneration
60
104
  };
105
+ function prepareRecordsBeforePageExit(pageExitEvent) {
106
+ if (!options.beforePageExitFlush) {
107
+ return;
108
+ }
109
+ try {
110
+ options.beforePageExitFlush(pageExitEvent);
111
+ } catch (error) {
112
+ addTelemetryDebug('Session Replay failed to prepare records before page exit.', {
113
+ reason: pageExitEvent && pageExitEvent.reason,
114
+ error: String(error)
115
+ });
116
+ }
117
+ }
61
118
  var subscribeViewCreated = lifeCycle.subscribe(LifeCycleEventType.VIEW_CREATED, function () {
62
119
  flushSegment('view_change');
63
120
  });
64
121
  var unsubscribeViewCreated = subscribeViewCreated.unsubscribe;
65
122
  var subscribePageExited = lifeCycle.subscribe(LifeCycleEventType.PAGE_EXITED, function (pageExitEvent) {
123
+ if (state.$rStatus === SegmentCollectionStatus.Stopped) {
124
+ return;
125
+ }
126
+ prepareRecordsBeforePageExit(pageExitEvent);
127
+ upgradeSegmentTransportsForPageExit(pageExitEvent.reason);
128
+ if (state.$rLocked && pageExitEvent.reason === PageExitReason.UNLOADING) {
129
+ lockedBufferGeneration += 1;
130
+ lockedSegments = [];
131
+ }
66
132
  flushSegment(pageExitEvent.reason);
133
+ if (flushPendingSegmentEncodingsForUnload(pageExitEvent.reason)) {
134
+ // The synchronous drain releases encoder backpressure. Give staged DOM
135
+ // mutations one final admission pass, then flush that second segment
136
+ // through the same unload-safe transport.
137
+ prepareRecordsBeforePageExit(pageExitEvent);
138
+ flushSegment(pageExitEvent.reason);
139
+ flushPendingSegmentEncodingsForUnload(pageExitEvent.reason);
140
+ }
67
141
  });
68
142
  var unsubscribePageExited = subscribePageExited.unsubscribe;
69
- var lockedFlushReason = ['view_change', 'buffer_checkout'];
70
- function flushSegment(flushReason, callback) {
71
- var isLocked = state.isLocked;
72
- if (state.status === SegmentCollectionStatus.SegmentPending) {
73
- if (isLocked && lockedFlushReason.includes(flushReason)) {
74
- state.segment.flush(function () {
75
- if (callback) callback();
76
- });
77
- } else {
78
- // if the segment is locked, we don't send it
79
- if (isLocked) {
80
- return;
81
- }
82
- state.segment.flush(function (metadata, encoderResult, recordCountsByType) {
83
- if (options.onSegmentFlushed) {
84
- options.onSegmentFlushed({
85
- creationReason: metadata.creation_reason,
86
- flushReason: flushReason,
87
- recordsCount: metadata.records_count,
88
- recordCountsByType: recordCountsByType,
89
- start: metadata.start,
90
- end: metadata.end,
91
- indexInView: metadata.index_in_view,
92
- rawBytesCount: encoderResult.rawBytesCount
93
- });
94
- }
95
- var payload = buildReplayPayload(encoderResult.output, metadata, encoderResult.rawBytesCount);
96
- if (isPageExitReason(flushReason)) {
97
- httpRequest.sendOnExit(payload);
98
- } else {
99
- httpRequest.send(payload);
143
+ function reportDroppedRecord(reason, estimatedBytesCount) {
144
+ if (reportedDropReasons[reason]) {
145
+ return;
146
+ }
147
+ reportedDropReasons[reason] = true;
148
+ addTelemetryDebug('Session Replay record discarded.', {
149
+ reason: reason,
150
+ estimated_bytes_count: estimatedBytesCount
151
+ });
152
+ }
153
+ function clearReplayResetNotificationTimeout() {
154
+ if (replayResetNotificationTimeoutId !== undefined) {
155
+ clearTimeout(replayResetNotificationTimeoutId);
156
+ replayResetNotificationTimeoutId = undefined;
157
+ }
158
+ }
159
+ function getPendingRawBytesCount() {
160
+ return encoder.getPendingRawBytesCount ? encoder.getPendingRawBytesCount() : 0;
161
+ }
162
+ function scheduleReplayResetNotification() {
163
+ if (!replayResetNeeded || replayResetNotificationSent || replayResetNotificationTimeoutId !== undefined || !options.onReplayResetNeeded || state.$rStatus === SegmentCollectionStatus.Stopped || getPendingRawBytesCount() > 0) {
164
+ return;
165
+ }
166
+ replayResetNotificationTimeoutId = setTimeout(function () {
167
+ replayResetNotificationTimeoutId = undefined;
168
+ if (!replayResetNeeded || replayResetNotificationSent || state.$rStatus === SegmentCollectionStatus.Stopped || getPendingRawBytesCount() > 0) {
169
+ return;
170
+ }
171
+ replayResetNotificationSent = true;
172
+ options.onReplayResetNeeded(replayResetReason);
173
+ }, 0);
174
+ }
175
+ function markReplayResetNeeded(reason, shouldNotifyAgain) {
176
+ if (!replayResetNeeded || shouldNotifyAgain) {
177
+ replayResetReason = reason;
178
+ replayResetNotificationSent = false;
179
+ if (shouldNotifyAgain) {
180
+ clearReplayResetNotificationTimeout();
181
+ }
182
+ }
183
+ replayResetNeeded = true;
184
+ scheduleReplayResetNotification();
185
+ }
186
+ function clearReplayResetNeeded() {
187
+ replayResetNeeded = false;
188
+ replayResetReason = undefined;
189
+ replayResetNotificationSent = false;
190
+ clearReplayResetNotificationTimeout();
191
+ }
192
+ function unsubscribeLifecycle() {
193
+ if (lifecycleSubscriptionsStopped) {
194
+ return;
195
+ }
196
+ lifecycleSubscriptionsStopped = true;
197
+ unsubscribeViewCreated();
198
+ unsubscribePageExited();
199
+ }
200
+ function exhaustReplayRecovery(reason) {
201
+ if (replayRecoveryExhausted) {
202
+ return;
203
+ }
204
+ replayRecoveryExhausted = true;
205
+ clearReplayResetNeeded();
206
+ clearCanvasFlushTimeout();
207
+ lockedBufferGeneration += 1;
208
+ lockedSegments = [];
209
+ baselineGenerationStates = {};
210
+ transportGenerationStates = {};
211
+ baselineGenerationInFlightCounts = {};
212
+ pendingSegmentResultsByGeneration = {};
213
+ if (state.$rStatus === SegmentCollectionStatus.SegmentPending) {
214
+ // A dependent segment can already exist when the asynchronous failure
215
+ // of the third replacement baseline arrives. Finalize-discard its
216
+ // shared deflate stream before stopping, otherwise a later explicit
217
+ // recorder restart can prepend these abandoned bytes to the new
218
+ // baseline.
219
+ discardCurrentSegment('recovery_exhausted');
220
+ }
221
+ state = {
222
+ $rStatus: SegmentCollectionStatus.Stopped,
223
+ $rLocked: false
224
+ };
225
+ unsubscribeLifecycle();
226
+ if (options.onReplayResetExhausted) {
227
+ options.onReplayResetExhausted(reason);
228
+ }
229
+ }
230
+ function failBaselineGeneration(baselineGeneration, reason, isFullSnapshotFailure) {
231
+ if (baselineGeneration > 0) {
232
+ baselineGenerationStates[baselineGeneration] = 'invalid';
233
+ delete pendingSegmentResultsByGeneration[baselineGeneration];
234
+ }
235
+ if (baselineGeneration !== activeBaselineGeneration) {
236
+ tryCleanupBaselineGeneration(baselineGeneration);
237
+ return;
238
+ }
239
+ if (isFullSnapshotFailure) {
240
+ consecutiveFullSnapshotFailures += 1;
241
+ if (consecutiveFullSnapshotFailures >= MAX_CONSECUTIVE_FULL_SNAPSHOT_FAILURES) {
242
+ exhaustReplayRecovery(reason);
243
+ return;
244
+ }
245
+ }
246
+ markReplayResetNeeded(reason, true);
247
+ }
248
+ function retainBaselineGeneration(baselineGeneration) {
249
+ if (baselineGeneration <= 0) {
250
+ return;
251
+ }
252
+ baselineGenerationInFlightCounts[baselineGeneration] = (baselineGenerationInFlightCounts[baselineGeneration] || 0) + 1;
253
+ }
254
+ function releaseBaselineGeneration(baselineGeneration) {
255
+ if (baselineGeneration <= 0 || !baselineGenerationInFlightCounts[baselineGeneration]) {
256
+ return;
257
+ }
258
+ baselineGenerationInFlightCounts[baselineGeneration] -= 1;
259
+ if (!baselineGenerationInFlightCounts[baselineGeneration]) {
260
+ delete baselineGenerationInFlightCounts[baselineGeneration];
261
+ }
262
+ tryCleanupBaselineGeneration(baselineGeneration);
263
+ }
264
+ function tryCleanupBaselineGeneration(baselineGeneration) {
265
+ if (baselineGeneration <= 0 || baselineGeneration === activeBaselineGeneration || baselineGenerationInFlightCounts[baselineGeneration] || pendingSegmentResultsByGeneration[baselineGeneration]) {
266
+ return;
267
+ }
268
+ delete baselineGenerationStates[baselineGeneration];
269
+ delete transportGenerationStates[baselineGeneration];
270
+ }
271
+ function getTransportGenerationState(baselineGeneration) {
272
+ if (!transportGenerationStates[baselineGeneration]) {
273
+ transportGenerationStates[baselineGeneration] = {
274
+ $rValid: true
275
+ };
276
+ }
277
+ return transportGenerationStates[baselineGeneration];
278
+ }
279
+ function clearCanvasFlushTimeout() {
280
+ if (canvasFlushTimeoutId !== undefined) {
281
+ clearTimeout(canvasFlushTimeoutId);
282
+ canvasFlushTimeoutId = undefined;
283
+ }
284
+ }
285
+ function upgradeSegmentTransportsForPageExit(flushReason) {
286
+ if (!isPageExitReason(flushReason)) {
287
+ return;
288
+ }
289
+ if (flushReason === PageExitReason.UNLOADING) {
290
+ unloadingTransportLatched = true;
291
+ if (unloadingDeliveryBytesRemaining === undefined) {
292
+ unloadingDeliveryBytesRemaining = SEGMENT_BYTES_LIMIT;
293
+ }
294
+ drainRetryPayloadsForUnload();
295
+ }
296
+ inFlightSegmentFlushes.forEach(function (transport) {
297
+ transport.$rExit = true;
298
+ });
299
+ // A dependent segment can finish encoding before its Full Snapshot and is
300
+ // then removed from inFlightSegmentFlushes while waiting for the baseline
301
+ // generation to be confirmed. Preserve the page-exit transport intent on
302
+ // those completed results as well. UNLOADING still uses the shared latch
303
+ // and aggregate delivery budget in sendSegment().
304
+ Object.keys(pendingSegmentResultsByGeneration).forEach(function (baselineGeneration) {
305
+ pendingSegmentResultsByGeneration[baselineGeneration].forEach(function (segmentResult) {
306
+ segmentResult.$rExit = true;
307
+ });
308
+ });
309
+ }
310
+ function flushPendingSegmentEncodingsSync() {
311
+ if (encoder.flushPendingActionsSync) {
312
+ encoder.flushPendingActionsSync(SEGMENT_BYTES_LIMIT);
313
+ return true;
314
+ }
315
+ return false;
316
+ }
317
+ function drainRetryPayloadsForUnload() {
318
+ if (unloadingRetryPayloadsDrained) {
319
+ return;
320
+ }
321
+ unloadingRetryPayloadsDrained = true;
322
+ if (typeof httpRequest.$rDrainOnExit !== 'function') {
323
+ return;
324
+ }
325
+ var deliveryResult = httpRequest.$rDrainOnExit(unloadingDeliveryBytesRemaining);
326
+ if (deliveryResult && typeof deliveryResult.$rBytesCount === 'number' && isFinite(deliveryResult.$rBytesCount) && deliveryResult.$rBytesCount >= 0) {
327
+ unloadingDeliveryBytesRemaining = Math.max(unloadingDeliveryBytesRemaining - deliveryResult.$rBytesCount, 0);
328
+ if (deliveryResult.$rAllPayloadsSent === false) {
329
+ // Replay segments are ordered. If an older queued payload does not fit,
330
+ // no current tail may overtake it.
331
+ unloadingDeliveryBudgetExhausted = true;
332
+ }
333
+ }
334
+ }
335
+ function flushPendingSegmentEncodingsForUnload(flushReason) {
336
+ return flushReason === PageExitReason.UNLOADING && flushPendingSegmentEncodingsSync();
337
+ }
338
+ function removeInFlightSegmentFlush(transport) {
339
+ inFlightSegmentFlushes["delete"](transport);
340
+ }
341
+ function handlePermanentTransportDrop(segmentResult, reason) {
342
+ // Invalidate the transport chain even after the recorder itself stopped;
343
+ // older queued dependents must never be promoted past the missing segment.
344
+ segmentResult.$rTransportGeneration.$rValid = false;
345
+ if (state.$rStatus === SegmentCollectionStatus.Stopped || replayRecoveryExhausted) {
346
+ return;
347
+ }
348
+ var dropReason = 'transport_' + reason;
349
+ reportDroppedRecord(dropReason, 0);
350
+ // Once a segment is permanently rejected, every later incremental in its
351
+ // generation may depend on replay state the player will never receive.
352
+ // Retire the generation and gate admission until a replacement Full
353
+ // Snapshot establishes a new chain. A transport failure is not evidence
354
+ // that Full Snapshot serialization itself is permanently broken.
355
+ failBaselineGeneration(segmentResult.$rGeneration, dropReason, false);
356
+ scheduleReplayResetNotification();
357
+ }
358
+ function sendSegment(segmentResult) {
359
+ var metadata = segmentResult.$rMetadata;
360
+ var encoderResult = segmentResult.$rEncoder;
361
+ if (false && options.onSegmentFlushed) {
362
+ options.onSegmentFlushed({
363
+ creationReason: metadata.creation_reason,
364
+ flushReason: segmentResult.$rReason,
365
+ recordsCount: metadata.records_count,
366
+ recordCountsByType: segmentResult.$rCounts,
367
+ start: metadata.start,
368
+ end: metadata.end,
369
+ indexInView: metadata.index_in_view,
370
+ rawBytesCount: encoderResult.rawBytesCount
371
+ });
372
+ }
373
+ var shouldUseExitTransport = !segmentResult.$rRegular && (segmentResult.$rExit || isPageExitReason(segmentResult.$rReason) || unloadingTransportLatched);
374
+ var estimatedDeliveryBytesCount = encoderResult.outputBytesCount + SEGMENT_FORM_DATA_ESTIMATED_OVERHEAD;
375
+ if (shouldUseExitTransport && unloadingTransportLatched) {
376
+ if (unloadingDeliveryBudgetExhausted || estimatedDeliveryBytesCount > unloadingDeliveryBytesRemaining) {
377
+ unloadingDeliveryBudgetExhausted = true;
378
+ reportDroppedRecord('page_exit_delivery_budget', estimatedDeliveryBytesCount);
379
+ return;
380
+ }
381
+ }
382
+ var payload = buildReplayPayload(encoderResult.output, metadata, encoderResult.rawBytesCount);
383
+ payload.$rExitBytesCount = estimatedDeliveryBytesCount;
384
+ payload.$rEnforceOrder = true;
385
+ payload.$rIsValid = function () {
386
+ return segmentResult.$rTransportGeneration.$rValid;
387
+ };
388
+ payload.$rOnPermanentDrop = function (reason) {
389
+ handlePermanentTransportDrop(segmentResult, reason);
390
+ };
391
+ if (shouldUseExitTransport) {
392
+ var exitDeliveryResult = httpRequest.sendOnExit(payload, unloadingTransportLatched ? unloadingDeliveryBytesRemaining : undefined);
393
+ if (unloadingTransportLatched) {
394
+ if (exitDeliveryResult && typeof exitDeliveryResult.$rBytesCount === 'number' && isFinite(exitDeliveryResult.$rBytesCount) && exitDeliveryResult.$rBytesCount >= 0) {
395
+ unloadingDeliveryBytesRemaining = Math.max(unloadingDeliveryBytesRemaining - exitDeliveryResult.$rBytesCount, 0);
396
+ if (!exitDeliveryResult.$rCurrentPayloadSent) {
397
+ unloadingDeliveryBudgetExhausted = true;
398
+ reportDroppedRecord('page_exit_delivery_budget', estimatedDeliveryBytesCount);
100
399
  }
101
- });
400
+ } else {
401
+ // Preserve compatibility with injected transports that predate the
402
+ // aggregate-budget result contract.
403
+ unloadingDeliveryBytesRemaining -= estimatedDeliveryBytesCount;
404
+ }
405
+ }
406
+ } else {
407
+ httpRequest.send(payload);
408
+ }
409
+ }
410
+ function retainLockedSegment(segmentResult) {
411
+ // A hidden-page beacon intent is only relevant while the page is hidden.
412
+ // If an error-session buffer is later unlocked, drain it through the
413
+ // regular transport instead of retaining a stale sendOnExit decision.
414
+ segmentResult.$rExit = false;
415
+ segmentResult.$rRegular = true;
416
+ if (replayResetNeeded) {
417
+ // A valid replacement snapshot clears the reset before delivery.
418
+ return;
419
+ }
420
+ lockedSegments.push(segmentResult);
421
+ var latestFullSnapshotIndex = -1;
422
+ for (var index = lockedSegments.length - 1; index >= 0; index -= 1) {
423
+ if (lockedSegments[index].$rMetadata.has_full_snapshot) {
424
+ latestFullSnapshotIndex = index;
425
+ break;
102
426
  }
103
- clearTimeout(state.expirationTimeoutId);
104
427
  }
428
+ if (latestFullSnapshotIndex > 0) {
429
+ lockedSegments.splice(0, latestFullSnapshotIndex);
430
+ }
431
+ if (lockedSegments.length > LOCKED_SEGMENTS_LIMIT) {
432
+ // Incremental segments form a dependency chain. Keeping the anchor while
433
+ // deleting a middle segment can leave later records referencing nodes the
434
+ // player never received. Retire the whole lock generation and admit no
435
+ // more incrementals until a replacement full snapshot starts a new chain.
436
+ lockedBufferGeneration += 1;
437
+ lockedSegments = [];
438
+ markReplayResetNeeded('locked_buffer_capacity');
439
+ // Records already admitted to the current segment still belong to the
440
+ // overflowing lock epoch. Finalize that segment now so its immutable
441
+ // epoch can reject the result, and force the replacement Full Snapshot
442
+ // to start a clean segment.
443
+ flushSegment('locked_buffer_capacity');
444
+ }
445
+ }
446
+ function drainLockedSegments() {
447
+ var segmentsToSend = lockedSegments;
448
+ lockedSegments = [];
449
+ if (segmentsToSend.length > 0 && !segmentsToSend.some(function (segmentResult) {
450
+ return segmentResult.$rMetadata.has_full_snapshot;
451
+ })) {
452
+ markReplayResetNeeded('locked_buffer_missing_full_snapshot');
453
+ return;
454
+ }
455
+ segmentsToSend.forEach(function (segmentResult) {
456
+ segmentResult.$rExit = false;
457
+ segmentResult.$rRegular = true;
458
+ sendSegment(segmentResult);
459
+ });
460
+ }
461
+ function deliverSegmentResult(segmentResult) {
462
+ if (!segmentResult.$rLocked) {
463
+ sendSegment(segmentResult);
464
+ return;
465
+ }
466
+ if (segmentResult.$rLockGeneration !== lockedBufferGeneration || segmentResult.$rReason === 'buffer_checkout' || segmentResult.$rReason === 'stop' || segmentResult.$rReason === PageExitReason.UNLOADING) {
467
+ return;
468
+ }
469
+ if (state.$rLocked) {
470
+ retainLockedSegment(segmentResult);
471
+ } else {
472
+ segmentResult.$rExit = false;
473
+ segmentResult.$rRegular = true;
474
+ sendSegment(segmentResult);
475
+ }
476
+ }
477
+ function retainPendingSegmentResult(baselineGeneration, segmentResult) {
478
+ if (!pendingSegmentResultsByGeneration[baselineGeneration]) {
479
+ pendingSegmentResultsByGeneration[baselineGeneration] = [];
480
+ }
481
+ pendingSegmentResultsByGeneration[baselineGeneration].push(segmentResult);
482
+ }
483
+ function confirmBaselineGeneration(baselineGeneration, segmentResult) {
484
+ if (replayRecoveryExhausted || baselineGenerationStates[baselineGeneration] === 'invalid') {
485
+ return;
486
+ }
487
+ baselineGenerationStates[baselineGeneration] = 'confirmed';
488
+ if (baselineGeneration === activeBaselineGeneration && (!replayResetNeeded || !segmentResult.$rLocked || segmentResult.$rLockGeneration === lockedBufferGeneration)) {
489
+ consecutiveFullSnapshotFailures = 0;
490
+ clearReplayResetNeeded();
491
+ }
492
+ deliverSegmentResult(segmentResult);
493
+ var pendingSegmentResults = pendingSegmentResultsByGeneration[baselineGeneration] || [];
494
+ delete pendingSegmentResultsByGeneration[baselineGeneration];
495
+ pendingSegmentResults.sort(function (first, second) {
496
+ return first.$rSequence - second.$rSequence;
497
+ });
498
+ pendingSegmentResults.forEach(deliverSegmentResult);
499
+ tryCleanupBaselineGeneration(baselineGeneration);
500
+ }
501
+ function handleSuccessfulSegment(baselineGeneration, segmentResult) {
502
+ if (segmentResult.$rMetadata.has_full_snapshot) {
503
+ confirmBaselineGeneration(baselineGeneration, segmentResult);
504
+ return;
505
+ }
506
+ if (baselineGeneration === 0) {
507
+ deliverSegmentResult(segmentResult);
508
+ return;
509
+ }
510
+ var baselineState = baselineGenerationStates[baselineGeneration];
511
+ if (baselineState === 'confirmed') {
512
+ deliverSegmentResult(segmentResult);
513
+ } else if (baselineState === 'pending') {
514
+ retainPendingSegmentResult(baselineGeneration, segmentResult);
515
+ } else if (baselineGeneration === activeBaselineGeneration && !replayRecoveryExhausted) {
516
+ failBaselineGeneration(baselineGeneration, 'missing_full_snapshot', false);
517
+ }
518
+ }
519
+ function resetState(flushReason) {
105
520
  if (flushReason !== 'stop') {
106
521
  state = {
107
- status: SegmentCollectionStatus.WaitingForInitialRecord,
108
- nextSegmentCreationReason: flushReason,
109
- isLocked: state.isLocked
522
+ $rStatus: SegmentCollectionStatus.WaitingForInitialRecord,
523
+ $rNextReason: flushReason,
524
+ $rLocked: state.$rLocked,
525
+ $rGeneration: activeBaselineGeneration
110
526
  };
111
527
  } else {
112
528
  state = {
113
- status: SegmentCollectionStatus.Stopped,
114
- isLocked: false
529
+ $rStatus: SegmentCollectionStatus.Stopped,
530
+ $rLocked: false
115
531
  };
116
532
  }
117
533
  }
118
- return {
119
- addRecord: function addRecord(record) {
120
- if (state.status === SegmentCollectionStatus.Stopped) {
534
+ function handleFlushedSegment(flushReason, wasLocked, lockedGeneration, baselineGeneration, metadata, encoderResult, recordCountsByType, transport) {
535
+ if (replayRecoveryExhausted) {
536
+ return;
537
+ }
538
+ if (encoderResult.error) {
539
+ reportDroppedRecord('encoder_error', 0);
540
+ failBaselineGeneration(baselineGeneration, 'encoder_error', metadata.has_full_snapshot);
541
+ scheduleReplayResetNotification();
542
+ return;
543
+ }
544
+ // SEGMENT_BYTES_LIMIT is a rolling target and a beacon budget, not a hard
545
+ // limit for regular fetch requests. The asynchronous deflate result can
546
+ // legitimately overshoot its estimate. Discarding that finalized segment
547
+ // would invalidate the replay chain and can force an impossible
548
+ // replacement snapshot on large pages. sendSegment() applies the bounded
549
+ // page-exit delivery budget separately.
550
+ var segmentResult = {
551
+ $rMetadata: metadata,
552
+ $rEncoder: encoderResult,
553
+ $rReason: flushReason,
554
+ $rExit: transport.$rExit,
555
+ $rLocked: wasLocked,
556
+ $rLockGeneration: lockedGeneration,
557
+ $rGeneration: baselineGeneration,
558
+ $rTransportGeneration: getTransportGenerationState(baselineGeneration),
559
+ $rSequence: transport.$rSequence
560
+ };
561
+ if (false) {
562
+ segmentResult.$rCounts = recordCountsByType;
563
+ }
564
+ handleSuccessfulSegment(baselineGeneration, segmentResult);
565
+ scheduleReplayResetNotification();
566
+ }
567
+ function flushSegment(flushReason, callback, isStopping) {
568
+ if (state.$rStatus === SegmentCollectionStatus.Stopped) {
569
+ if (callback) {
570
+ callback();
571
+ }
572
+ return;
573
+ }
574
+ if (state.$rStatus === SegmentCollectionStatus.SegmentPending && state.$rMandatoryRecoveryHold) {
575
+ if (isStopping) {
576
+ mandatoryRecoveryPending = false;
577
+ discardCurrentSegment('mandatory_recovery_incomplete');
578
+ // discardCurrentSegment() normally returns to Waiting so a recovery
579
+ // baseline can create the next stream. A terminal stop must override
580
+ // that reusable state even though the discard finish is asynchronous.
581
+ resetState('stop');
582
+ }
583
+ if (callback) {
584
+ callback();
585
+ }
586
+ return;
587
+ }
588
+ if (flushReason !== 'canvas_snapshot') {
589
+ clearCanvasFlushTimeout();
590
+ }
591
+ if (state.$rStatus === SegmentCollectionStatus.SegmentPending) {
592
+ var segmentState = state;
593
+ var wasLocked = segmentState.$rLocked;
594
+ var lockedGeneration = segmentState.$rLockGeneration;
595
+ var baselineGeneration = state.$rGeneration;
596
+ var transport = {
597
+ $rExit: isPageExitReason(flushReason),
598
+ $rSequence: ++nextSegmentFlushSequence
599
+ };
600
+ clearTimeout(state.$rExpiration);
601
+ resetState(isStopping ? 'stop' : flushReason);
602
+ if (!segmentState.$rSegment.isEmpty()) {
603
+ inFlightSegmentFlushes.add(transport);
604
+ retainBaselineGeneration(baselineGeneration);
605
+ segmentState.$rSegment.flush(function (metadata, encoderResult, recordCountsByType) {
606
+ removeInFlightSegmentFlush(transport);
607
+ try {
608
+ handleFlushedSegment(flushReason, wasLocked, lockedGeneration, baselineGeneration, metadata, encoderResult, recordCountsByType, transport);
609
+ } finally {
610
+ releaseBaselineGeneration(baselineGeneration);
611
+ }
612
+ if (callback) {
613
+ callback();
614
+ }
615
+ });
616
+ return;
617
+ }
618
+ }
619
+ resetState(isStopping ? 'stop' : flushReason);
620
+ if (callback) {
621
+ callback();
622
+ }
623
+ }
624
+ function ensureSegment() {
625
+ if (state.$rStatus !== SegmentCollectionStatus.WaitingForInitialRecord) {
626
+ return state.$rStatus === SegmentCollectionStatus.SegmentPending;
627
+ }
628
+ var context = getSegmentContext();
629
+ if (!context) {
630
+ return false;
631
+ }
632
+ state = {
633
+ $rStatus: SegmentCollectionStatus.SegmentPending,
634
+ $rSegment: createSegment({
635
+ encoder: encoder,
636
+ context: context,
637
+ creationReason: state.$rNextReason
638
+ }),
639
+ $rLocked: state.$rLocked,
640
+ $rLockGeneration: lockedBufferGeneration,
641
+ $rGeneration: activeBaselineGeneration,
642
+ $rHasSnapshot: false,
643
+ $rMandatoryRecoveryHold: mandatoryRecoveryPending,
644
+ $rExpiration: setTimeout(function () {
645
+ flushSegment('segment_duration_limit');
646
+ }, SEGMENT_DURATION_LIMIT)
647
+ };
648
+ return true;
649
+ }
650
+ function discardEmptyCurrentSegment(reason) {
651
+ if (state.$rStatus === SegmentCollectionStatus.SegmentPending && state.$rSegment.isEmpty()) {
652
+ clearTimeout(state.$rExpiration);
653
+ resetState(reason);
654
+ }
655
+ }
656
+ function discardCurrentSegment(reason) {
657
+ if (state.$rStatus !== SegmentCollectionStatus.SegmentPending) {
658
+ return;
659
+ }
660
+ var discardedSegment = state.$rSegment;
661
+ var isEmpty = discardedSegment.isEmpty();
662
+ clearTimeout(state.$rExpiration);
663
+ resetState(reason);
664
+ if (!isEmpty) {
665
+ // The deflate encoder is shared by consecutive segments. Merely
666
+ // forgetting this Segment would leave its already-written bytes in the
667
+ // active stream and prepend them to the replacement baseline. Finalize
668
+ // the stream to reset the encoder, but deliberately ignore its result.
669
+ discardedSegment.$rDiscard(function () {
670
+ // A rejected mandatory Full Snapshot may have marked recovery while
671
+ // encoder writes were still pending. Wake the deferred notification
672
+ // after finish drains that backlog, even though this segment result is
673
+ // intentionally not delivered.
674
+ scheduleReplayResetNotification();
675
+ });
676
+ }
677
+ }
678
+ function addRecordToCurrentSegment(record, serializedRecordData, ignoreSegmentBytesLimit) {
679
+ var segmentState = state;
680
+ var segment = segmentState.$rSegment;
681
+ var synchronousEncoderError;
682
+ var addResult = segment.addRecord(record, function (encodedBytesCount, error) {
683
+ if (state.$rStatus !== SegmentCollectionStatus.SegmentPending || state.$rSegment !== segment) {
684
+ scheduleReplayResetNotification();
121
685
  return;
122
686
  }
123
- if (state.status === SegmentCollectionStatus.WaitingForInitialRecord) {
124
- var context = getSegmentContext();
125
- if (!context) {
126
- return;
687
+ if (error) {
688
+ synchronousEncoderError = error;
689
+ var isBaselineTransactionFailure = activeBaselineTransaction && activeBaselineTransaction.$rSegment === segment;
690
+ clearTimeout(state.$rExpiration);
691
+ reportDroppedRecord('encoder_error', 0);
692
+ resetState('encoder_error');
693
+ failBaselineGeneration(segmentState.$rGeneration, 'encoder_error', segmentState.$rHasSnapshot || Boolean(isBaselineTransactionFailure));
694
+ } else if (encodedBytesCount > SEGMENT_BYTES_LIMIT && !segmentState.$rMandatoryRecoveryHold) {
695
+ if (activeBaselineTransaction && activeBaselineTransaction.$rSegment === segment) {
696
+ // Meta + Focus + FullSnapshot is one replay baseline. An encoder
697
+ // callback may run synchronously while those records are being
698
+ // added; flushing after Meta would expose an incomplete baseline
699
+ // and leave the following records without a current segment.
700
+ activeBaselineTransaction.$rExceededSegmentBytesLimit = true;
701
+ } else {
702
+ flushSegment('segment_bytes_limit');
703
+ }
704
+ }
705
+ scheduleReplayResetNotification();
706
+ }, ignoreSegmentBytesLimit ? undefined : SEGMENT_BYTES_LIMIT, pendingRawBytesLimit, serializedRecordData);
707
+ if (synchronousEncoderError) {
708
+ return {
709
+ status: 'encoder_error',
710
+ error: synchronousEncoderError
711
+ };
712
+ }
713
+ return addResult;
714
+ }
715
+ function flushCanvasWithRateLimit() {
716
+ var now = dateNow();
717
+ var timeUntilNextFlush = CANVAS_FLUSH_MIN_INTERVAL - (now - lastCanvasFlushAt);
718
+ if (timeUntilNextFlush <= 0) {
719
+ lastCanvasFlushAt = now;
720
+ flushSegment('canvas_snapshot');
721
+ return;
722
+ }
723
+ if (canvasFlushTimeoutId === undefined) {
724
+ canvasFlushTimeoutId = setTimeout(function () {
725
+ canvasFlushTimeoutId = undefined;
726
+ lastCanvasFlushAt = dateNow();
727
+ flushSegment('canvas_snapshot');
728
+ }, timeUntilNextFlush);
729
+ }
730
+ }
731
+ function addRecordWithBaselineGeneration(record, serializedRecordData, ignoreSegmentBytesLimit) {
732
+ var segmentState = state;
733
+ var previousBaselineGeneration = activeBaselineGeneration;
734
+ var previousSegmentBaselineGeneration = segmentState.$rGeneration;
735
+ var previousHasFullSnapshot = segmentState.$rHasSnapshot;
736
+ var fullSnapshotGeneration;
737
+ if (record.type === RecordType.FullSnapshot) {
738
+ var previousActiveBaselineGeneration = activeBaselineGeneration;
739
+ fullSnapshotGeneration = ++nextBaselineGeneration;
740
+ activeBaselineGeneration = fullSnapshotGeneration;
741
+ baselineGenerationStates[fullSnapshotGeneration] = 'pending';
742
+ segmentState.$rGeneration = fullSnapshotGeneration;
743
+ segmentState.$rHasSnapshot = true;
744
+ }
745
+ var result = addRecordToCurrentSegment(record, serializedRecordData, ignoreSegmentBytesLimit);
746
+ if (result.status === 'segment_full' && fullSnapshotGeneration !== undefined) {
747
+ delete baselineGenerationStates[fullSnapshotGeneration];
748
+ activeBaselineGeneration = previousBaselineGeneration;
749
+ segmentState.$rGeneration = previousSegmentBaselineGeneration;
750
+ segmentState.$rHasSnapshot = previousHasFullSnapshot;
751
+ fullSnapshotGeneration = undefined;
752
+ } else if (fullSnapshotGeneration !== undefined) {
753
+ tryCleanupBaselineGeneration(previousActiveBaselineGeneration);
754
+ }
755
+ return {
756
+ $rResult: result,
757
+ $rGeneration: segmentState.$rGeneration
758
+ };
759
+ }
760
+ function rejectRecordAdmission(wasBackpressured) {
761
+ lastAddRecordWasBackpressured = Boolean(wasBackpressured);
762
+ return false;
763
+ }
764
+ function startFreshBaselineTransactionSegment() {
765
+ if (state.$rStatus === SegmentCollectionStatus.SegmentPending && !state.$rSegment.isEmpty()) {
766
+ if (state.$rMandatoryRecoveryHold) {
767
+ discardCurrentSegment('mandatory_recovery_replaced');
768
+ } else {
769
+ flushSegment('full_snapshot');
770
+ }
771
+ }
772
+ return ensureSegment();
773
+ }
774
+ function tryAddBaselineTransaction(records, ignoreSegmentBytesLimit) {
775
+ var transaction = {
776
+ $rSegment: state.$rSegment,
777
+ $rExceededSegmentBytesLimit: false
778
+ };
779
+ activeBaselineTransaction = transaction;
780
+ var attempt;
781
+ try {
782
+ for (var index = 0; index < records.length; index += 1) {
783
+ var record = records[index];
784
+ var addResult = addRecordWithBaselineGeneration(record, backpressuredSerializedRecordData.get(record), ignoreSegmentBytesLimit);
785
+ if (addResult.$rResult.status !== 'added') {
786
+ attempt = {
787
+ $rAddResult: addResult,
788
+ $rRecord: record
789
+ };
790
+ break;
127
791
  }
128
- state = {
129
- status: SegmentCollectionStatus.SegmentPending,
130
- segment: createSegment({
131
- encoder: encoder,
132
- context: context,
133
- creationReason: state.nextSegmentCreationReason
134
- }),
135
- isLocked: state.isLocked,
136
- expirationTimeoutId: setTimeout(function () {
137
- flushSegment('segment_duration_limit');
138
- }, SEGMENT_DURATION_LIMIT)
792
+ }
793
+ if (!attempt) {
794
+ attempt = {
795
+ $rAddResult: addResult,
796
+ $rRecord: records[records.length - 1]
139
797
  };
140
798
  }
141
- state.segment.addRecord(record, function (encodedBytesCount) {
142
- if (encodedBytesCount > SEGMENT_BYTES_LIMIT) {
799
+ } finally {
800
+ activeBaselineTransaction = undefined;
801
+ }
802
+ attempt.$rExceededSegmentBytesLimit = transaction.$rExceededSegmentBytesLimit;
803
+ return attempt;
804
+ }
805
+ function rejectBaselineTransaction(records, attempt) {
806
+ var result = attempt.$rAddResult.$rResult;
807
+ var record = attempt.$rRecord;
808
+ records.forEach(function (baselineRecord) {
809
+ backpressuredSerializedRecordData["delete"](baselineRecord);
810
+ });
811
+ if (result.status === 'encoder_error') {
812
+ mandatoryRecoveryPending = false;
813
+ bufferCheckoutPending = false;
814
+ discardCurrentSegment('baseline_transaction_encoder_error');
815
+ return rejectRecordAdmission();
816
+ }
817
+ if (result.status === 'record_too_large') {
818
+ reportDroppedRecord(record.type === RecordType.FullSnapshot ? 'full_snapshot_too_large' : 'record_too_large', result.estimatedBytesCount);
819
+ } else {
820
+ reportDroppedRecord(record.type === RecordType.FullSnapshot ? 'full_snapshot_encoder_backpressure' : 'encoder_backpressure', result.estimatedBytesCount);
821
+ }
822
+ if (record.type === RecordType.FullSnapshot) {
823
+ failBaselineGeneration(attempt.$rAddResult.$rGeneration, result.status === 'record_too_large' ? 'full_snapshot_too_large' : 'full_snapshot_encoder_backpressure', result.status === 'record_too_large');
824
+ }
825
+ mandatoryRecoveryPending = false;
826
+ bufferCheckoutPending = false;
827
+ discardCurrentSegment('baseline_transaction_rejected');
828
+ return rejectRecordAdmission(result.status === 'encoder_backpressure');
829
+ }
830
+ function addBaselineRecords(records) {
831
+ lastAddRecordWasBackpressured = false;
832
+ if (state.$rStatus === SegmentCollectionStatus.Stopped || !records || records.length !== 3 || records[0].type !== RecordType.Meta || records[1].type !== RecordType.Focus || records[2].type !== RecordType.FullSnapshot || !startFreshBaselineTransactionSegment()) {
833
+ return rejectRecordAdmission();
834
+ }
835
+ var attempt = tryAddBaselineTransaction(records, false);
836
+ if (attempt.$rAddResult.$rResult.status === 'segment_full') {
837
+ if (typeof attempt.$rAddResult.$rResult.serializedRecordData === 'string') {
838
+ backpressuredSerializedRecordData.set(attempt.$rRecord, attempt.$rAddResult.$rResult.serializedRecordData);
839
+ }
840
+ // Meta and Focus are the prelude of the Full Snapshot, not independent
841
+ // replay state. Retire this unsent attempt and replay the complete
842
+ // transaction in a fresh segment. Like a Full Snapshot as the first
843
+ // physical record, the retry may exceed the estimated segment target by
844
+ // the small prelude; the finalized payload still goes through the hard
845
+ // SEGMENT_BYTES_LIMIT delivery check.
846
+ discardCurrentSegment('baseline_transaction_retry');
847
+ if (!ensureSegment()) {
848
+ return rejectRecordAdmission();
849
+ }
850
+ attempt = tryAddBaselineTransaction(records, true);
851
+ }
852
+ if (attempt.$rAddResult.$rResult.status !== 'added') {
853
+ return rejectBaselineTransaction(records, attempt);
854
+ }
855
+ records.forEach(function (record) {
856
+ backpressuredSerializedRecordData["delete"](record);
857
+ });
858
+ if (mandatoryRecoveryPending) {
859
+ mandatoryRecoveryPending = false;
860
+ bufferCheckoutPending = false;
861
+ state.$rMandatoryRecoveryHold = false;
862
+ flushSegment('mandatory_full_snapshot');
863
+ } else if (attempt.$rExceededSegmentBytesLimit) {
864
+ flushSegment('segment_bytes_limit');
865
+ }
866
+ return true;
867
+ }
868
+ var segmentCollection = {
869
+ $rAddBaselineRecords: addBaselineRecords,
870
+ addRecord: function addRecord(record) {
871
+ lastAddRecordWasBackpressured = false;
872
+ if (state.$rStatus === SegmentCollectionStatus.Stopped) {
873
+ return rejectRecordAdmission();
874
+ }
875
+ if (bufferCheckoutPending && record.type !== RecordType.FullSnapshot && record.type !== RecordType.Meta && record.type !== RecordType.Focus) {
876
+ return rejectRecordAdmission();
877
+ }
878
+ if (replayResetNeeded && record.type !== RecordType.FullSnapshot && record.type !== RecordType.Meta && record.type !== RecordType.Focus && baselineGenerationStates[activeBaselineGeneration] !== 'pending') {
879
+ return rejectRecordAdmission();
880
+ }
881
+ if (!ensureSegment()) {
882
+ return rejectRecordAdmission();
883
+ }
884
+ var addResult = addRecordWithBaselineGeneration(record, backpressuredSerializedRecordData.get(record));
885
+ var result = addResult.$rResult;
886
+ if (result.status === 'segment_full') {
887
+ var serializedRecordData = result.serializedRecordData;
888
+ if (state.$rMandatoryRecoveryHold) {
889
+ discardCurrentSegment('mandatory_recovery_replaced');
890
+ } else {
143
891
  flushSegment('segment_bytes_limit');
144
892
  }
145
- });
146
- if (options.flushCanvasImmediately && isCanvasMutationRecord(record) && state.status === SegmentCollectionStatus.SegmentPending) {
147
- flushSegment('canvas_snapshot');
893
+ if (!ensureSegment()) {
894
+ return rejectRecordAdmission();
895
+ }
896
+ addResult = addRecordWithBaselineGeneration(record, serializedRecordData);
897
+ result = addResult.$rResult;
898
+ }
899
+ if (result.status === 'record_too_large') {
900
+ backpressuredSerializedRecordData["delete"](record);
901
+ reportDroppedRecord('record_too_large', result.estimatedBytesCount);
902
+ discardEmptyCurrentSegment('record_too_large');
903
+ // Incremental admission fails synchronously, before the recorder
904
+ // publishes any DOM membership carried by the record. Returning false
905
+ // lets it cancel that staged membership, so the existing baseline
906
+ // remains valid and does not need a global reset.
907
+ if (record.type !== RecordType.IncrementalSnapshot) {
908
+ failBaselineGeneration(addResult.$rGeneration, record.type === RecordType.FullSnapshot ? 'full_snapshot_too_large' : 'record_too_large', record.type === RecordType.FullSnapshot);
909
+ }
910
+ if (record.type === RecordType.FullSnapshot && mandatoryRecoveryPending) {
911
+ mandatoryRecoveryPending = false;
912
+ bufferCheckoutPending = false;
913
+ discardCurrentSegment('mandatory_recovery_failed');
914
+ }
915
+ return rejectRecordAdmission();
148
916
  }
917
+ if (result.status === 'encoder_backpressure') {
918
+ if (typeof result.serializedRecordData === 'string') {
919
+ backpressuredSerializedRecordData.set(record, result.serializedRecordData);
920
+ }
921
+ reportDroppedRecord('encoder_backpressure', result.estimatedBytesCount);
922
+ if (state.$rSegment.isEmpty()) {
923
+ discardEmptyCurrentSegment('encoder_backpressure');
924
+ } else {
925
+ flushSegment('encoder_backpressure');
926
+ }
927
+ // See the synchronous incremental rejection rationale above. Full
928
+ // snapshots and non-incremental baseline records retain the existing
929
+ // recovery semantics.
930
+ if (record.type !== RecordType.IncrementalSnapshot) {
931
+ failBaselineGeneration(addResult.$rGeneration, record.type === RecordType.FullSnapshot ? 'full_snapshot_encoder_backpressure' : 'encoder_backpressure', false);
932
+ }
933
+ if (record.type === RecordType.FullSnapshot && mandatoryRecoveryPending) {
934
+ mandatoryRecoveryPending = false;
935
+ bufferCheckoutPending = false;
936
+ discardCurrentSegment('mandatory_recovery_failed');
937
+ }
938
+ return rejectRecordAdmission(true);
939
+ }
940
+ backpressuredSerializedRecordData["delete"](record);
941
+ if (result.status === 'encoder_error') {
942
+ if (record.type === RecordType.FullSnapshot && mandatoryRecoveryPending) {
943
+ mandatoryRecoveryPending = false;
944
+ bufferCheckoutPending = false;
945
+ discardCurrentSegment('mandatory_recovery_failed');
946
+ }
947
+ return rejectRecordAdmission();
948
+ }
949
+ if (record.type === RecordType.FullSnapshot && mandatoryRecoveryPending) {
950
+ mandatoryRecoveryPending = false;
951
+ bufferCheckoutPending = false;
952
+ state.$rMandatoryRecoveryHold = false;
953
+ flushSegment('mandatory_full_snapshot');
954
+ }
955
+ if (options.flushCanvasImmediately && isCanvasMutationRecord(record) && state.$rStatus === SegmentCollectionStatus.SegmentPending) {
956
+ flushCanvasWithRateLimit();
957
+ }
958
+ return true;
959
+ },
960
+ $rWasLastAddRecordBackpressured: function $rWasLastAddRecordBackpressured() {
961
+ return lastAddRecordWasBackpressured;
149
962
  },
150
963
  unlockSegment: function unlockSegment() {
151
- state.isLocked = false;
964
+ state.$rLocked = false;
965
+ drainLockedSegments();
152
966
  },
153
967
  flushBufferSegment: function flushBufferSegment(callback) {
154
- flushSegment('buffer_checkout', callback);
968
+ if (bufferCheckoutPending) {
969
+ return false;
970
+ }
971
+ bufferCheckoutPending = true;
972
+ lockedBufferGeneration += 1;
973
+ lockedSegments = [];
974
+ var callbackWasInvoked = false;
975
+ flushSegment('buffer_checkout', function () {
976
+ callbackWasInvoked = true;
977
+ beginMandatoryRecovery();
978
+ if (callback) {
979
+ callback();
980
+ }
981
+ });
982
+ // A non-empty segment finishes asynchronously. Enter the hold before
983
+ // application code can enqueue another record or unlock the error
984
+ // session, so no post-checkout incrementals can be sent without the
985
+ // replacement baseline.
986
+ if (!callbackWasInvoked) {
987
+ beginMandatoryRecovery();
988
+ }
989
+ return true;
155
990
  },
156
991
  isLocked: function isLocked() {
157
- return state.isLocked;
992
+ return state.$rLocked;
993
+ },
994
+ $rBeginMandatoryRecovery: function $rBeginMandatoryRecovery() {
995
+ beginMandatoryRecovery();
996
+ },
997
+ $rDiscardMandatoryRecovery: function $rDiscardMandatoryRecovery() {
998
+ if (!mandatoryRecoveryPending) {
999
+ return;
1000
+ }
1001
+ mandatoryRecoveryPending = false;
1002
+ bufferCheckoutPending = false;
1003
+ if (state.$rStatus === SegmentCollectionStatus.SegmentPending && state.$rMandatoryRecoveryHold) {
1004
+ discardCurrentSegment('mandatory_recovery_incomplete');
1005
+ }
158
1006
  },
159
- stop: function stop() {
160
- flushSegment('stop');
161
- unsubscribeViewCreated();
162
- unsubscribePageExited();
1007
+ stop: function stop(flushReason) {
1008
+ lockedBufferGeneration += 1;
1009
+ lockedSegments = [];
1010
+ bufferCheckoutPending = false;
1011
+ clearCanvasFlushTimeout();
1012
+ clearReplayResetNotificationTimeout();
1013
+ upgradeSegmentTransportsForPageExit(flushReason);
1014
+ var stopEvent = isPageExitReason(flushReason) ? {
1015
+ reason: flushReason
1016
+ } : undefined;
1017
+ prepareRecordsBeforePageExit(stopEvent);
1018
+ if (flushReason === PageExitReason.UNLOADING) {
1019
+ flushSegment(flushReason || 'stop');
1020
+ if (flushPendingSegmentEncodingsForUnload(flushReason)) {
1021
+ // A synchronous encoder drain can release admission backpressure.
1022
+ // Ask the still-active recorder for one final mutation pass before
1023
+ // terminally closing the second unload-safe segment.
1024
+ prepareRecordsBeforePageExit(stopEvent);
1025
+ }
1026
+ }
1027
+ flushSegment(flushReason || 'stop', undefined, true);
1028
+ // Normal stop/session renewal must not force a potentially large worker
1029
+ // backlog onto the main thread or apply the unload delivery budget. The
1030
+ // encoder queues a reset after each finish, so a restarted recorder can
1031
+ // append a new generation while these old results complete in order.
1032
+ // Only a real unload needs the bounded synchronous drain.
1033
+ flushPendingSegmentEncodingsForUnload(flushReason);
1034
+ unsubscribeLifecycle();
163
1035
  }
164
1036
  };
1037
+ if (false) {
1038
+ segmentCollection.getBaselineGenerationStateCountForDebug = function () {
1039
+ return Object.keys(baselineGenerationStates).length;
1040
+ };
1041
+ }
1042
+ return segmentCollection;
1043
+ function beginMandatoryRecovery() {
1044
+ mandatoryRecoveryPending = true;
1045
+ if (state.$rStatus === SegmentCollectionStatus.SegmentPending) {
1046
+ state.$rMandatoryRecoveryHold = true;
1047
+ clearTimeout(state.$rExpiration);
1048
+ }
1049
+ }
165
1050
  }
166
1051
  function isCanvasMutationRecord(record) {
167
1052
  return record && record.type === RecordType.IncrementalSnapshot && record.data && record.data.source === IncrementalSource.CanvasMutation;