@coda-console/friends 0.1.0 → 0.3.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 +44 -2
- package/lib/friends.mjs +111 -21
- package/lib/gateway.mjs +494 -0
- package/lib/json-file.mjs +25 -0
- package/lib/outbox.mjs +145 -0
- package/lib/policy.mjs +22 -0
- package/lib/social-streams.mjs +218 -0
- package/main.mjs +14 -5
- package/package.json +339 -2
- package/view/app.mjs +36 -19
package/lib/gateway.mjs
ADDED
|
@@ -0,0 +1,494 @@
|
|
|
1
|
+
// 抽象社交网关:实现 friends/social@1。业务无关——只认 kind、id、body;签名写入与记录查询全部透传 coda/accord@1,
|
|
2
|
+
// 自己不建第二份目录库,只在 outbox.json 里留还没发出去的 body(同步成功即释放)。所有会写盘、会外发的动作排成一条队,
|
|
3
|
+
// 发布、撤回、证书变化引起的冲洗互不交叉。
|
|
4
|
+
import { CARD_KIND, PROFILE_ID, PROFILE_KIND, mergeFriendRows, normalizeCardInput, statusOf } from './friends.mjs';
|
|
5
|
+
import { readNotes } from './notes.mjs';
|
|
6
|
+
import { canSkip, canonicalHash, certStateOf, checkId, checkKind, checkPublish, entryKey, holdState, keyOf, retractKey, invalid, isPending, markRejected, markSynced,
|
|
7
|
+
nextSeq, queuePublish, queueRetract, readOutbox, withState, writeOutbox } from './outbox.mjs';
|
|
8
|
+
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
|
+
|
|
11
|
+
const ACCORD = { kind: 'coda/accord@1', id: 'local' };
|
|
12
|
+
const SOCIAL = 'friends/social@1';
|
|
13
|
+
const MAX_PAGES = 50;
|
|
14
|
+
const HEARTBEAT_MS = 30_000;
|
|
15
|
+
const REJECTED = new Set(['invalid_input', 'forbidden']);
|
|
16
|
+
const message = e => String(e?.message ?? e);
|
|
17
|
+
const interrupted = effects => Object.assign(new Error('好友网关已停止'), { code: 'interrupted', effects });
|
|
18
|
+
|
|
19
|
+
export function createGateway(coda, dir) {
|
|
20
|
+
let stopped = false, watching = null, chain = Promise.resolve();
|
|
21
|
+
const handles = [];
|
|
22
|
+
const stateDir = () => {
|
|
23
|
+
if (!dir) throw new Error('这台机器没有插件状态目录,网关的待发队列存不下');
|
|
24
|
+
return dir;
|
|
25
|
+
};
|
|
26
|
+
// 停了以后不再发起新的签名写入、策略写入:每个副作用之前、每次 await 回来都过一下它。
|
|
27
|
+
const live = (effects = 'none') => { if (stopped) throw interrupted(effects); };
|
|
28
|
+
// 所有写盘与外发排成一条队;停了以后排着的活不再做。
|
|
29
|
+
const serial = work => {
|
|
30
|
+
const run = chain.then(() => { live(); return work(); });
|
|
31
|
+
chain = run.then(() => {}, () => {});
|
|
32
|
+
return run;
|
|
33
|
+
};
|
|
34
|
+
// `save` 落待处理的意图,在签名之前;停了就不写。`persist` 落已经确认的结果(签名已成功,磁盘不能比远端旧),停了也要写。
|
|
35
|
+
const save = async outbox => { live(); await writeOutbox(stateDir(), outbox); };
|
|
36
|
+
const persist = outbox => writeOutbox(stateDir(), outbox);
|
|
37
|
+
|
|
38
|
+
async function accordState() {
|
|
39
|
+
const accord = await coda.get(ACCORD);
|
|
40
|
+
return { accord, author: accord?.spec?.author ?? null, certState: certStateOf(accord) };
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
// 翻页读 coda/accord@1 的记录,至多 `maxPages` 页;cursor 重复就停,不会原地打转。
|
|
44
|
+
async function pages(input, maxPages = MAX_PAGES) {
|
|
45
|
+
const records = [], seen = new Set();
|
|
46
|
+
let cursor;
|
|
47
|
+
for (let page = 0; page < maxPages; page++) {
|
|
48
|
+
const read = await coda.query(ACCORD, 'records', { ...input, limit: 200, ...(cursor ? { cursor } : {}) });
|
|
49
|
+
records.push(...(read?.records ?? []));
|
|
50
|
+
cursor = read?.nextCursor;
|
|
51
|
+
if (!read?.truncated) return { records, truncated: false };
|
|
52
|
+
if (!cursor || seen.has(cursor)) break;
|
|
53
|
+
seen.add(cursor);
|
|
54
|
+
}
|
|
55
|
+
return { records, truncated: true };
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
// 本机在 Accord 里有没有这条记录。
|
|
59
|
+
async function holds(kind, author, id) {
|
|
60
|
+
const read = await coda.query(ACCORD, 'records', { kind, author, id, limit: 1 });
|
|
61
|
+
return (read?.records ?? []).some(record => record?.local === true && record.id === id);
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
// 把一条待发或待撤的条目交给 coda/accord@1 发出去(撤回是 body 为空、audience 为空的发布)。
|
|
65
|
+
async function attempt(entry, author) {
|
|
66
|
+
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
|
+
const input = entry.desired === 'publish' ? { kind: entry.kind, id: entry.id, body: entry.body, audience: entry.audience }
|
|
73
|
+
: { kind: entry.kind, id: entry.id, body: {}, audience: [] };
|
|
74
|
+
try {
|
|
75
|
+
const result = await coda.call(ACCORD, 'publish', input);
|
|
76
|
+
return entry.desired === 'publish' ? { state: 'synced', entry: markSynced(entry, result?.author ?? author, Date.now()), result } : { state: 'retracted', entry: null };
|
|
77
|
+
} catch (e) {
|
|
78
|
+
if (e?.code === 'invalid_state') return { state: 'needs_cert', entry: withState(entry, 'needs_cert', message(e)), error: message(e) };
|
|
79
|
+
if (REJECTED.has(e?.code)) return { state: 'error', entry: markRejected(entry, message(e)), error: message(e) };
|
|
80
|
+
return { state: 'queued', entry: withState(entry, 'queued', message(e)), error: message(e) };
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
// 冲洗:能发的待发、待撤条目发出去;证书不对或 kind 暂停的只更新状态。
|
|
85
|
+
async function flushNow() {
|
|
86
|
+
const d = stateDir(), outbox = await readOutbox(d);
|
|
87
|
+
if (!Object.values(outbox).some(isPending)) return;
|
|
88
|
+
const [{ author, certState }, { pausedKinds }] = await Promise.all([accordState(), readPolicy(d)]);
|
|
89
|
+
let changed = false;
|
|
90
|
+
for (const entry of Object.values(outbox).sort((a, b) => (a.seq ?? 0) - (b.seq ?? 0))) {
|
|
91
|
+
live();
|
|
92
|
+
if (!isPending(entry)) continue;
|
|
93
|
+
const key = keyOf(entry), hold = holdState(entry, certState, pausedKinds);
|
|
94
|
+
if (hold) {
|
|
95
|
+
if (entry.state !== hold) { outbox[key] = withState(entry, hold, entry.lastError); changed = true; }
|
|
96
|
+
continue;
|
|
97
|
+
}
|
|
98
|
+
// 待撤的条目只替排队时的作者撤:作者换了,同一个 id 可能是另一个人的记录。
|
|
99
|
+
// 没同步过的待撤条目,先确认本机在 Accord 里真有这条记录再签名;没有就清掉,不为从未发布的 id 生成墓碑。
|
|
100
|
+
if (entry.desired === 'retract') {
|
|
101
|
+
if (entry.targetAuthor !== author) continue;
|
|
102
|
+
// 同一条记录之后有更晚的发布,这条旧撤回已被取代:那条发布这位作者已经同步了,旧撤回直接删;还待发的,旧撤回先留着不执行,
|
|
103
|
+
// 等它发布成功时和 synced 一起落盘删除(被拒或中途停用,旧撤回就还在盘上)。
|
|
104
|
+
const later = outbox[entryKey(entry.kind, entry.id)];
|
|
105
|
+
if (later?.desired === 'publish' && (later.seq ?? 0) > (entry.seq ?? 0)) {
|
|
106
|
+
if (later.state === 'synced' && later.lastAuthor === author) {
|
|
107
|
+
live();
|
|
108
|
+
delete outbox[key];
|
|
109
|
+
await save(outbox);
|
|
110
|
+
changed = false;
|
|
111
|
+
continue;
|
|
112
|
+
}
|
|
113
|
+
if (isPending(later)) continue;
|
|
114
|
+
}
|
|
115
|
+
if (entry.lastSyncedHash === undefined) {
|
|
116
|
+
let held;
|
|
117
|
+
try { held = await holds(entry.kind, author, entry.id); } catch (e) {
|
|
118
|
+
// 一条查不出来是临时故障,不拦着后面不相干的条目:它留作 queued 并记下错误,下一次冲洗再试。
|
|
119
|
+
if (stopped) return;
|
|
120
|
+
outbox[key] = withState(entry, 'queued', message(e));
|
|
121
|
+
await persist(outbox);
|
|
122
|
+
changed = false;
|
|
123
|
+
continue;
|
|
124
|
+
}
|
|
125
|
+
if (stopped) return;
|
|
126
|
+
if (!held) {
|
|
127
|
+
delete outbox[key];
|
|
128
|
+
await persist(outbox);
|
|
129
|
+
changed = false;
|
|
130
|
+
continue;
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
const done = await attempt(entry, author);
|
|
135
|
+
if (done.entry) outbox[key] = done.entry; else delete outbox[key];
|
|
136
|
+
if (done.state === 'synced') {
|
|
137
|
+
const old = outbox[retractKey(done.entry.lastAuthor, entry.kind, entry.id)];
|
|
138
|
+
if (old && (old.seq ?? 0) < (entry.seq ?? 0)) delete outbox[keyOf(old)];
|
|
139
|
+
}
|
|
140
|
+
await persist(outbox);
|
|
141
|
+
changed = false;
|
|
142
|
+
if (done.state === 'needs_cert') break;
|
|
143
|
+
}
|
|
144
|
+
if (changed) await persist(outbox);
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
// 本机网关记录:别的插件读它就知道网关在不在、证书和待发队列的情况。读不到 Accord 就不更新。
|
|
148
|
+
async function refreshNow() {
|
|
149
|
+
if (stopped) return;
|
|
150
|
+
try {
|
|
151
|
+
const { accord, author, certState } = await accordState();
|
|
152
|
+
const outbox = dir ? await readOutbox(dir) : {}, { pausedKinds } = dir ? await readPolicy(dir) : { pausedKinds: [] };
|
|
153
|
+
const until = accord?.status?.certificate?.until;
|
|
154
|
+
const friends = Array.isArray(accord?.status?.friends) ? accord.status.friends : [];
|
|
155
|
+
const status = { author, certState, ...(Number.isSafeInteger(until) && until >= 0 ? { certUntil: until } : {}),
|
|
156
|
+
friendCount: friends.filter(friend => statusOf(friend) === 'bound').length, pendingCount: Object.values(outbox).filter(isPending).length, pausedKinds };
|
|
157
|
+
if (!stopped) await coda.put({ kind: SOCIAL, key: 'local' }, { spec: { version: 1 }, status });
|
|
158
|
+
} catch { /* 状态记录下一次动作会再写 */ }
|
|
159
|
+
}
|
|
160
|
+
const mutate = work => serial(async () => { try { return await work(); } finally { await refreshNow(); pullWatched(); } });
|
|
161
|
+
|
|
162
|
+
// ---- friends/social@1 的操作 ----
|
|
163
|
+
|
|
164
|
+
async function friends({ includePending = false } = {}) {
|
|
165
|
+
const { accord, author, certState } = await accordState();
|
|
166
|
+
const list = Array.isArray(accord?.status?.friends) ? accord.status.friends : [];
|
|
167
|
+
const none = { records: [], truncated: false };
|
|
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 };
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
function records({ kind, author, id, limit, cursor, includeAudience }) {
|
|
175
|
+
if (kind === 'binding') throw invalid('kind「binding」是保留类型,网关不读它');
|
|
176
|
+
if (id !== undefined) checkId(id, { query: true });
|
|
177
|
+
return coda.query(ACCORD, 'records', { kind, ...(author === undefined ? {} : { author }), ...(id === undefined ? {} : { id }),
|
|
178
|
+
...(limit === undefined ? {} : { limit }), ...(cursor === undefined ? {} : { cursor }), ...(includeAudience === undefined ? {} : { includeAudience }) });
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
function publish(input) {
|
|
182
|
+
const item = checkPublish(input);
|
|
183
|
+
return mutate(() => publishItem(item));
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
// publish 的本体,须已在队里(mutate)。
|
|
187
|
+
async function publishItem(item) {
|
|
188
|
+
const d = stateDir(), key = entryKey(item.kind, item.id), outbox = await readOutbox(d), prev = outbox[key];
|
|
189
|
+
let current;
|
|
190
|
+
try { current = await accordState(); } catch (e) {
|
|
191
|
+
outbox[key] = withState(queuePublish(prev, item, nextSeq(outbox)), 'queued', message(e));
|
|
192
|
+
await save(outbox);
|
|
193
|
+
return { state: 'queued', error: message(e) };
|
|
194
|
+
}
|
|
195
|
+
live();
|
|
196
|
+
const { author, certState } = current;
|
|
197
|
+
// 新发布盖过这个作者排着的待撤,免得旧的待撤之后又把新内容撤了。
|
|
198
|
+
const queuedRetract = author ? retractKey(author, item.kind, item.id) : null, prevRetract = outbox[queuedRetract];
|
|
199
|
+
if (canSkip(prev, canonicalHash({ body: item.body, audience: item.audience }), author)) return { state: 'synced', skipped: true, author };
|
|
200
|
+
const entry = queuePublish(prev, item, nextSeq(outbox)), hold = holdState(entry, certState, (await readPolicy(d)).pausedKinds);
|
|
201
|
+
live();
|
|
202
|
+
if (hold) {
|
|
203
|
+
outbox[key] = withState(entry, hold);
|
|
204
|
+
delete outbox[queuedRetract];
|
|
205
|
+
await save(outbox);
|
|
206
|
+
return { state: hold, author };
|
|
207
|
+
}
|
|
208
|
+
// 先把新内容的意图落盘(旧的已同步标记随之作废),再签名;签名后落盘失败,磁盘上也不会还当旧内容已同步。
|
|
209
|
+
outbox[key] = entry;
|
|
210
|
+
delete outbox[queuedRetract];
|
|
211
|
+
await save(outbox);
|
|
212
|
+
const done = await attempt(entry, author);
|
|
213
|
+
if (done.state === 'error') {
|
|
214
|
+
if (prev) outbox[key] = prev; else delete outbox[key];
|
|
215
|
+
if (prevRetract) outbox[queuedRetract] = prevRetract;
|
|
216
|
+
await persist(outbox);
|
|
217
|
+
return { state: 'error', author, error: done.error };
|
|
218
|
+
}
|
|
219
|
+
outbox[key] = done.entry;
|
|
220
|
+
await persist(outbox);
|
|
221
|
+
if (done.state === 'synced') return { state: 'synced', author: done.entry.lastAuthor, ...(Number.isSafeInteger(done.result?.version) ? { version: done.result.version } : {}) };
|
|
222
|
+
return { state: done.state, author, error: done.error };
|
|
223
|
+
}
|
|
224
|
+
|
|
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
|
+
function retract({ kind, id } = {}) {
|
|
269
|
+
checkKind(kind);
|
|
270
|
+
if (id !== undefined) checkId(id);
|
|
271
|
+
return mutate(async () => {
|
|
272
|
+
const d = stateDir(), outbox = await readOutbox(d);
|
|
273
|
+
// 网关替这个作者同步过这条记录的痕迹:发布条目是这个作者同步的,或这个作者先前排过的待撤。
|
|
274
|
+
const history = (entries, author, one) => {
|
|
275
|
+
const published = entries[entryKey(kind, one)];
|
|
276
|
+
return (published?.lastAuthor === author ? published : entries[retractKey(author, kind, one)])?.lastSyncedHash;
|
|
277
|
+
};
|
|
278
|
+
// `remote`:Accord 里本机已有的记录 id;`confirmed`:这份清单是读全了的(读全了又不在里面,才算远端没有)。
|
|
279
|
+
let current, remote = new Set(), confirmed = false, truncated = false;
|
|
280
|
+
try {
|
|
281
|
+
current = await accordState();
|
|
282
|
+
if (current.certState !== 'no_identity') {
|
|
283
|
+
if (id === undefined) {
|
|
284
|
+
const own = await pages({ kind, author: current.author });
|
|
285
|
+
truncated = own.truncated;
|
|
286
|
+
confirmed = !truncated;
|
|
287
|
+
remote = new Set(own.records.filter(record => record?.local === true && typeof record.id === 'string').map(record => record.id));
|
|
288
|
+
} else if (current.certState === 'active' && !history(outbox, current.author, id)) {
|
|
289
|
+
confirmed = true;
|
|
290
|
+
if (await holds(kind, current.author, id)) remote = new Set([id]);
|
|
291
|
+
}
|
|
292
|
+
}
|
|
293
|
+
} catch (e) {
|
|
294
|
+
live();
|
|
295
|
+
return { state: 'error', count: 0, error: message(e) };
|
|
296
|
+
}
|
|
297
|
+
live();
|
|
298
|
+
const { author } = current;
|
|
299
|
+
let { certState } = current, count = 0, queued = 0, rejected, failed;
|
|
300
|
+
// 没有身份:没有可撤的作者,只清本机还没发出去的待发;不排无主的待撤条目,免得将来换了身份被误撤。
|
|
301
|
+
if (certState === 'no_identity') {
|
|
302
|
+
const local = Object.entries(outbox).filter(([, entry]) => entry.kind === kind && (id === undefined || entry.id === id) && entry.desired === 'publish' && isPending(entry));
|
|
303
|
+
for (const [key] of local) delete outbox[key];
|
|
304
|
+
if (local.length) await save(outbox);
|
|
305
|
+
return { state: 'no_identity', count: 0 };
|
|
306
|
+
}
|
|
307
|
+
// 别的作者排下的待撤条目不是这次的:不纳入、不删、不计数。
|
|
308
|
+
const ids = id === undefined
|
|
309
|
+
? new Set([...Object.values(outbox).filter(entry => entry.kind === kind && (entry.desired === 'publish' || entry.targetAuthor === author)).map(entry => entry.id), ...remote])
|
|
310
|
+
: new Set([id]);
|
|
311
|
+
const sends = [];
|
|
312
|
+
// 先把待撤的意图一次落盘,再逐条签名;每条撤完立刻落盘确认,中途停下也不会把已撤的当成还同步着。
|
|
313
|
+
for (const one of ids) {
|
|
314
|
+
const pubKey = entryKey(kind, one), key = retractKey(author, kind, one), published = outbox[pubKey], prevRetract = outbox[key];
|
|
315
|
+
// 排下的待撤盖过这个作者没发出去的待发、或自己同步过的发布条目;别的作者同步的发布条目不动。
|
|
316
|
+
const superseded = published && (isPending(published) || published.lastAuthor === author);
|
|
317
|
+
// 网关没同步过它、远端也确认没有:只剩本机的待发条目,删掉就是撤回。
|
|
318
|
+
if (history(outbox, author, one) === undefined && confirmed && !remote.has(one)) {
|
|
319
|
+
if (superseded || prevRetract) { if (superseded) delete outbox[pubKey]; delete outbox[key]; count++; }
|
|
320
|
+
continue;
|
|
321
|
+
}
|
|
322
|
+
const entry = queueRetract(published?.lastAuthor === author ? published : prevRetract, kind, one, author, nextSeq(outbox));
|
|
323
|
+
if (superseded) delete outbox[pubKey];
|
|
324
|
+
if (certState === 'active') { outbox[key] = entry; sends.push([one, superseded ? published : undefined, prevRetract]); } else { outbox[key] = withState(entry, certState); queued++; }
|
|
325
|
+
}
|
|
326
|
+
await save(outbox);
|
|
327
|
+
// 意图已落盘,从这里起停用就不是什么都没做:effects 说 some。
|
|
328
|
+
for (const [one, published, prevRetract] of sends) {
|
|
329
|
+
live('some');
|
|
330
|
+
const key = retractKey(author, kind, one), entry = outbox[key];
|
|
331
|
+
if (certState !== 'active') { outbox[key] = withState(entry, certState); queued++; await persist(outbox); continue; }
|
|
332
|
+
const done = await attempt(entry, author);
|
|
333
|
+
if (done.state === 'retracted') { delete outbox[key]; count++; }
|
|
334
|
+
else if (done.state === 'error') {
|
|
335
|
+
rejected ??= done.error;
|
|
336
|
+
if (prevRetract) outbox[key] = prevRetract; else delete outbox[key];
|
|
337
|
+
if (published) outbox[entryKey(kind, one)] = published;
|
|
338
|
+
}
|
|
339
|
+
else {
|
|
340
|
+
outbox[key] = done.entry;
|
|
341
|
+
queued++;
|
|
342
|
+
if (done.state === 'needs_cert') certState = 'needs_cert'; else failed ??= done.error;
|
|
343
|
+
}
|
|
344
|
+
await persist(outbox);
|
|
345
|
+
}
|
|
346
|
+
const state = rejected ? 'error' : queued ? (certState === 'active' ? 'queued' : certState) : 'retracted', error = rejected ?? failed;
|
|
347
|
+
return { state, count, ...(queued ? { queued } : {}), ...(truncated ? { truncated } : {}), ...(error ? { error } : {}) };
|
|
348
|
+
});
|
|
349
|
+
}
|
|
350
|
+
|
|
351
|
+
async function outbox({ kind } = {}) {
|
|
352
|
+
const d = stateDir(), [{ author, certState }, { pausedKinds }, entries] = await Promise.all([accordState(), readPolicy(d), readOutbox(d)]);
|
|
353
|
+
const items = Object.values(entries).filter(entry => kind === undefined || entry.kind === kind).map(entry =>
|
|
354
|
+
({ kind: entry.kind, id: entry.id, desired: entry.desired, state: entry.state,
|
|
355
|
+
...(entry.lastSyncedAt === undefined ? {} : { lastSyncedAt: entry.lastSyncedAt }), ...(entry.lastError === undefined ? {} : { lastError: entry.lastError }) }));
|
|
356
|
+
return { author, certState, pausedKinds, pendingCount: Object.values(entries).filter(isPending).length, items };
|
|
357
|
+
}
|
|
358
|
+
|
|
359
|
+
// ---- 实时流 dm、feed ----
|
|
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 };
|
|
454
|
+
for (const [name, fn] of Object.entries(protocolHandlers)) handles.push(coda.handle(SOCIAL, name, input => fn(input ?? {})));
|
|
455
|
+
|
|
456
|
+
// 证书变成可用就冲洗待发队列;任何变化都刷新网关记录。
|
|
457
|
+
const onChange = ({ type, entry } = {}) => {
|
|
458
|
+
const ready = type !== 'DELETED' && certStateOf(entry) === 'active';
|
|
459
|
+
serial(async () => { if (ready) await flushNow(); await refreshNow(); }).catch(() => {});
|
|
460
|
+
pullWatched();
|
|
461
|
+
};
|
|
462
|
+
|
|
463
|
+
return {
|
|
464
|
+
// `coda self policy.get|policy.setKind` 的处理函数。
|
|
465
|
+
policy: {
|
|
466
|
+
'policy.get': () => readPolicy(stateDir()),
|
|
467
|
+
'policy.setKind': ({ kind, paused } = {}) => {
|
|
468
|
+
if (typeof paused !== 'boolean') throw invalid('paused 须是 true 或 false');
|
|
469
|
+
return mutate(async () => {
|
|
470
|
+
const policy = await setKindPaused(stateDir(), kind, paused, live);
|
|
471
|
+
await flushNow();
|
|
472
|
+
return policy;
|
|
473
|
+
});
|
|
474
|
+
},
|
|
475
|
+
},
|
|
476
|
+
// 实时流此刻的订阅者数,`{ dm, feed }`。
|
|
477
|
+
subscriberCount: () => ({ dm: hubs.dm.subs.size, feed: hubs.feed.subs.size }),
|
|
478
|
+
async start() {
|
|
479
|
+
for (const name of Object.keys(hubs)) {
|
|
480
|
+
const handle = await coda.stream(SOCIAL, name, (request, ctx) => serveStream(name, ctx));
|
|
481
|
+
if (stopped) handle?.dispose?.(); else handles.push(handle);
|
|
482
|
+
}
|
|
483
|
+
try { watching = await coda.watch(ACCORD.kind, onChange, { id: ACCORD.id }); } catch { /* 没有 Accord:网关记录照样写 */ }
|
|
484
|
+
await serial(refreshNow).catch(() => {});
|
|
485
|
+
},
|
|
486
|
+
stop() {
|
|
487
|
+
stopped = true;
|
|
488
|
+
for (const handle of handles.splice(0)) handle?.dispose?.();
|
|
489
|
+
watching?.dispose?.();
|
|
490
|
+
watching = null;
|
|
491
|
+
for (const one of Object.values(hubs)) for (const sub of [...one.subs]) sub.close();
|
|
492
|
+
},
|
|
493
|
+
};
|
|
494
|
+
}
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
// 插件状态目录里的 JSON 文件:不存在或不是合法 JSON 读成 null;其他读取错误(EACCES、EISDIR、EIO……)原样抛出,
|
|
2
|
+
// 免得读不出来的文件被当成空表绕过策略、覆盖队列。写入原子(临时文件 + rename)。调用方自己保证同一文件的读改写不交叉。
|
|
3
|
+
import { mkdir, readFile, rename, rm, writeFile } from 'node:fs/promises';
|
|
4
|
+
import { join } from 'node:path';
|
|
5
|
+
|
|
6
|
+
export async function readJson(dir, name) {
|
|
7
|
+
let text;
|
|
8
|
+
try { text = await readFile(join(dir, name), 'utf8'); } catch (e) {
|
|
9
|
+
if (e?.code === 'ENOENT') return null;
|
|
10
|
+
throw e;
|
|
11
|
+
}
|
|
12
|
+
try { return JSON.parse(text); } catch { return null; }
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
let counter = 0;
|
|
16
|
+
// `beforeWrite` 在动第一个字节之前调用(它抛错就不写),前面只隔着建目录这一步。
|
|
17
|
+
export async function writeJson(dir, name, value, beforeWrite) {
|
|
18
|
+
await mkdir(dir, { recursive: true });
|
|
19
|
+
beforeWrite?.();
|
|
20
|
+
const target = join(dir, name), temporary = join(dir, `${name}.${process.pid}.${++counter}.tmp`);
|
|
21
|
+
try {
|
|
22
|
+
await writeFile(temporary, `${JSON.stringify(value, null, 2)}\n`, { mode: 0o600 });
|
|
23
|
+
await rename(temporary, target);
|
|
24
|
+
} catch (e) { await rm(temporary, { force: true }).catch(() => {}); throw e; }
|
|
25
|
+
}
|