@lumesync/studio 0.0.0-stage → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,250 @@
1
+ // 目录级事务:先暂存,再写 journal,最后替换目标文件。
2
+ // 任一写入失败都按 journal 回滚到事务前状态;进程异常退出时由 recoverWorkspace 恢复。
3
+
4
+ import { randomBytes } from 'node:crypto';
5
+ import fsp from 'node:fs/promises';
6
+ import path from 'node:path';
7
+ import { ERROR_CODES, StudioError } from './errors.js';
8
+ import {
9
+ STUDIO_DIR, appendOperationLog, ensureRealDir, jsonText, listPackageFiles,
10
+ prepareOperationLog, resolveRealFile, sha256Hex, truncateOperationLog, writeJsonAtomic,
11
+ } from './storage.js';
12
+
13
+ const JOURNAL_NAME = 'transaction.json';
14
+
15
+ function journalPath(root) {
16
+ return path.join(path.resolve(root), STUDIO_DIR, JOURNAL_NAME);
17
+ }
18
+
19
+ function stagingRoot(root, txnId) {
20
+ return path.join(path.resolve(root), STUDIO_DIR, 'staging', txnId);
21
+ }
22
+
23
+ function toBuffer(content) {
24
+ return Buffer.isBuffer(content) ? content : Buffer.from(String(content), 'utf8');
25
+ }
26
+
27
+ // 计算事务提交后的 checksums.json:基于当前文件集合 + 本次写入与删除。
28
+ async function computeFutureChecksums(root, writes, deletes) {
29
+ const writeMap = new Map(writes.map((entry) => [entry.path, toBuffer(entry.content)]));
30
+ const future = new Set(listPackageFiles(root));
31
+ for (const relative of writeMap.keys()) {
32
+ if (!relative.startsWith('.') && relative !== 'checksums.json') future.add(relative);
33
+ }
34
+ for (const relative of deletes) future.delete(relative);
35
+ const files = {};
36
+ for (const relative of [...future].sort()) {
37
+ const content = writeMap.has(relative)
38
+ ? writeMap.get(relative)
39
+ : await fsp.readFile(resolveRealFile(root, relative));
40
+ files[relative] = sha256Hex(content);
41
+ }
42
+ return { algorithm: 'sha256', files };
43
+ }
44
+
45
+ export async function commitFileSet(root, { writes = [], deletes = [], checksum = null, logRecord = null }) {
46
+ if (!Array.isArray(writes) || writes.length === 0) {
47
+ throw new StudioError(ERROR_CODES.OPERATION_INVALID, '事务必须包含至少一个写入文件', undefined, 400);
48
+ }
49
+ const txnId = `txn-${Date.now()}-${randomBytes(4).toString('hex')}`;
50
+ const staging = stagingRoot(root, txnId);
51
+ const stagedFiles = path.join(staging, 'files');
52
+ const backupFiles = path.join(staging, 'backup');
53
+ const journal = journalPath(root);
54
+
55
+ const allWrites = [];
56
+ const writeMap = new Map();
57
+ const deleteSet = new Set(deletes);
58
+ for (const write of writes) {
59
+ // 删除优先:场景/题目/资源被删除时,Draft 中残留的正文不应再写回。
60
+ if (deleteSet.has(write.path)) continue;
61
+ writeMap.set(write.path, write);
62
+ }
63
+ if (checksum) {
64
+ writeMap.set('checksums.json', {
65
+ path: 'checksums.json',
66
+ content: jsonText(await computeFutureChecksums(root, [...writeMap.values()], deletes)),
67
+ });
68
+ }
69
+ for (const write of writeMap.values()) allWrites.push(write);
70
+
71
+ const entries = [];
72
+ try {
73
+ await fsp.rm(staging, { recursive: true, force: true }).catch(() => {});
74
+ await fsp.mkdir(stagedFiles, { recursive: true, mode: 0o700 });
75
+
76
+ for (const write of allWrites) {
77
+ const target = path.join(root, write.path);
78
+ const parent = path.posix.dirname(write.path);
79
+ if (parent !== '.') await ensureRealDir(root, parent);
80
+ let stat = null;
81
+ try {
82
+ stat = await fsp.lstat(target);
83
+ } catch {
84
+ stat = null;
85
+ }
86
+ if (stat?.isSymbolicLink()) {
87
+ throw new StudioError(ERROR_CODES.ROOT_FORBIDDEN, `拒绝覆盖符号链接:${write.path}`, { path: write.path }, 403);
88
+ }
89
+ if (stat && !stat.isFile()) {
90
+ throw new StudioError(ERROR_CODES.ROOT_FORBIDDEN, `目标不是普通文件:${write.path}`, { path: write.path }, 403);
91
+ }
92
+ const existed = Boolean(stat);
93
+ if (existed) resolveRealFile(root, write.path);
94
+ const staged = path.join(stagedFiles, write.path);
95
+ await fsp.mkdir(path.dirname(staged), { recursive: true, mode: 0o700 });
96
+ await fsp.writeFile(staged, toBuffer(write.content));
97
+ entries.push({ path: write.path, action: 'write', existed });
98
+ }
99
+
100
+ for (const relative of deletes) {
101
+ let existed = false;
102
+ try {
103
+ resolveRealFile(root, relative);
104
+ existed = true;
105
+ } catch {
106
+ // 不存在的文件无需删除;存在但不是安全普通文件时仍然拒绝事务。
107
+ const stat = await fsp.lstat(path.join(root, relative)).catch(() => null);
108
+ if (stat) {
109
+ throw new StudioError(ERROR_CODES.ROOT_FORBIDDEN, `拒绝删除非普通文件:${relative}`, { path: relative }, 403);
110
+ }
111
+ existed = false;
112
+ }
113
+ entries.push({ path: relative, action: 'delete', existed });
114
+ }
115
+
116
+ // 1) 记录事务前的日志大小,供回滚截断。
117
+ let previousLogSize = 0;
118
+ if (logRecord) {
119
+ previousLogSize = await prepareOperationLog(root);
120
+ }
121
+
122
+ // 2) 先写 journal 再执行任何目标文件变更。
123
+ await writeJsonAtomic(journal, {
124
+ txnId,
125
+ createdAt: new Date().toISOString(),
126
+ phase: 'prepared',
127
+ entries,
128
+ log: logRecord ? { previousSize: previousLogSize } : null,
129
+ }, { mode: 0o600 });
130
+
131
+ // 3) 追加操作日志(回滚时按记录截断)。
132
+ if (logRecord) {
133
+ await appendOperationLog(root, logRecord);
134
+ }
135
+
136
+ // 4) 替换目标文件:先备份旧文件,再 rename 暂存文件。
137
+ for (const [index, entry] of entries.entries()) {
138
+ if (!entry.existed) continue;
139
+ const source = path.join(root, entry.path);
140
+ const backup = path.join(backupFiles, entry.path);
141
+ await fsp.mkdir(path.dirname(backup), { recursive: true, mode: 0o700 });
142
+ await fsp.rename(source, backup);
143
+ entries[index].backedUp = true;
144
+ }
145
+ for (const entry of entries) {
146
+ if (entry.action !== 'write') continue;
147
+ const staged = path.join(stagedFiles, entry.path);
148
+ const target = path.join(root, entry.path);
149
+ await fsp.rename(staged, target);
150
+ entry.applied = true;
151
+ }
152
+
153
+ // 5) 提交点:此后崩溃只清理 staging,不再回滚。
154
+ await writeJsonAtomic(journal, { txnId, phase: 'committed', entries }, { mode: 0o600 });
155
+ await fsp.rm(staging, { recursive: true, force: true }).catch(() => {});
156
+ await fsp.rm(journal, { force: true }).catch(() => {});
157
+ return { txnId, written: entries.filter((entry) => entry.action === 'write').length, deleted: entries.filter((entry) => entry.action === 'delete').length };
158
+ } catch (error) {
159
+ await rollbackEntries(root, journal, staging, entries);
160
+ const reason = error instanceof StudioError ? error.message : error.message;
161
+ throw new StudioError(ERROR_CODES.STORAGE_WRITE_FAILED, `课件写入失败,已回滚本次事务:${reason}`, { txnId }, 500);
162
+ }
163
+ }
164
+
165
+ async function rollbackEntries(root, journal, staging, entries) {
166
+ const restored = [...entries].reverse();
167
+ for (const entry of restored) {
168
+ const target = path.join(root, entry.path);
169
+ const backup = path.join(staging, 'backup', entry.path);
170
+ if (entry.action === 'delete') {
171
+ if (await exists(backup)) {
172
+ await fsp.mkdir(path.dirname(target), { recursive: true });
173
+ await fsp.rm(target, { force: true }).catch(() => {});
174
+ await fsp.rename(backup, target).catch(() => {});
175
+ }
176
+ continue;
177
+ }
178
+ if (entry.existed) {
179
+ if (await exists(backup)) {
180
+ await fsp.rm(target, { force: true }).catch(() => {});
181
+ await fsp.mkdir(path.dirname(target), { recursive: true });
182
+ await fsp.rename(backup, target).catch(() => {});
183
+ }
184
+ } else {
185
+ await fsp.rm(target, { force: true }).catch(() => {});
186
+ }
187
+ }
188
+ const record = await readJournal(journal);
189
+ if (record?.log?.previousSize !== undefined) {
190
+ await truncateOperationLog(path.join(root, STUDIO_DIR, 'operations.jsonl'), record.log.previousSize);
191
+ }
192
+ await fsp.rm(staging, { recursive: true, force: true }).catch(() => {});
193
+ await fsp.rm(journal, { force: true }).catch(() => {});
194
+ }
195
+
196
+ async function exists(target) {
197
+ try {
198
+ await fsp.lstat(target);
199
+ return true;
200
+ } catch {
201
+ return false;
202
+ }
203
+ }
204
+
205
+ async function readJournal(journal) {
206
+ try {
207
+ return JSON.parse(await fsp.readFile(journal, 'utf8'));
208
+ } catch {
209
+ return null;
210
+ }
211
+ }
212
+
213
+ // 启动或加载课件前调用:未提交的事务回滚,已提交但未清理的只清理。
214
+ export async function recoverWorkspace(root) {
215
+ const studioDir = path.join(path.resolve(root), STUDIO_DIR);
216
+ let stat;
217
+ try {
218
+ stat = await fsp.lstat(studioDir);
219
+ } catch {
220
+ return { recovered: false };
221
+ }
222
+ // 符号链接形式的 .studio 不参与恢复;后续加载会按安全错误拒绝。
223
+ if (!stat.isDirectory() || stat.isSymbolicLink()) return { recovered: false };
224
+ const journal = journalPath(root);
225
+ const record = await readJournal(journal);
226
+ if (record) {
227
+ const staging = stagingRoot(root, record.txnId);
228
+ if (record.phase === 'committed') {
229
+ await fsp.rm(staging, { recursive: true, force: true }).catch(() => {});
230
+ await fsp.rm(journal, { force: true }).catch(() => {});
231
+ } else {
232
+ await rollbackEntries(root, journal, staging, Array.isArray(record.entries) ? record.entries : []);
233
+ }
234
+ }
235
+ // 清理没有 journal 归属的 staging 残留。
236
+ const stagingBase = path.join(studioDir, 'staging');
237
+ try {
238
+ const entries = await fsp.readdir(stagingBase, { withFileTypes: true });
239
+ for (const entry of entries) {
240
+ if (!entry.isDirectory()) continue;
241
+ if (record && entry.name === record.txnId && record.phase !== 'committed') continue;
242
+ await fsp.rm(path.join(stagingBase, entry.name), { recursive: true, force: true }).catch(() => {});
243
+ }
244
+ } catch {
245
+ // 没有 staging 目录是正常状态。
246
+ }
247
+ return { recovered: Boolean(record) };
248
+ }
249
+
250
+ export { JOURNAL_NAME };