Interactive home/lock-screen widget buttons (count +1, timer start/stop) gave touch feedback but often didn't persist, only working after several rapid taps. Two compounding defects in the widget-extension write path: - The extension could crash mid-write. refresh()/makeContainer() opens a new ModelContainer on every intent perform and every timeline read; in the extension that hit a local-store branch whose failure was fatalError. A transient App Group store contention with the running main app crashed the whole appex — the tap looked dead and only a later retry won the race. Split makeContainer into a throwing makeContainerThrowing(); refresh() now wraps it in try? and keeps the previous container on failure, so the extension degrades instead of crashing. The app's DataStore.shared keeps its crash-on-failure semantics. - Fetch → mutate → save could span different contexts and save errors were swallowed. IntentStore.context is a computed container.mainContext, and commit() re-read it for a try? save(), so a mid-flight container swap left the mutation on a dead context and any save failure vanished silently. Added IntentStore.performWrite(_:) which captures one context for the whole fetch+mutate+save, saves with a retry (no silent try?), then fires the Live Activity hook and reloadAllTimelines. All four mutating intents (RunAction/StartTime/StopTime/AddCount) now fetch in that single context. No @Model or main-app logic changed — fix is confined to the widget/intent data layer. Verified: 5 rapid RunActionIntent.perform() calls persist +5 with no lost writes across three cold launches (ok=true each). Build succeeds (app + embedded Haru_DanimWidgets.appex). Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_013yKDMhuF39GVYy3FMcGHh7
163 lines
7.3 KiB
Swift
163 lines
7.3 KiB
Swift
//
|
|
// DataStore.swift
|
|
// Haru_Danim
|
|
//
|
|
// SwiftData 컨테이너 구성 (CLAUDE.md §2.2)
|
|
// - 저장 위치: App Group 컨테이너 (위젯·App Intents가 같은 DB를 읽고 쓰기 위함)
|
|
// - 기존 앱 샌드박스의 default.store는 최초 1회 App Group으로 이관
|
|
// - iCloud 동기화(프리미엄): 켜져 있으면 CloudKit 연동 구성으로 컨테이너 생성, 실패 시 로컬로 폴백
|
|
// - CloudKit 미러링은 메인 앱 프로세스 전담. 위젯 확장(.appex)은 항상 로컬 전용 구성으로
|
|
// 같은 스토어 파일만 연다 — 확장에는 CloudKit 엔타이틀먼트가 없고 메모리·수명 제약으로
|
|
// 미러링 설정이 크래시/행을 일으킨다. 확장이 쓴 변경은 메인 앱이 히스토리로 집어 CloudKit에 내보낸다.
|
|
//
|
|
|
|
import Foundation
|
|
import SwiftData
|
|
|
|
nonisolated enum DataStore {
|
|
/// 프로세스 전체가 공유하는 컨테이너.
|
|
/// 앱 본체와 App Intents가 같은 인스턴스를 쓰게 해 변경 사항이 즉시 반영되게 한다.
|
|
static let shared: ModelContainer = makeContainer()
|
|
|
|
static let schema = Schema([
|
|
Tag.self,
|
|
Action.self,
|
|
TimeSession.self,
|
|
CountEntry.self,
|
|
Goal.self,
|
|
Quest.self,
|
|
])
|
|
|
|
/// iCloud 동기화 on/off (프리미엄, App Group defaults에 저장)
|
|
static let cloudSyncKey = "settings.cloudSync"
|
|
static let cloudContainerID = "iCloud.com.yechan.HaruDanim"
|
|
|
|
/// App Group 컨테이너 안의 스토어 파일 위치
|
|
static var storeURL: URL {
|
|
guard let base = FileManager.default.containerURL(
|
|
forSecurityApplicationGroupIdentifier: AppGroup.identifier
|
|
) else {
|
|
// App Group 미구성(이론상 없음) 시 기존 위치 유지
|
|
return URL.applicationSupportDirectory.appending(path: "default.store")
|
|
}
|
|
return base.appending(path: "HaruDanim.store")
|
|
}
|
|
|
|
/// 위젯 등 앱 확장(.appex) 프로세스에서 실행 중인지
|
|
static var isExtensionProcess: Bool {
|
|
Bundle.main.bundleURL.pathExtension == "appex"
|
|
}
|
|
|
|
/// iCloud 동기화를 시도해야 하는 상태인지 (프리미엄 + 설정 on)
|
|
static var wantsCloudSync: Bool {
|
|
#if DEBUG
|
|
if UserDefaults.standard.object(forKey: "cloudSync") != nil {
|
|
return UserDefaults.standard.bool(forKey: "cloudSync")
|
|
}
|
|
#endif
|
|
return PremiumGate.isUnlocked(.cloudSync) && AppGroup.defaults.bool(forKey: cloudSyncKey)
|
|
}
|
|
|
|
/// 앱·위젯·인텐트가 공유하는 컨테이너 생성.
|
|
/// CloudKit 연동은 메인 앱 프로세스에서만 — 확장은 같은 파일을 로컬 전용으로 연다.
|
|
/// 앱 본체(DataStore.shared)는 스토어 없이는 동작할 수 없어, 생성 실패 시 크래시한다.
|
|
static func makeContainer() -> ModelContainer {
|
|
do {
|
|
return try makeContainerThrowing()
|
|
} catch {
|
|
fatalError("[DataStore] 컨테이너 생성 실패: \(error)")
|
|
}
|
|
}
|
|
|
|
/// makeContainer의 throwing 버전.
|
|
/// 위젯 확장은 이 함수를 try?로 감싸므로, 메인 앱과의 일시적 스토어 경합으로 컨테이너
|
|
/// 생성이 실패해도 확장이 크래시(= 인터랙티브 위젯 버튼이 '먹통'처럼 보이고 방금 누른
|
|
/// 기록이 유실되는 원인)하지 않고 직전 컨테이너로 폴백할 수 있다.
|
|
static func makeContainerThrowing() throws -> ModelContainer {
|
|
migrateLegacyStoreIfNeeded()
|
|
if wantsCloudSync && !isExtensionProcess {
|
|
do {
|
|
let config = ModelConfiguration(
|
|
schema: schema,
|
|
url: storeURL,
|
|
cloudKitDatabase: .private(cloudContainerID)
|
|
)
|
|
return try ModelContainer(for: schema, configurations: [config])
|
|
} catch {
|
|
// iCloud 계정 없음/스키마 비호환 등 → 로컬 전용으로 폴백
|
|
print("[DataStore] CloudKit 컨테이너 생성 실패, 로컬로 폴백: \(error)")
|
|
}
|
|
}
|
|
let config = ModelConfiguration(schema: schema, url: storeURL, cloudKitDatabase: .none)
|
|
return try ModelContainer(for: schema, configurations: [config])
|
|
}
|
|
|
|
/// uuid 기본값 마이그레이션 보정: 기존 행들이 같은 기본 UUID로 채워졌을 수 있어
|
|
/// 중복을 찾아 재발급한다 (시리 단축어·위젯 식별자용, 앱 시작 시 1회 호출)
|
|
@MainActor
|
|
static func ensureUniqueEntityIDs(context: ModelContext) {
|
|
var changed = false
|
|
var tagIDs = Set<UUID>()
|
|
for tag in (try? context.fetch(FetchDescriptor<Tag>())) ?? [] where !tagIDs.insert(tag.uuid).inserted {
|
|
tag.uuid = UUID()
|
|
changed = true
|
|
}
|
|
var actionIDs = Set<UUID>()
|
|
for action in (try? context.fetch(FetchDescriptor<Action>())) ?? [] where !actionIDs.insert(action.uuid).inserted {
|
|
action.uuid = UUID()
|
|
changed = true
|
|
}
|
|
var goalIDs = Set<UUID>()
|
|
for goal in (try? context.fetch(FetchDescriptor<Goal>())) ?? [] where !goalIDs.insert(goal.uuid).inserted {
|
|
goal.uuid = UUID()
|
|
changed = true
|
|
}
|
|
var questIDs = Set<UUID>()
|
|
for quest in (try? context.fetch(FetchDescriptor<Quest>())) ?? [] where !questIDs.insert(quest.uuid).inserted {
|
|
quest.uuid = UUID()
|
|
changed = true
|
|
}
|
|
if changed { try? context.save() }
|
|
}
|
|
|
|
/// 기존 앱 샌드박스(Application Support/default.store)의 DB를 App Group으로 1회 복사
|
|
private static func migrateLegacyStoreIfNeeded() {
|
|
let fm = FileManager.default
|
|
let target = storeURL
|
|
guard target.path != URL.applicationSupportDirectory.appending(path: "default.store").path,
|
|
!fm.fileExists(atPath: target.path) else { return }
|
|
let legacy = URL.applicationSupportDirectory.appending(path: "default.store")
|
|
guard fm.fileExists(atPath: legacy.path) else { return }
|
|
// -wal/-shm 저널 파일까지 함께 복사해야 최신 데이터가 유지됨
|
|
for suffix in ["", "-shm", "-wal"] {
|
|
let from = URL(fileURLWithPath: legacy.path + suffix)
|
|
let to = URL(fileURLWithPath: target.path + suffix)
|
|
if fm.fileExists(atPath: from.path) {
|
|
try? fm.copyItem(at: from, to: to)
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
// MARK: - 설정 값 App Group 이관
|
|
|
|
/// 위젯·워치가 집계에 사용하는 설정(주 시작 요일, 하루 시작 시간, 대표 시간 기준)을
|
|
/// UserDefaults.standard → App Group defaults로 1회 이관
|
|
nonisolated enum SettingsMigration {
|
|
private static let doneKey = "migration.settingsToAppGroup"
|
|
|
|
static func runIfNeeded() {
|
|
let group = AppGroup.defaults
|
|
guard !group.bool(forKey: doneKey) else { return }
|
|
let standard = UserDefaults.standard
|
|
for key in [SettingsKeys.weekStartWeekday, SettingsKeys.dayStartMinutes,
|
|
SettingsKeys.liveActivityMode, SettingsKeys.minSessionSeconds,
|
|
SettingsKeys.theme] {
|
|
if group.object(forKey: key) == nil, let value = standard.object(forKey: key) {
|
|
group.set(value, forKey: key)
|
|
}
|
|
}
|
|
group.set(true, forKey: doneKey)
|
|
}
|
|
}
|