pi-roundtable 0.52.0 → 0.52.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 +23 -0
- package/README.md +1 -0
- package/docs/plugins.md +18 -6
- package/package.json +1 -1
- package/src/core/builtin/discord.ts +20 -35
- package/src/core/config/limits.ts +20 -1
- package/src/core/contract/surface.ts +7 -0
- package/src/core/discord/catch-up-gate.ts +220 -0
- package/src/core/discord/catch-up-journal.ts +61 -2
- package/src/core/discord/catch-up-reader.ts +44 -2
- package/src/core/discord/catch-up-service.ts +142 -0
- package/src/core/discord/catch-up.ts +138 -57
- package/src/core/discord/discord-surface.ts +5 -0
- package/src/core/host/define-roundtable.ts +5 -1
- package/src/core/host/drain.ts +1 -3
- package/src/core/host/host.ts +35 -2
- package/src/core/i18n/conversation.ts +2 -0
- package/src/core/routing/channel-router.ts +31 -11
- package/src/core/routing/queued-messages.ts +54 -10
|
@@ -10,6 +10,7 @@ import type {
|
|
|
10
10
|
ScannedMessage,
|
|
11
11
|
} from "./catch-up.ts";
|
|
12
12
|
import { timeOf } from "./catch-up.ts";
|
|
13
|
+
import type { PostedNotice } from "./catch-up-gate.ts";
|
|
13
14
|
import { toInbound } from "./inbound-message.ts";
|
|
14
15
|
|
|
15
16
|
/** What the bot needs in a server channel to read what was said there before. */
|
|
@@ -18,6 +19,11 @@ const READ = [
|
|
|
18
19
|
PermissionFlagsBits.ReadMessageHistory,
|
|
19
20
|
];
|
|
20
21
|
|
|
22
|
+
/** Discord's error code for a member who is not in the server. */
|
|
23
|
+
const UNKNOWN_MEMBER = 10007;
|
|
24
|
+
/** Discord's error code for a message that is not there. */
|
|
25
|
+
const UNKNOWN_MESSAGE = 10008;
|
|
26
|
+
|
|
21
27
|
function channelView(
|
|
22
28
|
channel: TextBasedChannel,
|
|
23
29
|
): CatchUpChannel<Message & ScannedMessage> {
|
|
@@ -37,7 +43,8 @@ function channelView(
|
|
|
37
43
|
* Catch-up's view of a ready client. The server channels, threads and forum posts come from the
|
|
38
44
|
* client's cache, which Discord fills as the connection becomes ready, with each channel's last
|
|
39
45
|
* message: choosing what to read costs no request. A message's author is fetched as a member
|
|
40
|
-
* before it is read in full, so its roles are those a live message carries
|
|
46
|
+
* before it is read in full, so its roles are those a live message carries; when that fails for
|
|
47
|
+
* any reason but the author having left, the message is not read, so a later restart may retry it.
|
|
41
48
|
*/
|
|
42
49
|
export function clientCatchUpReader(
|
|
43
50
|
client: Client,
|
|
@@ -68,12 +75,47 @@ export function clientCatchUpReader(
|
|
|
68
75
|
? channelView(channel)
|
|
69
76
|
: undefined;
|
|
70
77
|
},
|
|
78
|
+
message: async (channelId, messageId) => {
|
|
79
|
+
const channel = await client.channels.fetch(channelId);
|
|
80
|
+
if (!channel?.isTextBased()) return undefined;
|
|
81
|
+
return channel.messages.fetch(messageId).catch((error: unknown) => {
|
|
82
|
+
// Deleted since: nothing to answer.
|
|
83
|
+
if ((error as { code?: unknown }).code === UNKNOWN_MESSAGE)
|
|
84
|
+
return undefined;
|
|
85
|
+
throw error;
|
|
86
|
+
});
|
|
87
|
+
},
|
|
71
88
|
inbound: async (message) => {
|
|
72
89
|
if (message.inGuild() && !message.member)
|
|
73
90
|
await message.guild.members
|
|
74
91
|
.fetch(message.author.id)
|
|
75
|
-
.catch(() =>
|
|
92
|
+
.catch((error: unknown) => {
|
|
93
|
+
// An author who left has no roles; any other failure leaves the message for a later restart.
|
|
94
|
+
if ((error as { code?: unknown }).code !== UNKNOWN_MEMBER)
|
|
95
|
+
throw error;
|
|
96
|
+
});
|
|
76
97
|
return toInbound(message, identity);
|
|
77
98
|
},
|
|
78
99
|
};
|
|
79
100
|
}
|
|
101
|
+
|
|
102
|
+
/** Posts `text` in a channel with no mention, as a notice. */
|
|
103
|
+
export async function postNotice(
|
|
104
|
+
client: Client,
|
|
105
|
+
channelId: string,
|
|
106
|
+
text: string,
|
|
107
|
+
): Promise<PostedNotice> {
|
|
108
|
+
const channel = await client.channels.fetch(channelId);
|
|
109
|
+
if (!channel?.isSendable())
|
|
110
|
+
throw new Error(`channel ${channelId} takes no message`);
|
|
111
|
+
const posted = await channel.send({
|
|
112
|
+
content: text,
|
|
113
|
+
allowedMentions: { parse: [] },
|
|
114
|
+
});
|
|
115
|
+
return {
|
|
116
|
+
id: posted.id,
|
|
117
|
+
retract: async () => {
|
|
118
|
+
await posted.delete();
|
|
119
|
+
},
|
|
120
|
+
};
|
|
121
|
+
}
|
|
@@ -0,0 +1,142 @@
|
|
|
1
|
+
import type { Client } from "discord.js";
|
|
2
|
+
import type { InboundMessage } from "../contract/channels.ts";
|
|
3
|
+
import { messages } from "../i18n/index.ts";
|
|
4
|
+
import type { Logger } from "../kernel/log.ts";
|
|
5
|
+
import type { Service } from "../plugin-api/plugin.ts";
|
|
6
|
+
import {
|
|
7
|
+
type CatchUpSettings,
|
|
8
|
+
catchUp,
|
|
9
|
+
DAY_MS,
|
|
10
|
+
JOURNAL_DAYS,
|
|
11
|
+
} from "./catch-up.ts";
|
|
12
|
+
import { type JournalGate, journalGate } from "./catch-up-gate.ts";
|
|
13
|
+
import type { InboundJournal } from "./catch-up-journal.ts";
|
|
14
|
+
import { clientCatchUpReader, postNotice } from "./catch-up-reader.ts";
|
|
15
|
+
|
|
16
|
+
/** How often the journal forgets what is older than it keeps, while the host runs. */
|
|
17
|
+
const PRUNE_EVERY_MS = DAY_MS / 4;
|
|
18
|
+
|
|
19
|
+
export interface CatchUpWiringOptions {
|
|
20
|
+
journal: InboundJournal;
|
|
21
|
+
settings: CatchUpSettings;
|
|
22
|
+
logger: Logger;
|
|
23
|
+
/** The surface's client, once it is connected. */
|
|
24
|
+
client: () => Client;
|
|
25
|
+
/** Hands a caught-up message to routing. */
|
|
26
|
+
deliver: (message: InboundMessage) => void;
|
|
27
|
+
/** The interval timer, replaceable in a test. */
|
|
28
|
+
every?: (run: () => void, ms: number) => { stop(): void };
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
const interval = (run: () => void, ms: number) => {
|
|
32
|
+
const timer = setInterval(run, ms);
|
|
33
|
+
timer.unref?.();
|
|
34
|
+
return { stop: () => clearInterval(timer) };
|
|
35
|
+
};
|
|
36
|
+
|
|
37
|
+
/**
|
|
38
|
+
* The live gateway's journal gate and the catch-up service, sharing whether the host drains and
|
|
39
|
+
* which messages the gateway delivered without a record. The service prunes the journal now and
|
|
40
|
+
* then while it runs, so a host that is never restarted keeps only `JOURNAL_DAYS` of records.
|
|
41
|
+
*/
|
|
42
|
+
export function catchUpWiring(options: CatchUpWiringOptions): {
|
|
43
|
+
gate: JournalGate;
|
|
44
|
+
/** For a message routing refuses as the host stops; true when the gate took care of it. */
|
|
45
|
+
refused(message: InboundMessage): Promise<boolean>;
|
|
46
|
+
service: Service;
|
|
47
|
+
} {
|
|
48
|
+
const { journal, logger } = options;
|
|
49
|
+
let draining = false;
|
|
50
|
+
// Only catch-up reads it, and it runs once: after it, nothing more is kept.
|
|
51
|
+
const unrecorded = new Set<string>();
|
|
52
|
+
let caughtUp = false;
|
|
53
|
+
let pruning: { stop(): void } | undefined;
|
|
54
|
+
// A live message waits until catch-up knows which channels it reads, and in one of those, until it is done.
|
|
55
|
+
let plan!: (ids: Set<string>) => void;
|
|
56
|
+
const planned = new Promise<Set<string>>((resolve) => {
|
|
57
|
+
plan = resolve;
|
|
58
|
+
});
|
|
59
|
+
let finish!: () => void;
|
|
60
|
+
const finished = new Promise<void>((resolve) => {
|
|
61
|
+
finish = resolve;
|
|
62
|
+
});
|
|
63
|
+
const release = () => {
|
|
64
|
+
plan(new Set());
|
|
65
|
+
finish();
|
|
66
|
+
caughtUp = true;
|
|
67
|
+
unrecorded.clear();
|
|
68
|
+
};
|
|
69
|
+
const wait = async (channelId: string) => {
|
|
70
|
+
if ((await planned).has(channelId)) await finished;
|
|
71
|
+
};
|
|
72
|
+
const prune = () =>
|
|
73
|
+
void journal
|
|
74
|
+
.prune(new Date(Date.now() - JOURNAL_DAYS * DAY_MS))
|
|
75
|
+
.catch((error: unknown) =>
|
|
76
|
+
logger.warn({ err: error }, "could not prune the inbound journal"),
|
|
77
|
+
);
|
|
78
|
+
let seenBot: string | undefined;
|
|
79
|
+
const passing = journalGate({
|
|
80
|
+
journal,
|
|
81
|
+
logger,
|
|
82
|
+
draining: () => draining,
|
|
83
|
+
notify: (channelId, kind) =>
|
|
84
|
+
postNotice(
|
|
85
|
+
options.client(),
|
|
86
|
+
channelId,
|
|
87
|
+
kind === "later"
|
|
88
|
+
? messages().restartingAnswerLater
|
|
89
|
+
: messages().restartingNotice,
|
|
90
|
+
),
|
|
91
|
+
wait,
|
|
92
|
+
redeliver: options.deliver,
|
|
93
|
+
unrecorded: {
|
|
94
|
+
add: (id) => (caughtUp ? unrecorded : unrecorded.add(id)),
|
|
95
|
+
},
|
|
96
|
+
});
|
|
97
|
+
const gate: JournalGate = Object.assign(
|
|
98
|
+
(message: InboundMessage, botId: string) => {
|
|
99
|
+
seenBot = botId;
|
|
100
|
+
return passing(message, botId);
|
|
101
|
+
},
|
|
102
|
+
{ refused: passing.refused },
|
|
103
|
+
);
|
|
104
|
+
return {
|
|
105
|
+
gate,
|
|
106
|
+
refused: async (message) => {
|
|
107
|
+
// A refused message passed the gate, so the bot is known by then.
|
|
108
|
+
const botId = options.client().user?.id ?? seenBot;
|
|
109
|
+
return botId !== undefined && gate.refused(message, botId);
|
|
110
|
+
},
|
|
111
|
+
service: {
|
|
112
|
+
name: "discord-catch-up",
|
|
113
|
+
start: () => {
|
|
114
|
+
pruning = (options.every ?? interval)(prune, PRUNE_EVERY_MS);
|
|
115
|
+
},
|
|
116
|
+
// After every service is up, so the missed messages reach claims that are ready.
|
|
117
|
+
startInBackground: async () => {
|
|
118
|
+
try {
|
|
119
|
+
await catchUp({
|
|
120
|
+
reader: clientCatchUpReader(options.client()),
|
|
121
|
+
journal,
|
|
122
|
+
deliver: options.deliver,
|
|
123
|
+
settings: options.settings,
|
|
124
|
+
logger,
|
|
125
|
+
stopping: () => draining,
|
|
126
|
+
planned: (ids) => plan(new Set(ids)),
|
|
127
|
+
passedLive: (id) => unrecorded.has(id),
|
|
128
|
+
});
|
|
129
|
+
} finally {
|
|
130
|
+
release();
|
|
131
|
+
}
|
|
132
|
+
},
|
|
133
|
+
beginDrain: () => {
|
|
134
|
+
draining = true;
|
|
135
|
+
release();
|
|
136
|
+
},
|
|
137
|
+
stop: () => {
|
|
138
|
+
pruning?.stop();
|
|
139
|
+
},
|
|
140
|
+
},
|
|
141
|
+
};
|
|
142
|
+
}
|
|
@@ -16,15 +16,17 @@ export type CatchUpSettings = Required<CatchUpOptions>;
|
|
|
16
16
|
|
|
17
17
|
const DEFAULT_WINDOW_MINUTES = 10;
|
|
18
18
|
const DEFAULT_MAX_MESSAGES = 20;
|
|
19
|
-
/** How long a direct-message channel is remembered, to be looked into after a restart. */
|
|
20
|
-
const
|
|
19
|
+
/** How long a record is kept: a direct-message channel is remembered this long, to be looked into after a restart. */
|
|
20
|
+
export const JOURNAL_DAYS = 30;
|
|
21
21
|
/** The most remembered direct-message channels fetched to see whether they had a message lately. */
|
|
22
22
|
const DIRECT_PROBES = 25;
|
|
23
23
|
/** The most channels whose messages one catch-up reads, one request each. */
|
|
24
24
|
const MAX_CHANNEL_READS = 50;
|
|
25
25
|
/** The messages read before the ready time in each channel, one page. */
|
|
26
26
|
const PAGE = 100;
|
|
27
|
-
const DAY_MS = 86_400_000;
|
|
27
|
+
export const DAY_MS = 86_400_000;
|
|
28
|
+
/** How long a message a stopping process left is still answered by the next. */
|
|
29
|
+
const LEFT_KEPT_MS = DAY_MS;
|
|
28
30
|
const DISCORD_EPOCH = 1_420_070_400_000n;
|
|
29
31
|
|
|
30
32
|
const whole = (value: number | undefined, low: number, high: number) =>
|
|
@@ -76,6 +78,12 @@ export interface ScannedMessage {
|
|
|
76
78
|
users: { has(id: string): boolean };
|
|
77
79
|
repliedUser: { id: string } | null;
|
|
78
80
|
};
|
|
81
|
+
/** Whether a thread was started from it, as the bot answers a mention in a thread. */
|
|
82
|
+
hasThread?: boolean;
|
|
83
|
+
/** Its reactions; one the bot added counts as an answer. */
|
|
84
|
+
reactions?: {
|
|
85
|
+
cache: { some(test: (reaction: { me: boolean }) => boolean): boolean };
|
|
86
|
+
};
|
|
79
87
|
}
|
|
80
88
|
|
|
81
89
|
/** A channel catch-up may read. */
|
|
@@ -98,6 +106,8 @@ export interface CatchUpReader<M extends ScannedMessage> {
|
|
|
98
106
|
channels(): CatchUpChannel<M>[];
|
|
99
107
|
/** A direct-message channel by its id; undefined when it is not one. */
|
|
100
108
|
direct(channelId: string): Promise<CatchUpChannel<M> | undefined>;
|
|
109
|
+
/** A message by its channel and id; undefined when it is gone. */
|
|
110
|
+
message(channelId: string, messageId: string): Promise<M | undefined>;
|
|
101
111
|
/** The message as the live gateway would deliver it. */
|
|
102
112
|
inbound(message: M): Promise<InboundMessage | undefined>;
|
|
103
113
|
}
|
|
@@ -111,6 +121,10 @@ export interface CatchUpDeps<M extends ScannedMessage> {
|
|
|
111
121
|
logger: Logger;
|
|
112
122
|
/** True once the host shuts down: nothing more is delivered. */
|
|
113
123
|
stopping?: () => boolean;
|
|
124
|
+
/** Hears, before any is read, the channels catch-up may read, a few more than it does: those its cache shows active, and the remembered direct messages. */
|
|
125
|
+
planned?: (channelIds: string[]) => void;
|
|
126
|
+
/** Whether the live gateway delivered the message without recording it, in this process: it is not delivered again. */
|
|
127
|
+
passedLive?: (messageId: string) => boolean;
|
|
114
128
|
now?: () => number;
|
|
115
129
|
}
|
|
116
130
|
|
|
@@ -134,6 +148,7 @@ async function channelsToRead<M extends ScannedMessage>(
|
|
|
134
148
|
deps: CatchUpDeps<M>,
|
|
135
149
|
since: number,
|
|
136
150
|
now: number,
|
|
151
|
+
leftIn: string[],
|
|
137
152
|
): Promise<CatchUpChannel<M>[]> {
|
|
138
153
|
const { reader, journal, logger } = deps;
|
|
139
154
|
const known = reader.channels();
|
|
@@ -141,13 +156,21 @@ async function channelsToRead<M extends ScannedMessage>(
|
|
|
141
156
|
const directs = await journal
|
|
142
157
|
.directChannels(
|
|
143
158
|
reader.botId,
|
|
144
|
-
new Date(now -
|
|
159
|
+
new Date(now - JOURNAL_DAYS * DAY_MS),
|
|
145
160
|
DIRECT_PROBES,
|
|
146
161
|
)
|
|
147
162
|
.catch((error: unknown) => {
|
|
148
163
|
logger.warn({ err: error }, "catch-up could not list direct messages");
|
|
149
164
|
return [];
|
|
150
165
|
});
|
|
166
|
+
// Live messages wait for this, not for the direct messages to be fetched.
|
|
167
|
+
deps.planned?.([
|
|
168
|
+
...known
|
|
169
|
+
.filter((channel) => (channel.lastMessageAt ?? 0) >= since)
|
|
170
|
+
.map((channel) => channel.id),
|
|
171
|
+
...directs,
|
|
172
|
+
...leftIn,
|
|
173
|
+
]);
|
|
151
174
|
for (const id of directs) {
|
|
152
175
|
if (ids.has(id)) continue;
|
|
153
176
|
const channel = await reader.direct(id).catch(() => undefined);
|
|
@@ -159,6 +182,22 @@ async function channelsToRead<M extends ScannedMessage>(
|
|
|
159
182
|
.slice(0, MAX_CHANNEL_READS);
|
|
160
183
|
}
|
|
161
184
|
|
|
185
|
+
/** Which of the bot's posts are restart notices, recorded as it shut down; undefined when that cannot be read. */
|
|
186
|
+
async function restartNotices<M extends ScannedMessage>(
|
|
187
|
+
{ journal, reader, logger }: CatchUpDeps<M>,
|
|
188
|
+
posts: M[],
|
|
189
|
+
): Promise<Set<string> | undefined> {
|
|
190
|
+
return journal
|
|
191
|
+
.recordedAmong(
|
|
192
|
+
reader.botId,
|
|
193
|
+
posts.map((post) => post.id),
|
|
194
|
+
)
|
|
195
|
+
.catch((error: unknown) => {
|
|
196
|
+
logger.warn({ err: error }, "catch-up could not look up restart notices");
|
|
197
|
+
return undefined;
|
|
198
|
+
});
|
|
199
|
+
}
|
|
200
|
+
|
|
162
201
|
/**
|
|
163
202
|
* Answers the messages addressed to the bot that came while the host was down: after the
|
|
164
203
|
* connection is ready, reads the channels active in the window and hands routing each person's
|
|
@@ -184,17 +223,54 @@ export async function catchUp<M extends ScannedMessage>(
|
|
|
184
223
|
failed: 0,
|
|
185
224
|
delivered: 0,
|
|
186
225
|
};
|
|
187
|
-
await journal
|
|
188
|
-
.prune(new Date(now - DIRECT_MEMORY_DAYS * DAY_MS))
|
|
189
|
-
.catch((error: unknown) =>
|
|
190
|
-
logger.warn({ err: error }, "catch-up could not prune its journal"),
|
|
191
|
-
);
|
|
192
226
|
const own = reader.applicationId ?? botId;
|
|
193
227
|
const byBot = (message: M) =>
|
|
194
228
|
message.author.id === botId ||
|
|
195
229
|
(message.webhookId !== null && message.applicationId === own);
|
|
196
|
-
|
|
197
|
-
|
|
230
|
+
type Missed = {
|
|
231
|
+
message: M;
|
|
232
|
+
channel: Pick<CatchUpChannel<M>, "id" | "direct">;
|
|
233
|
+
left?: true;
|
|
234
|
+
};
|
|
235
|
+
const missed: Missed[] = [];
|
|
236
|
+
// What a stopping process left is answered whatever its channel shows since, outside the window and the cap.
|
|
237
|
+
const left = await journal
|
|
238
|
+
.left(botId, new Date(now - LEFT_KEPT_MS))
|
|
239
|
+
.catch((error: unknown) => {
|
|
240
|
+
logger.warn(
|
|
241
|
+
{ err: error },
|
|
242
|
+
"catch-up could not list the messages left to it",
|
|
243
|
+
);
|
|
244
|
+
return [];
|
|
245
|
+
});
|
|
246
|
+
// The left messages read, which the channel reads below leave alone.
|
|
247
|
+
const leftIds = new Set<string>();
|
|
248
|
+
const reading = await channelsToRead(
|
|
249
|
+
deps,
|
|
250
|
+
since,
|
|
251
|
+
now,
|
|
252
|
+
left.map((entry) => entry.channelId),
|
|
253
|
+
).catch((error: unknown) => {
|
|
254
|
+
logger.warn({ err: error }, "catch-up could not list its channels");
|
|
255
|
+
return [];
|
|
256
|
+
});
|
|
257
|
+
for (const entry of left) {
|
|
258
|
+
const channel = { id: entry.channelId, direct: entry.direct };
|
|
259
|
+
try {
|
|
260
|
+
const message = await reader.message(entry.channelId, entry.messageId);
|
|
261
|
+
if (message) {
|
|
262
|
+
missed.push({ message, channel, left: true });
|
|
263
|
+
leftIds.add(message.id);
|
|
264
|
+
}
|
|
265
|
+
} catch (error) {
|
|
266
|
+
report.failed += 1;
|
|
267
|
+
logger.warn(
|
|
268
|
+
{ ...channel, messageId: entry.messageId, err: error },
|
|
269
|
+
"catch-up could not read a message left to it",
|
|
270
|
+
);
|
|
271
|
+
}
|
|
272
|
+
}
|
|
273
|
+
for (const channel of reading) {
|
|
198
274
|
if (deps.stopping?.()) return report;
|
|
199
275
|
report.channels += 1;
|
|
200
276
|
let messages: M[];
|
|
@@ -208,13 +284,22 @@ export async function catchUp<M extends ScannedMessage>(
|
|
|
208
284
|
);
|
|
209
285
|
continue;
|
|
210
286
|
}
|
|
211
|
-
const
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
287
|
+
const notices = await restartNotices(deps, messages.filter(byBot));
|
|
288
|
+
// Not knowing which posts are notices, it could take one for an answer: the channel is left for a later restart.
|
|
289
|
+
if (!notices) {
|
|
290
|
+
report.unread += 1;
|
|
291
|
+
continue;
|
|
292
|
+
}
|
|
293
|
+
const answeredUpTo = messages
|
|
294
|
+
.filter((message) => byBot(message) && !notices.has(message.id))
|
|
295
|
+
.reduce((latest, message) => {
|
|
296
|
+
const id = BigInt(message.id);
|
|
297
|
+
return id > latest ? id : latest;
|
|
298
|
+
}, 0n);
|
|
215
299
|
for (const message of messages) {
|
|
216
300
|
const { author, mentions } = message;
|
|
217
301
|
if (
|
|
302
|
+
leftIds.has(message.id) ||
|
|
218
303
|
message.createdTimestamp < since ||
|
|
219
304
|
message.createdTimestamp >= readyAt ||
|
|
220
305
|
author.bot ||
|
|
@@ -227,16 +312,28 @@ export async function catchUp<M extends ScannedMessage>(
|
|
|
227
312
|
)
|
|
228
313
|
)
|
|
229
314
|
continue;
|
|
230
|
-
// The bot posted after it, so it was answered then
|
|
231
|
-
|
|
315
|
+
// The bot posted after it, so it was answered then; a notice that it restarts is no answer.
|
|
316
|
+
// A thread started from it or a reaction of the bot's is an answer the channel does not show.
|
|
317
|
+
if (
|
|
318
|
+
BigInt(message.id) < answeredUpTo ||
|
|
319
|
+
message.hasThread ||
|
|
320
|
+
message.reactions?.cache.some((reaction) => reaction.me)
|
|
321
|
+
)
|
|
322
|
+
report.replied += 1;
|
|
232
323
|
else missed.push({ message, channel });
|
|
233
324
|
}
|
|
234
325
|
}
|
|
235
326
|
missed.sort((a, b) => (BigInt(a.message.id) < BigInt(b.message.id) ? -1 : 1));
|
|
236
327
|
report.missed = missed.length;
|
|
237
|
-
|
|
238
|
-
|
|
328
|
+
const found = missed.filter((item) => !item.left);
|
|
329
|
+
report.overCap = Math.max(0, found.length - settings.maxMessages);
|
|
330
|
+
const dropped = new Set(found.slice(0, report.overCap));
|
|
331
|
+
for (const { message, channel } of missed.filter((m) => !dropped.has(m))) {
|
|
239
332
|
if (deps.stopping?.()) break;
|
|
333
|
+
if (deps.passedLive?.(message.id)) {
|
|
334
|
+
report.handled += 1;
|
|
335
|
+
continue;
|
|
336
|
+
}
|
|
240
337
|
try {
|
|
241
338
|
const inbound = await reader.inbound(message);
|
|
242
339
|
if (!inbound) continue;
|
|
@@ -250,6 +347,23 @@ export async function catchUp<M extends ScannedMessage>(
|
|
|
250
347
|
report.handled += 1;
|
|
251
348
|
continue;
|
|
252
349
|
}
|
|
350
|
+
// Routing refuses it once the host shuts down; the next process takes it in instead.
|
|
351
|
+
if (deps.stopping?.()) {
|
|
352
|
+
await journal
|
|
353
|
+
.leave({
|
|
354
|
+
botId,
|
|
355
|
+
messageId: message.id,
|
|
356
|
+
channelId: channel.id,
|
|
357
|
+
direct: channel.direct,
|
|
358
|
+
})
|
|
359
|
+
.catch((error: unknown) =>
|
|
360
|
+
logger.warn(
|
|
361
|
+
{ channelId: channel.id, messageId: message.id, err: error },
|
|
362
|
+
"catch-up could not leave a message as the host stops; no process answers it",
|
|
363
|
+
),
|
|
364
|
+
);
|
|
365
|
+
break;
|
|
366
|
+
}
|
|
253
367
|
deps.deliver({ ...inbound, caughtUp: true });
|
|
254
368
|
report.delivered += 1;
|
|
255
369
|
} catch (error) {
|
|
@@ -261,44 +375,11 @@ export async function catchUp<M extends ScannedMessage>(
|
|
|
261
375
|
);
|
|
262
376
|
}
|
|
263
377
|
}
|
|
378
|
+
await journal
|
|
379
|
+
.prune(new Date(now - JOURNAL_DAYS * DAY_MS))
|
|
380
|
+
.catch((error: unknown) =>
|
|
381
|
+
logger.warn({ err: error }, "catch-up could not prune its journal"),
|
|
382
|
+
);
|
|
264
383
|
logger.info({ ...report }, "discord catch-up done");
|
|
265
384
|
return report;
|
|
266
385
|
}
|
|
267
|
-
|
|
268
|
-
/**
|
|
269
|
-
* Records each addressed message the live gateway delivers before routing hears it, so catch-up
|
|
270
|
-
* after a restart leaves it alone; false for one already recorded, which is not delivered again.
|
|
271
|
-
* A message that cannot be recorded is still delivered, and logged. Once the host drains
|
|
272
|
-
* (`draining`), nothing is recorded: routing refuses those messages, and the next process answers
|
|
273
|
-
* those its restart notice did not.
|
|
274
|
-
*/
|
|
275
|
-
export function journalGate(
|
|
276
|
-
journal: InboundJournal,
|
|
277
|
-
logger: Logger,
|
|
278
|
-
draining: () => boolean = () => false,
|
|
279
|
-
): (message: InboundMessage, botId: string) => Promise<boolean> {
|
|
280
|
-
return async (message, botId) => {
|
|
281
|
-
if (!addressed(message) || draining()) return true;
|
|
282
|
-
const channelId = message.channel.slice("discord:".length);
|
|
283
|
-
try {
|
|
284
|
-
const first = await journal.claim({
|
|
285
|
-
botId,
|
|
286
|
-
messageId: message.messageId,
|
|
287
|
-
channelId,
|
|
288
|
-
direct: message.isDirect,
|
|
289
|
-
});
|
|
290
|
-
if (!first)
|
|
291
|
-
logger.info(
|
|
292
|
-
{ channelId, messageId: message.messageId },
|
|
293
|
-
"message already taken in; not delivered again",
|
|
294
|
-
);
|
|
295
|
-
return first;
|
|
296
|
-
} catch (error) {
|
|
297
|
-
logger.warn(
|
|
298
|
-
{ channelId, messageId: message.messageId, err: error },
|
|
299
|
-
"could not record an addressed message; delivered anyway",
|
|
300
|
-
);
|
|
301
|
-
return true;
|
|
302
|
-
}
|
|
303
|
-
};
|
|
304
|
-
}
|
|
@@ -87,6 +87,8 @@ export interface DiscordSurfaceOptions {
|
|
|
87
87
|
intercomTexts?: IntercomTexts;
|
|
88
88
|
/** Decides whether each live message is handed on, such as catch-up's journal; without it every one is. */
|
|
89
89
|
inboundGate?: InboundGate;
|
|
90
|
+
/** `ChatSurface.refuseStopping`, such as catch-up's; without it routing tells the channel. */
|
|
91
|
+
refuseStopping?: (message: InboundMessage) => Promise<boolean>;
|
|
90
92
|
/** Reads the channel context of an addressed message; without it the surface has none. */
|
|
91
93
|
channelContext?: (
|
|
92
94
|
message: InboundMessage,
|
|
@@ -120,8 +122,11 @@ export class DiscordSurface
|
|
|
120
122
|
#interactions: ComposedCommands = { commands: [], modules: [] };
|
|
121
123
|
#onMessage: ((message: InboundMessage) => void) | undefined;
|
|
122
124
|
|
|
125
|
+
readonly refuseStopping?: (message: InboundMessage) => Promise<boolean>;
|
|
126
|
+
|
|
123
127
|
constructor(options: DiscordSurfaceOptions) {
|
|
124
128
|
this.#options = options;
|
|
129
|
+
if (options.refuseStopping) this.refuseStopping = options.refuseStopping;
|
|
125
130
|
this.#client = new Client({
|
|
126
131
|
intents: [
|
|
127
132
|
GatewayIntentBits.Guilds,
|
|
@@ -360,7 +360,11 @@ export async function defineRoundtable(
|
|
|
360
360
|
],
|
|
361
361
|
judgeModel: judgeThrough(modelRuntime, config.judge.model),
|
|
362
362
|
apiKey: (provider) => registry.getApiKeyForProvider(provider),
|
|
363
|
-
drain: {
|
|
363
|
+
drain: {
|
|
364
|
+
limitMs: config.drainMs,
|
|
365
|
+
abortGraceMs: config.abortGraceMs,
|
|
366
|
+
refuseWaitingMs: config.refuseWaitingMs,
|
|
367
|
+
},
|
|
364
368
|
...(discord?.peerBots ? { peerBots: discord.peerBots } : {}),
|
|
365
369
|
...(overrides.aborted ? { aborted: overrides.aborted } : {}),
|
|
366
370
|
},
|
package/src/core/host/drain.ts
CHANGED
|
@@ -1,10 +1,8 @@
|
|
|
1
1
|
import { DRAIN_LIMIT_MS } from "../config/config-schema.ts";
|
|
2
|
+
import { ABORT_GRACE_MS } from "../config/limits.ts";
|
|
2
3
|
import type { Logger } from "../kernel/log.ts";
|
|
3
4
|
import type { Service } from "../plugin-api/plugin.ts";
|
|
4
5
|
|
|
5
|
-
/** How long work that was told to stop gets to end before the shutdown goes on without it. */
|
|
6
|
-
const ABORT_GRACE_MS = 10_000;
|
|
7
|
-
|
|
8
6
|
export interface DrainOptions {
|
|
9
7
|
/** What still runs or waits, one entry per piece of work; empty when idle. */
|
|
10
8
|
busy: () => string[];
|
package/src/core/host/host.ts
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import type { SQL } from "bun";
|
|
2
2
|
import type { Hex } from "../../characters/index.ts";
|
|
3
3
|
import type { AttachmentRetention } from "../attachments/attachment-retention.ts";
|
|
4
|
+
import { REFUSE_WAITING_MS } from "../config/limits.ts";
|
|
4
5
|
import type { PeerBotsConfig } from "../config/peer-bots.ts";
|
|
5
6
|
import { checkDatabase } from "../db/check-database.ts";
|
|
6
7
|
import { openPool, runMigrations } from "../db/migrations.ts";
|
|
@@ -100,9 +101,10 @@ export interface RoundtableOptions {
|
|
|
100
101
|
/**
|
|
101
102
|
* The shutdown drain: it waits up to `limitMs` (3 minutes by default) for the turns already
|
|
102
103
|
* running, then stops them, gives them `abortGraceMs` (10 seconds) to end, and goes on without
|
|
103
|
-
* them. Nothing new starts once it begins.
|
|
104
|
+
* them. Nothing new starts once it begins. The messages still waiting behind a turn then get
|
|
105
|
+
* `refuseWaitingMs` (15 seconds) to be refused. Tests shorten the limits and the clock.
|
|
104
106
|
*/
|
|
105
|
-
drain?: Omit<DrainOptions, "busy"
|
|
107
|
+
drain?: Omit<DrainOptions, "busy"> & { refuseWaitingMs?: number };
|
|
106
108
|
/** What `listen()` calls with the shutdown's exit code; the process's own exit by default. */
|
|
107
109
|
exit?: (code: number) => void;
|
|
108
110
|
}
|
|
@@ -110,6 +112,20 @@ export interface RoundtableOptions {
|
|
|
110
112
|
/** The host running in this process; the text catalog, time zone and environment are process-wide. */
|
|
111
113
|
let running: Roundtable | undefined;
|
|
112
114
|
|
|
115
|
+
/** `work`, or a rejection once `ms` pass; the timer never keeps the process alive. */
|
|
116
|
+
async function withinMs<T>(ms: number, work: Promise<T> | T): Promise<T> {
|
|
117
|
+
let timer: ReturnType<typeof setTimeout> | undefined;
|
|
118
|
+
const late = new Promise<never>((_, reject) => {
|
|
119
|
+
timer = setTimeout(() => reject(new Error(`not done in ${ms} ms`)), ms);
|
|
120
|
+
timer.unref?.();
|
|
121
|
+
});
|
|
122
|
+
try {
|
|
123
|
+
return await Promise.race([work, late]);
|
|
124
|
+
} finally {
|
|
125
|
+
clearTimeout(timer);
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
|
|
113
129
|
/**
|
|
114
130
|
* The process around the plugins: it sets them all up, links what they add (session parts,
|
|
115
131
|
* HTTP routes) and runs the preflight, then starts their services in order and the
|
|
@@ -305,6 +321,23 @@ export class Roundtable {
|
|
|
305
321
|
});
|
|
306
322
|
// Only what ran before the drain ended finishes; nothing delivered later starts.
|
|
307
323
|
this.#link.queue.seal();
|
|
324
|
+
// A message still waiting behind a turn never starts: its channel is told while the services run.
|
|
325
|
+
// Counted as it goes, and told to start no more once the limit passes.
|
|
326
|
+
const tally = { refused: 0, failed: 0, stopped: false };
|
|
327
|
+
const told = await attempt(() =>
|
|
328
|
+
withinMs(
|
|
329
|
+
drain?.refuseWaitingMs ?? REFUSE_WAITING_MS,
|
|
330
|
+
this.#link.router?.refuseWaiting(tally),
|
|
331
|
+
),
|
|
332
|
+
);
|
|
333
|
+
tally.stopped = true;
|
|
334
|
+
if (!told.ok || tally.failed > 0)
|
|
335
|
+
logger.error(
|
|
336
|
+
{ err: told.ok ? undefined : told.error, ...tally },
|
|
337
|
+
"not every waiting message was refused; the rest are not answered",
|
|
338
|
+
);
|
|
339
|
+
else if (tally.refused > 0)
|
|
340
|
+
logger.info({ refused: tally.refused }, "waiting messages refused");
|
|
308
341
|
// A turn that started during the abort grace, a report's, is stopped too, so the teardown does not wait for it.
|
|
309
342
|
if (left.length > 0) stopQueuedTurns();
|
|
310
343
|
if (left.length > 0) {
|
|
@@ -14,6 +14,7 @@ export function conversationEn(ctx: CatalogContext) {
|
|
|
14
14
|
"Sorry, this reply did not go through. Please try again later.",
|
|
15
15
|
stoppedNotice: "-# Stopped.",
|
|
16
16
|
restartingNotice: `-# ${ctx.assistant} is restarting and takes no new messages right now; please send this again in a few minutes.`,
|
|
17
|
+
restartingAnswerLater: `-# ${ctx.assistant} is restarting; it will answer this once it is back, so there is no need to send it again.`,
|
|
17
18
|
roundLimitNotice:
|
|
18
19
|
"-# This round already has 8 replies, so it stops here; call us again if you need more.",
|
|
19
20
|
roundStoppedNotice:
|
|
@@ -55,6 +56,7 @@ export function conversationZhTW(
|
|
|
55
56
|
failureNotice: "抱歉,這次沒能完成回覆,請稍後再試一次。",
|
|
56
57
|
stoppedNotice: "-# 已停止。",
|
|
57
58
|
restartingNotice: `-# ${ctx.assistant} 正在重新啟動,暫時不接新訊息;請過幾分鐘再傳一次。`,
|
|
59
|
+
restartingAnswerLater: `-# ${ctx.assistant} 正在重新啟動,回來後會回覆這則訊息,不用再傳一次。`,
|
|
58
60
|
roundLimitNotice:
|
|
59
61
|
"-# 這一輪已經有 8 則回覆,先停在這裡;需要的話請再叫我們。",
|
|
60
62
|
roundStoppedNotice: "-# 本輪已停止,還沒輪到的成員不再發言。",
|