@coda-console/resource-manager 0.2.0 → 0.4.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.
- package/README.md +12 -3
- package/lib/content.mjs +15 -2
- package/lib/snapshots.mjs +52 -0
- package/lib/tree.mjs +237 -48
- package/main.mjs +30 -10
- package/package.json +1 -1
- package/view/app.mjs +105 -33
- package/view/bar.mjs +15 -5
- package/view/file-app.mjs +8 -5
- package/view/file.html +1 -1
- package/view/format.mjs +40 -0
- package/view/icons.mjs +56 -0
- package/view/model.mjs +48 -19
- package/view/notice.mjs +15 -8
- package/view/preview.mjs +31 -19
- package/view/protocol.mjs +10 -3
- package/view/style.css +82 -26
- package/view/tree.mjs +69 -23
package/README.md
CHANGED
|
@@ -10,10 +10,12 @@ Coda 插件:会话旁的文件浏览器。浏览这个会话的工作目录,
|
|
|
10
10
|
- 按需展开目录,超大目录分页显示。
|
|
11
11
|
- 文本预览(带行号,可跨行选中复制,最多读 1 MiB)和图片预览(PNG、JPEG、GIF、WebP、SVG,最多 8 MiB)。
|
|
12
12
|
- Agent 一轮结束后,已展开的目录和正在看的文件自动更新。
|
|
13
|
+
- 每行带修改日期和大小:Mac 在名字右边(按日期排序时显示日期,否则显示大小,侧栏很窄时隐藏),iPhone 在名字下面一行。右键或长按的菜单里有大小和完整修改时间。文件夹不显示大小(列表和菜单都没有),只有修改日期。
|
|
14
|
+
- 可以按名称、种类、日期、大小排序,在「更多」菜单(Mac)或「⋯」菜单(iPhone)的「排序」一组里选,当前项有对勾。每种排序的方向固定:名称、种类升序,日期、大小降序(最新、最大在前),没有升降序切换。超过 2 万条的目录,日期和大小排序不可用,退回按名称并提示。排序全局一份,换了排序滚动位置回到顶部,选当前项什么都不做。
|
|
13
15
|
- 切换会话时换成新会话的内容,切回来恢复展开状态和滚动位置。
|
|
14
|
-
- Mac
|
|
15
|
-
- iPhone
|
|
16
|
-
- 默认隐藏 `.git`、`.DS_Store
|
|
16
|
+
- Mac:右键复制相对或绝对路径,或把文件拖到输入框;预览可以开到独立窗口;工具栏只有一个「更多」按钮,按下弹出菜单(刷新、显示隐藏文件、排序),侧栏预览头部最左边的「返回」回到目录树。
|
|
17
|
+
- iPhone:长按复制路径;目录树页右上角「⋯」里有刷新、显示隐藏文件和排序;文件页底部工具条有刷新和「复制路径」。
|
|
18
|
+
- 默认隐藏 `.git`、`.DS_Store`,Mac 在工具栏的「更多」菜单里、iPhone 在目录树页右上角的「⋯」里可切换显示全部。
|
|
17
19
|
|
|
18
20
|
只能读这个会话的工作目录。指向工作目录之外的符号链接只显示,不能打开。
|
|
19
21
|
|
|
@@ -36,6 +38,11 @@ Coda 插件:会话旁的文件浏览器。浏览这个会话的工作目录,
|
|
|
36
38
|
# 不进 Coda,用假的 window.coda 在浏览器里看真实页面
|
|
37
39
|
"$CODA_NODE" test/harness/server.mjs <会话A的目录> [会话B的目录] [端口]
|
|
38
40
|
|
|
41
|
+
# 真实布局的断言和截图:无头 Chrome 打开 Mac 侧栏、iPhone 竖屏和横屏的目录树与文件页(浅色、深色),
|
|
42
|
+
# 量行高、工具条、菜单的位置和尺寸。自己起服务和临时目录,用完删掉;截图在系统临时目录里,路径在最后打印。
|
|
43
|
+
# 失败时退出码非 0。Chrome 不在默认位置时把路径作参数传入
|
|
44
|
+
"$CODA_NODE" test/harness/layout.mjs [Chrome 的路径]
|
|
45
|
+
|
|
39
46
|
# 契约检查,<提交> 用 coda-console/coda-plugins 的提交号
|
|
40
47
|
npx --yes github:coda-console/coda-plugins#<提交> . --manifest
|
|
41
48
|
```
|
|
@@ -58,6 +65,8 @@ npx --yes github:coda-console/coda-plugins#<提交> . --manifest
|
|
|
58
65
|
|
|
59
66
|
工作流用 npm 可信发布,不需要令牌。只有手动运行才会发布,合并到 `main` 不会自动发布。
|
|
60
67
|
|
|
68
|
+
发布后 npm 可能要约 10 分钟才公开,工作流最多等 15 分钟确认。超时会显示失败,但摘要写着「发布已接受,公开确认超时,不要重发」:包已经发出,不要重跑工作流,先到 npm 上查这个版本。
|
|
69
|
+
|
|
61
70
|
首次发布要先有包,可信发布才能配置:在本机 `npm login` 后手动运行 `npm publish --access public`,再到 npm 上 `@coda-console/resource-manager` 的设置里配置可信发布,仓库填 `sealiu1997/coda_plugins_resource_manager`,流程文件填 `publish.yml`,并勾选允许 `npm publish`(Allow npm publish)。新配置默认只允许 `npm stage publish`,不勾选的话工作流的发布步骤会被拒绝。之后就按上面的步骤走。
|
|
62
71
|
|
|
63
72
|
## 许可
|
package/lib/content.mjs
CHANGED
|
@@ -1,10 +1,14 @@
|
|
|
1
1
|
// 分块读文件并判断类型。页面一块一块要,模块不记状态。
|
|
2
|
+
import { constants } from 'node:fs';
|
|
2
3
|
import { open } from 'node:fs/promises';
|
|
3
4
|
import {
|
|
4
5
|
CHUNK_BYTES, ContentKind, ErrorCode, IMAGE_LIMIT, SNIFF_BYTES, TEXT_LIMIT, fail, imageType,
|
|
5
6
|
} from '../view/protocol.mjs';
|
|
6
7
|
import { fromFsError, parseRelative, resolveInRoot } from './paths.mjs';
|
|
7
8
|
|
|
9
|
+
// 只作用于最后一级:校验之后目标被换成链接,打开会被拒绝而不是跟过去。平台没有这个常量就退回 0。
|
|
10
|
+
const NOFOLLOW = constants.O_NOFOLLOW ?? 0;
|
|
11
|
+
|
|
8
12
|
async function readAt(handle, position, length) {
|
|
9
13
|
const buffer = Buffer.allocUnsafe(length);
|
|
10
14
|
const { bytesRead } = length ? await handle.read(buffer, 0, length, position) : { bytesRead: 0 };
|
|
@@ -13,11 +17,20 @@ async function readAt(handle, position, length) {
|
|
|
13
17
|
|
|
14
18
|
// 返回 { data, offset, size, mtimeMs, kind, eof }。文本最多给前 TEXT_LIMIT 字节,
|
|
15
19
|
// 超过限制的图片和二进制文件不给内容(页面看 size 和 kind 说明)。
|
|
16
|
-
|
|
20
|
+
// deps.open 只给测试换,用来在校验和打开之间插入时机。
|
|
21
|
+
export async function readChunk(root, path, offset, deps = { open }) {
|
|
17
22
|
if (!Number.isSafeInteger(offset) || offset < 0) throw fail(ErrorCode.INVALID_OFFSET, '偏移无效');
|
|
18
23
|
const real = await resolveInRoot(root, path);
|
|
19
24
|
let handle;
|
|
20
|
-
try {
|
|
25
|
+
try {
|
|
26
|
+
handle = await deps.open(real, constants.O_RDONLY | NOFOLLOW);
|
|
27
|
+
} catch (error) {
|
|
28
|
+
// 被 O_NOFOLLOW 拒绝(macOS、Linux 是 ELOOP,BSD 是 EMLINK)说明校验后被换成了链接,按越界处理。
|
|
29
|
+
if (NOFOLLOW && (error?.code === 'ELOOP' || error?.code === 'EMLINK')) {
|
|
30
|
+
throw fail(ErrorCode.OUTSIDE_ROOT, '链接指向工作目录之外');
|
|
31
|
+
}
|
|
32
|
+
throw fromFsError(error);
|
|
33
|
+
}
|
|
21
34
|
try {
|
|
22
35
|
const info = await handle.stat();
|
|
23
36
|
if (!info.isFile()) throw fail(ErrorCode.NOT_FILE, '不是文件');
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
// 日期、大小排序的快照:第一页读全部条目并排好序,之后的页只从这里取,不再碰文件系统。
|
|
2
|
+
// 快照属于一个视图,由 main.mjs 建一份传给 lib/tree.mjs;这里只管存放、淘汰和释放,不碰 fs。
|
|
3
|
+
export const MAX_SNAPSHOTS = 8;
|
|
4
|
+
export const MAX_SNAPSHOT_ENTRIES = 100_000;
|
|
5
|
+
export const SNAPSHOT_IDLE_MS = 60_000;
|
|
6
|
+
|
|
7
|
+
export function createSnapshots({
|
|
8
|
+
now = Date.now, maxCount = MAX_SNAPSHOTS, maxEntries = MAX_SNAPSHOT_ENTRIES, idleMs = SNAPSHOT_IDLE_MS,
|
|
9
|
+
} = {}) {
|
|
10
|
+
const items = new Map(); // id → 快照;Map 的顺序就是最近使用的顺序,最前面的最久没用
|
|
11
|
+
let nextId = 1, total = 0;
|
|
12
|
+
|
|
13
|
+
const drop = id => {
|
|
14
|
+
const item = items.get(id);
|
|
15
|
+
if (item) { total -= item.entries.length; items.delete(id); }
|
|
16
|
+
};
|
|
17
|
+
// 不起定时器:每次访问任何快照时顺便清掉闲置的。
|
|
18
|
+
const sweep = () => {
|
|
19
|
+
const time = now();
|
|
20
|
+
for (const [id, item] of items) if (time - item.used > idleMs) drop(id);
|
|
21
|
+
};
|
|
22
|
+
|
|
23
|
+
return {
|
|
24
|
+
get size() { return items.size; },
|
|
25
|
+
get total() { return total; },
|
|
26
|
+
|
|
27
|
+
// 取快照并记为刚用过;已被淘汰、释放或闲置过期的返回 null。
|
|
28
|
+
get(id) {
|
|
29
|
+
sweep();
|
|
30
|
+
const item = items.get(id);
|
|
31
|
+
if (!item) return null;
|
|
32
|
+
item.used = now();
|
|
33
|
+
items.delete(id);
|
|
34
|
+
items.set(id, item);
|
|
35
|
+
return item;
|
|
36
|
+
},
|
|
37
|
+
|
|
38
|
+
// 存一份,替换同身份的旧快照,超出数量或总条目时淘汰最久没用的。id 递增、不复用,旧游标不会指到新快照上。
|
|
39
|
+
put({ identity, root, path, entries }) {
|
|
40
|
+
sweep();
|
|
41
|
+
for (const [id, item] of items) if (item.identity === identity) drop(id);
|
|
42
|
+
while (items.size > 0 && (items.size >= maxCount || total + entries.length > maxEntries)) drop(items.keys().next().value);
|
|
43
|
+
const item = { id: nextId++, identity, root, path, entries, used: now() };
|
|
44
|
+
items.set(item.id, item);
|
|
45
|
+
total += entries.length;
|
|
46
|
+
return item;
|
|
47
|
+
},
|
|
48
|
+
|
|
49
|
+
release: drop,
|
|
50
|
+
clear() { items.clear(); total = 0; },
|
|
51
|
+
};
|
|
52
|
+
}
|
package/lib/tree.mjs
CHANGED
|
@@ -1,74 +1,263 @@
|
|
|
1
|
-
//
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
import {
|
|
5
|
-
import {
|
|
1
|
+
// 读目录:文件夹在前,按排序键排序,按序列化字节数分页。模块回答全部条目,隐藏规则在页面。
|
|
2
|
+
// 名称、种类排序每页重读目录,游标是上一条的排序键,只读当前页条目的元数据;
|
|
3
|
+
// 日期、大小排序第一页读全部条目的元数据并建快照,之后的页从快照取,不再碰文件系统(设计见 docs/design/phase-3.md 第 12.3 节)。
|
|
4
|
+
import { lstat, readdir, realpath, stat } from 'node:fs/promises';
|
|
5
|
+
import { extname, join } from 'node:path';
|
|
6
|
+
import {
|
|
7
|
+
DEFAULT_SORT, EntryKind, ENVELOPE_BYTES, ErrorCode, PAGE_BYTES, SortKey, fail, parseSort,
|
|
8
|
+
} from '../view/protocol.mjs';
|
|
9
|
+
import { fromFsError, isInside, isSafeName, parseRelative, resolveInRoot } from './paths.mjs';
|
|
10
|
+
import { createSnapshots } from './snapshots.mjs';
|
|
6
11
|
|
|
7
12
|
const MAX_ENTRIES = 100_000;
|
|
8
|
-
|
|
13
|
+
// 日期、大小排序要读全部条目的元数据,超过这个数的目录退回按名称排。
|
|
14
|
+
export const SORT_STAT_LIMIT = 20_000;
|
|
15
|
+
const CONCURRENCY = 8;
|
|
16
|
+
// 一条的元数据最多占的字节(两个都是 16 位整数),用来在读元数据之前保守地决定一页放几条。
|
|
17
|
+
const META_BYTES = Buffer.byteLength(',"size":9007199254740991,"mtimeMs":9007199254740991');
|
|
18
|
+
|
|
19
|
+
// 并发上限:每个视图一个,classify 和读元数据都经它,所以并行多个目录也不会超过 limit 个同时在读。
|
|
20
|
+
export function createLimiter(limit = CONCURRENCY) {
|
|
21
|
+
let active = 0;
|
|
22
|
+
const waiting = [];
|
|
23
|
+
return async fn => {
|
|
24
|
+
if (active < limit) active++; else await new Promise(resolve => waiting.push(resolve));
|
|
25
|
+
try { return await fn(); } finally {
|
|
26
|
+
const next = waiting.shift();
|
|
27
|
+
if (next) next(); else active--; // 有人等就把坑位直接交给它
|
|
28
|
+
}
|
|
29
|
+
};
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
const realFs = { lstat, readdir, realpath, stat };
|
|
33
|
+
|
|
34
|
+
// 一个视图的读取状态:文件系统、共用的并发上限、快照、进行中的第一页读取。
|
|
35
|
+
// refresh、changed 后 detach:进行中的读取不再被新请求共用;换会话、根目录变化、视图关闭后 clear。
|
|
36
|
+
// latest 记着每个身份最新发起的读取:只有它能存快照,旧的读取晚到也不会顶掉新快照。detach 不动它,clear 才清(清了之后谁都不能存)。
|
|
37
|
+
export function createListing({ fs = realFs, limit = CONCURRENCY, snapshots = createSnapshots() } = {}) {
|
|
38
|
+
return {
|
|
39
|
+
fs, snapshots, run: createLimiter(limit), reads: new Map(), latest: new Map(), started: 0,
|
|
40
|
+
detach() { this.reads.clear(); },
|
|
41
|
+
clear() { this.reads.clear(); this.latest.clear(); this.snapshots.clear(); },
|
|
42
|
+
};
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
// ---- 排序 ----
|
|
9
46
|
|
|
10
47
|
const rank = entry => (entry.kind === EntryKind.DIR ? 0 : 1);
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
48
|
+
const extOf = name => extname(name).slice(1).toLowerCase();
|
|
49
|
+
|
|
50
|
+
// 排序键;undefined 是缺元数据(或文件夹没有大小),排在组内最后。
|
|
51
|
+
function keyOf(entry, key) {
|
|
52
|
+
switch (key) {
|
|
53
|
+
case SortKey.NAME: return entry.name.toLowerCase();
|
|
54
|
+
case SortKey.KIND: return entry.kind === EntryKind.DIR ? '' : extOf(entry.name);
|
|
55
|
+
case SortKey.DATE: return entry.mtimeMs;
|
|
56
|
+
default: return entry.kind === EntryKind.DIR ? undefined : entry.size;
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
// 每种排序的方向,只在这里定义:名称、种类升序,日期、大小降序(最新、最大在前)。
|
|
61
|
+
const DESCENDING = new Set([SortKey.DATE, SortKey.SIZE]);
|
|
62
|
+
|
|
63
|
+
// 全序:文件夹在前(不随方向反向);键按该排序的方向,缺的不管方向都在最后;平手按名字(不分大小写)升序,最后按原名。
|
|
64
|
+
function comparer(key) {
|
|
65
|
+
const desc = DESCENDING.has(key);
|
|
66
|
+
return (a, b) => {
|
|
67
|
+
if (rank(a) !== rank(b)) return rank(a) - rank(b);
|
|
68
|
+
const x = keyOf(a, key), y = keyOf(b, key);
|
|
69
|
+
if (x !== y) {
|
|
70
|
+
if (x === undefined) return 1;
|
|
71
|
+
if (y === undefined) return -1;
|
|
72
|
+
return (x < y ? -1 : 1) * (desc ? -1 : 1);
|
|
73
|
+
}
|
|
74
|
+
const p = a.name.toLowerCase(), q = b.name.toLowerCase();
|
|
75
|
+
if (p !== q) return p < q ? -1 : 1;
|
|
76
|
+
return a.name === b.name ? 0 : a.name < b.name ? -1 : 1;
|
|
77
|
+
};
|
|
16
78
|
}
|
|
17
79
|
|
|
18
|
-
|
|
80
|
+
// ---- 游标:名称、种类用排序键,日期、大小用快照编号加下标。解不开的一律当作过期。 ----
|
|
81
|
+
|
|
82
|
+
const encode = value => Buffer.from(JSON.stringify(value)).toString('base64url');
|
|
83
|
+
const encodeKeyCursor = (sort, entry) => encode(['k', sort, rank(entry), entry.name]);
|
|
84
|
+
const encodeSnapshotCursor = (id, index) => encode(['s', id, index]);
|
|
85
|
+
|
|
19
86
|
function decodeCursor(cursor) {
|
|
20
87
|
try {
|
|
21
|
-
const
|
|
22
|
-
if ((
|
|
88
|
+
const value = JSON.parse(Buffer.from(String(cursor), 'base64url').toString('utf8'));
|
|
89
|
+
if (Array.isArray(value)) {
|
|
90
|
+
if (value[0] === 's' && Number.isSafeInteger(value[1]) && Number.isSafeInteger(value[2]) && value[2] > 0) {
|
|
91
|
+
return { snapshot: value[1], index: value[2] };
|
|
92
|
+
}
|
|
93
|
+
const [tag, sort, group, name] = value;
|
|
94
|
+
if (value.length === 4 && tag === 'k' && (sort === SortKey.NAME || sort === SortKey.KIND)
|
|
95
|
+
&& (group === 0 || group === 1) && typeof name === 'string') {
|
|
96
|
+
return { sort, after: { name, kind: group === 0 ? EntryKind.DIR : EntryKind.FILE } };
|
|
97
|
+
}
|
|
98
|
+
}
|
|
23
99
|
} catch { /* 下面统一报错 */ }
|
|
24
|
-
throw fail(ErrorCode.
|
|
100
|
+
throw fail(ErrorCode.CURSOR_EXPIRED, '游标已过期');
|
|
25
101
|
}
|
|
26
102
|
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
103
|
+
// ---- 读条目 ----
|
|
104
|
+
|
|
105
|
+
// 只有符号链接要额外解析:目标在根目录内按目标显示(目标的 lstat 带回去给读元数据用,不解析第二次),在外或已失效显示为 link。
|
|
106
|
+
// 校验之后用 lstat 读目标,不跟随链接:realpath 之后目标被换成别的链接,读到的就是符号链接,按 link 处理,不带外面的元数据。
|
|
107
|
+
async function classifyLink(fs, root, dir, name) {
|
|
108
|
+
try {
|
|
109
|
+
const real = await fs.realpath(join(dir, name));
|
|
110
|
+
if (!isInside(root, real)) return { name, kind: EntryKind.LINK };
|
|
111
|
+
const info = await fs.lstat(real);
|
|
112
|
+
if (info.isSymbolicLink()) return { name, kind: EntryKind.LINK };
|
|
113
|
+
const kind = info.isDirectory() ? EntryKind.DIR : info.isFile() ? EntryKind.FILE : EntryKind.OTHER;
|
|
114
|
+
return { name, kind, link: true, info };
|
|
115
|
+
} catch { return { name, kind: EntryKind.LINK }; }
|
|
34
116
|
}
|
|
35
117
|
|
|
36
|
-
|
|
37
|
-
async function classify(root, dir, dirent) {
|
|
118
|
+
function classifyPlain(dirent) {
|
|
38
119
|
const { name } = dirent;
|
|
39
120
|
if (!isSafeName(name)) return { name, kind: EntryKind.OTHER };
|
|
40
121
|
if (dirent.isDirectory()) return { name, kind: EntryKind.DIR };
|
|
41
122
|
if (dirent.isFile()) return { name, kind: EntryKind.FILE };
|
|
42
|
-
|
|
123
|
+
return { name, kind: EntryKind.OTHER };
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
const needsResolve = dirent => dirent.isSymbolicLink() && isSafeName(dirent.name);
|
|
127
|
+
// 不是链接的不碰文件系统,不占并发坑位。
|
|
128
|
+
const classify = (listing, root, dir, dirent) => (needsResolve(dirent)
|
|
129
|
+
? listing.run(() => classifyLink(listing.fs, root, dir, dirent.name))
|
|
130
|
+
: classifyPlain(dirent));
|
|
131
|
+
|
|
132
|
+
// 读失败(刚被删、没权限)不算错误,这个条目不带字段。普通条目用 lstat,不跟随链接:
|
|
133
|
+
// 条目在 readdir 之后被换成指向外面的链接,lstat 读到的也只是链接自己,类型对不上就不带字段。
|
|
134
|
+
// link: true 的用 classify 校验时拿到的目标 lstat。link、other 不读。size、mtimeMs 取整后只有这一份值。
|
|
135
|
+
async function addMeta(listing, dir, item) {
|
|
136
|
+
if (item.kind !== EntryKind.DIR && item.kind !== EntryKind.FILE) return;
|
|
43
137
|
try {
|
|
44
|
-
const
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
const
|
|
48
|
-
|
|
49
|
-
|
|
138
|
+
const info = item.link ? item.info : await listing.fs.lstat(join(dir, item.name));
|
|
139
|
+
const isDir = info.isDirectory();
|
|
140
|
+
if (isDir !== (item.kind === EntryKind.DIR) || (!isDir && !info.isFile())) return;
|
|
141
|
+
const mtimeMs = Math.floor(info.mtimeMs), size = Math.floor(info.size);
|
|
142
|
+
if (Number.isFinite(mtimeMs)) item.mtimeMs = mtimeMs;
|
|
143
|
+
if (!isDir && Number.isFinite(size)) item.size = size;
|
|
144
|
+
} catch { /* 不带字段 */ }
|
|
50
145
|
}
|
|
51
146
|
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
entries.sort(compare);
|
|
147
|
+
function toEntry({ name, kind, link, size, mtimeMs }) {
|
|
148
|
+
const entry = { name, kind };
|
|
149
|
+
if (link) entry.link = true;
|
|
150
|
+
if (size !== undefined) entry.size = size;
|
|
151
|
+
if (mtimeMs !== undefined) entry.mtimeMs = mtimeMs;
|
|
152
|
+
return entry;
|
|
153
|
+
}
|
|
60
154
|
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
155
|
+
const entryBytes = entry => Buffer.byteLength(JSON.stringify(entry)) + 1;
|
|
156
|
+
|
|
157
|
+
// 从 start 起取一页,至少一条;返回下一页的下标。
|
|
158
|
+
function cut(entries, start, pageBytes) {
|
|
159
|
+
let end = start, used = 0;
|
|
160
|
+
while (end < entries.length) {
|
|
161
|
+
const size = entryBytes(entries[end]);
|
|
162
|
+
if (end > start && used + size > pageBytes - ENVELOPE_BYTES) break;
|
|
163
|
+
used += size;
|
|
164
|
+
end++;
|
|
165
|
+
}
|
|
166
|
+
return { entries: entries.slice(start, end), end };
|
|
167
|
+
}
|
|
64
168
|
|
|
65
|
-
|
|
169
|
+
async function readDirents(listing, dir) {
|
|
170
|
+
try { return await listing.fs.readdir(dir, { withFileTypes: true }); } catch (error) { throw fromFsError(error); }
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
// 名称、种类(和退回名称的日期、大小):读目录、classify 全部,排序,找到游标之后,只读这一页的元数据。
|
|
174
|
+
// 元数据的字节数在读之前不知道,所以按最大可能的字节数决定放几条,一页不会超。
|
|
175
|
+
async function pageByKey(listing, root, dir, dirents, sort, after, pageBytes) {
|
|
176
|
+
const items = await Promise.all(dirents.map(dirent => classify(listing, root, dir, dirent)));
|
|
177
|
+
const compare = comparer(sort);
|
|
178
|
+
items.sort(compare);
|
|
179
|
+
let index = 0;
|
|
180
|
+
if (after) while (index < items.length && compare(items[index], after) <= 0) index++;
|
|
181
|
+
const picked = [];
|
|
66
182
|
let used = 0;
|
|
67
|
-
while (index <
|
|
68
|
-
const size =
|
|
69
|
-
if (
|
|
183
|
+
while (index < items.length) {
|
|
184
|
+
const size = entryBytes(toEntry(items[index])) + META_BYTES;
|
|
185
|
+
if (picked.length && used + size > pageBytes - ENVELOPE_BYTES) break;
|
|
70
186
|
used += size;
|
|
71
|
-
|
|
187
|
+
picked.push(items[index++]);
|
|
72
188
|
}
|
|
73
|
-
|
|
189
|
+
await Promise.all(picked.map(item => listing.run(() => addMeta(listing, dir, item))));
|
|
190
|
+
return { entries: picked.map(toEntry), nextCursor: index < items.length ? encodeKeyCursor(sort, picked[picked.length - 1]) : null };
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
// 日期、大小的第一页:读全部条目的元数据,排序,存快照。一页放得下就不存。
|
|
194
|
+
// 读完核对代次和根路径:对不上说明读的时候会话或根目录换了,不存快照也不回答内容。
|
|
195
|
+
// isLatest:这次读取是不是同身份最新发起的;不是的照常回答,但不存快照(回答里的游标指向编号 0,永远查不到,页面丢弃这份回答)。
|
|
196
|
+
async function firstSnapshotPage(listing, root, rel, path, sort, { pageBytes, maxEntries, statLimit, valid, isLatest }) {
|
|
197
|
+
const dir = await resolveInRoot(root, path);
|
|
198
|
+
const dirents = await readDirents(listing, dir);
|
|
199
|
+
if (dirents.length > maxEntries) throw fail(ErrorCode.TOO_LARGE, `目录条目超过 ${maxEntries} 个`);
|
|
200
|
+
if (dirents.length > statLimit) {
|
|
201
|
+
return { ...await pageByKey(listing, root, dir, dirents, DEFAULT_SORT, null, pageBytes), sortFallback: true };
|
|
202
|
+
}
|
|
203
|
+
const items = await Promise.all(dirents.map(dirent => listing.run(async () => {
|
|
204
|
+
// 已经占着坑位,直接解析链接;再经 run 会等自己占的坑位。
|
|
205
|
+
const item = needsResolve(dirent) ? await classifyLink(listing.fs, root, dir, dirent.name) : classifyPlain(dirent);
|
|
206
|
+
await addMeta(listing, dir, item);
|
|
207
|
+
return item;
|
|
208
|
+
})));
|
|
209
|
+
const entries = items.map(toEntry).sort(comparer(sort));
|
|
210
|
+
if (!valid()) throw fail(ErrorCode.NO_ROOT, '工作目录已变化');
|
|
211
|
+
const page = cut(entries, 0, pageBytes);
|
|
212
|
+
if (page.end >= entries.length) return { entries, nextCursor: null };
|
|
213
|
+
if (!isLatest()) return { entries: page.entries, nextCursor: encodeSnapshotCursor(0, page.end) };
|
|
214
|
+
const snapshot = listing.snapshots.put({ identity: JSON.stringify([root, rel, sort]), root, path: rel, entries });
|
|
215
|
+
return { entries: page.entries, nextCursor: encodeSnapshotCursor(snapshot.id, page.end) };
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
function pageOfSnapshot(listing, root, rel, { snapshot: id, index }, pageBytes) {
|
|
219
|
+
const snapshot = listing.snapshots.get(id);
|
|
220
|
+
if (!snapshot || snapshot.root !== root || snapshot.path !== rel || index >= snapshot.entries.length) {
|
|
221
|
+
throw fail(ErrorCode.CURSOR_EXPIRED, '游标已过期');
|
|
222
|
+
}
|
|
223
|
+
const page = cut(snapshot.entries, index, pageBytes);
|
|
224
|
+
if (page.end < snapshot.entries.length) return { entries: page.entries, nextCursor: encodeSnapshotCursor(id, page.end) };
|
|
225
|
+
listing.snapshots.release(id);
|
|
226
|
+
return { entries: page.entries, nextCursor: null };
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
// options:sort(只对第一页有效,有游标时只认游标里的)、listing(视图共用的读取状态)、valid(回答前是否仍然有效,
|
|
230
|
+
// 由主模块按代次和根路径判断)、maxEntries、pageBytes、statLimit(测试可调)。
|
|
231
|
+
export async function listDirectory(root, path, cursor, options = {}) {
|
|
232
|
+
const {
|
|
233
|
+
listing = createListing(), maxEntries = MAX_ENTRIES, pageBytes = PAGE_BYTES, statLimit = SORT_STAT_LIMIT, valid = () => true,
|
|
234
|
+
} = options;
|
|
235
|
+
const requested = options.sort == null ? DEFAULT_SORT : parseSort(options.sort);
|
|
236
|
+
if (!requested) throw fail(ErrorCode.INVALID_SORT, '排序无效');
|
|
237
|
+
const rel = parseRelative(path).join('/');
|
|
238
|
+
const at = cursor == null ? null : decodeCursor(cursor);
|
|
239
|
+
if (at?.snapshot !== undefined) return pageOfSnapshot(listing, root, rel, at, pageBytes);
|
|
240
|
+
|
|
241
|
+
if (!at && (requested === SortKey.DATE || requested === SortKey.SIZE)) {
|
|
242
|
+
// 同身份的第一页并发时共用同一次读取。
|
|
243
|
+
const identity = JSON.stringify([root, rel, requested]);
|
|
244
|
+
let read = listing.reads.get(identity);
|
|
245
|
+
if (!read) {
|
|
246
|
+
const order = ++listing.started;
|
|
247
|
+
listing.latest.set(identity, order);
|
|
248
|
+
const isLatest = () => listing.latest.get(identity) === order;
|
|
249
|
+
read = firstSnapshotPage(listing, root, rel, path, requested, { pageBytes, maxEntries, statLimit, valid, isLatest })
|
|
250
|
+
.finally(() => {
|
|
251
|
+
if (listing.reads.get(identity) === read) listing.reads.delete(identity);
|
|
252
|
+
if (isLatest()) listing.latest.delete(identity);
|
|
253
|
+
});
|
|
254
|
+
listing.reads.set(identity, read);
|
|
255
|
+
}
|
|
256
|
+
return read;
|
|
257
|
+
}
|
|
258
|
+
|
|
259
|
+
const dir = await resolveInRoot(root, path);
|
|
260
|
+
const dirents = await readDirents(listing, dir);
|
|
261
|
+
if (dirents.length > maxEntries) throw fail(ErrorCode.TOO_LARGE, `目录条目超过 ${maxEntries} 个`);
|
|
262
|
+
return pageByKey(listing, root, dir, dirents, at ? at.sort : requested, at?.after ?? null, pageBytes);
|
|
74
263
|
}
|
package/main.mjs
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
// 资源管理器的模块:跟踪侧栏的会话、代次和根目录,把页面的请求交给 lib/*,把变化推给页面。
|
|
2
2
|
// 协议见 docs/design/phase-1.md 第 6 节,消息格式见 view/protocol.mjs。
|
|
3
|
-
import { listDirectory } from './lib/tree.mjs';
|
|
3
|
+
import { createListing, listDirectory } from './lib/tree.mjs';
|
|
4
4
|
import { readChunk } from './lib/content.mjs';
|
|
5
5
|
import { NO_ROOT, queryRoot, sameRoot } from './lib/root.mjs';
|
|
6
6
|
import {
|
|
@@ -17,19 +17,21 @@ const sessionOfFile = context => {
|
|
|
17
17
|
return typeof session === 'string' && session !== '' ? session : null;
|
|
18
18
|
};
|
|
19
19
|
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
coda.views.register('
|
|
20
|
+
// options.makeListing 只给测试用:换成带假文件系统的读取状态,运行时不传。
|
|
21
|
+
export function activate(coda, { makeListing = createListing } = {}) {
|
|
22
|
+
coda.views.register('files', { open: view => serve(coda, view, sessionOfTree, makeListing) });
|
|
23
|
+
coda.views.register('file', { open: view => serve(coda, view, sessionOfFile, makeListing) });
|
|
23
24
|
}
|
|
24
25
|
|
|
25
26
|
const validRequestId = id => (typeof id === 'string' && id.length <= REQUEST_ID_MAX) || Number.isSafeInteger(id);
|
|
26
27
|
const errorOf = error => (error?.protocol ? { code: error.code, message: error.message } : { code: ErrorCode.IO, message: '读取失败' });
|
|
27
28
|
|
|
28
|
-
function serve(coda, view, sessionOf) {
|
|
29
|
+
function serve(coda, view, sessionOf, makeListing) {
|
|
29
30
|
// 代次:每换一次会话加 1,所有异步出口回来后都要核对。
|
|
30
31
|
const s = {
|
|
31
32
|
session: sessionOf(view.context), generation: 1, root: NO_ROOT, sent: null,
|
|
32
33
|
hello: false, closed: false, rootSeq: 0, poll: null,
|
|
34
|
+
listing: makeListing(), // 这个视图共用的并发上限和快照;视图关闭、换会话、根目录变化时丢弃
|
|
33
35
|
};
|
|
34
36
|
const turns = new Map();
|
|
35
37
|
const stale = generation => s.closed || generation !== s.generation;
|
|
@@ -58,7 +60,10 @@ function serve(coda, view, sessionOf) {
|
|
|
58
60
|
let next = null;
|
|
59
61
|
try { next = await queryRoot(coda, s.session); } catch { /* 保留上一次 */ }
|
|
60
62
|
if (stale(generation) || seq !== s.rootSeq) return;
|
|
61
|
-
if (next)
|
|
63
|
+
if (next) {
|
|
64
|
+
if (next.path !== s.root.path) s.listing.clear();
|
|
65
|
+
s.root = next;
|
|
66
|
+
}
|
|
62
67
|
syncPoll();
|
|
63
68
|
if (s.hello && !sameRoot(s.sent, s.root)) postRoot();
|
|
64
69
|
}
|
|
@@ -81,6 +86,7 @@ function serve(coda, view, sessionOf) {
|
|
|
81
86
|
stopPoll();
|
|
82
87
|
s.session = session ?? null;
|
|
83
88
|
s.generation++;
|
|
89
|
+
s.listing.clear();
|
|
84
90
|
s.root = NO_ROOT;
|
|
85
91
|
s.sent = null;
|
|
86
92
|
if (s.hello) postSession();
|
|
@@ -93,9 +99,13 @@ function serve(coda, view, sessionOf) {
|
|
|
93
99
|
const reply = type === Type.LIST ? Type.LISTED : Type.CHUNK;
|
|
94
100
|
try {
|
|
95
101
|
if (s.root.state !== RootState.READY) throw fail(ErrorCode.NO_ROOT, '没有可浏览的工作目录');
|
|
102
|
+
const root = s.root.path;
|
|
103
|
+
// 读的途中根目录换了(同一会话从 A 换到 B),回答不能带 A 的内容。
|
|
104
|
+
const valid = () => !stale(generation) && s.root.state === RootState.READY && s.root.path === root;
|
|
96
105
|
const body = type === Type.LIST
|
|
97
|
-
? await listDirectory(
|
|
98
|
-
: await readChunk(
|
|
106
|
+
? await listDirectory(root, message.path, message.cursor, { listing: s.listing, sort: message.sort, valid })
|
|
107
|
+
: await readChunk(root, message.path, message.offset);
|
|
108
|
+
if (type === Type.LIST && !valid() && !stale(generation)) throw fail(ErrorCode.NO_ROOT, '工作目录已变化');
|
|
99
109
|
if (!stale(generation)) post({ type: reply, generation, requestId, ...body });
|
|
100
110
|
} catch (error) {
|
|
101
111
|
if (!stale(generation)) post({ type: reply, generation, requestId, error: errorOf(error) });
|
|
@@ -107,7 +117,10 @@ function serve(coda, view, sessionOf) {
|
|
|
107
117
|
switch (message.type) {
|
|
108
118
|
// 页面(重新)就绪:它什么都不知道,所以不管有没有变,下一次查询的结果都要推。
|
|
109
119
|
case Type.HELLO: s.hello = true; s.sent = null; postSession(); return refreshRoot();
|
|
110
|
-
case Type.REFRESH:
|
|
120
|
+
case Type.REFRESH:
|
|
121
|
+
if (stale(message.generation)) return undefined;
|
|
122
|
+
s.listing.detach();
|
|
123
|
+
return refreshRoot();
|
|
111
124
|
case Type.LIST: case Type.READ: return request(message);
|
|
112
125
|
}
|
|
113
126
|
});
|
|
@@ -124,11 +137,18 @@ function serve(coda, view, sessionOf) {
|
|
|
124
137
|
if (s.closed || id !== s.session || before === undefined || after === undefined || before === after) return;
|
|
125
138
|
const { generation } = s;
|
|
126
139
|
const refreshed = refreshRoot();
|
|
127
|
-
if (before)
|
|
140
|
+
if (before) {
|
|
141
|
+
refreshed.then(() => {
|
|
142
|
+
if (!s.hello || stale(generation)) return;
|
|
143
|
+
s.listing.detach(); // 页面接着重新取,进行中的旧读取不能再被共用
|
|
144
|
+
post({ type: Type.CHANGED, generation });
|
|
145
|
+
});
|
|
146
|
+
}
|
|
128
147
|
})).catch(() => null);
|
|
129
148
|
|
|
130
149
|
view.onClose(async () => {
|
|
131
150
|
s.closed = true;
|
|
151
|
+
s.listing.clear();
|
|
132
152
|
stopPoll();
|
|
133
153
|
try { await (await watching)?.dispose(); } catch { /* 已经取消 */ }
|
|
134
154
|
});
|