pi-roundtable 0.52.0 → 0.52.1
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 +11 -0
- package/docs/plugins.md +17 -5
- package/package.json +1 -1
- package/src/core/builtin/discord.ts +20 -35
- package/src/core/contract/surface.ts +7 -0
- package/src/core/discord/catch-up-gate.ts +207 -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/host.ts +31 -0
- package/src/core/i18n/conversation.ts +2 -0
- package/src/core/routing/channel-router.ts +27 -8
- package/src/core/routing/queued-messages.ts +33 -0
package/CHANGELOG.md
CHANGED
|
@@ -5,6 +5,17 @@ The format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).
|
|
|
5
5
|
|
|
6
6
|
## [Unreleased]
|
|
7
7
|
|
|
8
|
+
## [0.52.1] - 2026-11-17
|
|
9
|
+
|
|
10
|
+
### Fixed
|
|
11
|
+
|
|
12
|
+
- `discord.catchUp`: a message addressed to the bot that the old process does not run as it shuts down, whether it arrives during the shutdown or waits behind a running turn, is no longer refused with "please send this again". It is recorded as left in the journal (new migration `discord-inbound-journal-left`), and the channel is told once that the message will be answered after the restart. The next process answers it whatever was posted in the channel since, if it starts within a day. Restart notices are recorded, so catch-up does not take one for an answer. A process that loses a claim to another tries once more two seconds later, and delivers what it then takes marked `caughtUp`. A message still waiting behind a turn when the drain ends is now refused before the services stop, so its channel is told (and, with catch-up, it is left for the next process) instead of nothing. A chat surface takes such a message through the new optional `ChatSurface.refuseStopping`.
|
|
13
|
+
- `discord.catchUp`: when the member fetch for a caught-up message fails for any reason other than the author having left (Discord code 10007), catch-up skips the message without recording it, so a later restart can retry it. Before this fix, the message was answered without the author's roles and was never retried.
|
|
14
|
+
- `discord.catchUp`: a message the live connection delivered without a record, because the database was down at startup, is not caught up a second time by the same process.
|
|
15
|
+
- `discord.catchUp`: the inbound journal is pruned to 30 days every six hours while the host runs, not only at restart. The docs now say what happens when `catchUp` is turned off later.
|
|
16
|
+
- `discord.catchUp`: a mention that has a thread started from it, or a reaction from the bot, counts as answered. Before this fix, the first restart after catch-up was enabled re-delivered mentions answered in a thread, and the bot then posted a false "could not open a thread" notice.
|
|
17
|
+
- `discord.catchUp`: caught-up messages reach routing before the newer live messages in the same channel. A live message waits until catch-up has listed the channels it may read (one database query). In one of those channels, it also waits until catch-up is done.
|
|
18
|
+
|
|
8
19
|
## [0.52.0] - 2026-11-17
|
|
9
20
|
|
|
10
21
|
### Added
|
package/docs/plugins.md
CHANGED
|
@@ -2943,9 +2943,10 @@ Once every service has started, the Discord plugin reads the channels where some
|
|
|
2943
2943
|
It reads the server text channels, live threads and forum posts the bot can read, which it picks from the client's cache without a request, and the direct-message channels that brought the bot a message in the last 30 days.
|
|
2944
2944
|
It looks into at most the 25 direct-message channels that brought a message most recently, one request each, and reads at most 50 channels, one page of 100 messages each, before the ready time; Discord's rate limits pace the requests.
|
|
2945
2945
|
A message counts when a person wrote it (not a bot, a webhook or Discord itself) to the bot: a mention, a reply to one of the bot's messages, or a direct message.
|
|
2946
|
-
It is left alone when it is older than the window, when the bot or one of its own webhooks posted in that channel after it,
|
|
2946
|
+
It is left alone when it is older than the window, when it was already taken in, or when it shows an answer: the bot or one of its own webhooks posted in that channel after it, a thread was started from it (by anyone, as the bot answers a mention in a thread), or the bot reacted to it.
|
|
2947
|
+
The thread and the reaction matter at the first restart after `catchUp` is turned on, when nothing was recorded yet; a mention a person started a thread from is therefore not answered, since one missed answer is preferred to two.
|
|
2947
2948
|
Of what is left, the newest `maxMessages` (default 20, at most 100) go to routing oldest first.
|
|
2948
|
-
They go once every service has started
|
|
2949
|
+
They go once every service has started; a live message that came after the connection became ready waits until catch-up has listed the channels it may read (one database query, before any request), and, in one of those, until catch-up is done, so the caught-up messages of a channel reach routing before its newer live ones.
|
|
2949
2950
|
Each one passes through the same claims, identity resolution and gates as a live message, with `InboundMessage.caughtUp` set, so a claim may say its answer comes late, for example that the assistant just restarted.
|
|
2950
2951
|
The log carries only counts and ids, never text.
|
|
2951
2952
|
|
|
@@ -2953,9 +2954,20 @@ Nothing is answered twice.
|
|
|
2953
2954
|
With catch-up on, every addressed message is recorded in the `discord_inbound_journal` table before routing hears it: by the live connection as it arrives, or by catch-up before it hands the message on.
|
|
2954
2955
|
Whichever records a message first delivers it; the other drops it, so a second restart, or a message the gateway delivers while catch-up runs, is not answered again.
|
|
2955
2956
|
A message that catch-up cannot record is skipped, and a crash after the record but before the turn leaves it unanswered: one missed answer is preferred to two.
|
|
2956
|
-
The live connection still delivers a message it cannot record, such as while the database is down, and logs it;
|
|
2957
|
-
|
|
2958
|
-
|
|
2957
|
+
The live connection still delivers a message it cannot record, such as while the database is down, and logs it; catch-up in the same process leaves it alone, so only a later restart that finds no answer to it in its channel could answer it again.
|
|
2958
|
+
Catch-up reads the author of a server message as a member first; when that fails for any reason but the author having left the server, the message is skipped unrecorded, so a later restart may still answer it with the author's roles.
|
|
2959
|
+
Once the old process begins to shut down it runs no new turn, and an addressed message it has not started, whether it arrives then or already waits behind a running turn, is recorded as left (a `left_at` time in the journal), and its channel is told once that the message will be answered after the restart.
|
|
2960
|
+
The next process answers each message left within the last day first, whatever was posted in its channel since and whatever `windowMinutes`, the page and `maxMessages` say, and takes it from the journal as it does, so it is answered once.
|
|
2961
|
+
A message still waiting behind a turn that outlives the drain is refused, and so left, once the drain ends and before the services stop, within 15 seconds for all of them; this covers turns whose admission has a `busy` mark, as every turn the core's own claims admit does, while a plugin claim's turn without one is refused only when the turn ahead of it ends, which may be after the process has stopped. A message another process already took in is left alone, with no notice.
|
|
2962
|
+
A message that cannot be recorded as left gets the notice to send it again instead.
|
|
2963
|
+
Any other person's message that routing refuses then tells its channel once to send it again, as without catch-up.
|
|
2964
|
+
The Discord surface does this through the optional `ChatSurface.refuseStopping(message)`, which routing calls for a person's message it refuses while the host stops; a surface a plugin contributes may implement it too, and returns true when it told the channel itself, so routing posts no restart notice.
|
|
2965
|
+
Each notice is recorded in the journal, so the next process does not take it for an answer; a notice that cannot be recorded is deleted again, and when catch-up cannot look the notices up it leaves that channel unread rather than guess.
|
|
2966
|
+
A process that finds a message already recorded by another, as when two processes overlap during a deploy, claims it once more two seconds later, apart from the channel's other messages, so one the other leaves as it begins to shut down is still answered, marked `caughtUp` and after the channel's newer messages; one left later than that is answered by the next process to start, not by the one already running.
|
|
2967
|
+
A person who sends the message again anyway gets both answered, the copy live and the original by catch-up, since nothing tells the two apart.
|
|
2968
|
+
Records are kept 30 days: the plugin forgets older ones every six hours while it runs and once catch-up has run.
|
|
2969
|
+
Turning `catchUp` off later leaves the `discord_inbound_journal` table and its rows as they are, with nothing pruning them; turning it on again finds them and prunes them as usual, or a host may drop the table by hand.
|
|
2970
|
+
The first restart after `catchUp` is turned on has no records from before: a message the old process handled with no post in its channel after it, no thread from it and no reaction, such as one answered by a direct message, may be answered again.
|
|
2959
2971
|
A first direct message sent during the restart is not found, since Discord does not list a bot's direct-message channels.
|
|
2960
2972
|
|
|
2961
2973
|
### Reading a file's bytes: `DISCORD.readAttachment`
|
package/package.json
CHANGED
|
@@ -19,14 +19,9 @@ import {
|
|
|
19
19
|
validReadCap,
|
|
20
20
|
} from "../discord/attachment-read.ts";
|
|
21
21
|
import { CardCopies } from "../discord/card-copies.ts";
|
|
22
|
-
import {
|
|
23
|
-
type CatchUpOptions,
|
|
24
|
-
catchUp,
|
|
25
|
-
catchUpSettings,
|
|
26
|
-
journalGate,
|
|
27
|
-
} from "../discord/catch-up.ts";
|
|
22
|
+
import { type CatchUpOptions, catchUpSettings } from "../discord/catch-up.ts";
|
|
28
23
|
import { PgInboundJournal } from "../discord/catch-up-journal.ts";
|
|
29
|
-
import {
|
|
24
|
+
import { catchUpWiring } from "../discord/catch-up-service.ts";
|
|
30
25
|
import { ChannelContextReader } from "../discord/channel-context.ts";
|
|
31
26
|
import { CommandCollection } from "../discord/command-collection.ts";
|
|
32
27
|
import type { DiscordConnection } from "../discord/connection.ts";
|
|
@@ -226,7 +221,7 @@ export function discordPlugin(options: DiscordOptions): RoundtablePlugin {
|
|
|
226
221
|
return {
|
|
227
222
|
name: "discord",
|
|
228
223
|
provides: [DISCORD],
|
|
229
|
-
...(catchUpWith ? { migrations:
|
|
224
|
+
...(catchUpWith ? { migrations: PgInboundJournal.migrations } : {}),
|
|
230
225
|
preflight: () => {
|
|
231
226
|
// The host has applied its environment by now, so the description is in its language.
|
|
232
227
|
surface?.setCommands(
|
|
@@ -246,8 +241,19 @@ export function discordPlugin(options: DiscordOptions): RoundtablePlugin {
|
|
|
246
241
|
const journal = catchUpWith
|
|
247
242
|
? PgInboundJournal.attach(database())
|
|
248
243
|
: undefined;
|
|
249
|
-
//
|
|
250
|
-
|
|
244
|
+
// The journal's gate and the catch-up service, over the surface's client once it connects.
|
|
245
|
+
const caughtUp =
|
|
246
|
+
journal && catchUpWith
|
|
247
|
+
? catchUpWiring({
|
|
248
|
+
journal,
|
|
249
|
+
settings: catchUpWith,
|
|
250
|
+
logger,
|
|
251
|
+
client: () => connected.client(),
|
|
252
|
+
deliver: (message) => {
|
|
253
|
+
void conversations.handle(message);
|
|
254
|
+
},
|
|
255
|
+
})
|
|
256
|
+
: undefined;
|
|
251
257
|
// A host that keeps no copy texts on disk drops what an earlier run left.
|
|
252
258
|
if (options.cardCopies === false)
|
|
253
259
|
for (const name of ["card-copies.json", "intercom-texts.json"]) {
|
|
@@ -302,9 +308,10 @@ export function discordPlugin(options: DiscordOptions): RoundtablePlugin {
|
|
|
302
308
|
: { formatting: options.formatting }),
|
|
303
309
|
...(options.memberEvents ? { memberEvents: true } : {}),
|
|
304
310
|
...(options.voice ? { voice: true } : {}),
|
|
305
|
-
...(
|
|
311
|
+
...(caughtUp
|
|
306
312
|
? {
|
|
307
|
-
inboundGate:
|
|
313
|
+
inboundGate: caughtUp.gate,
|
|
314
|
+
refuseStopping: caughtUp.refused,
|
|
308
315
|
}
|
|
309
316
|
: {}),
|
|
310
317
|
});
|
|
@@ -427,29 +434,7 @@ export function discordPlugin(options: DiscordOptions): RoundtablePlugin {
|
|
|
427
434
|
await intercomTexts.stop();
|
|
428
435
|
},
|
|
429
436
|
},
|
|
430
|
-
|
|
431
|
-
...(journal && catchUpWith
|
|
432
|
-
? [
|
|
433
|
-
{
|
|
434
|
-
name: "discord-catch-up",
|
|
435
|
-
startInBackground: async () => {
|
|
436
|
-
await catchUp({
|
|
437
|
-
reader: clientCatchUpReader(connected.client()),
|
|
438
|
-
journal,
|
|
439
|
-
deliver: (message) => {
|
|
440
|
-
void conversations.handle(message);
|
|
441
|
-
},
|
|
442
|
-
settings: catchUpWith,
|
|
443
|
-
logger,
|
|
444
|
-
stopping: () => draining,
|
|
445
|
-
});
|
|
446
|
-
},
|
|
447
|
-
beginDrain: () => {
|
|
448
|
-
draining = true;
|
|
449
|
-
},
|
|
450
|
-
},
|
|
451
|
-
]
|
|
452
|
-
: []),
|
|
437
|
+
...(caughtUp ? [caughtUp.service] : []),
|
|
453
438
|
// Fails the start when the voice packages cannot be loaded; ends every session as the host stops.
|
|
454
439
|
...(voice
|
|
455
440
|
? [
|
|
@@ -179,6 +179,13 @@ export interface ChatSurface {
|
|
|
179
179
|
): Promise<void>;
|
|
180
180
|
/** Runs when the host stops, after the services started later have stopped. */
|
|
181
181
|
stop?(): Promise<void>;
|
|
182
|
+
/**
|
|
183
|
+
* A person's message routing does not run because the host is shutting down: the surface may
|
|
184
|
+
* take care of it, for example leave it for the next process to answer, and tell its channel
|
|
185
|
+
* itself. True = it did, and routing posts no restart notice. Absent, false, or a rejection
|
|
186
|
+
* (logged) = routing tells the channel once to send it again.
|
|
187
|
+
*/
|
|
188
|
+
refuseStopping?(message: InboundMessage): Promise<boolean>;
|
|
182
189
|
sendReply(channel: ChannelKey, reply: OutboundReply): Promise<void>;
|
|
183
190
|
/** Shows a typing indicator until the returned function is called; absent = none shown. */
|
|
184
191
|
startTyping?(channel: ChannelKey): () => void;
|
|
@@ -0,0 +1,207 @@
|
|
|
1
|
+
import type { InboundMessage } from "../contract/channels.ts";
|
|
2
|
+
import type { Logger } from "../kernel/log.ts";
|
|
3
|
+
import { addressed } from "./catch-up.ts";
|
|
4
|
+
import type { InboundJournal } from "./catch-up-journal.ts";
|
|
5
|
+
|
|
6
|
+
/** Which restart notice a channel is told: that its message is answered after the restart, or that it should be sent again. */
|
|
7
|
+
export type NoticeKind = "later" | "resend";
|
|
8
|
+
|
|
9
|
+
/** A notice posted in a channel. */
|
|
10
|
+
export interface PostedNotice {
|
|
11
|
+
id: string;
|
|
12
|
+
/** Deletes it again. */
|
|
13
|
+
retract(): Promise<void>;
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
/** What the live gateway's journal gate works with. */
|
|
17
|
+
export interface GateOptions {
|
|
18
|
+
journal: InboundJournal;
|
|
19
|
+
logger: Logger;
|
|
20
|
+
/** True once the host shuts down: from then on routing refuses what it hears. */
|
|
21
|
+
draining?: () => boolean;
|
|
22
|
+
/** Posts a restart notice in a channel. */
|
|
23
|
+
notify?: (channelId: string, kind: NoticeKind) => Promise<PostedNotice>;
|
|
24
|
+
/** Waits, once a message is recorded, until it may reach routing after the caught-up messages of its channel. */
|
|
25
|
+
wait?: (channelId: string) => Promise<void>;
|
|
26
|
+
/** The ids of messages delivered without a record, which catch-up in this process leaves alone. */
|
|
27
|
+
unrecorded?: Pick<Set<string>, "add">;
|
|
28
|
+
/**
|
|
29
|
+
* How long a message another process recorded first is given before it is claimed once more,
|
|
30
|
+
* since a process that begins to shut down leaves what it recorded. Default 2000; 0 = never.
|
|
31
|
+
*/
|
|
32
|
+
retryMs?: number;
|
|
33
|
+
/** Hands a message the retry claimed to routing; without it there is no retry. */
|
|
34
|
+
redeliver?: (message: InboundMessage) => void;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/** The gate: whether a live message reaches routing, and `refused`, for one routing refuses as the host stops. */
|
|
38
|
+
export type JournalGate = ((
|
|
39
|
+
message: InboundMessage,
|
|
40
|
+
botId: string,
|
|
41
|
+
) => Promise<boolean>) & {
|
|
42
|
+
/** Takes care of a message routing refuses because the host stops; true when it did, so routing posts nothing. */
|
|
43
|
+
refused(message: InboundMessage, botId: string): Promise<boolean>;
|
|
44
|
+
};
|
|
45
|
+
|
|
46
|
+
const DEFAULT_RETRY_MS = 2000;
|
|
47
|
+
|
|
48
|
+
/**
|
|
49
|
+
* Records each addressed message the live gateway delivers before routing hears it, so catch-up
|
|
50
|
+
* after a restart leaves it alone; false for one already recorded, which is not delivered again.
|
|
51
|
+
* A message that cannot be recorded is still delivered, logged, and kept in `unrecorded`.
|
|
52
|
+
* Once the host drains, an addressed message that has not run is recorded as left, and the next
|
|
53
|
+
* process answers it whatever its channel shows since; its channel is told so once. Any other message
|
|
54
|
+
* routing refuses then tells its channel once to send it again. Each notice is recorded, so
|
|
55
|
+
* catch-up does not take it for an answer, and deleted again when it cannot be.
|
|
56
|
+
*/
|
|
57
|
+
export function journalGate({
|
|
58
|
+
journal,
|
|
59
|
+
logger,
|
|
60
|
+
draining = () => false,
|
|
61
|
+
notify,
|
|
62
|
+
wait,
|
|
63
|
+
unrecorded,
|
|
64
|
+
retryMs = DEFAULT_RETRY_MS,
|
|
65
|
+
redeliver,
|
|
66
|
+
}: GateOptions): JournalGate {
|
|
67
|
+
const told = { later: new Set<string>(), resend: new Set<string>() };
|
|
68
|
+
const channelOf = (message: InboundMessage) =>
|
|
69
|
+
message.channel.slice("discord:".length);
|
|
70
|
+
const tell = async (
|
|
71
|
+
kind: NoticeKind,
|
|
72
|
+
message: InboundMessage,
|
|
73
|
+
botId: string,
|
|
74
|
+
) => {
|
|
75
|
+
const channelId = channelOf(message);
|
|
76
|
+
if (!notify || told[kind].has(channelId)) return;
|
|
77
|
+
told[kind].add(channelId);
|
|
78
|
+
let notice: PostedNotice;
|
|
79
|
+
try {
|
|
80
|
+
notice = await notify(channelId, kind);
|
|
81
|
+
} catch (error) {
|
|
82
|
+
logger.warn({ channelId, err: error }, "restart notice not posted");
|
|
83
|
+
return;
|
|
84
|
+
}
|
|
85
|
+
try {
|
|
86
|
+
await journal.claim({
|
|
87
|
+
botId,
|
|
88
|
+
messageId: notice.id,
|
|
89
|
+
channelId,
|
|
90
|
+
direct: message.isDirect,
|
|
91
|
+
});
|
|
92
|
+
} catch (error) {
|
|
93
|
+
// Unrecorded, catch-up would take it for an answer.
|
|
94
|
+
logger.warn(
|
|
95
|
+
{ channelId, err: error },
|
|
96
|
+
"restart notice not recorded; deleting it",
|
|
97
|
+
);
|
|
98
|
+
await notice
|
|
99
|
+
.retract()
|
|
100
|
+
.catch((retractError: unknown) =>
|
|
101
|
+
logger.warn(
|
|
102
|
+
{ channelId, err: retractError },
|
|
103
|
+
"unrecorded restart notice not deleted",
|
|
104
|
+
),
|
|
105
|
+
);
|
|
106
|
+
}
|
|
107
|
+
};
|
|
108
|
+
const entry = (message: InboundMessage, botId: string) => ({
|
|
109
|
+
botId,
|
|
110
|
+
messageId: message.messageId,
|
|
111
|
+
channelId: channelOf(message),
|
|
112
|
+
direct: message.isDirect,
|
|
113
|
+
});
|
|
114
|
+
// Left in the journal, the next process answers it whatever its channel shows; unrecorded, the channel is told to send it again.
|
|
115
|
+
const leave = async (
|
|
116
|
+
message: InboundMessage,
|
|
117
|
+
botId: string,
|
|
118
|
+
taken = true,
|
|
119
|
+
) => {
|
|
120
|
+
const where = {
|
|
121
|
+
channelId: channelOf(message),
|
|
122
|
+
messageId: message.messageId,
|
|
123
|
+
};
|
|
124
|
+
try {
|
|
125
|
+
if (taken) await journal.leave(entry(message, botId));
|
|
126
|
+
else if (!(await journal.leaveNew(entry(message, botId)))) {
|
|
127
|
+
// Another process took it in, and answers it.
|
|
128
|
+
logger.info(
|
|
129
|
+
where,
|
|
130
|
+
"shutting down; another process took this message in",
|
|
131
|
+
);
|
|
132
|
+
return;
|
|
133
|
+
}
|
|
134
|
+
} catch (error) {
|
|
135
|
+
logger.warn(
|
|
136
|
+
{ ...where, err: error },
|
|
137
|
+
"could not leave a message for the next process; its channel is told to send it again",
|
|
138
|
+
);
|
|
139
|
+
await tell("resend", message, botId);
|
|
140
|
+
return;
|
|
141
|
+
}
|
|
142
|
+
logger.info(where, "shutting down; the next process answers this message");
|
|
143
|
+
await tell("later", message, botId);
|
|
144
|
+
};
|
|
145
|
+
// Off the channel's chain: a process that begins to stop leaves what it recorded, and this one then takes it.
|
|
146
|
+
const retry = (message: InboundMessage, botId: string) => {
|
|
147
|
+
if (!redeliver || retryMs <= 0) return;
|
|
148
|
+
const timer = setTimeout(async () => {
|
|
149
|
+
if (draining()) return;
|
|
150
|
+
let first = false;
|
|
151
|
+
try {
|
|
152
|
+
first = await journal.claim(entry(message, botId));
|
|
153
|
+
if (!first) return;
|
|
154
|
+
await wait?.(channelOf(message));
|
|
155
|
+
// Late, and after newer messages of its channel.
|
|
156
|
+
redeliver({ ...message, caughtUp: true });
|
|
157
|
+
} catch (error) {
|
|
158
|
+
logger.warn(
|
|
159
|
+
{ messageId: message.messageId, err: error },
|
|
160
|
+
"could not claim or deliver a message again",
|
|
161
|
+
);
|
|
162
|
+
// Taken but not delivered: left, a later process answers it.
|
|
163
|
+
if (first)
|
|
164
|
+
await journal.leave(entry(message, botId)).catch(() => undefined);
|
|
165
|
+
}
|
|
166
|
+
}, retryMs);
|
|
167
|
+
timer.unref?.();
|
|
168
|
+
};
|
|
169
|
+
const pass = async (message: InboundMessage, botId: string) => {
|
|
170
|
+
if (!addressed(message)) return true;
|
|
171
|
+
if (draining()) {
|
|
172
|
+
await leave(message, botId, false);
|
|
173
|
+
return false;
|
|
174
|
+
}
|
|
175
|
+
const channelId = channelOf(message);
|
|
176
|
+
const { messageId } = message;
|
|
177
|
+
try {
|
|
178
|
+
if (!(await journal.claim(entry(message, botId)))) {
|
|
179
|
+
logger.info(
|
|
180
|
+
{ channelId, messageId },
|
|
181
|
+
"message already taken in; not delivered again",
|
|
182
|
+
);
|
|
183
|
+
retry(message, botId);
|
|
184
|
+
return false;
|
|
185
|
+
}
|
|
186
|
+
await wait?.(channelId);
|
|
187
|
+
if (!draining()) return true;
|
|
188
|
+
// The drain began while it was recorded: routing would refuse it, so the next process takes it.
|
|
189
|
+
await leave(message, botId);
|
|
190
|
+
return false;
|
|
191
|
+
} catch (error) {
|
|
192
|
+
unrecorded?.add(messageId);
|
|
193
|
+
logger.warn(
|
|
194
|
+
{ channelId, messageId, err: error },
|
|
195
|
+
"could not record an addressed message; delivered anyway",
|
|
196
|
+
);
|
|
197
|
+
return true;
|
|
198
|
+
}
|
|
199
|
+
};
|
|
200
|
+
const refused = async (message: InboundMessage, botId: string) => {
|
|
201
|
+
if (!notify || message.authorIsBot || message.integration) return false;
|
|
202
|
+
if (addressed(message)) await leave(message, botId);
|
|
203
|
+
else await tell("resend", message, botId);
|
|
204
|
+
return true;
|
|
205
|
+
};
|
|
206
|
+
return Object.assign(pass, { refused });
|
|
207
|
+
}
|
|
@@ -16,10 +16,22 @@ export interface JournalEntry {
|
|
|
16
16
|
* message first, the live gateway or catch-up after a restart, is the only one that delivers it.
|
|
17
17
|
*/
|
|
18
18
|
export interface InboundJournal {
|
|
19
|
-
/** Records the message as taken in; false when it
|
|
19
|
+
/** Records the message as taken in, or takes one a stopping process left; false when it is taken. */
|
|
20
20
|
claim(entry: JournalEntry): Promise<boolean>;
|
|
21
21
|
/** The bot's direct-message channels with a message recorded since `since`, the most recent first. */
|
|
22
22
|
directChannels(botId: string, since: Date, limit: number): Promise<string[]>;
|
|
23
|
+
/** Records a message this process took in as left, as it stops before running it, for the next process to take. */
|
|
24
|
+
leave(entry: JournalEntry): Promise<void>;
|
|
25
|
+
/** Records a message no one took in yet as left; false when someone did, and it is theirs. */
|
|
26
|
+
leaveNew(entry: JournalEntry): Promise<boolean>;
|
|
27
|
+
/** The messages left since `since`, the oldest first. */
|
|
28
|
+
left(botId: string, since: Date): Promise<JournalEntry[]>;
|
|
29
|
+
/**
|
|
30
|
+
* Which of the bot's own messages `ids` are recorded: the notices it posted while it shut down,
|
|
31
|
+
* which say a message will be answered after the restart rather than answer it. No other message
|
|
32
|
+
* of the bot's is recorded, since only a person's is ever taken in.
|
|
33
|
+
*/
|
|
34
|
+
recordedAmong(botId: string, ids: string[]): Promise<Set<string>>;
|
|
23
35
|
/** Forgets what was recorded before `before`. */
|
|
24
36
|
prune(before: Date): Promise<void>;
|
|
25
37
|
}
|
|
@@ -46,18 +58,58 @@ const migration: Migration = {
|
|
|
46
58
|
* The journal over the host's pool, built from closures rather than private fields, so a test
|
|
47
59
|
* proxy can carry it. One insert that does nothing on a conflict decides who records a message.
|
|
48
60
|
*/
|
|
61
|
+
/** Marks a message left by a stopping process, so the next one answers it whatever the channel shows. */
|
|
62
|
+
const leftMigration: Migration = {
|
|
63
|
+
name: "discord-inbound-journal-left",
|
|
64
|
+
up: async (sql) => {
|
|
65
|
+
await sql`
|
|
66
|
+
ALTER TABLE discord_inbound_journal ADD COLUMN IF NOT EXISTS left_at timestamptz`;
|
|
67
|
+
},
|
|
68
|
+
};
|
|
69
|
+
|
|
49
70
|
export const PgInboundJournal = {
|
|
50
|
-
migration,
|
|
71
|
+
migrations: [migration, leftMigration],
|
|
51
72
|
attach(sql: SQL): InboundJournal {
|
|
52
73
|
return {
|
|
53
74
|
async claim({ botId, messageId, channelId, direct }) {
|
|
54
75
|
const rows: unknown[] = await sql`
|
|
55
76
|
INSERT INTO discord_inbound_journal (bot_id, message_id, channel_id, direct)
|
|
56
77
|
VALUES (${botId}, ${messageId}, ${channelId}, ${direct})
|
|
78
|
+
ON CONFLICT (bot_id, message_id) DO UPDATE SET left_at = NULL
|
|
79
|
+
WHERE discord_inbound_journal.left_at IS NOT NULL
|
|
80
|
+
RETURNING message_id`;
|
|
81
|
+
return rows.length > 0;
|
|
82
|
+
},
|
|
83
|
+
async leave({ botId, messageId, channelId, direct }) {
|
|
84
|
+
await sql`
|
|
85
|
+
INSERT INTO discord_inbound_journal (bot_id, message_id, channel_id, direct, left_at)
|
|
86
|
+
VALUES (${botId}, ${messageId}, ${channelId}, ${direct}, now())
|
|
87
|
+
ON CONFLICT (bot_id, message_id) DO UPDATE SET left_at = now()`;
|
|
88
|
+
},
|
|
89
|
+
async leaveNew({ botId, messageId, channelId, direct }) {
|
|
90
|
+
const rows: unknown[] = await sql`
|
|
91
|
+
INSERT INTO discord_inbound_journal (bot_id, message_id, channel_id, direct, left_at)
|
|
92
|
+
VALUES (${botId}, ${messageId}, ${channelId}, ${direct}, now())
|
|
57
93
|
ON CONFLICT (bot_id, message_id) DO NOTHING
|
|
58
94
|
RETURNING message_id`;
|
|
59
95
|
return rows.length > 0;
|
|
60
96
|
},
|
|
97
|
+
async left(botId, since) {
|
|
98
|
+
const rows: {
|
|
99
|
+
message_id: string;
|
|
100
|
+
channel_id: string;
|
|
101
|
+
direct: boolean;
|
|
102
|
+
}[] = await sql`
|
|
103
|
+
SELECT message_id, channel_id, direct FROM discord_inbound_journal
|
|
104
|
+
WHERE bot_id = ${botId} AND left_at >= ${since}
|
|
105
|
+
ORDER BY left_at`;
|
|
106
|
+
return rows.map((row) => ({
|
|
107
|
+
botId,
|
|
108
|
+
messageId: row.message_id,
|
|
109
|
+
channelId: row.channel_id,
|
|
110
|
+
direct: row.direct,
|
|
111
|
+
}));
|
|
112
|
+
},
|
|
61
113
|
async directChannels(botId, since, limit) {
|
|
62
114
|
const rows: { channel_id: string }[] = await sql`
|
|
63
115
|
SELECT channel_id FROM discord_inbound_journal
|
|
@@ -67,6 +119,13 @@ export const PgInboundJournal = {
|
|
|
67
119
|
LIMIT ${limit}`;
|
|
68
120
|
return rows.map((row) => row.channel_id);
|
|
69
121
|
},
|
|
122
|
+
async recordedAmong(botId, ids) {
|
|
123
|
+
if (ids.length === 0) return new Set();
|
|
124
|
+
const rows: { message_id: string }[] = await sql`
|
|
125
|
+
SELECT message_id FROM discord_inbound_journal
|
|
126
|
+
WHERE bot_id = ${botId} AND message_id IN ${sql(ids)}`;
|
|
127
|
+
return new Set(rows.map((row) => row.message_id));
|
|
128
|
+
},
|
|
70
129
|
async prune(before) {
|
|
71
130
|
await sql`DELETE FROM discord_inbound_journal WHERE recorded_at < ${before}`;
|
|
72
131
|
},
|
|
@@ -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,
|
package/src/core/host/host.ts
CHANGED
|
@@ -110,6 +110,23 @@ export interface RoundtableOptions {
|
|
|
110
110
|
/** The host running in this process; the text catalog, time zone and environment are process-wide. */
|
|
111
111
|
let running: Roundtable | undefined;
|
|
112
112
|
|
|
113
|
+
/** How long the messages still waiting after the drain are given to be refused, before the teardown. */
|
|
114
|
+
const REFUSE_WAITING_MS = 15_000;
|
|
115
|
+
|
|
116
|
+
/** `work`, or a rejection once `ms` pass; the timer never keeps the process alive. */
|
|
117
|
+
async function withinMs<T>(ms: number, work: Promise<T> | T): Promise<T> {
|
|
118
|
+
let timer: ReturnType<typeof setTimeout> | undefined;
|
|
119
|
+
const late = new Promise<never>((_, reject) => {
|
|
120
|
+
timer = setTimeout(() => reject(new Error(`not done in ${ms} ms`)), ms);
|
|
121
|
+
timer.unref?.();
|
|
122
|
+
});
|
|
123
|
+
try {
|
|
124
|
+
return await Promise.race([work, late]);
|
|
125
|
+
} finally {
|
|
126
|
+
clearTimeout(timer);
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
|
|
113
130
|
/**
|
|
114
131
|
* The process around the plugins: it sets them all up, links what they add (session parts,
|
|
115
132
|
* HTTP routes) and runs the preflight, then starts their services in order and the
|
|
@@ -305,6 +322,20 @@ export class Roundtable {
|
|
|
305
322
|
});
|
|
306
323
|
// Only what ran before the drain ended finishes; nothing delivered later starts.
|
|
307
324
|
this.#link.queue.seal();
|
|
325
|
+
// A message still waiting behind a turn never starts: its channel is told while the services run.
|
|
326
|
+
// Counted as it goes, and told to start no more once the limit passes.
|
|
327
|
+
const tally = { refused: 0, failed: 0, stopped: false };
|
|
328
|
+
const told = await attempt(() =>
|
|
329
|
+
withinMs(REFUSE_WAITING_MS, this.#link.router?.refuseWaiting(tally)),
|
|
330
|
+
);
|
|
331
|
+
tally.stopped = true;
|
|
332
|
+
if (!told.ok || tally.failed > 0)
|
|
333
|
+
logger.error(
|
|
334
|
+
{ err: told.ok ? undefined : told.error, ...tally },
|
|
335
|
+
"not every waiting message was refused; the rest are not answered",
|
|
336
|
+
);
|
|
337
|
+
else if (tally.refused > 0)
|
|
338
|
+
logger.info({ refused: tally.refused }, "waiting messages refused");
|
|
308
339
|
// A turn that started during the abort grace, a report's, is stopped too, so the teardown does not wait for it.
|
|
309
340
|
if (left.length > 0) stopQueuedTurns();
|
|
310
341
|
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: "-# 本輪已停止,還沒輪到的成員不再發言。",
|
|
@@ -27,7 +27,11 @@ import { tellDeleted, tellEdited } from "./claim-events.ts";
|
|
|
27
27
|
import { ForwardJoin } from "./forward-join.ts";
|
|
28
28
|
import type { MessageObservers } from "./message-observers.ts";
|
|
29
29
|
import { type PeerBots, peerFacts } from "./peer-bots.ts";
|
|
30
|
-
import {
|
|
30
|
+
import {
|
|
31
|
+
type QueuedEntry,
|
|
32
|
+
QueuedMessages,
|
|
33
|
+
type RefuseTally,
|
|
34
|
+
} from "./queued-messages.ts";
|
|
31
35
|
|
|
32
36
|
export interface ChannelRouterOptions {
|
|
33
37
|
/** Claims in registration order; the router orders them by priority. */
|
|
@@ -248,16 +252,23 @@ export class ChannelRouter implements ConversationPort {
|
|
|
248
252
|
reason: new HostStoppingError().message,
|
|
249
253
|
});
|
|
250
254
|
logger.info({ channel }, "message not run: the host is shutting down");
|
|
251
|
-
if (message.authorIsBot || message.integration
|
|
252
|
-
return;
|
|
253
|
-
this.#told.add(channel);
|
|
255
|
+
if (message.authorIsBot || message.integration) return;
|
|
254
256
|
try {
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
});
|
|
257
|
+
// The surface may take it, and tell its channel itself.
|
|
258
|
+
if (await surfaces?.of(channel)?.refuseStopping?.(message)) return;
|
|
258
259
|
} catch (error) {
|
|
259
|
-
logger.warn(
|
|
260
|
+
logger.warn(
|
|
261
|
+
{ channel, err: error },
|
|
262
|
+
"surface did not take a refused message",
|
|
263
|
+
);
|
|
260
264
|
}
|
|
265
|
+
if (this.#told.has(channel)) return;
|
|
266
|
+
this.#told.add(channel);
|
|
267
|
+
await surfaces
|
|
268
|
+
?.sendReply?.(channel, { chunks: [messages().restartingNotice] })
|
|
269
|
+
.catch((error: unknown) =>
|
|
270
|
+
logger.warn({ channel, err: error }, "restart notice not posted"),
|
|
271
|
+
);
|
|
261
272
|
}
|
|
262
273
|
|
|
263
274
|
/**
|
|
@@ -313,6 +324,14 @@ export class ChannelRouter implements ConversationPort {
|
|
|
313
324
|
return { done };
|
|
314
325
|
}
|
|
315
326
|
|
|
327
|
+
/** Refuses each message still waiting behind a turn after the drain, counting in `tally`. */
|
|
328
|
+
refuseWaiting(tally: RefuseTally): Promise<void> {
|
|
329
|
+
return this.#queued.refuseAll(
|
|
330
|
+
(e) => this.#refuse(e.message, e.admission),
|
|
331
|
+
tally,
|
|
332
|
+
);
|
|
333
|
+
}
|
|
334
|
+
|
|
316
335
|
queued(channel: ChannelKey): readonly QueuedMessage[] {
|
|
317
336
|
return this.#queued.list(channel);
|
|
318
337
|
}
|
|
@@ -29,6 +29,13 @@ export interface QueuedEntry {
|
|
|
29
29
|
* can only reach a message that has not started. Everything is synchronous, so no cancel or edit
|
|
30
30
|
* races the start of a turn: whichever runs first wins.
|
|
31
31
|
*/
|
|
32
|
+
/** How a refusal of every waiting message went, filled in as it goes; set `stopped` to start no more. */
|
|
33
|
+
export interface RefuseTally {
|
|
34
|
+
refused: number;
|
|
35
|
+
failed: number;
|
|
36
|
+
stopped: boolean;
|
|
37
|
+
}
|
|
38
|
+
|
|
32
39
|
export class QueuedMessages {
|
|
33
40
|
readonly #entries = new Map<ChannelKey, Map<string, QueuedEntry>>();
|
|
34
41
|
readonly #logger: Logger;
|
|
@@ -131,6 +138,32 @@ export class QueuedMessages {
|
|
|
131
138
|
return "done";
|
|
132
139
|
}
|
|
133
140
|
|
|
141
|
+
/** Takes every waiting entry off the list and refuses it, the channels in parallel, each in order, until `tally.stopped`. */
|
|
142
|
+
async refuseAll(
|
|
143
|
+
refuse: (entry: QueuedEntry) => Promise<void>,
|
|
144
|
+
tally: RefuseTally,
|
|
145
|
+
): Promise<void> {
|
|
146
|
+
await Promise.all(
|
|
147
|
+
[...this.#entries.values()].map(async (entries) => {
|
|
148
|
+
for (const entry of [...entries.values()]) {
|
|
149
|
+
if (tally.stopped) return;
|
|
150
|
+
if (!this.remove(entry)) continue;
|
|
151
|
+
this.unmark(entry);
|
|
152
|
+
try {
|
|
153
|
+
await refuse(entry);
|
|
154
|
+
tally.refused += 1;
|
|
155
|
+
} catch (error) {
|
|
156
|
+
tally.failed += 1;
|
|
157
|
+
this.#logger.warn(
|
|
158
|
+
{ channel: entry.message.channel, err: error },
|
|
159
|
+
"a waiting message could not be refused",
|
|
160
|
+
);
|
|
161
|
+
}
|
|
162
|
+
}
|
|
163
|
+
}),
|
|
164
|
+
);
|
|
165
|
+
}
|
|
166
|
+
|
|
134
167
|
/** Removes the waiting mark; a failure is logged, since the message may be gone. */
|
|
135
168
|
unmark(entry: QueuedEntry): void {
|
|
136
169
|
const { channel } = entry.message;
|