cortico-world-bottle 0.2.0 → 0.2.2
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/CHANGELOG.md +37 -226
- package/README.md +32 -268
- package/describe.json +12 -0
- package/package.json +1 -4
- package/seeds/README.md +12 -28
- package/world/host-open.ts +58 -0
- package/world/tools.ts +11 -1
- package/world/world.ts +22 -0
- package/deploy/README.md +0 -200
- package/deploy/bottle-backup.service +0 -31
- package/deploy/bottle-backup.sh +0 -39
- package/deploy/bottle-backup.timer +0 -13
- package/deploy/bottle-seeds-pull.service +0 -18
- package/deploy/bottle-seeds-pull.timer +0 -12
- package/deploy/bottle-server.service +0 -55
- package/deploy/bottle-stats-view.sh +0 -88
- package/deploy/bottle-stats.service +0 -39
- package/deploy/bottle-stats.timer +0 -11
- package/server/app.ts +0 -764
- package/server/blind.ts +0 -150
- package/server/db.ts +0 -362
- package/server/main.ts +0 -343
- package/server/public/index.html +0 -115
- package/server/quota.ts +0 -86
- package/server/seeds.ts +0 -231
- package/server/snapshot.ts +0 -66
- package/server/stats.ts +0 -273
- package/server/tuning.ts +0 -146
package/server/seeds.ts
DELETED
|
@@ -1,231 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* 种子瓶(§13):海边邮局预先放进海里的信,真人信不够时补位。
|
|
3
|
-
*
|
|
4
|
-
* **内容与状态分离**:正文只从 `seeds/*.json` 读,谁见过谁只记在 `seeds_used` 表里。
|
|
5
|
-
* 所以服务端重启(正文海啸)之后,正文从文件原样回来,去重一条也不会丢。
|
|
6
|
-
*
|
|
7
|
-
* **热载不重启**:目录变化时重新读一遍,逐文件校验;解析失败的文件保留上一版,
|
|
8
|
-
* 坏的条目跳过并记日志。整个过程不抛异常——种子是兜底,绝不能把海搞挂。
|
|
9
|
-
*/
|
|
10
|
-
import { existsSync, mkdirSync, readFileSync, readdirSync, watch, type FSWatcher } from 'node:fs';
|
|
11
|
-
import { join } from 'node:path';
|
|
12
|
-
import { SEED_FROM } from '../shared/text.ts';
|
|
13
|
-
|
|
14
|
-
/** 种子信是作者手写的,可以比 Coo 的 120 字长,但也不能是一篇文章。 */
|
|
15
|
-
export const SEED_BODY_MAX = 400;
|
|
16
|
-
/**
|
|
17
|
-
* 固定的来源名。种子绝不伪装成某个人类。
|
|
18
|
-
* 定义在 `shared/text.ts`,因为页面与卡片也要认它;这里转出去,免得两处各写一份。
|
|
19
|
-
*/
|
|
20
|
-
export { SEED_FROM };
|
|
21
|
-
|
|
22
|
-
export interface SeedLetter {
|
|
23
|
-
id: string;
|
|
24
|
-
body: string;
|
|
25
|
-
/** 落款,可选。显示时附在正文后面,不替代「海边邮局」这个来源。 */
|
|
26
|
-
signature?: string;
|
|
27
|
-
/** 主题,可选。只当一行小标签用。 */
|
|
28
|
-
topic?: string;
|
|
29
|
-
/** 来自哪个文件;热载时按文件保留旧版。 */
|
|
30
|
-
file: string;
|
|
31
|
-
}
|
|
32
|
-
|
|
33
|
-
export interface SeedStats {
|
|
34
|
-
dir: string;
|
|
35
|
-
count: number;
|
|
36
|
-
/** 内容真的变了才 +1;验收时看它有没有热载成功。 */
|
|
37
|
-
generation: number;
|
|
38
|
-
/** 上一次内容变化的毫秒时间戳。 */
|
|
39
|
-
loadedAt: number;
|
|
40
|
-
errors: string[];
|
|
41
|
-
}
|
|
42
|
-
|
|
43
|
-
export interface SeedStoreOptions {
|
|
44
|
-
/** null = 完全不用种子。 */
|
|
45
|
-
dir: string | null;
|
|
46
|
-
maxChars?: number;
|
|
47
|
-
log?: (line: string) => void;
|
|
48
|
-
/** fs.watch 漏事件时的兜底扫描间隔;默认 30 秒,远小于验收要求的 5 分钟。 */
|
|
49
|
-
pollMs?: number;
|
|
50
|
-
}
|
|
51
|
-
|
|
52
|
-
export class SeedStore {
|
|
53
|
-
private byFile = new Map<string, SeedLetter[]>();
|
|
54
|
-
private seeds: SeedLetter[] = [];
|
|
55
|
-
private errors: string[] = [];
|
|
56
|
-
private generation = 0;
|
|
57
|
-
private loadedAt = 0;
|
|
58
|
-
private fingerprint = '';
|
|
59
|
-
private watcher: FSWatcher | null = null;
|
|
60
|
-
private debounce: ReturnType<typeof setTimeout> | null = null;
|
|
61
|
-
private poll: ReturnType<typeof setInterval> | null = null;
|
|
62
|
-
|
|
63
|
-
/** 普通字段赋值,不用参数属性:`node --experimental-strip-types` 不支持(见 `db.ts` 同一处注释)。 */
|
|
64
|
-
private readonly opts: SeedStoreOptions;
|
|
65
|
-
|
|
66
|
-
constructor(opts: SeedStoreOptions) {
|
|
67
|
-
this.opts = opts;
|
|
68
|
-
}
|
|
69
|
-
|
|
70
|
-
/** 读一遍并挂上监听。失败也不会挡住服务端起来。 */
|
|
71
|
-
start(): void {
|
|
72
|
-
this.reload();
|
|
73
|
-
if (!this.opts.dir) return;
|
|
74
|
-
try {
|
|
75
|
-
mkdirSync(this.opts.dir, { recursive: true });
|
|
76
|
-
} catch {
|
|
77
|
-
// 目录建不起来也只是没有种子
|
|
78
|
-
}
|
|
79
|
-
try {
|
|
80
|
-
this.watcher = watch(this.opts.dir, { persistent: false }, () => this.schedule());
|
|
81
|
-
} catch {
|
|
82
|
-
// 有轮询兜底
|
|
83
|
-
}
|
|
84
|
-
this.poll = setInterval(() => this.reload(), this.opts.pollMs ?? 30_000);
|
|
85
|
-
this.poll.unref?.();
|
|
86
|
-
}
|
|
87
|
-
|
|
88
|
-
stop(): void {
|
|
89
|
-
this.watcher?.close();
|
|
90
|
-
this.watcher = null;
|
|
91
|
-
if (this.debounce) clearTimeout(this.debounce);
|
|
92
|
-
if (this.poll) clearInterval(this.poll);
|
|
93
|
-
this.debounce = null;
|
|
94
|
-
this.poll = null;
|
|
95
|
-
}
|
|
96
|
-
|
|
97
|
-
/** 立即重读。返回是否顺利读完(不表示内容有没有变)。 */
|
|
98
|
-
reload(): boolean {
|
|
99
|
-
const dir = this.opts.dir;
|
|
100
|
-
if (!dir) return false;
|
|
101
|
-
if (!existsSync(dir)) {
|
|
102
|
-
this.errors = [`种子目录不存在:${dir}`];
|
|
103
|
-
this.log(`seeds: 目录不存在 ${dir}`);
|
|
104
|
-
return false;
|
|
105
|
-
}
|
|
106
|
-
|
|
107
|
-
let names: string[];
|
|
108
|
-
try {
|
|
109
|
-
names = readdirSync(dir)
|
|
110
|
-
.filter((name) => name.endsWith('.json') && !name.startsWith('.'))
|
|
111
|
-
.sort();
|
|
112
|
-
} catch (error) {
|
|
113
|
-
this.errors = ['种子目录读不了,保留上一版。'];
|
|
114
|
-
this.log(`seeds: 读目录失败 ${error instanceof Error ? error.name : 'unknown'}`);
|
|
115
|
-
return false;
|
|
116
|
-
}
|
|
117
|
-
|
|
118
|
-
const maxChars = this.opts.maxChars ?? SEED_BODY_MAX;
|
|
119
|
-
const nextByFile = new Map<string, SeedLetter[]>();
|
|
120
|
-
const errors: string[] = [];
|
|
121
|
-
const seen = new Set<string>();
|
|
122
|
-
|
|
123
|
-
for (const name of names) {
|
|
124
|
-
const path = join(dir, name);
|
|
125
|
-
let raw: string;
|
|
126
|
-
try {
|
|
127
|
-
raw = readFileSync(path, 'utf8');
|
|
128
|
-
} catch {
|
|
129
|
-
errors.push(`${name}:读不了,保留上一版`);
|
|
130
|
-
const old = this.byFile.get(name);
|
|
131
|
-
if (old) nextByFile.set(name, old);
|
|
132
|
-
continue;
|
|
133
|
-
}
|
|
134
|
-
|
|
135
|
-
let parsed: unknown;
|
|
136
|
-
try {
|
|
137
|
-
parsed = JSON.parse(raw);
|
|
138
|
-
} catch {
|
|
139
|
-
// git pull 拉到一半、手滑写坏 JSON,都不该让海里的种子凭空消失
|
|
140
|
-
errors.push(`${name}:JSON 解析失败,保留上一版`);
|
|
141
|
-
const old = this.byFile.get(name);
|
|
142
|
-
if (old) nextByFile.set(name, old);
|
|
143
|
-
continue;
|
|
144
|
-
}
|
|
145
|
-
|
|
146
|
-
const items = Array.isArray(parsed) ? parsed : [parsed];
|
|
147
|
-
const list: SeedLetter[] = [];
|
|
148
|
-
items.forEach((item, index) => {
|
|
149
|
-
const seed = normalizeSeed(item, name, maxChars);
|
|
150
|
-
if (!seed) {
|
|
151
|
-
errors.push(`${name}:第 ${index + 1} 条不合格,跳过`);
|
|
152
|
-
return;
|
|
153
|
-
}
|
|
154
|
-
if (seen.has(seed.id)) {
|
|
155
|
-
errors.push(`${name}:id「${seed.id}」和前面的重复,跳过`);
|
|
156
|
-
return;
|
|
157
|
-
}
|
|
158
|
-
seen.add(seed.id);
|
|
159
|
-
list.push(seed);
|
|
160
|
-
});
|
|
161
|
-
nextByFile.set(name, list);
|
|
162
|
-
}
|
|
163
|
-
|
|
164
|
-
this.byFile = nextByFile;
|
|
165
|
-
this.seeds = [...nextByFile.values()].flat();
|
|
166
|
-
this.errors = errors;
|
|
167
|
-
|
|
168
|
-
const fingerprint = JSON.stringify(this.seeds.map((s) => [s.id, s.body, s.signature ?? '', s.topic ?? '']));
|
|
169
|
-
if (fingerprint !== this.fingerprint) {
|
|
170
|
-
this.fingerprint = fingerprint;
|
|
171
|
-
this.generation += 1;
|
|
172
|
-
this.loadedAt = Date.now();
|
|
173
|
-
this.log(`seeds: 第 ${this.generation} 代,${this.seeds.length} 封`);
|
|
174
|
-
}
|
|
175
|
-
if (errors.length) this.log(`seeds: ${errors.join(';')}`);
|
|
176
|
-
return true;
|
|
177
|
-
}
|
|
178
|
-
|
|
179
|
-
list(): SeedLetter[] {
|
|
180
|
-
return this.seeds;
|
|
181
|
-
}
|
|
182
|
-
|
|
183
|
-
get(id: string): SeedLetter | undefined {
|
|
184
|
-
return this.seeds.find((seed) => seed.id === id);
|
|
185
|
-
}
|
|
186
|
-
|
|
187
|
-
stats(): SeedStats {
|
|
188
|
-
return {
|
|
189
|
-
dir: this.opts.dir ?? '',
|
|
190
|
-
count: this.seeds.length,
|
|
191
|
-
generation: this.generation,
|
|
192
|
-
loadedAt: this.loadedAt,
|
|
193
|
-
errors: [...this.errors],
|
|
194
|
-
};
|
|
195
|
-
}
|
|
196
|
-
|
|
197
|
-
private schedule(): void {
|
|
198
|
-
if (this.debounce) clearTimeout(this.debounce);
|
|
199
|
-
// 编辑器与 git 常常连续写好几下,合一次读就够
|
|
200
|
-
this.debounce = setTimeout(() => this.reload(), 250);
|
|
201
|
-
this.debounce.unref?.();
|
|
202
|
-
}
|
|
203
|
-
|
|
204
|
-
private log(line: string): void {
|
|
205
|
-
this.opts.log?.(line);
|
|
206
|
-
}
|
|
207
|
-
}
|
|
208
|
-
|
|
209
|
-
function normalizeSeed(value: unknown, file: string, maxChars: number): SeedLetter | null {
|
|
210
|
-
if (typeof value !== 'object' || value === null || Array.isArray(value)) return null;
|
|
211
|
-
const obj = value as Record<string, unknown>;
|
|
212
|
-
|
|
213
|
-
const id = typeof obj.id === 'string' ? obj.id.trim() : '';
|
|
214
|
-
// id 要进 /letter/{id} 的路径,限死在安全字符里;改名等于一封新种子
|
|
215
|
-
if (!/^[A-Za-z0-9_-]{1,64}$/.test(id)) return null;
|
|
216
|
-
|
|
217
|
-
const body = typeof obj.body === 'string' ? obj.body.replace(/\r\n/g, '\n').trim() : '';
|
|
218
|
-
if (!body) return null;
|
|
219
|
-
if ([...body].length > maxChars) return null;
|
|
220
|
-
|
|
221
|
-
const signature = typeof obj.signature === 'string' ? obj.signature.trim() : '';
|
|
222
|
-
const topic = typeof obj.topic === 'string' ? obj.topic.trim() : '';
|
|
223
|
-
|
|
224
|
-
return {
|
|
225
|
-
id,
|
|
226
|
-
body,
|
|
227
|
-
...(signature ? { signature: [...signature].slice(0, 40).join('') } : {}),
|
|
228
|
-
...(topic ? { topic: [...topic].slice(0, 20).join('') } : {}),
|
|
229
|
-
file,
|
|
230
|
-
};
|
|
231
|
-
}
|
package/server/snapshot.ts
DELETED
|
@@ -1,66 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* 每日快照。由 systemd timer 每天跑一次。
|
|
3
|
-
*
|
|
4
|
-
* 做两件事,**但不能做第三件**:
|
|
5
|
-
* 1. 真数追加到 `data/stats.jsonl`(只留在服务器上)
|
|
6
|
-
* 2. 盲化后的数原子写进 `server/public/stats.json`(给大屏读)
|
|
7
|
-
* 3. ❌ 绝不改动 `bottle.json`
|
|
8
|
-
*
|
|
9
|
-
* 第 3 条靠 `Db.readRaw()` 保证:它只解析、不做海啸巡查、不写盘。
|
|
10
|
-
* 用 `Db.open()` 的话,这个脚本每天夜里都会亲手制造一次海啸。
|
|
11
|
-
*/
|
|
12
|
-
import { existsSync } from 'node:fs';
|
|
13
|
-
import { dirname, resolve } from 'node:path';
|
|
14
|
-
import { readLedgerFile } from './blind.ts';
|
|
15
|
-
import { Db } from './db.ts';
|
|
16
|
-
import { SeedStore } from './seeds.ts';
|
|
17
|
-
import { appendStatsLine, applyBlinding, collectRealStats, writePublicStats } from './stats.ts';
|
|
18
|
-
import { dayIn } from './app.ts';
|
|
19
|
-
|
|
20
|
-
function main(): void {
|
|
21
|
-
const dataFile = resolve(process.env.BOTTLE_DATA ?? 'data/bottle.json');
|
|
22
|
-
const seedsDir = resolve(process.env.BOTTLE_SEEDS_DIR ?? 'seeds');
|
|
23
|
-
const ledgerPath = resolve(
|
|
24
|
-
process.env.BOTTLE_LEDGER ?? `${seedsDir}/almanac/ledger.json`,
|
|
25
|
-
);
|
|
26
|
-
const statsFile = resolve(process.env.BOTTLE_STATS_JSONL ?? `${dirname(dataFile)}/stats.jsonl`);
|
|
27
|
-
const publicFile = resolve(process.env.BOTTLE_PUBLIC_STATS ?? 'server/public/stats.json');
|
|
28
|
-
const timeZone = process.env.BOTTLE_TZ ?? 'Asia/Hong_Kong';
|
|
29
|
-
|
|
30
|
-
const at = Date.now();
|
|
31
|
-
|
|
32
|
-
// 只读:看一眼盘上的真实状态,不碰它
|
|
33
|
-
const db = Db.readRaw(existsSync(dataFile) ? dataFile : null);
|
|
34
|
-
|
|
35
|
-
// 种子只用来读计数,所以不启动 fs.watch —— 一个 CLI 不该留下监听器
|
|
36
|
-
const seeds = new SeedStore({ dir: existsSync(seedsDir) ? seedsDir : null });
|
|
37
|
-
seeds.reload();
|
|
38
|
-
const seedStats = seeds.stats();
|
|
39
|
-
|
|
40
|
-
const real = collectRealStats(db, seedStats, { timeZone, today: dayIn(timeZone, at), at });
|
|
41
|
-
const ledger = readLedgerFile(existsSync(ledgerPath) ? ledgerPath : null);
|
|
42
|
-
const pub = applyBlinding(real, ledger, at);
|
|
43
|
-
|
|
44
|
-
appendStatsLine(statsFile, real);
|
|
45
|
-
writePublicStats(publicFile, pub);
|
|
46
|
-
seeds.stop();
|
|
47
|
-
|
|
48
|
-
// 输出一行结果,方便在 journalctl 里对账
|
|
49
|
-
process.stdout.write(
|
|
50
|
-
`${JSON.stringify({
|
|
51
|
-
ok: true,
|
|
52
|
-
date: real.date,
|
|
53
|
-
bots: real.botsTotal,
|
|
54
|
-
active: real.botsActive,
|
|
55
|
-
floating: real.floating,
|
|
56
|
-
seeds: `${real.seedsClaimed}/${real.seedsTotal}`,
|
|
57
|
-
residentsPublic: pub.people.residents,
|
|
58
|
-
atSeaPublic: pub.letters.atSea,
|
|
59
|
-
ledgerFound: existsSync(ledgerPath),
|
|
60
|
-
statsFile,
|
|
61
|
-
publicFile,
|
|
62
|
-
})}\n`,
|
|
63
|
-
);
|
|
64
|
-
}
|
|
65
|
-
|
|
66
|
-
main();
|
package/server/stats.ts
DELETED
|
@@ -1,273 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* 统计:从磁盘算出运营要看的数,然后分两路输出。
|
|
3
|
-
*
|
|
4
|
-
* · `data/stats.jsonl` —— **真数**,每天一行,只留在服务器上,运维自己看
|
|
5
|
-
* · `public/stats.json` —— **盲化后**的数,给大屏看:真实值 + 世界台账里的量
|
|
6
|
-
*
|
|
7
|
-
* 两路必须分开写、分开存。公开文件里只要漏一个真数,整套盲化就白做了。
|
|
8
|
-
*
|
|
9
|
-
* 还有一条铁律:**统计只能看见,不能动手。** 所以调用方必须用 `Db.readRaw()`,
|
|
10
|
-
* 绝不能用 `Db.open()` —— 后者会把还漂着的信判定成海啸并写盘。
|
|
11
|
-
*/
|
|
12
|
-
import { mkdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs';
|
|
13
|
-
import { dirname } from 'node:path';
|
|
14
|
-
import { blindAtSea, blindEverSeen, blindResidents, bucketCount, type Ledger } from './blind.ts';
|
|
15
|
-
import type { Db } from './db.ts';
|
|
16
|
-
import type { SeedStats } from './seeds.ts';
|
|
17
|
-
import { seaStateAt, type SeaState } from '../shared/tide.ts';
|
|
18
|
-
|
|
19
|
-
const DAY = 86_400_000;
|
|
20
|
-
|
|
21
|
-
/** 只留在服务器上的真实数字。口径对齐设计稿 §14.3。 */
|
|
22
|
-
export interface RealStats {
|
|
23
|
-
/** YYYY-MM-DD(服务器时区)。 */
|
|
24
|
-
date: string;
|
|
25
|
-
at: string;
|
|
26
|
-
|
|
27
|
-
// ── 人 ──
|
|
28
|
-
botsTotal: number;
|
|
29
|
-
botsActive: number;
|
|
30
|
-
botsNew: number;
|
|
31
|
-
botsWhoWrote: number;
|
|
32
|
-
|
|
33
|
-
// ── 信 ──
|
|
34
|
-
lettersTotal: number;
|
|
35
|
-
floating: number;
|
|
36
|
-
caught: number;
|
|
37
|
-
replied: number;
|
|
38
|
-
sunk: number;
|
|
39
|
-
tsunamiLost: number;
|
|
40
|
-
/** 说不上死法的 archived(老数据没有 archivedReason)。 */
|
|
41
|
-
archivedUnknown: number;
|
|
42
|
-
thrownToday: number;
|
|
43
|
-
caughtToday: number;
|
|
44
|
-
repliesToday: number;
|
|
45
|
-
/**
|
|
46
|
-
* 今日动作:多少人 × 多少次。
|
|
47
|
-
*
|
|
48
|
-
* 全靠 bot 上那三个每日计数器(`bottlesUsed` / `catchesUsed` / `mailTaken`)算出来——
|
|
49
|
-
* 它们每天 0 点惰性清零,所以「`lastResetDate === 今天` 的 bot」身上的就是今天的数。
|
|
50
|
-
* 因此不需要任何事件日志表,也就不需要改 schema。
|
|
51
|
-
*/
|
|
52
|
-
throwUsersToday: number;
|
|
53
|
-
throwActionsToday: number;
|
|
54
|
-
catchUsersToday: number;
|
|
55
|
-
catchActionsToday: number;
|
|
56
|
-
seedUsersToday: number;
|
|
57
|
-
seedActionsToday: number;
|
|
58
|
-
catchCountTotal: number;
|
|
59
|
-
repliesTotal: number;
|
|
60
|
-
/** 回信 / 投入,0–1。**比率类,永不公开。** */
|
|
61
|
-
replyRate: number;
|
|
62
|
-
oldestAtSeaDays: number;
|
|
63
|
-
|
|
64
|
-
// ── 种子 ──
|
|
65
|
-
seedsTotal: number;
|
|
66
|
-
seedsClaimed: number;
|
|
67
|
-
seedsUnclaimed: number;
|
|
68
|
-
seedsClaimedToday: number;
|
|
69
|
-
|
|
70
|
-
// ── 世界 ──
|
|
71
|
-
tsunamiCount: number;
|
|
72
|
-
tsunamiLastAt: number | null;
|
|
73
|
-
tsunamiShatteredTotal: number;
|
|
74
|
-
}
|
|
75
|
-
|
|
76
|
-
/** 允许出现在 `public/` 里的那一份。 */
|
|
77
|
-
export interface PublicStats {
|
|
78
|
-
asOf: string;
|
|
79
|
-
sea: SeaState;
|
|
80
|
-
world: {
|
|
81
|
-
islands: number;
|
|
82
|
-
harbors: number;
|
|
83
|
-
lighthouses: number;
|
|
84
|
-
postmen: number;
|
|
85
|
-
coastlineKm: number;
|
|
86
|
-
};
|
|
87
|
-
/** 「居民」= 真实玩家 + 世界观具名人物。外人要还原真值得先数完所有种子信里的人物。 */
|
|
88
|
-
people: { residents: number };
|
|
89
|
-
letters: {
|
|
90
|
-
/** 海上漂着的瓶子 = 真实 floating + 居民写过的信 × 潮汐摆动。 */
|
|
91
|
-
atSea: number;
|
|
92
|
-
/** 海上出现过的信(累计)= 真实投递 + 居民写过的信。 */
|
|
93
|
-
everSeen: number;
|
|
94
|
-
/** 有回音的信:只给模糊区间 —— 单点值用加法盲化无效,只能降精度。 */
|
|
95
|
-
withEcho: string;
|
|
96
|
-
oldestAtSeaDays: number;
|
|
97
|
-
};
|
|
98
|
-
waves: { count: number; lastDaysAgo: number | null; shattered: number };
|
|
99
|
-
}
|
|
100
|
-
|
|
101
|
-
export interface CollectOptions {
|
|
102
|
-
/** 服务器时区,用来判断「今天」。 */
|
|
103
|
-
timeZone: string;
|
|
104
|
-
/** 今天的日期字符串(YYYY-MM-DD)。 */
|
|
105
|
-
today: string;
|
|
106
|
-
at: number;
|
|
107
|
-
}
|
|
108
|
-
|
|
109
|
-
/** 从磁盘状态算出真实数字。纯读取,不改任何东西。 */
|
|
110
|
-
export function collectRealStats(db: Db, seeds: SeedStats | null, opts: CollectOptions): RealStats {
|
|
111
|
-
const { at, today } = opts;
|
|
112
|
-
|
|
113
|
-
let dayFormat: Intl.DateTimeFormat | null = null;
|
|
114
|
-
try {
|
|
115
|
-
dayFormat = new Intl.DateTimeFormat('en-CA', {
|
|
116
|
-
timeZone: opts.timeZone,
|
|
117
|
-
year: 'numeric',
|
|
118
|
-
month: '2-digit',
|
|
119
|
-
day: '2-digit',
|
|
120
|
-
});
|
|
121
|
-
} catch {
|
|
122
|
-
dayFormat = null;
|
|
123
|
-
}
|
|
124
|
-
const dayStart = (ts: number): string =>
|
|
125
|
-
dayFormat ? dayFormat.format(new Date(ts)) : new Date(ts).toISOString().slice(0, 10);
|
|
126
|
-
|
|
127
|
-
const bots = db.bots;
|
|
128
|
-
const letters = db.letters;
|
|
129
|
-
/** 计数器只属于「它被清零的那一天」:昨天动过、今天还没来的账号不算今天的人。 */
|
|
130
|
-
const todayBots = bots.filter((bot) => bot.lastResetDate === today);
|
|
131
|
-
const byState = (state: string): number => letters.filter((letter) => letter.state === state).length;
|
|
132
|
-
|
|
133
|
-
const sunk = letters.filter((letter) => letter.archivedReason === 'sunk').length;
|
|
134
|
-
const tsunamiLost = letters.filter((letter) => letter.archivedReason === 'tsunami').length;
|
|
135
|
-
const repliesTotal = db.replies.length;
|
|
136
|
-
const catchCountTotal = letters.reduce((sum, letter) => sum + (letter.deliveredCount || 0), 0);
|
|
137
|
-
|
|
138
|
-
const floatingLetters = letters.filter((letter) => letter.state === 'floating');
|
|
139
|
-
const oldestAtSeaDays = floatingLetters.length
|
|
140
|
-
? Math.max(...floatingLetters.map((letter) => Math.floor((at - letter.createdAt) / DAY)))
|
|
141
|
-
: 0;
|
|
142
|
-
|
|
143
|
-
const claimedSeeds = new Set(db.seedUses.map((use) => use.seedId));
|
|
144
|
-
const seedsTotal = seeds?.count ?? claimedSeeds.size;
|
|
145
|
-
|
|
146
|
-
return {
|
|
147
|
-
date: today,
|
|
148
|
-
at: new Date(at).toISOString(),
|
|
149
|
-
|
|
150
|
-
botsTotal: bots.length,
|
|
151
|
-
// 老数据没有 lastSeenAt:退回用 lastResetDate 估,口径略窄(只查信箱的人不算)
|
|
152
|
-
botsActive: bots.filter((bot) =>
|
|
153
|
-
typeof bot.lastSeenAt === 'number'
|
|
154
|
-
? dayStart(bot.lastSeenAt) === today
|
|
155
|
-
: bot.lastResetDate === today,
|
|
156
|
-
).length,
|
|
157
|
-
botsNew: bots.filter((bot) => dayStart(bot.createdAt) === today).length,
|
|
158
|
-
botsWhoWrote: new Set(letters.map((letter) => letter.authorHash)).size,
|
|
159
|
-
|
|
160
|
-
lettersTotal: letters.length,
|
|
161
|
-
floating: byState('floating'),
|
|
162
|
-
caught: byState('caught'),
|
|
163
|
-
replied: byState('replied'),
|
|
164
|
-
sunk,
|
|
165
|
-
tsunamiLost,
|
|
166
|
-
archivedUnknown: Math.max(0, byState('archived') - sunk - tsunamiLost),
|
|
167
|
-
thrownToday: letters.filter((letter) => dayStart(letter.createdAt) === today).length,
|
|
168
|
-
caughtToday: letters.filter(
|
|
169
|
-
(letter) => letter.caughtAt !== null && dayStart(letter.caughtAt) === today,
|
|
170
|
-
).length,
|
|
171
|
-
repliesToday: db.replies.filter((reply) => dayStart(reply.createdAt) === today).length,
|
|
172
|
-
|
|
173
|
-
// 今天动过的人:计数器只属于今天,别把昨天没清零的算进来
|
|
174
|
-
throwUsersToday: todayBots.filter((bot) => (bot.bottlesUsed ?? 0) > 0).length,
|
|
175
|
-
throwActionsToday: todayBots.reduce((sum, bot) => sum + Math.max(0, bot.bottlesUsed ?? 0), 0),
|
|
176
|
-
catchUsersToday: todayBots.filter((bot) => (bot.catchesUsed ?? 0) > 0).length,
|
|
177
|
-
catchActionsToday: todayBots.reduce((sum, bot) => sum + Math.max(0, bot.catchesUsed ?? 0), 0),
|
|
178
|
-
seedUsersToday: todayBots.filter((bot) => (bot.mailTaken ?? 0) > 0).length,
|
|
179
|
-
seedActionsToday: todayBots.reduce((sum, bot) => sum + Math.max(0, bot.mailTaken ?? 0), 0),
|
|
180
|
-
|
|
181
|
-
catchCountTotal,
|
|
182
|
-
repliesTotal,
|
|
183
|
-
replyRate: letters.length ? Math.round((repliesTotal / letters.length) * 1000) / 1000 : 0,
|
|
184
|
-
oldestAtSeaDays,
|
|
185
|
-
|
|
186
|
-
seedsTotal,
|
|
187
|
-
seedsClaimed: claimedSeeds.size,
|
|
188
|
-
seedsUnclaimed: Math.max(0, seedsTotal - claimedSeeds.size),
|
|
189
|
-
seedsClaimedToday: db.seedUses.filter((use) => dayStart(use.usedAt) === today).length,
|
|
190
|
-
|
|
191
|
-
tsunamiCount: db.tsunami.count,
|
|
192
|
-
tsunamiLastAt: db.tsunami.lastAt,
|
|
193
|
-
tsunamiShatteredTotal: db.tsunami.totalLost ?? 0,
|
|
194
|
-
};
|
|
195
|
-
}
|
|
196
|
-
|
|
197
|
-
/**
|
|
198
|
-
* 把真数加工成可以公开的那份。
|
|
199
|
-
* **这个函数的返回值是唯一允许写进 `public/` 的东西。**
|
|
200
|
-
*/
|
|
201
|
-
export function applyBlinding(real: RealStats, ledger: Ledger, at: number): PublicStats {
|
|
202
|
-
const sea = seaStateAt(at);
|
|
203
|
-
return {
|
|
204
|
-
asOf: new Date(at).toISOString(),
|
|
205
|
-
sea,
|
|
206
|
-
world: {
|
|
207
|
-
islands: ledger.islands,
|
|
208
|
-
harbors: ledger.harbors,
|
|
209
|
-
lighthouses: ledger.lighthouses,
|
|
210
|
-
postmen: ledger.postmen,
|
|
211
|
-
coastlineKm: ledger.coastlineKm,
|
|
212
|
-
},
|
|
213
|
-
people: { residents: blindResidents(real.botsTotal, ledger) },
|
|
214
|
-
letters: {
|
|
215
|
-
atSea: blindAtSea(real.floating, ledger, sea.tide.level),
|
|
216
|
-
everSeen: blindEverSeen(real.lettersTotal, ledger),
|
|
217
|
-
withEcho: bucketCount(real.repliesTotal),
|
|
218
|
-
oldestAtSeaDays: real.oldestAtSeaDays,
|
|
219
|
-
},
|
|
220
|
-
waves: {
|
|
221
|
-
count: real.tsunamiCount,
|
|
222
|
-
lastDaysAgo:
|
|
223
|
-
real.tsunamiLastAt === null
|
|
224
|
-
? null
|
|
225
|
-
: Math.max(0, Math.floor((at - real.tsunamiLastAt) / DAY)),
|
|
226
|
-
shattered: real.tsunamiShatteredTotal,
|
|
227
|
-
},
|
|
228
|
-
};
|
|
229
|
-
}
|
|
230
|
-
|
|
231
|
-
/**
|
|
232
|
-
* 写入某一天的真数。
|
|
233
|
-
*
|
|
234
|
-
* **按日期去重**:同一天重跑快照是「更新」而不是「再追加一行」。
|
|
235
|
-
* 否则一天跑两次就会有两条,画曲线时会冒出个假的重复点。
|
|
236
|
-
*/
|
|
237
|
-
export function appendStatsLine(file: string, stat: RealStats): void {
|
|
238
|
-
try {
|
|
239
|
-
mkdirSync(dirname(file), { recursive: true });
|
|
240
|
-
let kept = '';
|
|
241
|
-
try {
|
|
242
|
-
kept = readFileSync(file, 'utf8')
|
|
243
|
-
.split('\n')
|
|
244
|
-
.filter((line) => line.trim() !== '')
|
|
245
|
-
.filter((line) => {
|
|
246
|
-
try {
|
|
247
|
-
return (JSON.parse(line) as { date?: string }).date !== stat.date;
|
|
248
|
-
} catch {
|
|
249
|
-
return true; // 坏行留着,别因为一行脏数据丢掉整段历史
|
|
250
|
-
}
|
|
251
|
-
})
|
|
252
|
-
.map((line) => `${line}\n`)
|
|
253
|
-
.join('');
|
|
254
|
-
} catch {
|
|
255
|
-
// 文件还不存在:从这个日期开始记
|
|
256
|
-
}
|
|
257
|
-
const tmp = `${file}.tmp`;
|
|
258
|
-
writeFileSync(tmp, `${kept}${JSON.stringify(stat)}\n`, 'utf8');
|
|
259
|
-
renameSync(tmp, file);
|
|
260
|
-
} catch (error) {
|
|
261
|
-
process.stderr.write(
|
|
262
|
-
`stats.jsonl 写入失败:${error instanceof Error ? error.message : 'unknown'}\n`,
|
|
263
|
-
);
|
|
264
|
-
}
|
|
265
|
-
}
|
|
266
|
-
|
|
267
|
-
/** 原子写公开数字(tmp + rename),避免大屏读到半截 JSON。 */
|
|
268
|
-
export function writePublicStats(file: string, pub: PublicStats): void {
|
|
269
|
-
mkdirSync(dirname(file), { recursive: true });
|
|
270
|
-
const tmp = `${file}.tmp`;
|
|
271
|
-
writeFileSync(tmp, `${JSON.stringify(pub, null, 2)}\n`, 'utf8');
|
|
272
|
-
renameSync(tmp, file);
|
|
273
|
-
}
|