Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -323,7 +323,7 @@ public class ReplayIntegration(
scopes?.configureScope { it.replayId = current.replayId }
if (isTerminating == true) {
// A main-thread crash blocks the looper while flushing, so mark termination synchronously.
current.captureStrategy?.captureReplay(true) {}
current.captureStrategy?.captureReplay(true) { _, _ -> }
} else {
enqueueOnMainThread {
captureCurrentReplay(current.generation, current.replayId) { strategy, onSegmentSent ->
Expand All @@ -337,7 +337,7 @@ public class ReplayIntegration(
private fun captureCurrentReplay(
expectedGeneration: Long,
expectedReplayId: SentryId,
capture: (CaptureStrategy, (Date) -> Unit) -> Unit,
capture: (CaptureStrategy, (Int, Date) -> Unit) -> Unit,
) {
val current = state.get()
val strategy = current.captureStrategy
Expand All @@ -356,12 +356,13 @@ public class ReplayIntegration(

// Convert before capturing, so the callback knows which strategy continues the replay.
val activeStrategy = strategy.convert()
capture(strategy) { newTimestamp ->
// Runs on the replay executor, which the converted strategy shares. Advancing the segment
// here lands before any segment the converted strategy creates later (e.g. on stop), so the
// flushed segment id is not reused. A stale strategy (stopped or restarted replay) is not
// in the state anymore, so updating it has no effect.
activeStrategy.currentSegment++
capture(strategy) { sentSegmentId, newTimestamp ->
// Runs on the replay executor, which the converted strategy shares. Setting the next segment
// from the sent segment id lands before any segment the converted strategy creates later
// (e.g. on stop), even if queued buffer tasks changed currentSegment after convert() ran.
// A stale strategy (stopped or restarted replay) is not in the state anymore, so updating it
// has no effect.
activeStrategy.currentSegment = sentSegmentId + 1
activeStrategy.segmentTimestamp = newTimestamp
activeStrategy.isFlushed = true
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,7 @@ constructor(
private val ticker: MonotonicTicker,
protected val replayExecutor: ScheduledExecutorService,
protected val persistingExecutor: ScheduledExecutorService,
private val replayCacheProvider: ((replayId: SentryId) -> ReplayCache)? = null,
protected val replayCacheProvider: ((replayId: SentryId) -> ReplayCache)? = null,
) : CaptureStrategy {
internal companion object {
private const val TAG = "CaptureStrategy"
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -91,7 +91,7 @@ constructor(
super.stop()
}

override fun captureReplay(isTerminating: Boolean, onSegmentSent: (Date) -> Unit) {
override fun captureReplay(isTerminating: Boolean, onSegmentSent: (Int, Date) -> Unit) {
if (isTerminating) {
this.isTerminating.set(true)
// avoid capturing replay, because the video will be malformed
Expand All @@ -115,19 +115,20 @@ constructor(
}

createCurrentSegment("capture_replay") { segment ->
bufferedSegments.capture()
val lastBufferedSegment = bufferedSegments.capture()

if (segment is ReplaySegment.Created) {
segment.capture(scopes)
// we only want to increment segment_id in the case of success, but currentSegment
// might be irrelevant since we changed strategies, so in the callback we increment
// it on the new strategy already
onSegmentSent(segment.replay.timestamp)
// pass the sent segment id so the converted strategy advances from what was actually sent
// rather than a snapshot taken before queued buffer tasks updated currentSegment
onSegmentSent(segment.replay.segmentId, segment.replay.timestamp)
} else if (lastBufferedSegment != null) {
onSegmentSent(lastBufferedSegment.replay.segmentId, lastBufferedSegment.replay.timestamp)
}
}
}

override fun flush(onSegmentSent: (Date) -> Unit) = captureReplay(false, onSegmentSent)
override fun flush(onSegmentSent: (Int, Date) -> Unit) = captureReplay(false, onSegmentSent)

override fun onScreenshotRecorded(
bitmap: Bitmap?,
Expand Down Expand Up @@ -184,10 +185,13 @@ constructor(
ticker,
replayExecutor,
persistingExecutor,
replayCacheProvider,
)
captureStrategy.recorderConfig = recorderConfig
// Start at 0; captureReplay's onSegmentSent sets the exact next ID from the last sent segment
// on replayExecutor before any session segment runs, and 0 is right if nothing ends up sent.
captureStrategy.start(
segmentId = currentSegment,
segmentId = 0,
replayId = currentReplayId,
replayType = BUFFER,
)
Expand Down Expand Up @@ -218,16 +222,19 @@ constructor(
}
}

private fun MutableList<ReplaySegment.Created>.capture() {
private fun MutableList<ReplaySegment.Created>.capture(): ReplaySegment.Created? {
var lastCaptured: ReplaySegment.Created? = null
var bufferedSegment = removeFirstOrNull()
while (bufferedSegment != null) {
bufferedSegment.capture(scopes)
lastCaptured = bufferedSegment
bufferedSegment = removeFirstOrNull()
// a short delay between processing envelopes to avoid bursting our server and hitting
// another rate limit https://develop.sentry.dev/sdk/features/#additional-capabilities
// InterruptedException will be handled by the outer try-catch
Thread.sleep(ENVELOPE_PROCESSING_DELAY)
}
return lastCaptured
}

private fun MutableList<ReplaySegment.Created>.rotate(bufferLimit: Long) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -43,10 +43,10 @@ internal interface CaptureStrategy {
* Captures replay data for an event. Session mode may defer sending until its normal segment
* boundary because the replay is already being uploaded continuously.
*/
fun captureReplay(isTerminating: Boolean, onSegmentSent: (Date) -> Unit)
fun captureReplay(isTerminating: Boolean, onSegmentSent: (Int, Date) -> Unit)

/** Explicitly sends the current replay data to Sentry in either session or buffer mode. */
fun flush(onSegmentSent: (Date) -> Unit)
fun flush(onSegmentSent: (Int, Date) -> Unit)

fun onScreenshotRecorded(
bitmap: Bitmap? = null,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -86,7 +86,7 @@ constructor(
super.stop()
}

override fun captureReplay(isTerminating: Boolean, onSegmentSent: (Date) -> Unit) {
override fun captureReplay(isTerminating: Boolean, onSegmentSent: (Int, Date) -> Unit) {
if (options.sessionReplay.isDebug) {
options.logger.log(
DEBUG,
Expand All @@ -96,7 +96,7 @@ constructor(
this.isTerminating.set(isTerminating)
}

override fun flush(onSegmentSent: (Date) -> Unit) {
override fun flush(onSegmentSent: (Int, Date) -> Unit) {
createCurrentSegment("flush") { segment ->
if (segment is ReplaySegment.Created) {
segment.capture(scopes)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -716,13 +716,13 @@ class ReplayIntegrationTest {
fun `stale capture callback cannot mutate restarted replay`() {
val oldReplayId = SentryId()
val newReplayId = SentryId()
var onSegmentSent: ((Date) -> Unit)? = null
var onSegmentSent: ((Int, Date) -> Unit)? = null
val oldStrategy = mock<BufferCaptureStrategy>()
whenever(oldStrategy.currentReplayId).thenReturn(oldReplayId)
whenever(oldStrategy.convert()).thenReturn(oldStrategy)
doAnswer {
@Suppress("UNCHECKED_CAST")
onSegmentSent = it.arguments[1] as (Date) -> Unit
onSegmentSent = it.arguments[1] as (Int, Date) -> Unit
}
.whenever(oldStrategy)
.captureReplay(any(), any())
Expand All @@ -746,7 +746,7 @@ class ReplayIntegrationTest {
replay.stop()
replay.start()
shadowOf(Looper.getMainLooper()).idle()
onSegmentSent?.invoke(Date())
onSegmentSent?.invoke(0, Date())
shadowOf(Looper.getMainLooper()).idle()

assertThat(replay.replayId).isEqualTo(newReplayId)
Expand All @@ -755,12 +755,12 @@ class ReplayIntegrationTest {
@Test
fun `flush followed by immediate stop advances the converted strategy segment`() {
val replayId = SentryId()
var onSegmentSent: ((Date) -> Unit)? = null
var onSegmentSent: ((Int, Date) -> Unit)? = null
val bufferStrategy = mock<BufferCaptureStrategy>()
whenever(bufferStrategy.currentReplayId).thenReturn(replayId)
doAnswer {
@Suppress("UNCHECKED_CAST")
onSegmentSent = it.arguments[0] as (Date) -> Unit
onSegmentSent = it.arguments[0] as (Int, Date) -> Unit
}
.whenever(bufferStrategy)
.flush(any())
Expand Down Expand Up @@ -788,7 +788,7 @@ class ReplayIntegrationTest {
// the flushed segment completes on the replay executor after stop ran on the main thread,
// but before the stop segment of the converted strategy is created
val timestamp = Date()
onSegmentSent!!.invoke(timestamp)
onSegmentSent!!.invoke(0, timestamp)

verify(sessionStrategy).currentSegment = 1
verify(sessionStrategy).segmentTimestamp = timestamp
Expand Down Expand Up @@ -1551,6 +1551,168 @@ class ReplayIntegrationTest {
verify(fixture.scopes).captureReplay(any(), any())
}

private fun createQueuedBufferReplay(
nowProvider: () -> Long,
holdQueue: () -> Boolean,
queuedTasks: ArrayDeque<Runnable>,
capturedSegmentIds: MutableList<Int>,
): ReplayIntegration {
whenever(fixture.replayCache.firstFrameTimestamp()).thenAnswer {
nowProvider() - VIDEO_DURATION
}
val replayExecutor =
mock<java.util.concurrent.ScheduledExecutorService> {
whenever(mock.submit(any<Runnable>())).doAnswer { invocation ->
val task = invocation.arguments[0] as Runnable
if (holdQueue()) queuedTasks.addLast(task) else task.run()
null
}
}
val persistingExecutor =
mock<java.util.concurrent.ScheduledExecutorService> {
whenever(mock.submit(any<Runnable>())).doAnswer { invocation ->
(invocation.arguments[0] as Runnable).run()
null
}
}
doAnswer { invocation ->
capturedSegmentIds += (invocation.arguments[0] as io.sentry.SentryReplayEvent).segmentId
SentryId()
}
.whenever(fixture.scopes)
.captureReplay(any(), any())

fixture.options.cacheDirPath = tmpDir.newFolder().absolutePath
return fixture.getSut(
context,
sessionSampleRate = 0.0,
onErrorSampleRate = 1.0,
dateProvider = ICurrentDateProvider { nowProvider() },
recorderProvider = { mock() },
replayCaptureStrategyProvider = {
BufferCaptureStrategy(
fixture.options,
fixture.scopes,
ICurrentDateProvider { nowProvider() },
fixture.options.monotonicTicker,
replayExecutor,
persistingExecutor,
) { _ ->
fixture.replayCache
}
},
)
}

@Test
fun `queued configuration change before captureReplay does not repeat session segment id`() {
var now = 1_720_693_524_000L
var holdQueue = false
val queuedTasks = ArrayDeque<Runnable>()
val capturedSegmentIds = mutableListOf<Int>()
val replay = createQueuedBufferReplay({ now }, { holdQueue }, queuedTasks, capturedSegmentIds)

replay.register(fixture.scopes, fixture.options)
replay.start()
val config = ScreenshotRecorderConfig(100, 200, 1f, 1f, 1, 20_000)
replay.onConfigurationChanged(config)

holdQueue = true
replay.onConfigurationChanged(config.copy(recordingWidth = 200, recordingHeight = 100))
replay.captureReplay(false)

holdQueue = false
while (queuedTasks.isNotEmpty()) {
queuedTasks.removeFirst().run()
}

now += fixture.options.sessionReplay.sessionSegmentDuration
replay.onScreenshotRecorded(mock())

assertThat(capturedSegmentIds).containsExactly(0, 1, 2).inOrder()
}

@Test
fun `queued frame rotating out a buffered segment before captureReplay does not skip a session segment id`() {
var now = 1_720_693_524_000L
var holdQueue = false
val queuedTasks = ArrayDeque<Runnable>()
val capturedSegmentIds = mutableListOf<Int>()
val replay = createQueuedBufferReplay({ now }, { holdQueue }, queuedTasks, capturedSegmentIds)

replay.register(fixture.scopes, fixture.options)
replay.start()
val config = ScreenshotRecorderConfig(100, 200, 1f, 1f, 1, 20_000)
replay.onConfigurationChanged(config)

// Buffer two segments: segment 0 ends at now, segment 1 ends 20s later
replay.pause()
replay.resume()
now += 20_000L
replay.onConfigurationChanged(config.copy(recordingWidth = 200, recordingHeight = 100))

// Move past errorReplayDuration for segment 0 only, then queue add_frame ahead of captureReplay
now += 15_000L
holdQueue = true
replay.onScreenshotRecorded(mock())
replay.captureReplay(false)

holdQueue = false
while (queuedTasks.isNotEmpty()) {
queuedTasks.removeFirst().run()
}

now += fixture.options.sessionReplay.sessionSegmentDuration
replay.onScreenshotRecorded(mock())

assertThat(capturedSegmentIds).containsExactly(0, 1, 2).inOrder()
}

@Test
fun `queued pause before captureReplay advances session segment id even when current segment fails`() {
var now = 1_720_693_524_000L
var holdQueue = false
val queuedTasks = ArrayDeque<Runnable>()
val capturedSegmentIds = mutableListOf<Int>()
var createCalls = 0
whenever(
fixture.replayCache.createVideoOf(
anyLong(),
anyLong(),
anyInt(),
anyInt(),
anyInt(),
anyInt(),
anyInt(),
any(),
),
)
.thenAnswer {
// Call 1 (pause) and call 3 (session) succeed; call 2 (capture_replay current segment)
// fails
if (++createCalls == 2) null else GeneratedVideo(File("0.mp4"), 5, VIDEO_DURATION)
}
val replay = createQueuedBufferReplay({ now }, { holdQueue }, queuedTasks, capturedSegmentIds)

replay.register(fixture.scopes, fixture.options)
replay.start()
replay.onConfigurationChanged(ScreenshotRecorderConfig(100, 200, 1f, 1f, 1, 20_000))

holdQueue = true
replay.pause()
replay.captureReplay(false)

holdQueue = false
while (queuedTasks.isNotEmpty()) {
queuedTasks.removeFirst().run()
}

now += fixture.options.sessionReplay.sessionSegmentDuration
replay.onScreenshotRecorded(mock())

assertThat(capturedSegmentIds).containsExactly(0, 1).inOrder()
}

@Test
fun `closed replay cannot be started`() {
val replay = fixture.getSut(context)
Expand Down
Loading
Loading