StoragePathMerge.js
12.5 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
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
import { TEMP_DB_FILE, DB_FILE, ENABLE_LEGACY_FLAT_DB_MERGE } from './constants.js'
import { normalizePath } from './pathCache.js'
import {
loadPathCache,
savePathCache,
createDefaultCache,
ensureDefaultRootsInCache,
getNonCurrentPaths
} from './pathCache.js'
import {
getCurrentPackageRoot,
findDbInPackageRoot,
getRuntimePackageName,
getAppId
} from './pathResolver.js'
import { PathUtils } from '@/utils/recordManager/index.js'
import { copyFileToDoc, removeFile, removeDocRelative, fileExists } from './fileIo.js'
import {
openTempDb,
closeTempDb,
selectTempRecords,
mergeRecordsToMain
} from './dbMerge.js'
import { isRestrictedInternalPath, isOwnAppStoragePath } from './pathAccess.js'
import { resolveUniappSaveDir } from './docMediaMerge.js'
import { verifyAndRepairRecordMediaPaths } from './recordMediaVerify.js'
import {
planAlternateScan,
markAlternateRootHandled,
resetAlternateHandledForForce
} from './mergeState.js'
import { logStep, logStepFail, waitForPlus } from './log.js'
const STAGE = {
RUN: '归并·总流程',
DB: '归并·数据库',
PATH: '归并·路径',
MEDIA: '归并·媒体'
}
function isAndroidApp(plusRef) {
const osName = plusRef?.os?.name
return !!plusRef && (osName === 'Android' || osName === 'android')
}
async function safeRemoveDocRelative(relativePath, label) {
logStep(STAGE.DB, `清理临时文件:${relativePath}`, { 说明: label })
const ok = await removeDocRelative(relativePath)
if (ok) {
logStep(STAGE.DB, `临时文件已删除:${relativePath}`)
} else {
logStep(STAGE.DB, `临时文件不存在或无需删除:${relativePath}`)
}
return ok
}
/** @returns {'restricted'|'copy_failed'|'empty'|'merged'|'merge_failed'|'error'} */
async function mergeFromDbFile(dbPath, label, mergePkg) {
const tag = label || dbPath
if (!dbPath) {
logStepFail(STAGE.DB, '跳过:数据库路径为空', { 标签: tag })
return 'error'
}
if (isRestrictedInternalPath(dbPath, mergePkg)) {
logStepFail(STAGE.DB, '跳过:非本应用内部路径', { 路径: dbPath, 标签: tag })
return 'restricted'
}
const hint = isOwnAppStoragePath(dbPath, mergePkg) ? '本应用' : '其它'
logStep(STAGE.DB, '开始处理来源库', { 来源: dbPath, 标签: tag, 归属: hint })
await safeRemoveDocRelative(TEMP_DB_FILE, '合并前清理旧临时库')
logStep(STAGE.DB, '开始复制来源库到 _doc 临时库', {
来源: dbPath,
目标: `_doc/${TEMP_DB_FILE}`
})
try {
await copyFileToDoc(dbPath, TEMP_DB_FILE)
logStep(STAGE.DB, '来源库复制到临时库成功', { 来源: dbPath })
} catch (e) {
logStepFail(STAGE.DB, '复制来源库到临时库失败', {
来源: dbPath,
错误: e?.message || String(e)
})
return 'copy_failed'
}
try {
logStep(STAGE.DB, '打开临时库', { 路径: TEMP_DB_FILE })
await openTempDb()
logStep(STAGE.DB, '临时库打开成功')
logStep(STAGE.DB, '查询临时库 records 表')
const rows = await selectTempRecords()
const count = rows?.length || 0
logStep(STAGE.DB, '临时库 records 查询完成', { 条数: count })
if (!rows || count === 0) {
logStep(STAGE.DB, '临时库无数据,结束本来源合并', { 标签: tag, 来源: dbPath })
await closeTempDb()
await safeRemoveDocRelative(TEMP_DB_FILE, '无数据清理临时库')
return 'empty'
}
logStep(STAGE.DB, '开始向主库合并记录', { 待合并条数: count, 来源: dbPath })
const ok = await mergeRecordsToMain(rows, { 来源: dbPath })
logStep(STAGE.DB, '关闭临时库')
await closeTempDb()
await safeRemoveDocRelative(TEMP_DB_FILE, '合并后清理临时库')
if (ok) {
logStep(STAGE.DB, '记录已写入主库,准备删除来源库', { 来源: dbPath })
try {
const removed = await removeFile(dbPath)
if (removed) {
logStep(STAGE.DB, '来源库删除成功', { 路径: dbPath })
} else {
logStepFail(STAGE.DB, '来源库删除失败:文件未找到或无法解析', { 路径: dbPath })
}
} catch (e) {
logStepFail(STAGE.DB, '来源库删除异常', {
路径: dbPath,
错误: e?.message || String(e)
})
}
return 'merged'
}
logStepFail(STAGE.DB, '写入主库未完全成功,保留来源库', { 来源: dbPath, 标签: tag })
return 'merge_failed'
} catch (e) {
logStepFail(STAGE.DB, '处理来源库异常', {
来源: dbPath,
标签: tag,
错误: e?.message || String(e)
})
try {
await closeTempDb()
} catch (closeErr) {
logStepFail(STAGE.DB, '异常后关闭临时库失败', { 错误: closeErr?.message || closeErr })
}
try {
await safeRemoveDocRelative(TEMP_DB_FILE, '异常后清理临时库')
} catch (_) {
/* ignore */
}
return 'error'
}
}
async function processPath(packageRoot, mergePkg, currentRoot, index, total) {
logStep(STAGE.PATH, `扫描包根 (${index}/${total})`, { 包根: packageRoot })
if (isRestrictedInternalPath(packageRoot, mergePkg)) {
logStepFail(STAGE.PATH, '跳过:非本应用内部包根', { 包根: packageRoot })
return 'restricted'
}
if (isOwnAppStoragePath(packageRoot, mergePkg)) {
logStep(STAGE.PATH, '本应用 alternate 包根,开始探测数据库', { 包根: packageRoot })
}
const dbPath = await findDbInPackageRoot(packageRoot)
let outcome = 'no_db'
if (dbPath) {
if (!isRestrictedInternalPath(dbPath, mergePkg)) {
outcome = await mergeFromDbFile(dbPath, packageRoot, mergePkg)
} else {
logStepFail(STAGE.PATH, '发现库但路径受限,跳过合并', { 库路径: dbPath })
outcome = 'restricted'
}
} else {
logStep(STAGE.PATH, '该包根下未找到 zyzs.db', { 包根: packageRoot })
}
const canMarkHandled = ['no_db', 'empty', 'merged', 'restricted'].includes(outcome)
if (canMarkHandled) {
markAlternateRootHandled(currentRoot, packageRoot)
logStep(STAGE.PATH, '已记录 alternate 包根为已处理', {
包根: packageRoot,
结果: outcome
})
} else {
logStep(STAGE.PATH, '未标记已处理(便于下次重试)', { 包根: packageRoot, 结果: outcome })
}
logStep(STAGE.PATH, `包根扫描结束 (${index}/${total})`, { 包根: packageRoot, 结果: outcome })
return outcome
}
/** 主库在 apps/xxx/doc 时,包根下扁平 zyzs.db 视为遗留库 */
async function processLegacyFlatDbAtCurrentRoot(currentRoot, mergePkg) {
logStep(STAGE.PATH, '开始检查当前包根遗留扁平库')
if (!currentRoot || isRestrictedInternalPath(currentRoot, mergePkg)) {
logStep(STAGE.PATH, '跳过遗留扁平库检查', {
原因: !currentRoot ? '无当前包根' : '内部路径受限',
包根: currentRoot
})
return
}
const root = normalizePath(currentRoot)
const flatDb = `${root}/${DB_FILE}`
const mainDocDb = normalizePath(`${root}/apps/${getAppId()}/doc/${DB_FILE}`)
logStep(STAGE.PATH, '探测遗留扁平库路径', { 扁平库: flatDb, 主库doc: mainDocDb })
if (!(await fileExists(flatDb))) {
logStep(STAGE.PATH, '当前包根无遗留扁平库', { 路径: flatDb })
return
}
if (normalizePath(flatDb) === mainDocDb) {
logStep(STAGE.PATH, '扁平库与主 doc 库为同一路径,跳过', { 路径: flatDb })
return
}
logStep(STAGE.PATH, '发现遗留扁平库,进入合并流程', { 路径: flatDb })
await mergeFromDbFile(flatDb, `${currentRoot}#legacy-flat`, mergePkg)
logStep(STAGE.PATH, '遗留扁平库检查结束')
}
class StoragePathMerge {
/** 进行中的归并 Promise,并发调用时复用 */
static _running = null
/** 当前进程内是否已成功跑完一次归并(force 可打破) */
static _completed = false
/**
* @param {{ force?: boolean }} [options] force=true:忽略「已完成」限制(悬浮窗手动归并)
*/
static async run(options = {}) {
const force = !!options.force
if (StoragePathMerge._running) {
logStep(STAGE.RUN, '防重入:归并正在进行,等待当前任务结束', { force })
return StoragePathMerge._running
}
if (StoragePathMerge._completed && !force) {
logStep(STAGE.RUN, '防重入:本会话已完成归并,跳过重复调用')
return
}
if (force) {
logStep(STAGE.RUN, '强制重新归并(手动触发)')
}
const task = StoragePathMerge.executeRun({ force })
StoragePathMerge._running = task
try {
await task
StoragePathMerge._completed = true
} finally {
StoragePathMerge._running = null
}
}
static async executeRun({ force = false } = {}) {
logStep(STAGE.RUN, '======== 路径合并开始 ========')
logStep(STAGE.RUN, '目标:外置 emulated ↔ 内部 /data/data、/data/user')
logStep(STAGE.RUN, '等待 Plus 环境就绪')
const plusRef = await waitForPlus()
if (!isAndroidApp(plusRef)) {
logStep(STAGE.RUN, '结束:非 Android APP-PLUS,跳过归并', {
有Plus: !!plusRef,
系统: plusRef?.os?.name
})
return
}
logStep(STAGE.RUN, 'Plus 环境就绪', { 系统: plusRef?.os?.name })
try {
logStep(STAGE.RUN, '初始化主库 uni.$dbRecord.init()')
await uni.$dbRecord.init()
logStep(STAGE.RUN, '主库 init 完成')
logStep(STAGE.RUN, '解析当前包根与 doc 路径')
const currentRoot = await getCurrentPackageRoot()
const currentDocPath = normalizePath(await PathUtils.getFilePath())
const mergePkg = getRuntimePackageName()
logStep(STAGE.RUN, '当前运行环境', {
包名: mergePkg,
包根: currentRoot,
doc根: currentDocPath,
appId: getAppId()
})
logStep(STAGE.RUN, '加载 PathCache')
let cache = loadPathCache()
if (!cache || !cache.length) {
logStep(STAGE.RUN, 'PathCache 为空,创建默认缓存')
cache = createDefaultCache(currentRoot)
} else {
logStep(STAGE.RUN, 'PathCache 已存在,补全默认包根', { 条目数: cache.length })
cache = ensureDefaultRootsInCache(cache, currentRoot)
}
savePathCache(cache)
logStep(STAGE.RUN, 'PathCache 已保存', {
条目: cache.map(c => ({ 路径: c.path, 当前: c.isCurrent }))
})
const nonCurrentItems = getNonCurrentPaths(cache)
const allAlternateRoots = nonCurrentItems.map(p => p.path)
if (force) {
resetAlternateHandledForForce(currentRoot)
}
const scanPlan = planAlternateScan(currentRoot, nonCurrentItems, force)
logStep(STAGE.RUN, 'alternate 包根扫描计划', {
说明: '均为当前 app 在不同沙箱下的包根(外置 /data/data /data/user),非其它应用',
全部非当前包根: allAlternateRoots,
计划: scanPlan
})
const appId = getAppId()
const alternateSaveDirs = allAlternateRoots.map(root => resolveUniappSaveDir(root, appId))
if (scanPlan.skip) {
logStep(STAGE.RUN, '跳过 alternate 库扫描', { 原因: scanPlan.reason })
} else {
const scanList = scanPlan.paths
const total = scanList.length
let idx = 0
for (const packageRoot of scanList) {
idx++
try {
await processPath(packageRoot, mergePkg, currentRoot, idx, total)
} catch (e) {
logStepFail(STAGE.PATH, `包根扫描异常 (${idx}/${total})`, {
包根: packageRoot,
错误: e?.message || String(e)
})
}
}
}
if (ENABLE_LEGACY_FLAT_DB_MERGE) {
try {
await processLegacyFlatDbAtCurrentRoot(currentRoot, mergePkg)
} catch (e) {
logStepFail(STAGE.PATH, '遗留扁平库检查异常', { 错误: e?.message || String(e) })
}
} else {
logStep(STAGE.PATH, '已关闭:当前包根遗留扁平库检测(ENABLE_LEGACY_FLAT_DB_MERGE=false)')
}
try {
logStep(STAGE.MEDIA, '======== 主库媒体路径校验开始 ========')
await verifyAndRepairRecordMediaPaths(currentDocPath, alternateSaveDirs)
logStep(STAGE.MEDIA, '======== 主库媒体路径校验结束 ========')
} catch (e) {
logStepFail(STAGE.MEDIA, '媒体路径校验流程异常', { 错误: e?.message || String(e) })
}
logStep(STAGE.RUN, '======== 路径合并全部完成 ========')
} catch (e) {
logStepFail(STAGE.RUN, '路径合并总流程失败', { 错误: e?.message || String(e) })
throw e
}
}
}
export default StoragePathMerge