@coda-console/friends 0.5.0 → 0.6.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 +18 -37
- package/lib/avatar.mjs +5 -27
- package/lib/friends.mjs +9 -142
- package/lib/gateway.mjs +16 -165
- package/lib/nickname.mjs +43 -0
- package/lib/outbox.mjs +14 -12
- package/lib/view-members.mjs +5 -17
- package/main.mjs +5 -31
- package/package.json +7 -175
- package/view/app.mjs +40 -302
- package/view/style.css +10 -53
- package/lib/notes.mjs +0 -65
- package/lib/social-streams.mjs +0 -218
- package/view/cropper.mjs +0 -106
package/README.md
CHANGED
|
@@ -1,20 +1,20 @@
|
|
|
1
1
|
# 好友
|
|
2
2
|
|
|
3
|
-
管理本机的 Accord
|
|
3
|
+
管理本机的 Accord 身份与熟人好友通道(`coda/accord@1`),并提供业务无关的好友网关(`friends/social@1`)。
|
|
4
4
|
|
|
5
|
-
-
|
|
6
|
-
-
|
|
7
|
-
-
|
|
8
|
-
-
|
|
9
|
-
- **社交网关 `friends/social@1`**:业务无关,别的插件(在 `optionalUses`
|
|
5
|
+
- **本机身份**:身份卡显示本机的展示名、确定性几何纹头像、公钥短码(点按复制),下方状态条给出已互认好友数(有待互认、冲突时提示)与身份、证书状态。没有建身份时显示「未建身份」并提示前往客户端「设置 › 身份」创建。
|
|
6
|
+
- **公钥派生的昵称与头像**:本机和好友都没有可编辑的昵称、照片、Emoji 或主题色,统一由 Accord 公钥推出。展示名是 `昵称 #尾号`:昵称按 coda#3040 的算法取公钥 256 位,从最高位起每 7 位一组(至多 36 组),`0–77` 为字母、`78–87` 为数字、`88–127` 为结束符(已有不足 2 位时跳过,够 2 位就结束,读完仍不足 2 位则没有昵称);尾号是公钥按大端整数转成十进制(补零到 78 位)后的末 4 位。解不出昵称时退回公钥短码(`ed25519:` 之后前 8 位),还没有公钥的待互认好友用节点名。头像是由公钥确定性生成的 5×5 几何纹,灰色,换设备也一样;没有合法公钥时取名字首字。算法在 `lib/nickname.mjs`,浏览器与 Node 通用。
|
|
7
|
+
- **添加好友**:点身份卡上的「添加好友」,粘贴对方给的邀请(JSON、`coda-friend://` 链接或多行 `key=value`),接受后自动尝试互认。暂需由对方提供 friend 角色入网码。
|
|
8
|
+
- **好友列表**:实时跟随好友表变化,宽屏双列。点好友打开详情:昵称、几何纹头像、完整公钥(可复制)、节点名、连接状态、重新互认、二次确认后移除。
|
|
9
|
+
- **社交网关 `friends/social@1`**:业务无关,别的插件(在 `optionalUses` 里声明)经它读好友与好友分享的记录、向好友发布与撤回记录,不必各自处理没有身份、证书过期和重试。
|
|
10
10
|
|
|
11
11
|
## 几台电脑
|
|
12
12
|
|
|
13
13
|
页面不自己选电脑:App 的全局视图里有哪几台,页面就读哪几台,没有机器标签。
|
|
14
14
|
|
|
15
|
-
-
|
|
16
|
-
- **好友按电脑分节**:每台一节,顺序同视图,节标题是电脑名;节里是这台自己的好友通道(好友关系按机器上的通道登记,在 A 上加的好友 B
|
|
17
|
-
-
|
|
15
|
+
- **本机身份按公钥显示**:按各台 Accord 的 `spec.author` 分组,同一身份只显示一张身份卡,视图里有不同身份的电脑时每个身份一张。
|
|
16
|
+
- **好友按电脑分节**:每台一节,顺序同视图,节标题是电脑名;节里是这台自己的好友通道(好友关系按机器上的通道登记,在 A 上加的好友 B 上不会自动出现),状态条(好友数、证书状态、待互认与冲突)和「添加好友」也在这一节。接受邀请与随后的互认、好友详情里的重新互认、移除,都发给这一节、这一行所在的电脑。没有好友的电脑也占一节;同一个好友在两台上都加了,就在两节里各出现一次,不合并。读不到的电脑(`unreachable`)节里写明原因,不出「添加好友」。
|
|
17
|
+
- **只有一台时**页面不出现节标题,状态条与「添加好友」仍在身份卡上。
|
|
18
18
|
- **推荐用法**:好友只在一台电脑上加。好友关系登记在那台电脑上,别的电脑不会自动出现这个好友。邀请里的入网码只能用一次,不必在每台上重复加。
|
|
19
19
|
- **几台电脑绑定同一个身份、又在同一个空间里时**,其他电脑发布的记录由 Coda 在这几台之间同步,好友从加了他的那台读取(见 Coda 仓库 `docs/peers.md`)。这是 Coda 基座的行为,本插件不另外保证,也不检查同步是否已经完成。
|
|
20
20
|
|
|
@@ -24,45 +24,26 @@
|
|
|
24
24
|
|
|
25
25
|
| 操作 | 作用 |
|
|
26
26
|
| --- | --- |
|
|
27
|
-
| `friends`(读) | 互认的好友(`includePending`
|
|
27
|
+
| `friends`(读) | 互认的好友(`includePending` 带上待互认与冲突的),只来自 Accord 的好友表:`{ selfAuthor, certState, friends }`,每行的 `title` 是公钥派生的展示名,不读名片记录 |
|
|
28
28
|
| `records`(读) | 按 `kind`、`author`、`id`、`cursor` 读好友分享的记录,不读 `binding` |
|
|
29
29
|
| `publish` | 发布 `{ kind, id, body, audience? }`;同作者同内容不重发,换作者重发 |
|
|
30
|
-
| `set-card` | 发布本机社交名片 `friends/card` / `self`:`{ name, emoji?, color?, avatar? }`,`avatar` 只收 `content/<sha256>` 指针(至多 5 MiB),`null` 清除;与 `publish` 同一条队 |
|
|
31
|
-
| `send-dm` | 发一条私信 `friends/dm`:`{ to, id?, text?, attachments?, replyTo? }`,受众只有 `to` 一人(不收 `public`、不收自己);结果带最终用的 `id` |
|
|
32
|
-
| `post-feed` | 发一条动态 `friends/feed`:`{ id?, text?, media?, audience? }`,`audience` 缺省 `['public']`,写了须是 1–500 项(去重);结果带最终用的 `id` |
|
|
33
30
|
| `retract` | 撤回一条,或省略 `id` 撤回本机在这个 `kind` 下的全部(含队列里还没发出去的) |
|
|
34
31
|
| `outbox`(读) | 待发与已同步条目的状态,从不给出 `body` |
|
|
35
32
|
|
|
36
|
-
- `publish`、`retract` 拒绝保留类型 `binding`、`profile`、`friends`、`coda/profile`、`coda/friends`;`kind` 须是 Accord 的格式,`id` 至多 200 个字符、256 字节,`body` 是对象且 JSON 至多 64 KiB,`audience` 每项是 `public` 或 `ed25519:` 加 64 位十六进制,至多 500 项。
|
|
33
|
+
- `publish`、`retract` 拒绝保留类型 `binding`、`profile`、`friends`、`friends/card`、`coda/profile`、`coda/friends`;`kind` 须是 Accord 的格式,`id` 至多 200 个字符、256 字节,`body` 是对象且 JSON 至多 64 KiB,`audience` 每项是 `public` 或 `ed25519:` 加 64 位十六进制,至多 500 项。
|
|
37
34
|
- 没有身份、证书过期(或发布遇到 `invalid_state`)、`kind` 被暂停、发布失败时,待发的 `body` 暂存在本机 `outbox.json`;同步成功就释放 `body`,只留去重用的 `lastAuthor`、`lastSyncedHash`、`lastSyncedAt`;撤回完成就删掉条目。证书恢复后自动补发、补撤;待撤的条目记着排队时的作者(`targetAuthor`),换了作者不会替新作者撤,没有身份时的撤回只清本机未发出的待发,不排待撤。意图先落盘再签名,签名成功立即落盘确认;`outbox.json`、`policy.json` 读不出来(不是缺失或损坏)就报错,不当空表。
|
|
38
|
-
-
|
|
35
|
+
- 旧版留在 `outbox.json` 里的保留类型条目(如已下线的名片 `friends/card`)读表时直接丢掉,随启动或下一次冲洗落盘清理,不补发、也不挡着别的待发条目。插件不会去撤回 Accord 里历史上已发布的旧名片记录。
|
|
39
36
|
- 暂停与恢复某个 `kind` 的外发:`coda self policy.setKind '{"kind":"…","paused":true}'`,`coda self policy.get` 读现状(`policy.json`);暂停只拦发布,不拦撤回。
|
|
40
37
|
|
|
41
|
-
##
|
|
38
|
+
## 已下线的功能
|
|
42
39
|
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
- **正文**:`text` 按原样(含首尾空白)至多 8000 个字(码点,与 schema 的 `maxLength` 一致),发布时去首尾空白;图片指针(`attachments` / `media`)1–4 个,只收 `content/<sha256>`;两者不能都空。`id` 省略时网关生成 UUID,给了须是至多 200 个字符、且 UTF-8 至多 256 字节(与 Accord 一致;schema 表达不了字节数,超了由网关以 `invalid_input` 拒绝)、不含控制字符,去首尾空白后不能为空;`replyTo` 同。
|
|
46
|
-
- **只发给别人**:私信的 `to` 不能是本人。排队时还没有身份、后来绑定的身份正好是收件人的,补发时按实际签名的作者再判一次,标成被拒(`error`),不签。
|
|
47
|
-
- **幂等重试**:`body.createdAt` 先沿用同一 `id` 已有的:`outbox.json` 里待发条目的,或已同步条目留下的 `lastCreatedAt`;队列里没有才查本机在 Accord 里的那条,查明没有才取当前时间,查询失败报可重试的 `unavailable`,不拿新时间戳重签。所以同一 `id`、同样内容的重试按 `publish` 的去重返回 `skipped: true`,不会重签。
|
|
48
|
-
- **投影**:每个 `(author, id)` 只取 `version` 最大的一条,它若是撤回(空 `body`)或畸形,整条就没了,不回落旧版本。私信只收本机发出(本人签、发给别人)或发给本机(别人签、`to` 是本人)的,`peer` 是对面那个人;串线、伪造的丢掉。私信按 `(createdAt, version, author, id)` 升序,动态降序。
|
|
49
|
-
|
|
50
|
-
### 实时流 `dm`、`feed`
|
|
51
|
-
|
|
52
|
-
两条都是 `read` 形状的帧流(`application/x-ndjson`,30 秒没东西写一个空行心跳),参数走查询串:`dm` 收 `peer`(只看与这位好友的),`feed` 收 `author`(只看这一位的),都收 `after`(上次拿到的游标)。
|
|
53
|
-
|
|
54
|
-
- 快照分片发出:每帧 `{ type: 'snapshot', cursor, items, more }`,单帧 JSON 至多 256 KiB(远低于 `readFrames` 默认的一行 1 MiB);后面还有分片的 `more` 为 `true`,最后一片(空快照也有这一片,`items: []`)为 `false`。客户端把各片的 `items` 依次拼起来,收到 `more: false` 才落定整份快照与游标。
|
|
55
|
-
- 之后每次变化一帧 `{ type: 'upsert', cursor, item }` 或 `{ type: 'retract', cursor, author, id, peer? }`。同一条私信改投新收件人时,旧会话先收到 `retract`(`peer` 是旧收件人),新会话再收到 `upsert`。
|
|
56
|
-
- 游标是 `<epoch>:<seq>`:`epoch` 每次网关启动重新生成,`seq` 单调递增。网关在内存里留最近 500 次变化;`after` 有效时只补它之后的增量(含撤回,不重复)。`after` 缺失、不合法、来自上一次启动、比现在还新或已被挤出这 500 条的,回到全量快照。
|
|
57
|
-
- 只在有订阅者或新流连入时才翻页读 Accord,随本机 Accord 记录的变化和本机的发布、撤回刷新;刷新排成一条队,不会交错。每次都翻页读到底,读不全(翻页截断、查询失败)就不动内存里上一份完整的投影,不推虚假的快照或撤回;还从没读全过时新连入的流在第一个字节之前以 `unavailable` 失败。
|
|
58
|
-
- 调用方中止请求、取消应答体,或插件停用时,流当场收尾,订阅与监听随之释放(不等下一帧、也不管调用方读没读)。
|
|
40
|
+
名片编辑(昵称、照片、Emoji、字标、主题色、裁剪上传)、本机备注(`notes.json`、`coda self notes.*`)、`set-card`、私信 `send-dm`、动态 `post-feed` 与 `dm`、`feed` 两条帧流都已移除。插件本地只写 `outbox.json` 与 `policy.json`;旧版留下的 `notes.json` 不再被读取。
|
|
59
41
|
|
|
60
42
|
## 权限与数据边界
|
|
61
43
|
|
|
62
|
-
- `friends/social@1` 的权限组:`read` 管 `friends`、`records
|
|
63
|
-
- `uses`:`coda/accord@1` 的 `read
|
|
44
|
+
- `friends/social@1` 的权限组:`read` 管 `friends`、`records`;`publish` 管 `publish`、`retract`、`outbox`。
|
|
45
|
+
- `uses`:`coda/accord@1` 的 `read`(读好友表)、`publish`(网关代别的插件发布)、`manage`(接受邀请、互认、移除)。
|
|
64
46
|
- 入网码(`authKey`)是凭据:只在提交时用一次,提交后立即清空输入框,不写入任何文件、日志或页面状态。
|
|
65
|
-
-
|
|
66
|
-
- 好友发来的昵称、Emoji、颜色按同一套规则清洗,只当文本渲染(`textContent`),不当指令或 HTML。
|
|
47
|
+
- 节点名等外来数据只当文本渲染(`textContent`),不当指令或 HTML。
|
|
67
48
|
- 好友页的 Accord 读写在页面交互时发起;模块只在 `activate` 时监听本机 Accord 记录(证书、好友表),用来刷新网关记录、证书恢复后冲洗待发队列。
|
|
68
|
-
-
|
|
49
|
+
- 待发的 `body` 只在本机 `outbox.json`,不经别处。
|
package/lib/avatar.mjs
CHANGED
|
@@ -1,26 +1,12 @@
|
|
|
1
|
-
// 好友页头像与 Accord
|
|
1
|
+
// 好友页头像与 Accord 状态的纯逻辑:确定性几何纹、无公钥时的首字兜底、身份与好友统计。
|
|
2
2
|
// 页面(WKWebView)与 Node 单测都直接加载它,所以只用标准 JS 和 ./friends.mjs,不拼 HTML。
|
|
3
3
|
|
|
4
|
-
import { certStateOf,
|
|
5
|
-
|
|
6
|
-
/** 头像图片的大小上限,与客户端和后端的 5 MiB 一致。 */
|
|
7
|
-
export const BLOB_MAX_BYTES = 5 * 1024 * 1024;
|
|
4
|
+
import { certStateOf, shortAuthor } from './friends.mjs';
|
|
8
5
|
|
|
9
6
|
const CONTROL_CHARS = /[\p{Cc}\u2028\u2029]/gu;
|
|
10
7
|
const AUTHOR = /^ed25519:([0-9a-f]{64})$/;
|
|
11
|
-
const MAX_EMOJI = 8;
|
|
12
8
|
|
|
13
9
|
const clean = text => typeof text === 'string' ? text.replace(CONTROL_CHARS, '').trim() : '';
|
|
14
|
-
const machineQuery = machine => typeof machine === 'string' && machine.trim() ? `?coda-machine=${encodeURIComponent(machine.trim())}` : '';
|
|
15
|
-
|
|
16
|
-
/** 头像指针的读取地址:指针不合法(或为空)给 null;多机空间里带上 machine。 */
|
|
17
|
-
export function blobReadUrl(pointer, machine) {
|
|
18
|
-
const p = readContentPointer(pointer);
|
|
19
|
-
return p ? `coda-view://blob/${p.owner}/content/${p.sha256}${machineQuery(machine)}` : null;
|
|
20
|
-
}
|
|
21
|
-
|
|
22
|
-
/** 上传头像的地址;多机空间里带上 machine。 */
|
|
23
|
-
export const blobUploadUrl = machine => `coda-view://blob/content${machineQuery(machine)}`;
|
|
24
10
|
|
|
25
11
|
/** 一串字节的确定性混合(FNV-1a 作种,mulberry32 取数),给几何纹用。 */
|
|
26
12
|
function* stream(bytes) {
|
|
@@ -59,17 +45,9 @@ export function initialChar(text, fallback = '友') {
|
|
|
59
45
|
return first ? (/^[a-z]$/.test(first) ? first.toUpperCase() : first) : fallback;
|
|
60
46
|
}
|
|
61
47
|
|
|
62
|
-
/**
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
* photo 带 `fallback`:图片加载失败时直接换用的描述。
|
|
66
|
-
*/
|
|
67
|
-
export function resolveAvatar({ avatar, emoji, author, name, fallback = '友', machine, photoFailed = false, prefer = 'auto' } = {}) {
|
|
68
|
-
const url = photoFailed ? null : blobReadUrl(avatar, machine);
|
|
69
|
-
if (url) return { kind: 'photo', url, fallback: resolveAvatar({ avatar, emoji, author, name, fallback, machine, photoFailed: true, prefer }) };
|
|
70
|
-
const mark = clean(emoji);
|
|
71
|
-
if (mark && [...mark].length <= MAX_EMOJI) return { kind: 'emoji', emoji: mark };
|
|
72
|
-
if (prefer !== 'monogram' && AUTHOR.test(author ?? '')) return { kind: 'identicon', grid: identiconPattern(author), author };
|
|
48
|
+
/** 决定头像怎么展示,只返回纯数据:合法的 author 画它的几何纹(identicon),否则取 name 的首字(monogram)。 */
|
|
49
|
+
export function resolveAvatar({ author, name, fallback = '友' } = {}) {
|
|
50
|
+
if (AUTHOR.test(author ?? '')) return { kind: 'identicon', grid: identiconPattern(author), author };
|
|
73
51
|
return { kind: 'monogram', text: initialChar(name, fallback) };
|
|
74
52
|
}
|
|
75
53
|
|
package/lib/friends.mjs
CHANGED
|
@@ -1,23 +1,17 @@
|
|
|
1
|
-
//
|
|
1
|
+
// 好友页的纯逻辑:解析邀请、证书状态、把好友表合成列表行。不碰 Coda,也不碰磁盘。
|
|
2
2
|
// 页面也加载它,所以只用浏览器和 Node 都有的 API。
|
|
3
|
+
import { identityTitle, shortAuthor } from './nickname.mjs';
|
|
4
|
+
|
|
5
|
+
export { shortAuthor };
|
|
3
6
|
|
|
4
|
-
export const COLORS = ['blue', 'orange', 'green', 'purple', 'pink', 'teal', 'gray'];
|
|
5
|
-
export const PROFILE_KIND = 'profile';
|
|
6
|
-
export const PROFILE_ID = 'self';
|
|
7
|
-
// 可代签的社交名片:和 profile 同形,id 也是 self;profile 须客户端根签,绑定代签证书后用它。
|
|
8
|
-
export const CARD_KIND = 'friends/card';
|
|
9
|
-
const MAX_NAME = 40, MAX_EMOJI = 8;
|
|
10
7
|
// 邀请各字段的上限,与 coda/accord@1 的 accept 输入一致。
|
|
11
8
|
const LIMITS = { control: 500, authKey: 500, linkId: 64, scope: 520, hostname: 100, peerNode: 100 };
|
|
12
9
|
const LABELS = { control: '入网地址 control', authKey: '入网码 authKey', linkId: 'linkId', scope: 'scope', hostname: 'hostname', peerNode: 'peerNode', peerPort: 'peerPort' };
|
|
13
10
|
const LINK_ID = /^[a-z0-9][a-z0-9_-]{0,63}$/;
|
|
14
11
|
const ALIASES = { controlurl: 'control', control_url: 'control', authkey: 'authKey', auth_key: 'authKey', linkid: 'linkId', link_id: 'linkId',
|
|
15
12
|
link: 'linkId', peernode: 'peerNode', peer_node: 'peerNode', peerport: 'peerPort', peer_port: 'peerPort' };
|
|
16
|
-
const CONTROL_CHARS = /[\p{Cc}\u2028\u2029]/gu;
|
|
17
13
|
const length = text => [...text].length;
|
|
18
14
|
|
|
19
|
-
const clean = text => typeof text === 'string' ? text.replace(CONTROL_CHARS, '').trim() : '';
|
|
20
|
-
|
|
21
15
|
// ---- 邀请 ----
|
|
22
16
|
|
|
23
17
|
const fail = message => { throw new Error(message); };
|
|
@@ -106,117 +100,6 @@ export function checked(input) {
|
|
|
106
100
|
return invite;
|
|
107
101
|
}
|
|
108
102
|
|
|
109
|
-
// ---- 头像指针 ----
|
|
110
|
-
|
|
111
|
-
const MAX_BLOB = 5 * 1024 * 1024, MAX_MIME = 128, MAX_FILE_NAME = 200;
|
|
112
|
-
const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
|
|
113
|
-
const CONTENT_PATH = /^content\/([0-9a-f]{64})$/;
|
|
114
|
-
const MIME = /^[a-z0-9][a-z0-9!#$&^_.+-]*\/[a-z0-9][a-z0-9!#$&^_.+-]*$/i;
|
|
115
|
-
const POINTER_KEYS = new Set(['owner', 'path', 'sha256', 'mime', 'size', 'name']);
|
|
116
|
-
|
|
117
|
-
/**
|
|
118
|
-
* 内容寻址的图片指针(BlobPointer,`path` 只收 `content/<sha256>`)的校验:`{ owner, path, sha256, mime?, size?, name? }`,
|
|
119
|
-
* 不许别的键,`sha256` 须与 `path` 里的一致,`size` 至多 5 MiB。合法返回只含这些字段的新对象,不合法抛出中文错误。
|
|
120
|
-
*/
|
|
121
|
-
export function normalizeContentPointer(pointer) {
|
|
122
|
-
if (!pointer || typeof pointer !== 'object' || Array.isArray(pointer)) fail('头像须是图片指针对象');
|
|
123
|
-
for (const key of Object.keys(pointer)) if (!POINTER_KEYS.has(key)) fail(`头像指针不认识的字段:${key}`);
|
|
124
|
-
const { owner, path, sha256, mime, size, name } = pointer;
|
|
125
|
-
if (typeof owner !== 'string' || !UUID.test(owner)) fail('头像指针的 owner 须是小写 UUID');
|
|
126
|
-
const match = typeof path === 'string' ? CONTENT_PATH.exec(path) : null;
|
|
127
|
-
if (!match) fail('头像指针的 path 须是 content/<64 位小写十六进制 SHA-256>');
|
|
128
|
-
if (sha256 !== match[1]) fail('头像指针的 sha256 须与 path 里的一致');
|
|
129
|
-
const out = { owner, path, sha256 };
|
|
130
|
-
if (mime !== undefined) {
|
|
131
|
-
if (typeof mime !== 'string' || !mime || mime.length > MAX_MIME || !MIME.test(mime)) fail(`头像指针的 mime 须是合法的 MIME 类型(最多 ${MAX_MIME} 字)`);
|
|
132
|
-
out.mime = mime;
|
|
133
|
-
}
|
|
134
|
-
if (size !== undefined) {
|
|
135
|
-
if (!Number.isSafeInteger(size) || size < 0 || size > MAX_BLOB) fail('头像指针的 size 须是 0 到 5 MiB 之间的整数');
|
|
136
|
-
out.size = size;
|
|
137
|
-
}
|
|
138
|
-
if (name !== undefined) {
|
|
139
|
-
const text = clean(name);
|
|
140
|
-
if (!text || length(text) > MAX_FILE_NAME) fail(`头像指针的 name 须是非空文本(最多 ${MAX_FILE_NAME} 字)`);
|
|
141
|
-
out.name = text;
|
|
142
|
-
}
|
|
143
|
-
return out;
|
|
144
|
-
}
|
|
145
|
-
|
|
146
|
-
/** 读外来记录里的图片指针:合法给规范化的指针,不合法给 null,从不抛错。 */
|
|
147
|
-
export function readContentPointer(pointer) {
|
|
148
|
-
try { return normalizeContentPointer(pointer); } catch { return null; }
|
|
149
|
-
}
|
|
150
|
-
|
|
151
|
-
// ---- 名片 ----
|
|
152
|
-
|
|
153
|
-
/**
|
|
154
|
-
* 名片输入的清洗(profile 与 friends/card 同形):昵称 1–40 字,emoji 最多 8 字,颜色须在白名单里;
|
|
155
|
-
* avatar 省略不写,null 表示清除,否则须是合法的 content 指针。不合法的昵称、emoji、头像抛错;不认识的颜色丢掉。
|
|
156
|
-
*/
|
|
157
|
-
export function normalizeCardInput({ name, emoji, color, avatar } = {}) {
|
|
158
|
-
const body = { name: clean(name) };
|
|
159
|
-
if (!body.name) fail('昵称不能为空');
|
|
160
|
-
if (length(body.name) > MAX_NAME) fail(`昵称最多 ${MAX_NAME} 个字`);
|
|
161
|
-
const mark = clean(emoji);
|
|
162
|
-
if (mark) { if (length(mark) > MAX_EMOJI) fail(`头像最多 ${MAX_EMOJI} 个字符`); body.emoji = mark; }
|
|
163
|
-
if (typeof color === 'string' && COLORS.includes(color)) body.color = color;
|
|
164
|
-
if (avatar !== undefined) body.avatar = avatar === null ? null : normalizeContentPointer(avatar);
|
|
165
|
-
return body;
|
|
166
|
-
}
|
|
167
|
-
export const normalizeProfileInput = normalizeCardInput;
|
|
168
|
-
|
|
169
|
-
/**
|
|
170
|
-
* 读 Accord 记录里的名片,来自好友的外来数据:按同样的规则清洗,不合法的字段忽略,昵称不合法整张忽略(null)。
|
|
171
|
-
* 头像分三种:没写或畸形是 `avatarPresent: false`;显式清除(`avatar: null`)与合法指针是 `avatarPresent: true`,`avatar` 为 null 或指针。
|
|
172
|
-
* 结果只当文本用,不当指令或 HTML。
|
|
173
|
-
*/
|
|
174
|
-
export const readProfileRecord = record => readNameRecord(record, PROFILE_KIND);
|
|
175
|
-
/** 同 readProfileRecord,读 friends/card 记录。 */
|
|
176
|
-
export const readCardRecord = record => readNameRecord(record, CARD_KIND);
|
|
177
|
-
|
|
178
|
-
function readNameRecord(record, kind) {
|
|
179
|
-
if (!record || record.kind !== kind || record.id !== PROFILE_ID) return null;
|
|
180
|
-
const body = record.body;
|
|
181
|
-
if (!body || typeof body !== 'object' || Array.isArray(body)) return null;
|
|
182
|
-
const name = clean(body.name);
|
|
183
|
-
if (!name || length(name) > MAX_NAME) return null;
|
|
184
|
-
const profile = { author: typeof record.author === 'string' ? record.author : null, version: Number.isFinite(record.version) ? record.version : 0, name };
|
|
185
|
-
const emoji = clean(body.emoji);
|
|
186
|
-
if (emoji && length(emoji) <= MAX_EMOJI) profile.emoji = emoji;
|
|
187
|
-
if (typeof body.color === 'string' && COLORS.includes(body.color)) profile.color = body.color;
|
|
188
|
-
const avatar = body.avatar === null ? null : readContentPointer(body.avatar);
|
|
189
|
-
profile.avatar = avatar;
|
|
190
|
-
profile.avatarPresent = body.avatar === null || avatar !== null;
|
|
191
|
-
return profile;
|
|
192
|
-
}
|
|
193
|
-
|
|
194
|
-
/**
|
|
195
|
-
* 同一作者的 profile(根私钥签名)与 friends/card(可代签)合成一张名片:profile 写了的字段优先,免得代签的机器盖过根签的资料;
|
|
196
|
-
* profile 没写的由 friends/card 补。头像看 `avatarPresent`:profile 写了(含显式清除的 null)就用 profile 的。两张都没有给 null。
|
|
197
|
-
*/
|
|
198
|
-
export function mergeProfileAndCard(profile, card) {
|
|
199
|
-
if (!profile && !card) return null;
|
|
200
|
-
const pick = key => profile?.[key] ?? card?.[key];
|
|
201
|
-
const from = profile?.avatarPresent ? profile : card?.avatarPresent ? card : null;
|
|
202
|
-
return { name: pick('name'), emoji: pick('emoji'), color: pick('color'), avatar: from ? from.avatar : null, avatarPresent: Boolean(from) };
|
|
203
|
-
}
|
|
204
|
-
|
|
205
|
-
/**
|
|
206
|
-
* 代签回退发布了 friends/card 之后的提示:`true` 已确认有根签的 profile,如实说明好友看到的仍以它为准;`false` 已确认没有;
|
|
207
|
-
* `null` / `undefined` 没读出来,不承诺好友看到的是哪张。
|
|
208
|
-
*/
|
|
209
|
-
export const cardFallbackNotice = hasRootProfile => hasRootProfile === true
|
|
210
|
-
? '社交名片已保存,但你已有根私钥签名的名片,昵称等已有项仍以根签名为准(未设项由社交名片补充)'
|
|
211
|
-
: hasRootProfile === false ? '本机用的是代签证书,名片已改作社交名片(friends/card)发布,好友会看到它'
|
|
212
|
-
: '社交名片已保存;若你曾用根私钥发布过名片,昵称等已有项仍以根签名为准';
|
|
213
|
-
|
|
214
|
-
/** 密钥的短码:`ed25519:` 之后的前 8 位(没有就空串)。 */
|
|
215
|
-
export function shortAuthor(author) {
|
|
216
|
-
const match = /^ed25519:([0-9a-f]{64})$/.exec(author ?? '');
|
|
217
|
-
return match ? match[1].slice(0, 8) : '';
|
|
218
|
-
}
|
|
219
|
-
|
|
220
103
|
/**
|
|
221
104
|
* 本机 Accord 记录(`coda/accord@1` 的 local)的证书状态:状态里写了 `certificate` 的按它判:null 没有身份,
|
|
222
105
|
* `active` 为 true 才是可发布,其余要换证书;旧宿主不写这个键,有作者就当可发布(发布遇 invalid_state 再落到需要证书)。
|
|
@@ -236,27 +119,11 @@ const RANK = { conflict: 0, pending: 1, bound: 2 };
|
|
|
236
119
|
export const statusOf = friend => friend.conflict ? 'conflict' : friend.bound ? 'bound' : 'pending';
|
|
237
120
|
|
|
238
121
|
/**
|
|
239
|
-
* 好友表(`status.friends
|
|
240
|
-
*
|
|
241
|
-
* 同样的输入排出同样的顺序。
|
|
122
|
+
* 好友表(`status.friends`)合成的行:标题是公钥派生的昵称(见 nickname.mjs),没有公钥的待互认项用节点名;
|
|
123
|
+
* 按状态(冲突、待互认、已互认)再按更新时间新的在前排序,同样的输入排出同样的顺序。
|
|
242
124
|
*/
|
|
243
|
-
export function mergeFriendRows(
|
|
244
|
-
const
|
|
245
|
-
|
|
246
|
-
for (const record of records) {
|
|
247
|
-
const one = read(record);
|
|
248
|
-
if (one?.author && (!latest.has(one.author) || one.version > latest.get(one.author).version)) latest.set(one.author, one);
|
|
249
|
-
}
|
|
250
|
-
return latest;
|
|
251
|
-
};
|
|
252
|
-
const byProfile = latestOf(profiles, readProfileRecord), byCard = latestOf(cards, readCardRecord);
|
|
253
|
-
const note = friend => (Object.hasOwn(notes, friend.node) ? notes[friend.node] : friend.author && Object.hasOwn(notes, friend.author) ? notes[friend.author] : '');
|
|
254
|
-
const rows = friends.map(friend => {
|
|
255
|
-
const card = friend.author ? mergeProfileAndCard(byProfile.get(friend.author), byCard.get(friend.author)) : null;
|
|
256
|
-
const status = statusOf(friend), remark = clean(note(friend)), short = shortAuthor(friend.author), name = card?.name;
|
|
257
|
-
return { node: friend.node, author: friend.author ?? null, short, status, peerNode: friend.peerNode ?? null, scope: friend.scope, updatedAt: friend.updatedAt ?? 0,
|
|
258
|
-
note: remark, profileName: name ?? '', emoji: card?.emoji ?? '', color: card?.color ?? 'gray', avatar: card?.avatar ?? null,
|
|
259
|
-
title: remark || name || (short ? `好友 ${short}` : friend.node) };
|
|
260
|
-
});
|
|
125
|
+
export function mergeFriendRows(friends = []) {
|
|
126
|
+
const rows = friends.map(friend => ({ node: friend.node, author: friend.author ?? null, short: shortAuthor(friend.author), status: statusOf(friend),
|
|
127
|
+
peerNode: friend.peerNode ?? null, scope: friend.scope, updatedAt: friend.updatedAt ?? 0, title: identityTitle(friend.author, friend.node) }));
|
|
261
128
|
return rows.sort((a, b) => RANK[a.status] - RANK[b.status] || b.updatedAt - a.updatedAt || (a.node < b.node ? -1 : a.node > b.node ? 1 : 0));
|
|
262
129
|
}
|
package/lib/gateway.mjs
CHANGED
|
@@ -1,17 +1,14 @@
|
|
|
1
1
|
// 抽象社交网关:实现 friends/social@1。业务无关——只认 kind、id、body;签名写入与记录查询全部透传 coda/accord@1,
|
|
2
2
|
// 自己不建第二份目录库,只在 outbox.json 里留还没发出去的 body(同步成功即释放)。所有会写盘、会外发的动作排成一条队,
|
|
3
3
|
// 发布、撤回、证书变化引起的冲洗互不交叉。
|
|
4
|
-
import {
|
|
5
|
-
import { readNotes } from './notes.mjs';
|
|
4
|
+
import { mergeFriendRows, statusOf } from './friends.mjs';
|
|
6
5
|
import { canSkip, canonicalHash, certStateOf, checkId, checkKind, checkPublish, entryKey, holdState, keyOf, retractKey, invalid, isPending, markRejected, markSynced,
|
|
7
6
|
nextSeq, queuePublish, queueRetract, readOutbox, withState, writeOutbox } from './outbox.mjs';
|
|
8
7
|
import { readPolicy, setKindPaused } from './policy.mjs';
|
|
9
|
-
import { DM_KIND, FEED_KIND, createStreamHub, frameOf, normalizeDmInput, normalizeFeedInput, projectDmRecords, projectFeedRecords, snapshotFrames, subjectOf } from './social-streams.mjs';
|
|
10
8
|
|
|
11
9
|
const ACCORD = { kind: 'coda/accord@1', id: 'local' };
|
|
12
10
|
const SOCIAL = 'friends/social@1';
|
|
13
11
|
const MAX_PAGES = 50;
|
|
14
|
-
const HEARTBEAT_MS = 30_000;
|
|
15
12
|
const REJECTED = new Set(['invalid_input', 'forbidden']);
|
|
16
13
|
const message = e => String(e?.message ?? e);
|
|
17
14
|
const interrupted = effects => Object.assign(new Error('好友网关已停止'), { code: 'interrupted', effects });
|
|
@@ -40,11 +37,11 @@ export function createGateway(coda, dir) {
|
|
|
40
37
|
return { accord, author: accord?.spec?.author ?? null, certState: certStateOf(accord) };
|
|
41
38
|
}
|
|
42
39
|
|
|
43
|
-
// 翻页读 coda/accord@1 的记录,至多
|
|
44
|
-
async function pages(input
|
|
40
|
+
// 翻页读 coda/accord@1 的记录,至多 MAX_PAGES 页;cursor 重复就停,不会原地打转。
|
|
41
|
+
async function pages(input) {
|
|
45
42
|
const records = [], seen = new Set();
|
|
46
43
|
let cursor;
|
|
47
|
-
for (let page = 0; page <
|
|
44
|
+
for (let page = 0; page < MAX_PAGES; page++) {
|
|
48
45
|
const read = await coda.query(ACCORD, 'records', { ...input, limit: 200, ...(cursor ? { cursor } : {}) });
|
|
49
46
|
records.push(...(read?.records ?? []));
|
|
50
47
|
cursor = read?.nextCursor;
|
|
@@ -64,11 +61,6 @@ export function createGateway(coda, dir) {
|
|
|
64
61
|
// 把一条待发或待撤的条目交给 coda/accord@1 发出去(撤回是 body 为空、audience 为空的发布)。
|
|
65
62
|
async function attempt(entry, author) {
|
|
66
63
|
live();
|
|
67
|
-
// 私信不签给自己:按此刻真正签名的作者判,排队时还没有身份、后来绑成了收件人的也拦下,标成被拒。
|
|
68
|
-
if (entry.desired === 'publish' && entry.kind === DM_KIND && entry.body?.to === author) {
|
|
69
|
-
const error = '不能给自己发私信';
|
|
70
|
-
return { state: 'error', entry: markRejected(entry, error), error };
|
|
71
|
-
}
|
|
72
64
|
const input = entry.desired === 'publish' ? { kind: entry.kind, id: entry.id, body: entry.body, audience: entry.audience }
|
|
73
65
|
: { kind: entry.kind, id: entry.id, body: {}, audience: [] };
|
|
74
66
|
try {
|
|
@@ -81,9 +73,16 @@ export function createGateway(coda, dir) {
|
|
|
81
73
|
}
|
|
82
74
|
}
|
|
83
75
|
|
|
76
|
+
// 读出待发队列;旧版残留的保留类型条目(如 friends/card)已被读表丢掉,这里把清理落盘,之后不再补发,也不挡着别的条目。
|
|
77
|
+
async function purgeReserved() {
|
|
78
|
+
const outbox = await readOutbox(stateDir());
|
|
79
|
+
if (outbox.dropped) await persist(outbox);
|
|
80
|
+
return outbox;
|
|
81
|
+
}
|
|
82
|
+
|
|
84
83
|
// 冲洗:能发的待发、待撤条目发出去;证书不对或 kind 暂停的只更新状态。
|
|
85
84
|
async function flushNow() {
|
|
86
|
-
const d = stateDir(), outbox = await
|
|
85
|
+
const d = stateDir(), outbox = await purgeReserved();
|
|
87
86
|
if (!Object.values(outbox).some(isPending)) return;
|
|
88
87
|
const [{ author, certState }, { pausedKinds }] = await Promise.all([accordState(), readPolicy(d)]);
|
|
89
88
|
let changed = false;
|
|
@@ -157,18 +156,14 @@ export function createGateway(coda, dir) {
|
|
|
157
156
|
if (!stopped) await coda.put({ kind: SOCIAL, key: 'local' }, { spec: { version: 1 }, status });
|
|
158
157
|
} catch { /* 状态记录下一次动作会再写 */ }
|
|
159
158
|
}
|
|
160
|
-
const mutate = work => serial(async () => { try { return await work(); } finally { await refreshNow();
|
|
159
|
+
const mutate = work => serial(async () => { try { return await work(); } finally { await refreshNow(); } });
|
|
161
160
|
|
|
162
161
|
// ---- friends/social@1 的操作 ----
|
|
163
162
|
|
|
164
163
|
async function friends({ includePending = false } = {}) {
|
|
165
164
|
const { accord, author, certState } = await accordState();
|
|
166
165
|
const list = Array.isArray(accord?.status?.friends) ? accord.status.friends : [];
|
|
167
|
-
|
|
168
|
-
const [profiles, cards] = list.length ? await Promise.all([pages({ kind: PROFILE_KIND }), pages({ kind: CARD_KIND })]) : [none, none];
|
|
169
|
-
const notes = dir ? await readNotes(dir) : {};
|
|
170
|
-
const rows = mergeFriendRows({ friends: list, profiles: profiles.records, cards: cards.records, notes }).filter(row => includePending || row.status === 'bound');
|
|
171
|
-
return { selfAuthor: author, certState, friends: rows, truncated: profiles.truncated || cards.truncated };
|
|
166
|
+
return { selfAuthor: author, certState, friends: mergeFriendRows(list).filter(row => includePending || row.status === 'bound') };
|
|
172
167
|
}
|
|
173
168
|
|
|
174
169
|
function records({ kind, author, id, limit, cursor, includeAudience }) {
|
|
@@ -222,49 +217,6 @@ export function createGateway(coda, dir) {
|
|
|
222
217
|
return { state: done.state, author, error: done.error };
|
|
223
218
|
}
|
|
224
219
|
|
|
225
|
-
// 同一 id 已有的 createdAt:待发条目 body 里的,或这位作者自己同步过的条目留下的 lastCreatedAt(别的作者同步的不算);
|
|
226
|
-
// 都没有才按当前作者查本机在 Accord 里的那条。查不了(读不到 Accord、查询失败)就报可重试的错,不拿新时间戳重签;查明没有才给 undefined。
|
|
227
|
-
async function existingCreatedAt(kind, id, current) {
|
|
228
|
-
const entry = (await readOutbox(stateDir()))[entryKey(kind, id)];
|
|
229
|
-
const known = entry?.body?.createdAt ?? (current?.author && entry?.lastAuthor === current.author ? entry.lastCreatedAt : undefined);
|
|
230
|
-
if (known !== undefined) return known;
|
|
231
|
-
let read;
|
|
232
|
-
try {
|
|
233
|
-
const { author } = current ?? await accordState();
|
|
234
|
-
if (!author) return undefined;
|
|
235
|
-
read = await coda.query(ACCORD, 'records', { kind, author, id, limit: 1 });
|
|
236
|
-
} catch (e) {
|
|
237
|
-
throw coda.error('unavailable', `查不到这个 id 已发过的内容,稍后重试:${message(e)}`, { effects: 'none' });
|
|
238
|
-
}
|
|
239
|
-
return (read?.records ?? []).find(record => record?.local === true && record.id === id)?.body?.createdAt;
|
|
240
|
-
}
|
|
241
|
-
|
|
242
|
-
// 私信与动态:清洗后走 publish 的同一条队(没有身份、证书过期一样排队、恢复后补发),结果带上最终用的 id。
|
|
243
|
-
function sendSocial(kind, input, normalize) {
|
|
244
|
-
return mutate(async () => {
|
|
245
|
-
let current = null;
|
|
246
|
-
try { current = await accordState(); } catch { /* 读不到身份:没给 id 的照样排队;给了 id 的下面查不了已有的 createdAt 就报错 */ }
|
|
247
|
-
const check = more => { try { return normalize(input, { selfAuthor: current?.author ?? null, now: Date.now(), ...more }); } catch (e) { throw invalid(message(e)); } };
|
|
248
|
-
let item = check({});
|
|
249
|
-
if (item.id !== undefined) {
|
|
250
|
-
const existing = await existingCreatedAt(kind, item.id, current);
|
|
251
|
-
if (existing !== undefined) item = check({ existingCreatedAt: existing });
|
|
252
|
-
}
|
|
253
|
-
live();
|
|
254
|
-
const id = item.id ?? globalThis.crypto.randomUUID();
|
|
255
|
-
return { ...await publishItem(checkPublish({ kind, id, body: item.body, audience: item.audience })), id };
|
|
256
|
-
});
|
|
257
|
-
}
|
|
258
|
-
const sendDm = input => sendSocial(DM_KIND, input, normalizeDmInput);
|
|
259
|
-
const postFeed = input => sendSocial(FEED_KIND, input, normalizeFeedInput);
|
|
260
|
-
|
|
261
|
-
// 可代签的社交名片:清洗后走 publish 的同一条队,没有身份或证书过期一样排队、恢复后补发。
|
|
262
|
-
function setCard(input) {
|
|
263
|
-
let body;
|
|
264
|
-
try { body = normalizeCardInput(input); } catch (e) { throw invalid(message(e)); }
|
|
265
|
-
return publish({ kind: CARD_KIND, id: PROFILE_ID, body, audience: ['public'] });
|
|
266
|
-
}
|
|
267
|
-
|
|
268
220
|
function retract({ kind, id } = {}) {
|
|
269
221
|
checkKind(kind);
|
|
270
222
|
if (id !== undefined) checkId(id);
|
|
@@ -356,108 +308,13 @@ export function createGateway(coda, dir) {
|
|
|
356
308
|
return { author, certState, pausedKinds, pendingCount: Object.values(entries).filter(isPending).length, items };
|
|
357
309
|
}
|
|
358
310
|
|
|
359
|
-
|
|
360
|
-
// 每条流一个 hub(内存里的投影与变化环缓冲)和它的订阅者;有订阅者、或新流连入时才翻页读 Accord,读全了才比对出增量推给订阅者,
|
|
361
|
-
// 读不全(截断、查询失败)不动 hub,留着上一份完整的投影。`ready`:hub 里已有过一份完整的投影。
|
|
362
|
-
// 私信的投影取决于本机作者:dm 的 `author` 是这份投影确认过的作者;换了作者就换一个新 hub(新 epoch、未就绪)、
|
|
363
|
-
// 关掉旧作者的订阅,读不出本机作者时也不算就绪,绝不把上一位作者的私信给新连入的流。
|
|
364
|
-
// 刷新排成一条队(和发布的队分开),先后两次刷新不会交错。
|
|
365
|
-
const hubs = {
|
|
366
|
-
dm: { kind: DM_KIND, hub: createStreamHub(), subs: new Set(), author: null, project: (records, author) => projectDmRecords(records, { selfAuthor: author }),
|
|
367
|
-
match: ({ peer }) => peer === undefined ? () => true : one => one.peer === peer },
|
|
368
|
-
feed: { kind: FEED_KIND, hub: createStreamHub(), subs: new Set(), project: records => projectFeedRecords(records),
|
|
369
|
-
match: ({ author }) => author === undefined ? () => true : one => one.author === author },
|
|
370
|
-
};
|
|
371
|
-
let pulling = Promise.resolve();
|
|
372
|
-
const pull = name => {
|
|
373
|
-
const run = pulling.then(async () => {
|
|
374
|
-
if (stopped) return;
|
|
375
|
-
const one = hubs[name];
|
|
376
|
-
let author = null;
|
|
377
|
-
if (name === 'dm') {
|
|
378
|
-
try { ({ author } = await accordState()); } catch (e) { one.ready = false; throw e; }
|
|
379
|
-
if (one.author !== author) {
|
|
380
|
-
Object.assign(one, { hub: createStreamHub(), ready: false, author });
|
|
381
|
-
for (const sub of [...one.subs]) sub.close();
|
|
382
|
-
}
|
|
383
|
-
}
|
|
384
|
-
const { records, truncated } = await pages({ kind: one.kind }, Infinity);
|
|
385
|
-
if (truncated) throw new Error(`${one.kind} 的记录翻页没有读全`);
|
|
386
|
-
if (stopped) return;
|
|
387
|
-
// hub 整份换上(投影、seq、历史)之后才算就绪、才通知订阅者。
|
|
388
|
-
const events = one.hub.applySnapshot(one.project(records, author));
|
|
389
|
-
one.ready = true;
|
|
390
|
-
for (const event of events)
|
|
391
|
-
for (const sub of one.subs) if (sub.match(subjectOf(event))) { sub.queue.push(event); sub.wake?.(); }
|
|
392
|
-
});
|
|
393
|
-
pulling = run.catch(() => {});
|
|
394
|
-
return run;
|
|
395
|
-
};
|
|
396
|
-
const pullWatched = () => { for (const [name, one] of Object.entries(hubs)) if (one.subs.size) pull(name).catch(() => {}); };
|
|
397
|
-
|
|
398
|
-
// 一条流的应答:先给快照(分片,或按 after 续上的增量),之后每次变化一帧。连入时读不出完整的投影:hub 已有完整的就用它,
|
|
399
|
-
// 还没有就在第一个字节之前报错,不发残缺的快照。调用方中止、取消应答体、网关停了都走同一个 cleanup:订阅、监听当场释放,
|
|
400
|
-
// 等着的 next 被唤醒结束。用手写的迭代器而不是 async generator:后者停在 yield 或 await 上时 return() 要排队等它。
|
|
401
|
-
// frames.write 的流外面再包一层:cleanup 当场取消里面那层(连同它的心跳定时器),哪怕首帧还没人读、正卡在背压上。
|
|
402
|
-
async function serveStream(name, { input = {}, signal }) {
|
|
403
|
-
live();
|
|
404
|
-
const one = hubs[name], match = one.match(input);
|
|
405
|
-
try { await pull(name); } catch (e) {
|
|
406
|
-
if (!one.ready) throw coda.error('unavailable', `读不出完整的${name === 'dm' ? '私信' : '动态'},稍后重连:${message(e)}`, { effects: 'none' });
|
|
407
|
-
}
|
|
408
|
-
live();
|
|
409
|
-
const start = one.hub.resume(input.after, match), epoch = one.hub.epoch;
|
|
410
|
-
const ahead = start.mode === 'snapshot' ? snapshotFrames(start.cursor, start.items) : start.events.map(event => frameOf(epoch, event));
|
|
411
|
-
let closed = false, outer = null;
|
|
412
|
-
const sub = { match, queue: [], wake: null };
|
|
413
|
-
const frames = {
|
|
414
|
-
async next() {
|
|
415
|
-
for (;;) {
|
|
416
|
-
if (closed) return { done: true, value: undefined };
|
|
417
|
-
if (ahead.length) return { done: false, value: ahead.shift() };
|
|
418
|
-
if (sub.queue.length) return { done: false, value: frameOf(epoch, sub.queue.shift()) };
|
|
419
|
-
await new Promise(resolve => { sub.wake = resolve; });
|
|
420
|
-
sub.wake = null;
|
|
421
|
-
}
|
|
422
|
-
},
|
|
423
|
-
async return() { cleanup(); return { done: true, value: undefined }; },
|
|
424
|
-
[Symbol.asyncIterator]() { return this; },
|
|
425
|
-
};
|
|
426
|
-
const reader = coda.frames.write(frames, { heartbeatMs: HEARTBEAT_MS }).getReader();
|
|
427
|
-
const cleanup = () => {
|
|
428
|
-
if (closed) return;
|
|
429
|
-
closed = true;
|
|
430
|
-
one.subs.delete(sub);
|
|
431
|
-
signal?.removeEventListener('abort', cleanup);
|
|
432
|
-
sub.wake?.();
|
|
433
|
-
reader.cancel().catch(() => {});
|
|
434
|
-
outer?.close();
|
|
435
|
-
};
|
|
436
|
-
const body = new ReadableStream({
|
|
437
|
-
start(controller) { outer = controller; },
|
|
438
|
-
async pull(controller) {
|
|
439
|
-
const { done, value } = await reader.read();
|
|
440
|
-
if (done) cleanup(); else if (!closed) controller.enqueue(value);
|
|
441
|
-
},
|
|
442
|
-
// 调用方取消了应答体:这一层已经关了,cleanup 不再去关它。
|
|
443
|
-
cancel() { outer = null; cleanup(); },
|
|
444
|
-
});
|
|
445
|
-
sub.close = cleanup;
|
|
446
|
-
one.subs.add(sub);
|
|
447
|
-
signal?.addEventListener('abort', cleanup);
|
|
448
|
-
if (signal?.aborted) cleanup();
|
|
449
|
-
return new Response(body,
|
|
450
|
-
{ status: 200, headers: { 'content-type': 'application/x-ndjson', 'cache-control': 'no-store' } });
|
|
451
|
-
}
|
|
452
|
-
|
|
453
|
-
const protocolHandlers = { friends, records, publish, 'set-card': setCard, 'send-dm': sendDm, 'post-feed': postFeed, retract, outbox };
|
|
311
|
+
const protocolHandlers = { friends, records, publish, retract, outbox };
|
|
454
312
|
for (const [name, fn] of Object.entries(protocolHandlers)) handles.push(coda.handle(SOCIAL, name, input => fn(input ?? {})));
|
|
455
313
|
|
|
456
314
|
// 证书变成可用就冲洗待发队列;任何变化都刷新网关记录。
|
|
457
315
|
const onChange = ({ type, entry } = {}) => {
|
|
458
316
|
const ready = type !== 'DELETED' && certStateOf(entry) === 'active';
|
|
459
317
|
serial(async () => { if (ready) await flushNow(); await refreshNow(); }).catch(() => {});
|
|
460
|
-
pullWatched();
|
|
461
318
|
};
|
|
462
319
|
|
|
463
320
|
return {
|
|
@@ -473,13 +330,8 @@ export function createGateway(coda, dir) {
|
|
|
473
330
|
});
|
|
474
331
|
},
|
|
475
332
|
},
|
|
476
|
-
// 实时流此刻的订阅者数,`{ dm, feed }`。
|
|
477
|
-
subscriberCount: () => ({ dm: hubs.dm.subs.size, feed: hubs.feed.subs.size }),
|
|
478
333
|
async start() {
|
|
479
|
-
|
|
480
|
-
const handle = await coda.stream(SOCIAL, name, (request, ctx) => serveStream(name, ctx));
|
|
481
|
-
if (stopped) handle?.dispose?.(); else handles.push(handle);
|
|
482
|
-
}
|
|
334
|
+
if (dir) await serial(purgeReserved).catch(() => {});
|
|
483
335
|
try { watching = await coda.watch(ACCORD.kind, onChange, { id: ACCORD.id }); } catch { /* 没有 Accord:网关记录照样写 */ }
|
|
484
336
|
await serial(refreshNow).catch(() => {});
|
|
485
337
|
},
|
|
@@ -488,7 +340,6 @@ export function createGateway(coda, dir) {
|
|
|
488
340
|
for (const handle of handles.splice(0)) handle?.dispose?.();
|
|
489
341
|
watching?.dispose?.();
|
|
490
342
|
watching = null;
|
|
491
|
-
for (const one of Object.values(hubs)) for (const sub of [...one.subs]) sub.close();
|
|
492
343
|
},
|
|
493
344
|
};
|
|
494
345
|
}
|