fix(training): 修复课程学习倒计时停顿
This commit is contained in:
@@ -250,8 +250,11 @@ enum TrainingValidation {
|
|||||||
struct TrainingReadingClock {
|
struct TrainingReadingClock {
|
||||||
private var lastUptime: TimeInterval?
|
private var lastUptime: TimeInterval?
|
||||||
|
|
||||||
/// 页面内容可见且 App 活跃时开始一个新的计时片段。
|
/// 暂停后开始新的计时片段;持续可见时重复恢复不改变正在累计的起点。
|
||||||
mutating func resume(at uptime: TimeInterval) { lastUptime = uptime }
|
mutating func resume(at uptime: TimeInterval) {
|
||||||
|
guard lastUptime == nil else { return }
|
||||||
|
lastUptime = uptime
|
||||||
|
}
|
||||||
|
|
||||||
/// 失去前台可见性时丢弃未满一秒的片段。
|
/// 失去前台可见性时丢弃未满一秒的片段。
|
||||||
mutating func pause() { lastUptime = nil }
|
mutating func pause() { lastUptime = nil }
|
||||||
|
|||||||
@@ -103,6 +103,12 @@ final class TrainingRemoteReadingViewModel {
|
|||||||
&& progress?.canStudy == true && progress?.readingCompleted == false && !isInvalidated
|
&& progress?.canStudy == true && progress?.readingCompleted == false && !isInvalidated
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// 上一次请求结束后才允许发送下一次心跳;保存失败交由用户重试。
|
||||||
|
var needsReadingFlush: Bool {
|
||||||
|
guard !isInvalidated, !isSessionBusy, readingErrorMessage == nil, let session else { return false }
|
||||||
|
return finalRequested || activeSecondsTotal - acceptedActiveSecondsTotal >= max(1, session.heartbeatIntervalSeconds)
|
||||||
|
}
|
||||||
|
|
||||||
/// 首次只读课程元信息、附件第一页与进度,并为首个附件授权;不请求小节标题或 HTML。
|
/// 首次只读课程元信息、附件第一页与进度,并为首个附件授权;不请求小节标题或 HTML。
|
||||||
func load() async {
|
func load() async {
|
||||||
guard !isLoading, !isInvalidated else { return }
|
guard !isLoading, !isInvalidated else { return }
|
||||||
@@ -248,14 +254,15 @@ final class TrainingRemoteReadingViewModel {
|
|||||||
attachmentErrorMessage = nil
|
attachmentErrorMessage = nil
|
||||||
}
|
}
|
||||||
|
|
||||||
/// 附件已渲染且前台可见时建立或恢复会话;创建丢响应时沿用原 requestID。
|
/// 附件已渲染且前台可见时建立或恢复会话;正在阅读时重复调用不重启计时。
|
||||||
func startReading(at uptime: TimeInterval) async {
|
func startReading(at uptime: TimeInterval) async {
|
||||||
guard isAttachmentRendered, currentAttachmentLink != nil, canStudy else { return }
|
guard isAttachmentRendered, currentAttachmentLink != nil, canStudy else { return }
|
||||||
|
lastVisibleUptime = uptime
|
||||||
|
guard !isReading else { return }
|
||||||
let epoch = generation
|
let epoch = generation
|
||||||
wantsReading = true
|
wantsReading = true
|
||||||
lastVisibleUptime = uptime
|
|
||||||
await waitForSessionOperation(epoch: epoch)
|
await waitForSessionOperation(epoch: epoch)
|
||||||
guard generation == epoch, !isInvalidated, wantsReading, canStudy, isAttachmentRendered else { return }
|
guard generation == epoch, !isInvalidated, wantsReading, canStudy, isAttachmentRendered, !isReading else { return }
|
||||||
isSessionBusy = true
|
isSessionBusy = true
|
||||||
defer { finishSessionOperation(epoch: epoch) }
|
defer { finishSessionOperation(epoch: epoch) }
|
||||||
do {
|
do {
|
||||||
@@ -272,16 +279,21 @@ final class TrainingRemoteReadingViewModel {
|
|||||||
} catch { await handleReadingError(error, epoch: epoch) }
|
} catch { await handleReadingError(error, epoch: epoch) }
|
||||||
}
|
}
|
||||||
|
|
||||||
/// 由前台定时器驱动,每次最多记一秒;到间隔或门槛才发送网络心跳。
|
/// 前台可见时每次最多记一秒;网络心跳进行中仍累计,到门槛时同步停止。
|
||||||
func recordVisibleTime(at uptime: TimeInterval) async {
|
@discardableResult
|
||||||
|
func accumulateVisibleTime(at uptime: TimeInterval) -> Bool {
|
||||||
lastVisibleUptime = uptime
|
lastVisibleUptime = uptime
|
||||||
guard isReading, wantsReading, canStudy, isAttachmentRendered, !isSessionBusy, pendingHeartbeat == nil,
|
guard session != nil, isReading, wantsReading, canStudy, isAttachmentRendered, readingErrorMessage == nil,
|
||||||
readingClock.takeSecond(at: uptime) else { return }
|
readingClock.takeSecond(at: uptime) else { return false }
|
||||||
activeSecondsTotal += 1
|
activeSecondsTotal += 1
|
||||||
let interval = max(1, session?.heartbeatIntervalSeconds ?? 5)
|
if remainingSeconds == 0 { pauseReading() }
|
||||||
if activeSecondsTotal - acceptedActiveSecondsTotal >= interval || remainingSeconds == 0 {
|
return true
|
||||||
await flush(final: remainingSeconds == 0)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// 累计可见读时并等待本次保存;持续刷新的页面可分别调用累计与保存方法。
|
||||||
|
func recordVisibleTime(at uptime: TimeInterval) async {
|
||||||
|
accumulateVisibleTime(at: uptime)
|
||||||
|
if needsReadingFlush { await flush() }
|
||||||
}
|
}
|
||||||
|
|
||||||
/// 页面隐藏、锁屏、文档切换或预览失败时同步停止计时,丢弃未满一秒片段。
|
/// 页面隐藏、锁屏、文档切换或预览失败时同步停止计时,丢弃未满一秒片段。
|
||||||
|
|||||||
@@ -398,7 +398,12 @@ final class TrainingCourseViewController: TrainingBaseViewController {
|
|||||||
@objc private func appDidBecomeActive() { appIsActive = true; resumeReading() }
|
@objc private func appDidBecomeActive() { appIsActive = true; resumeReading() }
|
||||||
|
|
||||||
private func resumeReading(retrying: Bool = false) {
|
private func resumeReading(retrying: Bool = false) {
|
||||||
guard isContentVisible, viewModel.canStudy, (retrying || viewModel.readingErrorMessage == nil), readingTask == nil else { return }
|
guard isContentVisible, viewModel.canStudy, (retrying || viewModel.readingErrorMessage == nil) else { return }
|
||||||
|
if viewModel.isReading {
|
||||||
|
installReadingTimer()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
guard readingTask == nil else { return }
|
||||||
let request = retrying ? beginUserRequest(showsLoading: true) : nil
|
let request = retrying ? beginUserRequest(showsLoading: true) : nil
|
||||||
guard !retrying || request != nil else { return }
|
guard !retrying || request != nil else { return }
|
||||||
let pendingClose = closingTask
|
let pendingClose = closingTask
|
||||||
@@ -427,13 +432,15 @@ final class TrainingCourseViewController: TrainingBaseViewController {
|
|||||||
}
|
}
|
||||||
|
|
||||||
private func readingTick() {
|
private func readingTick() {
|
||||||
guard isContentVisible, readingTask == nil, viewModel.isReading else { return }
|
guard isContentVisible else { return }
|
||||||
|
if viewModel.accumulateVisibleTime(at: ProcessInfo.processInfo.systemUptime) { applyState() }
|
||||||
|
guard readingTask == nil, viewModel.needsReadingFlush else { return }
|
||||||
readingTask = Task { @MainActor [weak self] in
|
readingTask = Task { @MainActor [weak self] in
|
||||||
guard let self else { return }
|
guard let self else { return }
|
||||||
await viewModel.recordVisibleTime(at: ProcessInfo.processInfo.systemUptime)
|
await viewModel.flush()
|
||||||
readingTask = nil
|
readingTask = nil
|
||||||
applyState()
|
applyState()
|
||||||
if isContentVisible, viewModel.canStudy, !viewModel.isReading { resumeReading() }
|
if isContentVisible, viewModel.canStudy, !viewModel.isReading, viewModel.remainingSeconds > 0 { resumeReading() }
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -203,6 +203,93 @@ final class TrainingDocumentPreviewTests: XCTestCase {
|
|||||||
XCTAssertFalse(calls.contains { ["sections", "section"].contains($0.name) })
|
XCTAssertFalse(calls.contains { ["sections", "section"].contains($0.name) })
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// 实际课程滚动回调持续触发时,按钮倒计时仍随有效阅读时间减少。
|
||||||
|
func testContinuousCourseScrollingKeepsCountdownRunning() async throws {
|
||||||
|
let document = try temporaryDocument(text: (1...120).map { "第 \($0) 行:滑动阅读时仍应累计有效读时。" }.joined(separator: "\n"), kind: .txt)
|
||||||
|
defer { try? FileManager.default.removeItem(at: document.fileURL.deletingLastPathComponent()) }
|
||||||
|
let (controller, _, scroll, window) = try await makeCourseWindow(document: document, readingSeconds: 0)
|
||||||
|
defer { closeWindow(window) }
|
||||||
|
let action = try XCTUnwrap(allViews(controller.view).compactMap { $0 as? UIButton }
|
||||||
|
.first { $0.accessibilityIdentifier == "training.reading.action" })
|
||||||
|
func remainingSeconds() -> Int? {
|
||||||
|
guard let title = action.configuration?.title, let start = title.lastIndex(of: "("),
|
||||||
|
let end = title.range(of: "s)")?.lowerBound else { return nil }
|
||||||
|
return Int(title[title.index(after: start)..<end])
|
||||||
|
}
|
||||||
|
try await waitUntil { remainingSeconds() != nil }
|
||||||
|
let before = try XCTUnwrap(remainingSeconds())
|
||||||
|
let deadline = ContinuousClock.now.advanced(by: .milliseconds(3200))
|
||||||
|
var frame = 0
|
||||||
|
while ContinuousClock.now < deadline {
|
||||||
|
scroll.setContentOffset(CGPoint(x: 0, y: 220 + frame % 80), animated: false)
|
||||||
|
frame += 1
|
||||||
|
try await Task.sleep(for: .milliseconds(16))
|
||||||
|
}
|
||||||
|
XCTAssertGreaterThan(frame, 60)
|
||||||
|
let after = try XCTUnwrap(remainingSeconds())
|
||||||
|
XCTAssertLessThanOrEqual(after, before - 2, "正文持续可见时,滚动不能重置计时起点")
|
||||||
|
record(UIGraphicsImageRenderer(size: controller.view.bounds.size).image { _ in
|
||||||
|
controller.view.drawHierarchy(in: controller.view.bounds, afterScreenUpdates: true)
|
||||||
|
}, name: "课程持续滚动倒计时")
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 慢心跳不能冻结真实页面倒计时,读满后仍须等待后端确认才能开始考试。
|
||||||
|
func testSlowHeartbeatKeepsCountdownRunningUntilServerConfirmsReading() async throws {
|
||||||
|
let document = try temporaryDocument(text: (1...120).map { "第 \($0) 行:课程阅读期间上报进度不应打断倒计时。" }.joined(separator: "\n"), kind: .txt)
|
||||||
|
defer { try? FileManager.default.removeItem(at: document.fileURL.deletingLastPathComponent()) }
|
||||||
|
let gate = TrainingCourseHeartbeatGate()
|
||||||
|
defer { Task { await gate.releaseAll() } }
|
||||||
|
var configuration = TrainingDataStub.Configuration()
|
||||||
|
configuration.readingSeconds = 14
|
||||||
|
let source = TrainingDataStub(configuration: configuration)
|
||||||
|
await source.configure {
|
||||||
|
$0.heartbeatHandler = { call in
|
||||||
|
await gate.wait(sequence: call.sequence)
|
||||||
|
return TrainingHeartbeatConfirmation(sessionID: call.sessionID, acceptedSequence: call.sequence,
|
||||||
|
acceptedActiveSecondsTotal: call.activeSecondsTotal, sessionClosed: call.final,
|
||||||
|
progress: TrainingRemoteFixtures.progress(seconds: min(20, 14 + call.activeSecondsTotal)))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let controller = TrainingCourseViewController(taskID: "task_1", service: source,
|
||||||
|
documentLoader: TrainingFixtureDocumentLoader { _, _ in document })
|
||||||
|
let navigation = UINavigationController(rootViewController: controller)
|
||||||
|
let window = try makeWindow(navigation)
|
||||||
|
defer { closeWindow(window) }
|
||||||
|
let action = try XCTUnwrap(allViews(controller.view).compactMap { $0 as? UIButton }
|
||||||
|
.first { $0.accessibilityIdentifier == "training.reading.action" })
|
||||||
|
try await waitUntil {
|
||||||
|
await source.heartbeats.count == 1 && action.configuration?.title == "开始考试(1s)"
|
||||||
|
}
|
||||||
|
let firstHeartbeats = await source.heartbeats
|
||||||
|
let first = try XCTUnwrap(firstHeartbeats.first)
|
||||||
|
XCTAssertEqual(first.sequence, 1)
|
||||||
|
XCTAssertEqual(first.activeSecondsTotal, 5)
|
||||||
|
XCTAssertFalse(first.final)
|
||||||
|
try await waitUntil { action.configuration?.title == "开始考试(0s)" }
|
||||||
|
XCTAssertFalse(action.isEnabled, "本地读满而首个心跳尚未返回,不能提前开始考试")
|
||||||
|
let heldHeartbeats = await source.heartbeats
|
||||||
|
XCTAssertEqual(heldHeartbeats.count, 1, "同一会话的心跳必须串行发送")
|
||||||
|
action.sendActions(for: .touchUpInside)
|
||||||
|
XCTAssertTrue(navigation.topViewController === controller)
|
||||||
|
let callsBeforeConfirmation = await source.calls
|
||||||
|
XCTAssertFalse(callsBeforeConfirmation.contains { ["paper", "questions", "draft"].contains($0.name) })
|
||||||
|
|
||||||
|
await gate.release(sequence: 1)
|
||||||
|
try await waitUntil { await source.heartbeats.count == 2 }
|
||||||
|
let finalHeartbeats = await source.heartbeats
|
||||||
|
let final = try XCTUnwrap(finalHeartbeats.last)
|
||||||
|
XCTAssertEqual(final.sessionID, first.sessionID)
|
||||||
|
XCTAssertEqual(final.sequence, 2)
|
||||||
|
XCTAssertEqual(final.activeSecondsTotal, 6)
|
||||||
|
XCTAssertTrue(final.final)
|
||||||
|
XCTAssertEqual(action.configuration?.title, "开始考试(0s)")
|
||||||
|
XCTAssertFalse(action.isEnabled, "后端只确认了 19 秒,最终 20 秒确认返回前仍应禁用")
|
||||||
|
|
||||||
|
await gate.release(sequence: 2)
|
||||||
|
try await waitUntil { action.isEnabled && action.configuration?.title == "开始考试" }
|
||||||
|
XCTAssertTrue(navigation.topViewController === controller)
|
||||||
|
}
|
||||||
|
|
||||||
/// 长文件由课程页面统一滚动,原生信息随正文离屏,换为短文件后不残留空白高度。
|
/// 长文件由课程页面统一滚动,原生信息随正文离屏,换为短文件后不残留空白高度。
|
||||||
func testLongTextUsesOuterPageScrollingAndShrinksForNextDocument() async throws {
|
func testLongTextUsesOuterPageScrollingAndShrinksForNextDocument() async throws {
|
||||||
let lines = (1...120).map { "第 \($0) 行:这是完整课程阅读内容,向上滑动时标题和正文应一同移动。" }
|
let lines = (1...120).map { "第 \($0) 行:这是完整课程阅读内容,向上滑动时标题和正文应一同移动。" }
|
||||||
@@ -374,8 +461,10 @@ final class TrainingDocumentPreviewTests: XCTestCase {
|
|||||||
return TrainingLocalDocument(fileURL: file, kind: kind, name: file.lastPathComponent, temporaryDirectory: nil)
|
return TrainingLocalDocument(fileURL: file, kind: kind, name: file.lastPathComponent, temporaryDirectory: nil)
|
||||||
}
|
}
|
||||||
|
|
||||||
private func makeCourseWindow(document: TrainingLocalDocument) async throws -> (TrainingCourseViewController, TrainingDocumentPreviewView, UIScrollView, UIWindow) {
|
private func makeCourseWindow(document: TrainingLocalDocument, readingSeconds: Int = 20) async throws -> (TrainingCourseViewController, TrainingDocumentPreviewView, UIScrollView, UIWindow) {
|
||||||
let source = TrainingDataStub()
|
var configuration = TrainingDataStub.Configuration()
|
||||||
|
configuration.readingSeconds = readingSeconds
|
||||||
|
let source = TrainingDataStub(configuration: configuration)
|
||||||
let name = document.name
|
let name = document.name
|
||||||
let mime: String
|
let mime: String
|
||||||
switch document.kind {
|
switch document.kind {
|
||||||
@@ -469,3 +558,27 @@ final class TrainingDocumentPreviewTests: XCTestCase {
|
|||||||
guard reached else { throw CancellationError() }
|
guard reached else { throw CancellationError() }
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// 精确挂起课程心跳响应,确保超时或断言失败后也能释放所有等待。
|
||||||
|
private actor TrainingCourseHeartbeatGate {
|
||||||
|
private var releasedSequences: Set<Int> = []
|
||||||
|
private var didReleaseAll = false
|
||||||
|
private var waiters: [Int: [CheckedContinuation<Void, Never>]] = [:]
|
||||||
|
|
||||||
|
func wait(sequence: Int) async {
|
||||||
|
guard !didReleaseAll, !releasedSequences.contains(sequence) else { return }
|
||||||
|
await withCheckedContinuation { waiters[sequence, default: []].append($0) }
|
||||||
|
}
|
||||||
|
|
||||||
|
func release(sequence: Int) {
|
||||||
|
releasedSequences.insert(sequence)
|
||||||
|
waiters.removeValue(forKey: sequence)?.forEach { $0.resume() }
|
||||||
|
}
|
||||||
|
|
||||||
|
func releaseAll() {
|
||||||
|
didReleaseAll = true
|
||||||
|
let pending = waiters.values.flatMap { $0 }
|
||||||
|
waiters.removeAll()
|
||||||
|
pending.forEach { $0.resume() }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
@@ -112,7 +112,9 @@ struct TrainingFeatureTests {
|
|||||||
func foregroundClock() {
|
func foregroundClock() {
|
||||||
var clock = TrainingReadingClock()
|
var clock = TrainingReadingClock()
|
||||||
clock.resume(at: 10)
|
clock.resume(at: 10)
|
||||||
|
clock.resume(at: 10.5)
|
||||||
let partial = clock.takeSecond(at: 10.99)
|
let partial = clock.takeSecond(at: 10.99)
|
||||||
|
clock.resume(at: 10.99)
|
||||||
let whole = clock.takeSecond(at: 11)
|
let whole = clock.takeSecond(at: 11)
|
||||||
#expect(!partial)
|
#expect(!partial)
|
||||||
#expect(whole)
|
#expect(whole)
|
||||||
|
|||||||
@@ -97,6 +97,153 @@ struct TrainingRemoteReadingTests {
|
|||||||
#expect(model.remainingSeconds == 0)
|
#expect(model.remainingSeconds == 0)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// 滚动每帧重新确认正文可见,不能重置已经运行的整秒计时片段。
|
||||||
|
@Test("持续滚动十秒仍正常倒计时,只按五秒间隔上报")
|
||||||
|
func continuousScrollingPreservesReadingTime() async {
|
||||||
|
let source = source()
|
||||||
|
let model = model(source)
|
||||||
|
await loadRendered(model)
|
||||||
|
await model.startReading(at: 0)
|
||||||
|
for frame in 1...600 {
|
||||||
|
let uptime = Double(frame) / 60
|
||||||
|
await model.startReading(at: uptime)
|
||||||
|
if frame.isMultiple(of: 15) { await model.recordVisibleTime(at: uptime) }
|
||||||
|
}
|
||||||
|
#expect(model.isReading)
|
||||||
|
#expect(model.activeSecondsTotal == 10)
|
||||||
|
#expect(model.remainingSeconds == 10)
|
||||||
|
#expect(model.progress?.readingSeconds == 10)
|
||||||
|
#expect(await source.startReadingRequests.count == 1)
|
||||||
|
let heartbeats = await source.heartbeats
|
||||||
|
#expect(heartbeats.map(\.activeSecondsTotal) == [5, 10])
|
||||||
|
#expect(heartbeats.map(\.sequence) == [1, 2])
|
||||||
|
#expect(heartbeats.allSatisfy { !$0.final })
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 请求等待响应期间,本地倒计时继续;迟到确认不能覆盖后续可见读时。
|
||||||
|
@Test("五秒心跳挂起时继续累计到八秒,确认后倒计时不回跳")
|
||||||
|
func slowHeartbeatDoesNotBlockLocalCountdown() async {
|
||||||
|
let source = source()
|
||||||
|
let gate = TrainingReadingHeartbeatGate()
|
||||||
|
await source.configure { $0.heartbeatHandler = { await gate.confirm($0) } }
|
||||||
|
let model = model(source)
|
||||||
|
await loadRendered(model)
|
||||||
|
await model.startReading(at: 0)
|
||||||
|
for second in 1...4 { await model.recordVisibleTime(at: Double(second)) }
|
||||||
|
let operation = Task { await model.recordVisibleTime(at: 5) }
|
||||||
|
await gate.waitUntilRequested()
|
||||||
|
for second in 6...8 { #expect(model.accumulateVisibleTime(at: Double(second))) }
|
||||||
|
#expect(model.activeSecondsTotal == 8)
|
||||||
|
#expect(model.remainingSeconds == 12)
|
||||||
|
#expect(model.progress?.readingSeconds == 0)
|
||||||
|
#expect(!model.needsReadingFlush)
|
||||||
|
#expect(await source.heartbeats.count == 1)
|
||||||
|
await gate.release()
|
||||||
|
await operation.value
|
||||||
|
#expect(model.activeSecondsTotal == 8)
|
||||||
|
#expect(model.remainingSeconds == 12)
|
||||||
|
#expect(model.progress?.readingSeconds == 5)
|
||||||
|
#expect(!model.needsReadingFlush)
|
||||||
|
#expect(model.accumulateVisibleTime(at: 9))
|
||||||
|
#expect(!model.needsReadingFlush)
|
||||||
|
#expect(model.accumulateVisibleTime(at: 10))
|
||||||
|
#expect(model.needsReadingFlush)
|
||||||
|
await model.flush()
|
||||||
|
let heartbeats = await source.heartbeats
|
||||||
|
#expect(heartbeats.map(\.activeSecondsTotal) == [5, 10])
|
||||||
|
#expect(heartbeats.map(\.sequence) == [1, 2])
|
||||||
|
#expect(heartbeats.allSatisfy { !$0.final })
|
||||||
|
#expect(model.activeSecondsTotal == 10)
|
||||||
|
#expect(model.remainingSeconds == 10)
|
||||||
|
#expect(model.progress?.readingSeconds == 10)
|
||||||
|
#expect(await source.startReadingRequests.count == 1)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 慢请求已经提交但丢响应时,后续本地读时不能混入同序号重试负载。
|
||||||
|
@Test("慢心跳丢响应后冻结五秒负载重试,后续读时使用新序号")
|
||||||
|
func slowHeartbeatResponseLossKeepsFrozenPayload() async {
|
||||||
|
let source = source()
|
||||||
|
let server = TrainingReadingReplyController(loseHeartbeatResponse: true)
|
||||||
|
let gate = TrainingReadingHeartbeatGate()
|
||||||
|
await bind(server, to: source)
|
||||||
|
await source.configure { $0.heartbeatHandler = { call in
|
||||||
|
_ = await gate.confirm(call)
|
||||||
|
return try await server.confirm(call)
|
||||||
|
} }
|
||||||
|
let model = model(source)
|
||||||
|
await loadRendered(model)
|
||||||
|
await model.startReading(at: 0)
|
||||||
|
for second in 1...4 { await model.recordVisibleTime(at: Double(second)) }
|
||||||
|
let operation = Task { await model.recordVisibleTime(at: 5) }
|
||||||
|
await gate.waitUntilRequested()
|
||||||
|
for second in 6...8 { #expect(model.accumulateVisibleTime(at: Double(second))) }
|
||||||
|
await gate.release()
|
||||||
|
await operation.value
|
||||||
|
#expect(model.readingErrorMessage != nil)
|
||||||
|
#expect(!model.isReading)
|
||||||
|
#expect(model.activeSecondsTotal == 8)
|
||||||
|
#expect(model.remainingSeconds == 12)
|
||||||
|
#expect(!model.needsReadingFlush)
|
||||||
|
#expect(!model.accumulateVisibleTime(at: 9))
|
||||||
|
await model.flush()
|
||||||
|
let retried = await source.heartbeats
|
||||||
|
#expect(retried.count == 2)
|
||||||
|
#expect(retried[0] == retried[1])
|
||||||
|
#expect(retried[0].activeSecondsTotal == 5 && !retried[0].final)
|
||||||
|
#expect(model.progress?.readingSeconds == 5)
|
||||||
|
#expect(model.activeSecondsTotal == 8)
|
||||||
|
#expect(model.remainingSeconds == 12)
|
||||||
|
await model.startReading(at: 100)
|
||||||
|
#expect(model.accumulateVisibleTime(at: 101))
|
||||||
|
#expect(model.accumulateVisibleTime(at: 102))
|
||||||
|
#expect(model.needsReadingFlush)
|
||||||
|
await model.flush()
|
||||||
|
let heartbeats = await source.heartbeats
|
||||||
|
#expect(heartbeats.map(\.activeSecondsTotal) == [5, 5, 10])
|
||||||
|
#expect(heartbeats.map(\.sequence) == [1, 1, 2])
|
||||||
|
#expect(model.progress?.readingSeconds == 10)
|
||||||
|
#expect(model.remainingSeconds == 10)
|
||||||
|
#expect(await source.startReadingRequests.count == 1)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 首次建会话期间到达的重复恢复,等待完成后也不能覆盖首个计时起点。
|
||||||
|
@Test("并发恢复等待同一会话,返回后不重置正在运行的时钟")
|
||||||
|
func concurrentResumesPreserveFirstReadingStart() async {
|
||||||
|
let source = source()
|
||||||
|
let server = TrainingReadingReplyController()
|
||||||
|
let gate = TrainingReadingSessionGate()
|
||||||
|
await bind(server, to: source)
|
||||||
|
await source.configure { $0.startReadingHandler = { requestID in
|
||||||
|
let session = try await server.create(requestID: requestID)
|
||||||
|
await gate.wait()
|
||||||
|
return session
|
||||||
|
} }
|
||||||
|
let model = model(source)
|
||||||
|
await loadRendered(model)
|
||||||
|
let starting = Task { await model.startReading(at: 0) }
|
||||||
|
await gate.waitUntilRequested()
|
||||||
|
let probes = (0..<3).map { _ in TrainingReadingResumeProbe() }
|
||||||
|
let repeated = probes.map { probe in
|
||||||
|
Task {
|
||||||
|
probe.started = true
|
||||||
|
await model.startReading(at: 0.75)
|
||||||
|
probe.finished = true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
while probes.contains(where: { !$0.started }) { await Task.yield() }
|
||||||
|
#expect(probes.allSatisfy { !$0.finished })
|
||||||
|
#expect(await source.startReadingRequests.count == 1)
|
||||||
|
await gate.release()
|
||||||
|
await starting.value
|
||||||
|
for operation in repeated { await operation.value }
|
||||||
|
await model.recordVisibleTime(at: 1)
|
||||||
|
#expect(model.isReading)
|
||||||
|
#expect(model.activeSecondsTotal == 1)
|
||||||
|
#expect(model.remainingSeconds == 19)
|
||||||
|
#expect(await source.startReadingRequests.count == 1)
|
||||||
|
#expect(await source.heartbeats.isEmpty)
|
||||||
|
}
|
||||||
|
|
||||||
/// 已保存读时不混入会话累计;不足五秒的门槛片段也即时确认。
|
/// 已保存读时不混入会话累计;不足五秒的门槛片段也即时确认。
|
||||||
@Test("历史十二秒加新会话八秒,心跳总数仍从零开始")
|
@Test("历史十二秒加新会话八秒,心跳总数仍从零开始")
|
||||||
func historyAndSessionAreSeparate() async {
|
func historyAndSessionAreSeparate() async {
|
||||||
@@ -201,8 +348,8 @@ struct TrainingRemoteReadingTests {
|
|||||||
#expect(model.activeSecondsTotal == 0)
|
#expect(model.activeSecondsTotal == 0)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// 暂停发生在网络请求中间时,先确认旧负载,再以新序号关闭。
|
/// 慢请求中新增读时先留在本地,暂停后确认旧负载,再以新序号关闭全部片段。
|
||||||
@Test("普通心跳请求中途暂停,确认后再发送 final")
|
@Test("普通心跳请求中继续累计后暂停,确认旧负载再 final 保存全部读时")
|
||||||
func pauseDuringHeartbeatFinishesSequentially() async {
|
func pauseDuringHeartbeatFinishesSequentially() async {
|
||||||
let source = source()
|
let source = source()
|
||||||
let gate = TrainingReadingHeartbeatGate()
|
let gate = TrainingReadingHeartbeatGate()
|
||||||
@@ -213,9 +360,15 @@ struct TrainingRemoteReadingTests {
|
|||||||
for second in 1...4 { await model.recordVisibleTime(at: Double(second)) }
|
for second in 1...4 { await model.recordVisibleTime(at: Double(second)) }
|
||||||
let operation = Task { await model.recordVisibleTime(at: 5) }
|
let operation = Task { await model.recordVisibleTime(at: 5) }
|
||||||
await gate.waitUntilRequested()
|
await gate.waitUntilRequested()
|
||||||
|
#expect(model.accumulateVisibleTime(at: 6))
|
||||||
|
#expect(model.accumulateVisibleTime(at: 7))
|
||||||
|
#expect(model.activeSecondsTotal == 7)
|
||||||
|
#expect(model.remainingSeconds == 13)
|
||||||
model.pauseReading()
|
model.pauseReading()
|
||||||
|
#expect(!model.accumulateVisibleTime(at: 8))
|
||||||
let closing = Task { await model.flush() }
|
let closing = Task { await model.flush() }
|
||||||
#expect(await source.heartbeats.count == 1)
|
#expect(await source.heartbeats.count == 1)
|
||||||
|
#expect(await source.heartbeats.first?.activeSecondsTotal == 5)
|
||||||
await gate.release()
|
await gate.release()
|
||||||
await operation.value
|
await operation.value
|
||||||
await closing.value
|
await closing.value
|
||||||
@@ -223,9 +376,10 @@ struct TrainingRemoteReadingTests {
|
|||||||
#expect(calls.count == 2)
|
#expect(calls.count == 2)
|
||||||
#expect(calls[0].sequence == 1 && !calls[0].final)
|
#expect(calls[0].sequence == 1 && !calls[0].final)
|
||||||
#expect(calls[1].sequence == 2 && calls[1].final)
|
#expect(calls[1].sequence == 2 && calls[1].final)
|
||||||
#expect(calls[0].activeSecondsTotal == calls[1].activeSecondsTotal)
|
#expect(calls[0].activeSecondsTotal == 5)
|
||||||
|
#expect(calls[1].activeSecondsTotal == 7)
|
||||||
#expect(!model.isReading)
|
#expect(!model.isReading)
|
||||||
#expect(model.progress?.readingSeconds == 5)
|
#expect(model.progress?.readingSeconds == 7)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// 前台恢复发生在 final 请求中途,等待结束后必须真正建立新会话。
|
/// 前台恢复发生在 final 请求中途,等待结束后必须真正建立新会话。
|
||||||
@@ -740,13 +894,13 @@ private actor TrainingReadingAttachmentGate {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// 精确挂起首个普通心跳,验证暂停不会并行发送或更改该请求。
|
/// 精确挂起首个普通心跳,验证后续读时、暂停和重试不会更改已发送负载。
|
||||||
private actor TrainingReadingHeartbeatGate {
|
private actor TrainingReadingHeartbeatGate {
|
||||||
private var response: CheckedContinuation<Void, Never>?
|
private var response: CheckedContinuation<Void, Never>?
|
||||||
private var waiters: [CheckedContinuation<Void, Never>] = []
|
private var waiters: [CheckedContinuation<Void, Never>] = []
|
||||||
private var hasDelayed = false
|
private var hasDelayed = false
|
||||||
|
|
||||||
/// 首个请求等待测试释放,后续最终心跳立即确认。
|
/// 首个请求等待测试释放,后续请求立即确认。
|
||||||
func confirm(_ call: TrainingDataStub.HeartbeatCall) async -> TrainingHeartbeatConfirmation {
|
func confirm(_ call: TrainingDataStub.HeartbeatCall) async -> TrainingHeartbeatConfirmation {
|
||||||
if !hasDelayed {
|
if !hasDelayed {
|
||||||
hasDelayed = true
|
hasDelayed = true
|
||||||
@@ -767,7 +921,31 @@ private actor TrainingReadingHeartbeatGate {
|
|||||||
await withCheckedContinuation { waiters.append($0) }
|
await withCheckedContinuation { waiters.append($0) }
|
||||||
}
|
}
|
||||||
|
|
||||||
/// 让普通心跳完成,页面随后应使用新序号发送 final。
|
/// 释放已挂起的普通心跳,让测试检查迟到确认之后的状态。
|
||||||
|
func release() { response?.resume(); response = nil }
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 挂起首次建会话响应,让并发可见性恢复请求稳定进入等待队列。
|
||||||
|
private actor TrainingReadingSessionGate {
|
||||||
|
private var response: CheckedContinuation<Void, Never>?
|
||||||
|
private var waiters: [CheckedContinuation<Void, Never>] = []
|
||||||
|
|
||||||
|
/// 等待测试释放创建响应,不使用真实时间延时。
|
||||||
|
func wait() async {
|
||||||
|
await withCheckedContinuation {
|
||||||
|
response = $0
|
||||||
|
waiters.forEach { $0.resume() }
|
||||||
|
waiters = []
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 等待首次会话创建已在响应边界挂起。
|
||||||
|
func waitUntilRequested() async {
|
||||||
|
if response != nil { return }
|
||||||
|
await withCheckedContinuation { waiters.append($0) }
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 允许首次创建完成,其余恢复应复用已经运行的会话。
|
||||||
func release() { response?.resume(); response = nil }
|
func release() { response?.resume(); response = nil }
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user