Skip to content
Merged
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
84 changes: 84 additions & 0 deletions MemoryEcho/Core/SuspensionGuard.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
//
// SuspensionGuard.swift
// MemoryEcho
//
// Holds off suspension after the app backgrounds until the store has gone
// quiet. The store lives in the App Group container, and iOS kills (0xdead10cc)
// any process that is suspended while holding a lock on a shared file. A save
// queues a CloudKit export that runs a moment later, so "add, then straight to
// the home screen" lands that export's SQLite write exactly on the suspension.
//
// A background task keeps the process running; it is released once no sync
// event is in flight and none has started for `Tuning.backgroundSettleSeconds`.
// SwiftData's mirroring posts the same event notification Core Data does,
// which is how the in-flight set is tracked.
//

import CoreData
import MemoryEchoCore
import UIKit

final class SuspensionGuard {
static let shared = SuspensionGuard()

private var backgroundTask = UIBackgroundTaskIdentifier.invalid
private var syncEventsInFlight: Set<UUID> = []
private var pendingRelease: Task<Void, Never>?

private init() {
NotificationCenter.default.addObserver(
forName: NSPersistentCloudKitContainer.eventChangedNotification,
object: nil,
queue: nil
) { notification in
let key = NSPersistentCloudKitContainer.eventNotificationUserInfoKey
guard let event = notification.userInfo?[key] as? NSPersistentCloudKitContainer.Event else { return }
// Posted off the main thread; carry only the Sendable facts across.
let id = event.identifier
let finished = event.endDate != nil
Task { @MainActor in SuspensionGuard.shared.record(id, finished: finished) }
}
}

func didEnterBackground() {
guard backgroundTask == .invalid else { return }
// iOS grants roughly 30s. On expiry the task must end regardless, or the
// app is killed for overrunning instead.
backgroundTask = UIApplication.shared.beginBackgroundTask(withName: "StoreSettle") { [weak self] in
self?.release()
}
scheduleRelease()
}

func didBecomeActive() {
release()
}

private func record(_ id: UUID, finished: Bool) {
if finished {
syncEventsInFlight.remove(id)
} else {
syncEventsInFlight.insert(id)
}
if backgroundTask != .invalid { scheduleRelease() }
}

/// Restart the quiet-period countdown. If an event is still in flight when
/// it fires, nothing happens — that event finishing restarts it.
private func scheduleRelease() {
pendingRelease?.cancel()
pendingRelease = Task {
try? await Task.sleep(for: .seconds(Tuning.backgroundSettleSeconds))
guard !Task.isCancelled, syncEventsInFlight.isEmpty else { return }
release()
}
}

private func release() {
pendingRelease?.cancel()
pendingRelease = nil
guard backgroundTask != .invalid else { return }
UIApplication.shared.endBackgroundTask(backgroundTask)
backgroundTask = .invalid
}
}
9 changes: 9 additions & 0 deletions MemoryEcho/MemoryEchoApp.swift
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,8 @@ struct MemoryEchoApp: App {
/// reads the same store (see MemoryEchoCore.MemoryEchoStore).
let sharedModelContainer = MemoryEchoStore.shared

@Environment(\.scenePhase) private var scenePhase

var body: some Scene {
WindowGroup {
RootView()
Expand All @@ -27,6 +29,13 @@ struct MemoryEchoApp: App {
try? StoreMaintenance.purgeCompleted(in: context)
syncSettings(in: context)
}
.onChange(of: scenePhase, initial: true) { _, phase in
switch phase {
case .background: SuspensionGuard.shared.didEnterBackground()
case .active: SuspensionGuard.shared.didBecomeActive()
default: break
}
}
}
.modelContainer(sharedModelContainer)
}
Expand Down
5 changes: 5 additions & 0 deletions MemoryEchoCore/Sources/MemoryEchoCore/Tuning.swift
Original file line number Diff line number Diff line change
Expand Up @@ -82,6 +82,11 @@ public enum Tuning {
/// both the app and the widget, since they share one store.
public static let cloudKitContainerID = "iCloud.org.mattnitzken.MemoryEcho"

/// How long the store must stay quiet after backgrounding before the app
/// lets itself be suspended (see SuspensionGuard). Has to outlast the gap
/// between a save and the CloudKit export it queues.
public static let backgroundSettleSeconds: Double = 3

// MARK: Widget (user-tunable via WidgetSettings)

/// How many memories any memory-showing widget lists — user-set within this
Expand Down
Loading