diff --git a/suixinkan/Features/Training/Models/TrainingModels.swift b/suixinkan/Features/Training/Models/TrainingModels.swift index 00e0e0c..fe5788f 100644 --- a/suixinkan/Features/Training/Models/TrainingModels.swift +++ b/suixinkan/Features/Training/Models/TrainingModels.swift @@ -250,8 +250,11 @@ enum TrainingValidation { struct TrainingReadingClock { 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 } diff --git a/suixinkan/Features/Training/ViewModels/TrainingRemoteReadingViewModel.swift b/suixinkan/Features/Training/ViewModels/TrainingRemoteReadingViewModel.swift index 2ac9056..d8617bc 100644 --- a/suixinkan/Features/Training/ViewModels/TrainingRemoteReadingViewModel.swift +++ b/suixinkan/Features/Training/ViewModels/TrainingRemoteReadingViewModel.swift @@ -103,6 +103,12 @@ final class TrainingRemoteReadingViewModel { && 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。 func load() async { guard !isLoading, !isInvalidated else { return } @@ -248,14 +254,15 @@ final class TrainingRemoteReadingViewModel { attachmentErrorMessage = nil } - /// 附件已渲染且前台可见时建立或恢复会话;创建丢响应时沿用原 requestID。 + /// 附件已渲染且前台可见时建立或恢复会话;正在阅读时重复调用不重启计时。 func startReading(at uptime: TimeInterval) async { guard isAttachmentRendered, currentAttachmentLink != nil, canStudy else { return } + lastVisibleUptime = uptime + guard !isReading else { return } let epoch = generation wantsReading = true - lastVisibleUptime = uptime 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 defer { finishSessionOperation(epoch: epoch) } do { @@ -272,16 +279,21 @@ final class TrainingRemoteReadingViewModel { } catch { await handleReadingError(error, epoch: epoch) } } - /// 由前台定时器驱动,每次最多记一秒;到间隔或门槛才发送网络心跳。 - func recordVisibleTime(at uptime: TimeInterval) async { + /// 前台可见时每次最多记一秒;网络心跳进行中仍累计,到门槛时同步停止。 + @discardableResult + func accumulateVisibleTime(at uptime: TimeInterval) -> Bool { lastVisibleUptime = uptime - guard isReading, wantsReading, canStudy, isAttachmentRendered, !isSessionBusy, pendingHeartbeat == nil, - readingClock.takeSecond(at: uptime) else { return } + guard session != nil, isReading, wantsReading, canStudy, isAttachmentRendered, readingErrorMessage == nil, + readingClock.takeSecond(at: uptime) else { return false } activeSecondsTotal += 1 - let interval = max(1, session?.heartbeatIntervalSeconds ?? 5) - if activeSecondsTotal - acceptedActiveSecondsTotal >= interval || remainingSeconds == 0 { - await flush(final: remainingSeconds == 0) - } + if remainingSeconds == 0 { pauseReading() } + return true + } + + /// 累计可见读时并等待本次保存;持续刷新的页面可分别调用累计与保存方法。 + func recordVisibleTime(at uptime: TimeInterval) async { + accumulateVisibleTime(at: uptime) + if needsReadingFlush { await flush() } } /// 页面隐藏、锁屏、文档切换或预览失败时同步停止计时,丢弃未满一秒片段。 diff --git a/suixinkan/UI/Training/TrainingCourseViewController.swift b/suixinkan/UI/Training/TrainingCourseViewController.swift index ef6eac5..176bf71 100644 --- a/suixinkan/UI/Training/TrainingCourseViewController.swift +++ b/suixinkan/UI/Training/TrainingCourseViewController.swift @@ -398,7 +398,12 @@ final class TrainingCourseViewController: TrainingBaseViewController { @objc private func appDidBecomeActive() { appIsActive = true; resumeReading() } 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 guard !retrying || request != nil else { return } let pendingClose = closingTask @@ -427,13 +432,15 @@ final class TrainingCourseViewController: TrainingBaseViewController { } 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 guard let self else { return } - await viewModel.recordVisibleTime(at: ProcessInfo.processInfo.systemUptime) + await viewModel.flush() readingTask = nil applyState() - if isContentVisible, viewModel.canStudy, !viewModel.isReading { resumeReading() } + if isContentVisible, viewModel.canStudy, !viewModel.isReading, viewModel.remainingSeconds > 0 { resumeReading() } } } diff --git a/suixinkanTests/TrainingDocumentPreviewTests.swift b/suixinkanTests/TrainingDocumentPreviewTests.swift index 14dab85..216deed 100644 --- a/suixinkanTests/TrainingDocumentPreviewTests.swift +++ b/suixinkanTests/TrainingDocumentPreviewTests.swift @@ -203,6 +203,93 @@ final class TrainingDocumentPreviewTests: XCTestCase { 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).. (TrainingCourseViewController, TrainingDocumentPreviewView, UIScrollView, UIWindow) { - let source = TrainingDataStub() + private func makeCourseWindow(document: TrainingLocalDocument, readingSeconds: Int = 20) async throws -> (TrainingCourseViewController, TrainingDocumentPreviewView, UIScrollView, UIWindow) { + var configuration = TrainingDataStub.Configuration() + configuration.readingSeconds = readingSeconds + let source = TrainingDataStub(configuration: configuration) let name = document.name let mime: String switch document.kind { @@ -469,3 +558,27 @@ final class TrainingDocumentPreviewTests: XCTestCase { guard reached else { throw CancellationError() } } } + +/// 精确挂起课程心跳响应,确保超时或断言失败后也能释放所有等待。 +private actor TrainingCourseHeartbeatGate { + private var releasedSequences: Set = [] + private var didReleaseAll = false + private var waiters: [Int: [CheckedContinuation]] = [:] + + 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() } + } +} diff --git a/suixinkanTests/TrainingFeatureTests.swift b/suixinkanTests/TrainingFeatureTests.swift index cfdbe7a..591c17a 100644 --- a/suixinkanTests/TrainingFeatureTests.swift +++ b/suixinkanTests/TrainingFeatureTests.swift @@ -112,7 +112,9 @@ struct TrainingFeatureTests { func foregroundClock() { var clock = TrainingReadingClock() clock.resume(at: 10) + clock.resume(at: 10.5) let partial = clock.takeSecond(at: 10.99) + clock.resume(at: 10.99) let whole = clock.takeSecond(at: 11) #expect(!partial) #expect(whole) diff --git a/suixinkanTests/TrainingRemoteReadingTests.swift b/suixinkanTests/TrainingRemoteReadingTests.swift index 0e4d977..1edf39b 100644 --- a/suixinkanTests/TrainingRemoteReadingTests.swift +++ b/suixinkanTests/TrainingRemoteReadingTests.swift @@ -97,6 +97,153 @@ struct TrainingRemoteReadingTests { #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("历史十二秒加新会话八秒,心跳总数仍从零开始") func historyAndSessionAreSeparate() async { @@ -201,8 +348,8 @@ struct TrainingRemoteReadingTests { #expect(model.activeSecondsTotal == 0) } - /// 暂停发生在网络请求中间时,先确认旧负载,再以新序号关闭。 - @Test("普通心跳请求中途暂停,确认后再发送 final") + /// 慢请求中新增读时先留在本地,暂停后确认旧负载,再以新序号关闭全部片段。 + @Test("普通心跳请求中继续累计后暂停,确认旧负载再 final 保存全部读时") func pauseDuringHeartbeatFinishesSequentially() async { let source = source() let gate = TrainingReadingHeartbeatGate() @@ -213,9 +360,15 @@ struct TrainingRemoteReadingTests { for second in 1...4 { await model.recordVisibleTime(at: Double(second)) } let operation = Task { await model.recordVisibleTime(at: 5) } await gate.waitUntilRequested() + #expect(model.accumulateVisibleTime(at: 6)) + #expect(model.accumulateVisibleTime(at: 7)) + #expect(model.activeSecondsTotal == 7) + #expect(model.remainingSeconds == 13) model.pauseReading() + #expect(!model.accumulateVisibleTime(at: 8)) let closing = Task { await model.flush() } #expect(await source.heartbeats.count == 1) + #expect(await source.heartbeats.first?.activeSecondsTotal == 5) await gate.release() await operation.value await closing.value @@ -223,9 +376,10 @@ struct TrainingRemoteReadingTests { #expect(calls.count == 2) #expect(calls[0].sequence == 1 && !calls[0].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.progress?.readingSeconds == 5) + #expect(model.progress?.readingSeconds == 7) } /// 前台恢复发生在 final 请求中途,等待结束后必须真正建立新会话。 @@ -740,13 +894,13 @@ private actor TrainingReadingAttachmentGate { } } -/// 精确挂起首个普通心跳,验证暂停不会并行发送或更改该请求。 +/// 精确挂起首个普通心跳,验证后续读时、暂停和重试不会更改已发送负载。 private actor TrainingReadingHeartbeatGate { private var response: CheckedContinuation? private var waiters: [CheckedContinuation] = [] private var hasDelayed = false - /// 首个请求等待测试释放,后续最终心跳立即确认。 + /// 首个请求等待测试释放,后续请求立即确认。 func confirm(_ call: TrainingDataStub.HeartbeatCall) async -> TrainingHeartbeatConfirmation { if !hasDelayed { hasDelayed = true @@ -767,7 +921,31 @@ private actor TrainingReadingHeartbeatGate { await withCheckedContinuation { waiters.append($0) } } - /// 让普通心跳完成,页面随后应使用新序号发送 final。 + /// 释放已挂起的普通心跳,让测试检查迟到确认之后的状态。 + func release() { response?.resume(); response = nil } +} + +/// 挂起首次建会话响应,让并发可见性恢复请求稳定进入等待队列。 +private actor TrainingReadingSessionGate { + private var response: CheckedContinuation? + private var waiters: [CheckedContinuation] = [] + + /// 等待测试释放创建响应,不使用真实时间延时。 + 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 } }