@coralai/sps-plugin-storage-sync 0.1.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,204 @@
1
+ /**
2
+ * @module providers/storage/scanWorkspace
3
+ * @description 按声明枚举工作区里要同步的文件 + 发现项目 + 新鲜度。
4
+ *
5
+ * @layer providers
6
+ *
7
+ * 🔴 **发现判据只看布局,不猜产品语义。** coral sidecar 用「目录下含 `assets/`」当发现判据,
8
+ * 于是"只有 `docs/`、还没有 `assets/`"的**设计师阶段项目整批静默缺席**(实测 163 个里 36 个)。
9
+ * 这里的判据是**三段布局**(`t<租户>/<产品>/<项目>`)—— 它是 sps 自己的工作区约定,
10
+ * 不是对产品内容的猜测。
11
+ *
12
+ * 🔴 **新鲜度按「同步范围」算,不是按某个固定目录算。** coral 那侧改对了发现判据、
13
+ * 却坏在紧挨着的下一行:`projectLastModified(p.abs, 'assets')` 对只有 `docs/` 的项目返回 `0`,
14
+ * `0 >= cutoff` 恒假 ⇒ 36 个又被当成"30 天没动"跳过。
15
+ * > 判据一:**范围一旦放宽,紧跟其后的每一道过滤都要跟着放宽** ——
16
+ * > 漏掉的那道会把范围**原样缩回去**,而且报的是**另一个原因**("太旧"),查的人会去看时间。
17
+ * > 判据二:**别让一个返回值同时表示两件事** —— 那个 `0` 同时是"从没改过"和"目录不存在"。
18
+ * ⇒ 所以这里 `scopeLastModified` 回 `number | null`:**null = 范围内一个路径都不存在**,
19
+ * 与"存在但很旧"分开,由调用方分别计数、分别报。
20
+ */
21
+ import { createHash } from 'node:crypto';
22
+ import { readdir, readFile, stat } from 'node:fs/promises';
23
+ import { join } from 'node:path';
24
+ /** 发现共享根下的全部项目(三段布局)。不做任何内容判断。 */
25
+ export async function discoverProjects(root) {
26
+ const out = [];
27
+ let tenants;
28
+ try {
29
+ tenants = (await readdir(root, { withFileTypes: true })).filter((e) => e.isDirectory()).map((e) => e.name);
30
+ }
31
+ catch {
32
+ return out;
33
+ }
34
+ for (const t of tenants) {
35
+ let products;
36
+ try {
37
+ products = (await readdir(join(root, t), { withFileTypes: true })).filter((e) => e.isDirectory()).map((e) => e.name);
38
+ }
39
+ catch {
40
+ continue;
41
+ }
42
+ for (const p of products) {
43
+ let projects;
44
+ try {
45
+ projects = (await readdir(join(root, t, p), { withFileTypes: true })).filter((e) => e.isDirectory()).map((e) => e.name);
46
+ }
47
+ catch {
48
+ continue;
49
+ }
50
+ for (const g of projects)
51
+ out.push({ rel: `${t}/${p}/${g}`, abs: join(root, t, p, g), product: p });
52
+ }
53
+ }
54
+ return out;
55
+ }
56
+ /**
57
+ * 声明范围内最近一次改动的时间。
58
+ *
59
+ * @returns 毫秒时间戳;**`null` = 范围内一个路径都不存在**(与"存在但很旧"是两件事)
60
+ */
61
+ export async function scopeLastModified(projectAbs, include) {
62
+ let newest = null;
63
+ const bump = (ms) => {
64
+ if (newest === null || ms > newest)
65
+ newest = ms;
66
+ };
67
+ for (const entry of include) {
68
+ const abs = join(projectAbs, entry.replace(/\/+$/, ''));
69
+ let st;
70
+ try {
71
+ st = await stat(abs);
72
+ }
73
+ catch {
74
+ continue; // 这一项不存在 —— 不是"很旧",继续看下一项
75
+ }
76
+ if (!st.isDirectory()) {
77
+ bump(st.mtimeMs);
78
+ continue;
79
+ }
80
+ await walkMtime(abs, bump);
81
+ }
82
+ return newest;
83
+ }
84
+ async function walkMtime(dir, bump) {
85
+ let entries;
86
+ try {
87
+ entries = await readdir(dir, { withFileTypes: true });
88
+ }
89
+ catch {
90
+ return;
91
+ }
92
+ for (const e of entries) {
93
+ // 🔴 只看普通文件与目录:软链**不跟随**(跟随会把树外文件的 mtime 当成本项目的动静)。
94
+ if (e.isSymbolicLink())
95
+ continue;
96
+ const p = join(dir, e.name);
97
+ if (e.isDirectory()) {
98
+ await walkMtime(p, bump);
99
+ continue;
100
+ }
101
+ try {
102
+ bump((await stat(p)).mtimeMs);
103
+ }
104
+ catch {
105
+ /* 读不到就不算动静 */
106
+ }
107
+ }
108
+ }
109
+ /**
110
+ * 按声明枚举文件并算 md5。
111
+ *
112
+ * ⚠️ `maxBytes`:整份读进内存算 md5(与 coral 同做法 —— 上传时本来也要这份字节)。
113
+ * 上限**显式**给,不靠运气:树里有 172MB 的项目,一个失控的大文件不该把进程带走。
114
+ * 超限的算**失败**(计入 errors),不是静默跳过 —— 静默跳过会让"这个资源永远不在桶里"没人知道。
115
+ */
116
+ export async function scanByScope(projectAbs, include, maxBytes) {
117
+ const files = [];
118
+ const unreadable = [];
119
+ const missing = [];
120
+ const skippedDot = [];
121
+ const oversized = [];
122
+ const seen = new Set();
123
+ /** ENOENT 不是"读不到",是"没有"。分开归类,否则告警恒响。 */
124
+ const isMissing = (e) => typeof e === 'object' && e !== null && e.code === 'ENOENT';
125
+ const addFile = async (abs, rel) => {
126
+ if (seen.has(rel))
127
+ return; // 声明里目录与文件重叠时不重复推
128
+ seen.add(rel);
129
+ let st;
130
+ try {
131
+ st = await stat(abs);
132
+ }
133
+ catch (e) {
134
+ (isMissing(e) ? missing : unreadable).push(rel);
135
+ return;
136
+ }
137
+ if (st.size > maxBytes) {
138
+ oversized.push(rel);
139
+ return;
140
+ }
141
+ let bytes;
142
+ try {
143
+ bytes = await readFile(abs);
144
+ }
145
+ catch (e) {
146
+ // 0600 读不到走 unreadable(必须被报出来);文件刚被删走 ENOENT ⇒ missing
147
+ (isMissing(e) ? missing : unreadable).push(rel);
148
+ return;
149
+ }
150
+ files.push({ rel, abs, size: st.size, md5: createHash('md5').update(bytes).digest('hex') });
151
+ };
152
+ const walk = async (absDir, relDir) => {
153
+ let entries;
154
+ try {
155
+ entries = await readdir(absDir, { withFileTypes: true });
156
+ }
157
+ catch (e) {
158
+ (isMissing(e) ? missing : unreadable).push(relDir);
159
+ return;
160
+ }
161
+ for (const e of entries) {
162
+ // 软链不跟随:枚举阶段就排除,别指望后面的围栏兜底
163
+ // (围栏仍然会跑 —— 两道都在,但**枚举不该把它交给围栏去拒**)。
164
+ if (e.isSymbolicLink())
165
+ continue;
166
+ // 点开头条目:枚举阶段就不产出。它们是中间产物(`.sprites.pre-orient.png`),
167
+ // 交给下限会触发**整趟拒绝** ⇒ 整个项目永久停同步,而且理由看起来像安全事件。
168
+ if (e.name.startsWith('.')) {
169
+ skippedDot.push(relDir ? `${relDir}/${e.name}` : e.name);
170
+ continue;
171
+ }
172
+ const abs = join(absDir, e.name);
173
+ const rel = relDir ? `${relDir}/${e.name}` : e.name;
174
+ if (e.isDirectory())
175
+ await walk(abs, rel);
176
+ else if (e.isFile())
177
+ await addFile(abs, rel);
178
+ }
179
+ };
180
+ for (const entry of include) {
181
+ const isDir = entry.endsWith('/');
182
+ const clean = entry.replace(/^\.\//, '').replace(/\/+$/, '');
183
+ if (!clean)
184
+ continue;
185
+ const abs = join(projectAbs, clean);
186
+ if (isDir) {
187
+ await walk(abs, clean);
188
+ continue;
189
+ }
190
+ // 不带尾斜杠的声明可能仍是目录(声明方少写了斜杠)—— 按实际类型走,别按写法猜
191
+ let st = null;
192
+ try {
193
+ st = await stat(abs);
194
+ }
195
+ catch {
196
+ continue; // 声明了但项目里没有:合法(比如设计师还没写 PRD),不是错误
197
+ }
198
+ if (st.isDirectory())
199
+ await walk(abs, clean);
200
+ else
201
+ await addFile(abs, clean);
202
+ }
203
+ return { files, unreadable, missing, skippedDot, oversized };
204
+ }
@@ -0,0 +1,37 @@
1
+ /**
2
+ * @module schema
3
+ * @description 配置的**形状声明** —— 宿主的插件页据此通用渲染表单。
4
+ *
5
+ * 🔴 `schemastery` 必须是 **peer 依赖**:宿主会把自己那份软链进来
6
+ * (`linkHostPeers`)。插件自带一份的话会有两个 Schema 实例,
7
+ * 而 `Config` 是靠 `JSON.stringify` 出的 `{uid, refs}` 引用表传给前端的 ——
8
+ * 两个实例的 uid 对不上,表单就渲染不出来。
9
+ *
10
+ * ⚠️ `role('secret')` 让插件页把它当密码框。**它不改变落盘方式** ——
11
+ * 值仍然明文写进装配档(`~/.coral/assembly/base.yml`,0600)。
12
+ * 个人工具场景下已拍板可接受;要不写进装配档得走 `sps.credentials` 引用。
13
+ */
14
+ import Schema from '@deepseek-ai/schemastery';
15
+ export declare const Config: Schema<Schemastery.ObjectS<{
16
+ enabled: Schema<boolean, boolean>;
17
+ endpoint: Schema<string, string>;
18
+ bucket: Schema<string, string>;
19
+ accessKey: Schema<string, string>;
20
+ secretKey: Schema<string, string>;
21
+ region: Schema<string, string>;
22
+ pathStyle: Schema<boolean, boolean>;
23
+ intervalSec: Schema<number, number>;
24
+ sinceDays: Schema<number, number>;
25
+ maxBytes: Schema<number, number>;
26
+ }>, Schemastery.ObjectT<{
27
+ enabled: Schema<boolean, boolean>;
28
+ endpoint: Schema<string, string>;
29
+ bucket: Schema<string, string>;
30
+ accessKey: Schema<string, string>;
31
+ secretKey: Schema<string, string>;
32
+ region: Schema<string, string>;
33
+ pathStyle: Schema<boolean, boolean>;
34
+ intervalSec: Schema<number, number>;
35
+ sinceDays: Schema<number, number>;
36
+ maxBytes: Schema<number, number>;
37
+ }>>;
package/dist/schema.js ADDED
@@ -0,0 +1,32 @@
1
+ /**
2
+ * @module schema
3
+ * @description 配置的**形状声明** —— 宿主的插件页据此通用渲染表单。
4
+ *
5
+ * 🔴 `schemastery` 必须是 **peer 依赖**:宿主会把自己那份软链进来
6
+ * (`linkHostPeers`)。插件自带一份的话会有两个 Schema 实例,
7
+ * 而 `Config` 是靠 `JSON.stringify` 出的 `{uid, refs}` 引用表传给前端的 ——
8
+ * 两个实例的 uid 对不上,表单就渲染不出来。
9
+ *
10
+ * ⚠️ `role('secret')` 让插件页把它当密码框。**它不改变落盘方式** ——
11
+ * 值仍然明文写进装配档(`~/.coral/assembly/base.yml`,0600)。
12
+ * 个人工具场景下已拍板可接受;要不写进装配档得走 `sps.credentials` 引用。
13
+ */
14
+ import Schema from '@deepseek-ai/schemastery';
15
+ export const Config = Schema.object({
16
+ enabled: Schema.boolean()
17
+ .default(false)
18
+ .description('是否开启同步。**默认关** —— 没配桶时开着只会每轮打日志。'),
19
+ endpoint: Schema.string().description('S3 兼容端点,如 http://127.0.0.1:9000'),
20
+ bucket: Schema.string().description('桶名。插件只认这一个名字,不认识桶里的语义分区。'),
21
+ accessKey: Schema.string().role('secret').description('访问密钥 ID'),
22
+ secretKey: Schema.string().role('secret').description('访问密钥'),
23
+ region: Schema.string().default('us-east-1').description('S3 region。MinIO 通常用 us-east-1,给值只是为了签名能算出来。'),
24
+ pathStyle: Schema.boolean()
25
+ .default(true)
26
+ .description('路径式寻址(http://host/bucket/key)。MinIO 自建部署一般需要它;虚拟主机式要 DNS 配合。'),
27
+ intervalSec: Schema.number().default(600).description('扫描间隔(秒)'),
28
+ sinceDays: Schema.number()
29
+ .default(7)
30
+ .description('只看近 N 天有改动的项目;0 = 全量。全量扫一遍很贵,而老项目通常已经同步过。'),
31
+ maxBytes: Schema.number().default(2097152).description('单文件大小上限(字节)。超过的跳过并计数。'),
32
+ });
@@ -0,0 +1,66 @@
1
+ /**
2
+ * @module providers/storage/syncProject
3
+ * @description 一个项目的一轮对账同步:枚举 → 过下限 → 与桶对账 → 上传(缩略图先、原图后)。
4
+ *
5
+ * @layer providers
6
+ *
7
+ * 九条不变量见 `docs/design/storage-sync-implementation.md` §〇。落在代码里的要害是这几条:
8
+ *
9
+ * 🔴 **对账基准是桶本身,不是本地状态文件。** 本地清单一旦与桶脱节(桶被清过 / 上轮崩在一半 /
10
+ * 换了机器)会**永久跳过**某些文件且不报错;以桶的实际内容为准,一轮巡检就自愈。
11
+ *
12
+ * 🔴 **不删。** 本地文件没了 ≠ 用户要删桶里那份(工作区可能被重建、节点可能换了)。
13
+ * `StorageBackend` 接口上**根本没有 delete** —— 比"记得别调"可靠。
14
+ *
15
+ * 🔴 **幂等判据的覆盖面必须等于产物面。** 这一轮产出两样(原图 + 缩略图),判据就得同时问两样:
16
+ * 只问原图 ⇒ 一张生成失败过的缩略图**永远不会被补上**,表现是"同步很成功、预览是空的"。
17
+ *
18
+ * 🔴 **缩略图先写、原图后写**,且缩略图**上传**失败时本轮不写原图 ——
19
+ * 原图 etag 与本地相等是这条流水线的**提交点**,顺序反了会永久停留在旧缩略图且不报错。
20
+ * ⚠️ 区分**生成**失败(确定性:图坏了,照常传原图,否则坏文件把自己永远挡在桶外)
21
+ * 与**上传**失败(会留下陈旧缩略图 ⇒ 必须回退)。
22
+ *
23
+ * 🔴 **枚举完再判下限,再推第一个字节。** 下限若写在上传循环里,
24
+ * 排在拒绝项前面的文件**已经进桶了** —— 「整体失败」是关于**副作用**的断言,不是返回码。
25
+ *
26
+ * 🔴🔴 **但被拒的文件是"跳过并报出来",不是"整趟不推"**(coral 2026-08-19 指出,已改):
27
+ * 同一条下限用在**发布**路上,"整趟失败"是对的 —— 半个包比拒绝更难查;
28
+ * 用在**周期性**的同步路上就变成**那个项目永久停止同步**,而且理由看起来像安全事件。
29
+ * > 判据:**同一条规则,在"一次性动作"和"周期性动作"上后果完全不同。**
30
+ * > 周期性的路上,任何"整趟失败"都要能自己恢复,否则它等于一个**不报警的开关**。
31
+ * 而下限要防的事(凭据进桶)本来就是**逐文件**的 —— 跳过那一个就够了,
32
+ * 赔上整个项目既不更安全,又制造了一个静默停摆。
33
+ */
34
+ import type { StorageBackend } from './StorageBackend.js';
35
+ import { type ProjectDir } from './scanWorkspace.js';
36
+ import { type SyncRejection } from './syncable.js';
37
+ export declare const contentTypeOf: (rel: string) => string | undefined;
38
+ export declare const thumbnailable: (rel: string) => boolean;
39
+ export interface SyncStats {
40
+ project: string;
41
+ scanned: number;
42
+ uploaded: number;
43
+ /** 与 uploaded **分开计** —— 合在一起就看不出预览到底有没有产出。 */
44
+ thumbs: number;
45
+ skipped: number;
46
+ failed: number;
47
+ unreadable: number;
48
+ /** 声明里有、盘上没有 —— **不是错误**(设计师还没写 PRD 也走这里)。与 unreadable 分开。 */
49
+ missing: number;
50
+ /** 枚举阶段跳过的点开头条目(中间产物)。不触发整趟拒绝。 */
51
+ skippedDot: number;
52
+ oversized: number;
53
+ /** 被安全下限拒的项。**整趟不推**(见模块头)。 */
54
+ rejected: SyncRejection[];
55
+ /** 用了窄兜底(该产品没有声明)。**必须被报出来**。 */
56
+ usedDefaultScope: boolean;
57
+ errors: string[];
58
+ }
59
+ export interface SyncDeps {
60
+ storage: StorageBackend;
61
+ /** 缩略图生成。注入是为了让用例不必依赖 sharp 的原生二进制。 */
62
+ makeThumb: (input: Buffer) => Promise<Buffer>;
63
+ /** 单文件上限(字节)。显式给,不靠运气。 */
64
+ maxBytes: number;
65
+ }
66
+ export declare function syncProject(deps: SyncDeps, project: ProjectDir, include: string[], usedDefaultScope: boolean): Promise<SyncStats>;
@@ -0,0 +1,135 @@
1
+ /**
2
+ * @module providers/storage/syncProject
3
+ * @description 一个项目的一轮对账同步:枚举 → 过下限 → 与桶对账 → 上传(缩略图先、原图后)。
4
+ *
5
+ * @layer providers
6
+ *
7
+ * 九条不变量见 `docs/design/storage-sync-implementation.md` §〇。落在代码里的要害是这几条:
8
+ *
9
+ * 🔴 **对账基准是桶本身,不是本地状态文件。** 本地清单一旦与桶脱节(桶被清过 / 上轮崩在一半 /
10
+ * 换了机器)会**永久跳过**某些文件且不报错;以桶的实际内容为准,一轮巡检就自愈。
11
+ *
12
+ * 🔴 **不删。** 本地文件没了 ≠ 用户要删桶里那份(工作区可能被重建、节点可能换了)。
13
+ * `StorageBackend` 接口上**根本没有 delete** —— 比"记得别调"可靠。
14
+ *
15
+ * 🔴 **幂等判据的覆盖面必须等于产物面。** 这一轮产出两样(原图 + 缩略图),判据就得同时问两样:
16
+ * 只问原图 ⇒ 一张生成失败过的缩略图**永远不会被补上**,表现是"同步很成功、预览是空的"。
17
+ *
18
+ * 🔴 **缩略图先写、原图后写**,且缩略图**上传**失败时本轮不写原图 ——
19
+ * 原图 etag 与本地相等是这条流水线的**提交点**,顺序反了会永久停留在旧缩略图且不报错。
20
+ * ⚠️ 区分**生成**失败(确定性:图坏了,照常传原图,否则坏文件把自己永远挡在桶外)
21
+ * 与**上传**失败(会留下陈旧缩略图 ⇒ 必须回退)。
22
+ *
23
+ * 🔴 **枚举完再判下限,再推第一个字节。** 下限若写在上传循环里,
24
+ * 排在拒绝项前面的文件**已经进桶了** —— 「整体失败」是关于**副作用**的断言,不是返回码。
25
+ *
26
+ * 🔴🔴 **但被拒的文件是"跳过并报出来",不是"整趟不推"**(coral 2026-08-19 指出,已改):
27
+ * 同一条下限用在**发布**路上,"整趟失败"是对的 —— 半个包比拒绝更难查;
28
+ * 用在**周期性**的同步路上就变成**那个项目永久停止同步**,而且理由看起来像安全事件。
29
+ * > 判据:**同一条规则,在"一次性动作"和"周期性动作"上后果完全不同。**
30
+ * > 周期性的路上,任何"整趟失败"都要能自己恢复,否则它等于一个**不报警的开关**。
31
+ * 而下限要防的事(凭据进桶)本来就是**逐文件**的 —— 跳过那一个就够了,
32
+ * 赔上整个项目既不更安全,又制造了一个静默停摆。
33
+ */
34
+ import { readFile } from 'node:fs/promises';
35
+ import { extname } from 'node:path';
36
+ import { assetKey, assetPrefix, thumbKey } from './keys.js';
37
+ import { scanByScope } from './scanWorkspace.js';
38
+ import { screenAll } from './syncable.js';
39
+ /** 桶是直连的 —— **没有一层服务器能在返回时补救**,缺省的 octet-stream 会让预览图变成一次下载。 */
40
+ const MIME = {
41
+ '.png': 'image/png', '.jpg': 'image/jpeg', '.jpeg': 'image/jpeg', '.webp': 'image/webp',
42
+ '.gif': 'image/gif', '.svg': 'image/svg+xml', '.json': 'application/json', '.txt': 'text/plain',
43
+ '.mp3': 'audio/mpeg', '.wav': 'audio/wav', '.ogg': 'audio/ogg', '.m4a': 'audio/mp4',
44
+ '.html': 'text/html', '.js': 'text/javascript', '.css': 'text/css', '.md': 'text/markdown',
45
+ };
46
+ export const contentTypeOf = (rel) => MIME[extname(rel).toLowerCase()];
47
+ /** 能缩略的栅格图。**不认识的类型一律否**,别去猜;SVG 不缩(本来就小,且避开服务端光栅化任意 SVG)。 */
48
+ const RASTER = new Set(['.png', '.jpg', '.jpeg', '.webp', '.gif', '.bmp', '.tiff', '.avif']);
49
+ export const thumbnailable = (rel) => RASTER.has(extname(rel).toLowerCase());
50
+ export async function syncProject(deps, project, include, usedDefaultScope) {
51
+ const stats = {
52
+ project: project.rel, scanned: 0, uploaded: 0, thumbs: 0, skipped: 0, failed: 0,
53
+ unreadable: 0, missing: 0, skippedDot: 0, oversized: 0, rejected: [], usedDefaultScope, errors: [],
54
+ };
55
+ const scan = await scanByScope(project.abs, include, deps.maxBytes);
56
+ stats.scanned = scan.files.length;
57
+ stats.unreadable = scan.unreadable.length;
58
+ stats.missing = scan.missing.length;
59
+ stats.skippedDot = scan.skippedDot.length;
60
+ stats.oversized = scan.oversized.length;
61
+ for (const rel of scan.unreadable.slice(0, 3))
62
+ stats.errors.push(`权限读不到(已跳过) ${rel}`);
63
+ for (const rel of scan.oversized.slice(0, 3))
64
+ stats.errors.push(`超过单文件上限(未同步) ${rel}`);
65
+ // 🔴 下限在**推第一个字节之前**整趟判完(不是边推边判)。
66
+ // 但结果是**把被拒的那些从名单里摘掉**,不是整趟不推 —— 理由见模块头。
67
+ stats.rejected = await screenAll(scan.files.map((f) => ({ rel: f.rel, abs: f.abs })), project.abs);
68
+ const blocked = new Set(stats.rejected.map((r) => r.rel));
69
+ // 拒绝项要把名字报出去:清单会过期,而**漏掉的必须能被看见**。
70
+ for (const r of stats.rejected.slice(0, 5))
71
+ stats.errors.push(`安全下限拒绝 ${r.code}: ${r.rel}`);
72
+ const allowed = scan.files.filter((f) => !blocked.has(f.rel));
73
+ let remote;
74
+ try {
75
+ remote = new Map((await deps.storage.list(assetPrefix(project.rel))).map((o) => [o.key, o.etag]));
76
+ }
77
+ catch (e) {
78
+ stats.failed++;
79
+ stats.errors.push(`列举桶失败:${e instanceof Error ? e.message : String(e)}`);
80
+ return stats;
81
+ }
82
+ for (const f of allowed) {
83
+ const key = assetKey(project.rel, f.rel);
84
+ const changed = remote.get(key) !== f.md5; // ETag == md5,**不看 mtime**
85
+ const tKey = thumbnailable(f.rel) ? thumbKey(project.rel, f.rel) : null;
86
+ const thumbMissing = tKey !== null && !remote.has(tKey);
87
+ if (!changed && !thumbMissing) {
88
+ stats.skipped++;
89
+ continue;
90
+ }
91
+ const fail = (e, what) => {
92
+ stats.failed++;
93
+ if (stats.errors.length < 8)
94
+ stats.errors.push(`${what} ${f.rel}: ${e instanceof Error ? e.message : String(e)}`);
95
+ };
96
+ let bytes;
97
+ try {
98
+ bytes = await readFile(f.abs);
99
+ }
100
+ catch (e) {
101
+ fail(e, '读文件');
102
+ continue;
103
+ }
104
+ let thumbUploadFailed = false;
105
+ if (tKey !== null && (changed || thumbMissing)) {
106
+ let thumb = null;
107
+ try {
108
+ thumb = await deps.makeThumb(bytes);
109
+ }
110
+ catch (e) {
111
+ fail(e, '生成缩略图'); // 生成失败是确定性的 ⇒ 照常传原图
112
+ }
113
+ if (thumb) {
114
+ try {
115
+ await deps.storage.put(tKey, thumb, 'image/webp');
116
+ stats.thumbs++;
117
+ }
118
+ catch (e) {
119
+ fail(e, '上传缩略图');
120
+ thumbUploadFailed = true; // ⇒ 本轮不写原图,免得下一轮判"没变"而永远停在旧缩略图
121
+ }
122
+ }
123
+ }
124
+ if (!changed || thumbUploadFailed)
125
+ continue;
126
+ try {
127
+ await deps.storage.put(key, bytes, contentTypeOf(f.rel));
128
+ stats.uploaded++;
129
+ }
130
+ catch (e) {
131
+ fail(e, '上传'); // 单文件失败不中断整轮 —— 下轮对账会再试,但原因要留下
132
+ }
133
+ }
134
+ return stats;
135
+ }
@@ -0,0 +1,82 @@
1
+ /**
2
+ * @module providers/storage/syncRunner
3
+ * @description 对账循环:发现项目 → 新鲜度过滤 → 逐项目同步 → 汇总。
4
+ *
5
+ * @layer providers
6
+ *
7
+ * 🔴 **它是对账循环,不是事件驱动**(照抄 coral 的判断,它是对的):
8
+ * 文件事件会漏(worker 在别的用户下写 / 容器里写 / 进程崩在一半),
9
+ * 而漏掉的表现是"桶里少了一个文件",**没有任何报错**。对账每轮都会自愈。
10
+ *
11
+ * 🔴 **跑在 daemon,不在 console 的请求路径。**
12
+ * sidecar 是独立进程,而 console 是**共享事件循环** —— 同一段代码换了宿主就会开始
13
+ * 阻塞 `/api/health` 探针与 SSE 心跳。
14
+ * > 判据:**同步在移交件里是对的 —— 它本来跑在 CLI 里;换了宿主之后才变错。**
15
+ *
16
+ * 🔴 **每一类"没做"都要有自己的计数**,别合并成一个"跳过":
17
+ * 超期跳过 / 范围内一个路径都不存在 / 权限读不到 / 超大 / 被下限拒 —— 五种原因,五个数。
18
+ * 合并的代价今天实测过:coral 那个 `0` 同时表示"从没改过"和"目录不存在",吃掉了 36 个项目。
19
+ */
20
+ import type { StorageBackend } from './StorageBackend.js';
21
+ import { type SyncStats } from './syncProject.js';
22
+ import type { StorageSyncConfig } from './config.js';
23
+ export interface SyncPassOptions {
24
+ /**
25
+ * 工作区布局 —— **由宿主的 `sps.workspace` seam 提供**,插件不自己扫目录。
26
+ *
27
+ * 🔴 发现判据(三段布局)与资产声明都是**宿主知识**。插件各带一份的话两份必漂,
28
+ * 而漂的症状是**一部分项目静默缺席**,不是报错 ——
29
+ * 实测同族:用「目录下含 assets/」当判据,163 个项目里 36 个整批缺席。
30
+ */
31
+ workspace: {
32
+ discover(): Promise<Array<{
33
+ rel: string;
34
+ abs: string;
35
+ product: string;
36
+ }>>;
37
+ assetScope(product: string): {
38
+ include: string[];
39
+ usedDefault: boolean;
40
+ };
41
+ };
42
+ /**
43
+ * 插件配置(装配档那一行的 `config:`)。**不传 = 没配置**,整条路径静默不存在。
44
+ * 🔴 别在这里回落读文件 —— "配置在哪"只能有一个答案。
45
+ */
46
+ config?: StorageSyncConfig;
47
+ root: string;
48
+ /** 只同步近 N 天动过的项目;0 = 全部。 */
49
+ sinceDays: number;
50
+ /** 单文件上限。 */
51
+ maxBytes: number;
52
+ /** 只跑一个项目(相对共享根),排障用。 */
53
+ onlyProject?: string;
54
+ log?: (line: string) => void;
55
+ /** 注入点:用例用假后端 / 假缩略图,不碰 minio 与 sharp 的原生依赖。 */
56
+ storage?: StorageBackend;
57
+ makeThumb?: (input: Buffer) => Promise<Buffer>;
58
+ now?: number;
59
+ }
60
+ export interface PassSummary {
61
+ projects: number;
62
+ scanned: number;
63
+ uploaded: number;
64
+ thumbs: number;
65
+ skipped: number;
66
+ failed: number;
67
+ unreadable: number;
68
+ missing: number;
69
+ skippedDot: number;
70
+ oversized: number;
71
+ rejected: number;
72
+ /** 因超过 sinceDays 没动而跳过。 */
73
+ skippedOld: number;
74
+ /** 🔴 范围内**一个路径都不存在** —— 与"很旧"分开数(它多半意味着声明写错了)。 */
75
+ skippedEmptyScope: number;
76
+ /** 用了窄兜底(该产品没有声明)的项目数。 */
77
+ defaultScope: number;
78
+ perProject: SyncStats[];
79
+ }
80
+ export declare function runSyncPass(opts: SyncPassOptions): Promise<PassSummary | null>;
81
+ /** 汇总行。每一类"没做"都占一格 —— 一个悄悄缩小了范围的同步器,和一个坏掉的同步器,日志上一模一样。 */
82
+ export declare function formatSummary(sum: PassSummary, started: number, opts: SyncPassOptions): string;