forked from mxx1111/mdlook
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsync.ts
More file actions
206 lines (178 loc) · 5.6 KB
/
Copy pathsync.ts
File metadata and controls
206 lines (178 loc) · 5.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
import type { SyncDocument } from '@/services/sync/types'
import { ApiError } from '@/services/account/client'
import { isSyncConfigured } from '@/services/sync/client'
import { mergeRemoteIntoLocal, postToDoc, toMs } from '@/services/sync/merge'
import { isProPlan, SYNC_DEBOUNCE_MS_PRO, SYNC_PRO_ENABLED } from '@/services/sync/plan'
import { applyRemoteSettings, collectChangedSettings } from '@/services/sync/settings'
import { useAuthStore } from '@/stores/auth'
import { usePostStore } from '@/stores/post'
import { addPrefix } from '@/utils'
import { store } from '@/utils/storage'
export type SyncStatus = 'idle' | 'syncing' | 'error'
const SYNCED_IDS_KEY = addPrefix(`sync_post_ids`)
function readSyncedIds(): string[] {
try {
const raw = localStorage.getItem(SYNCED_IDS_KEY)
return raw ? JSON.parse(raw) as string[] : []
}
catch {
return []
}
}
function writeSyncedIds(ids: string[]): void {
try {
localStorage.setItem(SYNCED_IDS_KEY, JSON.stringify(ids))
}
catch { /* 配额错误,非致命 */ }
}
/**
* 云同步 Store
* 负责同步状态机、手动/自动同步编排、上次同步时间
*/
export const useSyncStore = defineStore(`sync`, () => {
const authStore = useAuthStore()
const postStore = usePostStore()
const status = ref<SyncStatus>(`idle`)
const lastError = ref<string>(``)
const lastSyncAt = store.reactive<number>(addPrefix(`sync_last_at`), 0)
const autoSyncEnabled = store.reactive(addPrefix(`sync_auto`), false)
const needsRefresh = ref(false)
let cursor = 0
let debounceTimer: ReturnType<typeof setTimeout> | null = null
const isAvailable = computed(() => isSyncConfigured() && authStore.isLoggedIn)
const isSyncing = computed(() => status.value === `syncing`)
const isPro = computed(() => isProPlan(authStore.user?.plan))
const syncDebounceMs = computed(() => SYNC_DEBOUNCE_MS_PRO)
const lastLocalEditAt = computed(() => {
let max = 0
for (const p of postStore.posts) {
const t = new Date(p.updateDatetime).getTime()
if (Number.isFinite(t) && t > max)
max = t
}
return max
})
const hasPendingChanges = computed(() => lastSyncAt.value === 0 || lastLocalEditAt.value > lastSyncAt.value)
const syncState = computed<'syncing' | 'synced' | 'error' | 'pending'>(() => {
if (status.value === `syncing`)
return `syncing`
if (status.value === `error`)
return `error`
if (lastSyncAt.value > 0 && !hasPendingChanges.value)
return `synced`
return `pending`
})
function collectLocalDocuments(): SyncDocument[] {
const now = Date.now()
const since = lastSyncAt.value
const currentIds = new Set(postStore.posts.map(p => p.id))
const changedDocs = postStore.posts
.filter(p => since === 0 || toMs(p.updateDatetime) > since)
.map(postToDoc)
const tombstones: SyncDocument[] = readSyncedIds()
.filter(id => !currentIds.has(id))
.map(id => ({
id,
title: ``,
content: ``,
parentId: null,
history: [],
createDatetime: now,
updateDatetime: now,
deleted: true,
}))
return [...changedDocs, ...tombstones]
}
function formatSyncError(e: unknown): string {
if (e instanceof ApiError) {
if (e.status === 429)
return `同步次数已达上限,请稍后再试`
return e.message
}
return e instanceof Error ? e.message : String(e)
}
async function sync(): Promise<void> {
if (!isAvailable.value || status.value === `syncing`)
return
status.value = `syncing`
lastError.value = ``
try {
const pulled = await authStore.syncClient.pull(cursor)
if (pulled.documents.length) {
const { posts, changed } = mergeRemoteIntoLocal(postStore.posts, pulled.documents)
if (changed)
postStore.posts = posts
}
if (pulled.settings.length) {
const applied = applyRemoteSettings(pulled.settings)
if (applied > 0)
needsRefresh.value = true
}
cursor = Math.max(cursor, pulled.cursor)
const documents = collectLocalDocuments()
const settings = collectChangedSettings()
if (documents.length || settings.length) {
const pushed = await authStore.syncClient.push({ documents, settings })
cursor = Math.max(cursor, pushed.cursor)
}
writeSyncedIds(postStore.posts.map(p => p.id))
lastSyncAt.value = Date.now()
status.value = `idle`
}
catch (e) {
status.value = `error`
lastError.value = formatSyncError(e)
}
}
function scheduleAutoSync(): void {
if (!isPro.value || !autoSyncEnabled.value || !isAvailable.value)
return
if (debounceTimer)
clearTimeout(debounceTimer)
debounceTimer = setTimeout(() => {
debounceTimer = null
sync()
}, syncDebounceMs.value)
}
function startAutoSyncWatcher(): void {
if (!SYNC_PRO_ENABLED)
return
watch(
() => postStore.posts,
() => scheduleAutoSync(),
{ deep: true },
)
watch(syncDebounceMs, () => {
if (autoSyncEnabled.value)
scheduleAutoSync()
})
}
function reset(): void {
cursor = 0
lastSyncAt.value = 0
needsRefresh.value = false
status.value = `idle`
try {
localStorage.removeItem(SYNCED_IDS_KEY)
localStorage.removeItem(addPrefix(`sync_settings_meta`))
}
catch { /* ignore */ }
}
return {
status,
lastError,
lastSyncAt,
autoSyncEnabled,
needsRefresh,
isAvailable,
isSyncing,
isPro,
syncDebounceMs,
hasPendingChanges,
syncState,
sync,
scheduleAutoSync,
startAutoSyncWatcher,
reset,
}
})