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
package/CHANGELOG.md
CHANGED
|
@@ -5,6 +5,29 @@ The format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).
|
|
|
5
5
|
|
|
6
6
|
## [Unreleased]
|
|
7
7
|
|
|
8
|
+
## [0.52.2] - 2026-11-17
|
|
9
|
+
|
|
10
|
+
### Added
|
|
11
|
+
|
|
12
|
+
- New config keys `abortGraceSeconds` (default 10, 1 to 600) and `refuseWaitingSeconds` (default 15, 1 to 600), and `drain.refuseWaitingMs` in `RoundtableOptions`: how long a shutdown gives the turns it stops at the drain limit to end, and the messages still waiting behind a turn to be refused. The service manager's kill timeout must be longer than `drainSeconds` + `abortGraceSeconds` + `refuseWaitingSeconds` plus a few seconds of teardown; under a 30-second kill, for example, 12 + 5 + 8 leaves five.
|
|
13
|
+
|
|
14
|
+
### Fixed
|
|
15
|
+
|
|
16
|
+
- `discord.catchUp`: during the shutdown, a message addressed to the bot is promised an answer after the restart, and recorded as left, only when routing refuses it because the host stops, that is when a claim would have answered it. A message in a channel the bot does not serve, or one no claim admits, no longer gets a false "will answer this once back" notice.
|
|
17
|
+
- `discord.catchUp`: a message that arrived during the shutdown and could not be recorded as left no longer gets the "send it again" notice, which together with catch-up answering it from the window could answer it twice; it gets no notice and the next process's catch-up answers it.
|
|
18
|
+
- A message waiting behind a running turn is now refused when the shutdown drain ends whatever claim admitted it. Before, only a message whose claim marks waiting messages (a `busy` admission, as the core's own claims give) was refused then; one waiting behind a plugin claim's turn that ignored its abort was neither answered nor told. Such a message is not listed among the channel's queued messages, as before.
|
|
19
|
+
|
|
20
|
+
## [0.52.1] - 2026-11-17
|
|
21
|
+
|
|
22
|
+
### Fixed
|
|
23
|
+
|
|
24
|
+
- `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`.
|
|
25
|
+
- `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.
|
|
26
|
+
- `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.
|
|
27
|
+
- `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.
|
|
28
|
+
- `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.
|
|
29
|
+
- `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 (two database queries). In one of those channels, it also waits until catch-up is done.
|
|
30
|
+
|
|
8
31
|
## [0.52.0] - 2026-11-17
|
|
9
32
|
|
|
10
33
|
### Added
|
package/README.md
CHANGED
|
@@ -194,6 +194,7 @@ A turn works 10 minutes by default before it asks you whether to go on, and 30 m
|
|
|
194
194
|
| `autonomy.yolo.allow`, `autonomy.yolo.card` | none | Hold classes yolo mode may approve beyond its defaults (`shell.rm`, say), and rule names whose calls it approves although the rule reports no classes (`tool:repo_push`, say), and classes or rule names it never approves (`shell.push`, say). By default yolo approves a plain `git push` and writes outside the workspace and cards the other destructive shell classes; see the [plugin guide](docs/plugins.md#hold-classes-and-yolo-mode) |
|
|
195
195
|
| `autonomy.yolo.questionGraceSeconds` | `30` | In a yolo conversation, how long an `ask_user` card holds the turn, 5 to 600; unanswered, the turn goes on with its own best choice and the card stays open |
|
|
196
196
|
| `autonomy.yolo.timeoutCardSeconds` | `60` | In a yolo conversation, how long the timeout card waits, 10 to 3600; unanswered, the turn goes on as if you pressed Continue, up to `autonomy.longRunning.maxSeconds` |
|
|
197
|
+
| `drainSeconds`, `abortGraceSeconds`, `refuseWaitingSeconds` | `180`, `10`, `15` | On a shutdown, how long running turns get to finish, then how long the ones stopped at that limit get to end, then how long the messages still waiting behind a turn get to be refused; the service manager's stop or kill timeout should be longer than the three together, plus a few seconds for the teardown |
|
|
197
198
|
|
|
198
199
|
Without `discord`, or with `discord` but no `discord.guild`, the agents still run when `agents` lists them, in the rooms of a surface that hosts them, such as pi-roundtable-web; the host refuses to start when none does:
|
|
199
200
|
|
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 (two database queries, 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 that routing refuses for that reason, 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. Routing decides first: a message no claim would answer, such as one in a channel the bot does not serve, is neither left nor promised an answer.
|
|
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 (`refuseWaitingSeconds`); this covers every message waiting behind a turn, whether or not its claim's admission has a `busy` mark. A message another process already took in is left alone, with no notice.
|
|
2962
|
+
A message that cannot be recorded as left gets no notice when it arrived during the shutdown, since it has no record and the next catch-up finds it in its window; one recorded before 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`
|
|
@@ -4410,7 +4422,7 @@ The same host may call `run()` again after that.
|
|
|
4410
4422
|
On `SIGTERM` or `SIGINT` the bot takes no new work at once, finishes what runs, and stops serving last:
|
|
4411
4423
|
|
|
4412
4424
|
1. It stops starting work: the channel queue closes (`context.queue.closed` turns true), and from then on no new turn starts, whoever asks. A message that arrives is not run; its channel gets one short "restarting, try again shortly" reply, except a bot's or an integration's message, which is only logged. A background turn (a schedule's, a delegated task's report, an error report) is skipped, and so is a turn a plugin asks of `context.turns.run`, which rejects with `HostStoppingError`; a task for the queue that has not started, whether queued before or after, is refused with the same error. The scheduler claims nothing, so a due schedule stays due and fires after the next start if it is less than twelve hours late. A turn that is already running finishes. A plugin that starts turns from a timer or a route of its own should check `context.queue.closed` first.
|
|
4413
|
-
2. It waits until the channel queue is empty and no service reports `busy()` work, for at most three minutes by default (`drainSeconds` in the config, up to 14,400, that is four hours; `drain.limitMs` in `RoundtableOptions`). If work is left, it stops each running turn as the owner's stop does and calls `abort()` of each service that still has work, gives them ten seconds (`drain.abortGraceMs`) to end, and goes on; whatever is left is logged and given up on, and a turn still running in the queue after the grace is told to stop once more. Work that ends during the wait delivers its report through `context.queue.finishing`, which the queue admits until the wait is over; the queue is sealed after it.
|
|
4425
|
+
2. It waits until the channel queue is empty and no service reports `busy()` work, for at most three minutes by default (`drainSeconds` in the config, up to 14,400, that is four hours; `drain.limitMs` in `RoundtableOptions`). If work is left, it stops each running turn as the owner's stop does and calls `abort()` of each service that still has work, gives them ten seconds (`abortGraceSeconds` in the config, `drain.abortGraceMs`) to end, and goes on; whatever is left is logged and given up on, and a turn still running in the queue after the grace is told to stop once more. Work that ends during the wait delivers its report through `context.queue.finishing`, which the queue admits until the wait is over; the queue is sealed after it. Messages still waiting behind a turn, whatever claim admitted them, are then refused within 15 seconds (`refuseWaitingSeconds` in the config, `drain.refuseWaitingMs`) before the services stop. The service manager's stop or kill timeout must be longer than `drainSeconds` + `abortGraceSeconds` + `refuseWaitingSeconds` plus a few seconds for the teardown; a shorter one cuts the refusal and teardown off, and a message waiting behind a turn that ignores its abort is then neither answered nor told. Under a 30-second kill, for example, `drainSeconds: 12`, `abortGraceSeconds: 5` and `refuseWaitingSeconds: 8` leave five seconds.
|
|
4414
4426
|
3. Every plugin hears `shutdown(left)`, while every service is still running.
|
|
4415
4427
|
4. The HTTP listener closes, so no request reaches a service that has stopped.
|
|
4416
4428
|
5. Services stop in the reverse of the order they started.
|
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
|
? [
|
|
@@ -7,8 +7,21 @@ import {
|
|
|
7
7
|
} from "../modes/autonomy.ts";
|
|
8
8
|
import { integer, list, optional, shape, text } from "./schema.ts";
|
|
9
9
|
|
|
10
|
+
/** How long work that was told to stop at the drain limit gets to end before the shutdown goes on. */
|
|
11
|
+
export const ABORT_GRACE_MS = 10_000;
|
|
12
|
+
/** How long the messages still waiting after the drain are given to be refused, before the teardown. */
|
|
13
|
+
export const REFUSE_WAITING_MS = 15_000;
|
|
14
|
+
|
|
10
15
|
/** The configuration's `turnLimits` and `autonomy`: how long a turn works, and what runs without a person. */
|
|
11
16
|
export interface LimitsConfig {
|
|
17
|
+
/**
|
|
18
|
+
* Seconds a shutdown gives the turns it stops at the drain limit to end; 1 to 600, default 10.
|
|
19
|
+
* A service manager's kill timeout should exceed `drainSeconds` + this + `refuseWaitingSeconds`,
|
|
20
|
+
* plus a few seconds for the teardown.
|
|
21
|
+
*/
|
|
22
|
+
abortGraceSeconds?: number;
|
|
23
|
+
/** Seconds a shutdown gives the refusal of the messages still waiting behind a turn; 1 to 600, default 15. */
|
|
24
|
+
refuseWaitingSeconds?: number;
|
|
12
25
|
/**
|
|
13
26
|
* How long one turn may work before it asks the owner on a card whether to go on, or is
|
|
14
27
|
* stopped when it cannot show a card. Time spent waiting on the owner's cards does not count.
|
|
@@ -51,8 +64,10 @@ export interface LimitsConfig {
|
|
|
51
64
|
};
|
|
52
65
|
}
|
|
53
66
|
|
|
54
|
-
/** The
|
|
67
|
+
/** The keys' shapes, spread into the configuration's. */
|
|
55
68
|
export const limitsShape = {
|
|
69
|
+
abortGraceSeconds: optional(integer(1, 600)),
|
|
70
|
+
refuseWaitingSeconds: optional(integer(1, 600)),
|
|
56
71
|
turnLimits: optional(
|
|
57
72
|
shape({
|
|
58
73
|
timeoutSeconds: optional(integer(60, 86_400)),
|
|
@@ -79,6 +94,8 @@ export const limitsShape = {
|
|
|
79
94
|
|
|
80
95
|
/** The limits with their defaults, in ms; `maxMs` is never below `timeoutMs`. */
|
|
81
96
|
export interface ResolvedLimits {
|
|
97
|
+
abortGraceMs: number;
|
|
98
|
+
refuseWaitingMs: number;
|
|
82
99
|
turnLimits: { timeoutMs: number; maxMs: number; cardMs: number };
|
|
83
100
|
autonomy: Autonomy;
|
|
84
101
|
}
|
|
@@ -94,6 +111,8 @@ export function limitsOf(config: LimitsConfig): ResolvedLimits {
|
|
|
94
111
|
);
|
|
95
112
|
const longRunning = autonomy?.longRunning?.maxSeconds;
|
|
96
113
|
return {
|
|
114
|
+
abortGraceMs: secondsOr(config.abortGraceSeconds, ABORT_GRACE_MS),
|
|
115
|
+
refuseWaitingMs: secondsOr(config.refuseWaitingSeconds, REFUSE_WAITING_MS),
|
|
97
116
|
turnLimits: {
|
|
98
117
|
timeoutMs: timeoutSeconds * 1_000,
|
|
99
118
|
maxMs: maxSeconds * 1_000,
|
|
@@ -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,220 @@
|
|
|
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 still reaches routing unrecorded, so only one routing
|
|
53
|
+
* refuses as the host stops, one a claim would have answered, is recorded as left: the next process
|
|
54
|
+
* answers it whatever its channel shows since, and its channel is told so once. One that cannot be
|
|
55
|
+
* left gets no notice, as catch-up finds it unrecorded in its window. Any other message routing
|
|
56
|
+
* refuses then tells its channel once to send it again. Each notice is recorded, so
|
|
57
|
+
* catch-up does not take it for an answer, and deleted again when it cannot be.
|
|
58
|
+
*/
|
|
59
|
+
export function journalGate({
|
|
60
|
+
journal,
|
|
61
|
+
logger,
|
|
62
|
+
draining = () => false,
|
|
63
|
+
notify,
|
|
64
|
+
wait,
|
|
65
|
+
unrecorded,
|
|
66
|
+
retryMs = DEFAULT_RETRY_MS,
|
|
67
|
+
redeliver,
|
|
68
|
+
}: GateOptions): JournalGate {
|
|
69
|
+
const told = { later: new Set<string>(), resend: new Set<string>() };
|
|
70
|
+
// Addressed messages passed during the drain without a record: routing decides whether they are left.
|
|
71
|
+
// An entry routing never refuses stays until the process exits; the drain bounds the set, and the process ends after it.
|
|
72
|
+
const unclaimed = new Set<string>();
|
|
73
|
+
const channelOf = (message: InboundMessage) =>
|
|
74
|
+
message.channel.slice("discord:".length);
|
|
75
|
+
const tell = async (
|
|
76
|
+
kind: NoticeKind,
|
|
77
|
+
message: InboundMessage,
|
|
78
|
+
botId: string,
|
|
79
|
+
) => {
|
|
80
|
+
const channelId = channelOf(message);
|
|
81
|
+
if (!notify || told[kind].has(channelId)) return;
|
|
82
|
+
told[kind].add(channelId);
|
|
83
|
+
let notice: PostedNotice;
|
|
84
|
+
try {
|
|
85
|
+
notice = await notify(channelId, kind);
|
|
86
|
+
} catch (error) {
|
|
87
|
+
logger.warn({ channelId, err: error }, "restart notice not posted");
|
|
88
|
+
return;
|
|
89
|
+
}
|
|
90
|
+
try {
|
|
91
|
+
await journal.claim({
|
|
92
|
+
botId,
|
|
93
|
+
messageId: notice.id,
|
|
94
|
+
channelId,
|
|
95
|
+
direct: message.isDirect,
|
|
96
|
+
});
|
|
97
|
+
} catch (error) {
|
|
98
|
+
// Unrecorded, catch-up would take it for an answer.
|
|
99
|
+
logger.warn(
|
|
100
|
+
{ channelId, err: error },
|
|
101
|
+
"restart notice not recorded; deleting it",
|
|
102
|
+
);
|
|
103
|
+
await notice
|
|
104
|
+
.retract()
|
|
105
|
+
.catch((retractError: unknown) =>
|
|
106
|
+
logger.warn(
|
|
107
|
+
{ channelId, err: retractError },
|
|
108
|
+
"unrecorded restart notice not deleted",
|
|
109
|
+
),
|
|
110
|
+
);
|
|
111
|
+
}
|
|
112
|
+
};
|
|
113
|
+
const entry = (message: InboundMessage, botId: string) => ({
|
|
114
|
+
botId,
|
|
115
|
+
messageId: message.messageId,
|
|
116
|
+
channelId: channelOf(message),
|
|
117
|
+
direct: message.isDirect,
|
|
118
|
+
});
|
|
119
|
+
// Left in the journal, the next process answers it whatever its channel shows. A recorded one that
|
|
120
|
+
// cannot be left is told to be sent again; an unrecorded one is told nothing, as catch-up answers it.
|
|
121
|
+
const leave = async (
|
|
122
|
+
message: InboundMessage,
|
|
123
|
+
botId: string,
|
|
124
|
+
taken = true,
|
|
125
|
+
) => {
|
|
126
|
+
const where = {
|
|
127
|
+
channelId: channelOf(message),
|
|
128
|
+
messageId: message.messageId,
|
|
129
|
+
};
|
|
130
|
+
try {
|
|
131
|
+
if (taken) await journal.leave(entry(message, botId));
|
|
132
|
+
else if (!(await journal.leaveNew(entry(message, botId)))) {
|
|
133
|
+
// Another process took it in, and answers it.
|
|
134
|
+
logger.info(
|
|
135
|
+
where,
|
|
136
|
+
"shutting down; another process took this message in",
|
|
137
|
+
);
|
|
138
|
+
return;
|
|
139
|
+
}
|
|
140
|
+
} catch (error) {
|
|
141
|
+
if (!taken) {
|
|
142
|
+
logger.warn(
|
|
143
|
+
{ ...where, err: error },
|
|
144
|
+
"could not leave a message for the next process; unrecorded, catch-up answers it",
|
|
145
|
+
);
|
|
146
|
+
return;
|
|
147
|
+
}
|
|
148
|
+
logger.warn(
|
|
149
|
+
{ ...where, err: error },
|
|
150
|
+
"could not leave a message for the next process; its channel is told to send it again",
|
|
151
|
+
);
|
|
152
|
+
await tell("resend", message, botId);
|
|
153
|
+
return;
|
|
154
|
+
}
|
|
155
|
+
logger.info(where, "shutting down; the next process answers this message");
|
|
156
|
+
await tell("later", message, botId);
|
|
157
|
+
};
|
|
158
|
+
// Off the channel's chain: a process that begins to stop leaves what it recorded, and this one then takes it.
|
|
159
|
+
const retry = (message: InboundMessage, botId: string) => {
|
|
160
|
+
if (!redeliver || retryMs <= 0) return;
|
|
161
|
+
const timer = setTimeout(async () => {
|
|
162
|
+
if (draining()) return;
|
|
163
|
+
let first = false;
|
|
164
|
+
try {
|
|
165
|
+
first = await journal.claim(entry(message, botId));
|
|
166
|
+
if (!first) return;
|
|
167
|
+
await wait?.(channelOf(message));
|
|
168
|
+
// Late, and after newer messages of its channel.
|
|
169
|
+
redeliver({ ...message, caughtUp: true });
|
|
170
|
+
} catch (error) {
|
|
171
|
+
logger.warn(
|
|
172
|
+
{ messageId: message.messageId, err: error },
|
|
173
|
+
"could not claim or deliver a message again",
|
|
174
|
+
);
|
|
175
|
+
// Taken but not delivered: left, a later process answers it.
|
|
176
|
+
if (first)
|
|
177
|
+
await journal.leave(entry(message, botId)).catch(() => undefined);
|
|
178
|
+
}
|
|
179
|
+
}, retryMs);
|
|
180
|
+
timer.unref?.();
|
|
181
|
+
};
|
|
182
|
+
const pass = async (message: InboundMessage, botId: string) => {
|
|
183
|
+
if (!addressed(message)) return true;
|
|
184
|
+
if (draining()) {
|
|
185
|
+
// Routing refuses it, through `refused`, only when a claim would have answered it.
|
|
186
|
+
unclaimed.add(message.messageId);
|
|
187
|
+
return true;
|
|
188
|
+
}
|
|
189
|
+
const channelId = channelOf(message);
|
|
190
|
+
const { messageId } = message;
|
|
191
|
+
try {
|
|
192
|
+
if (!(await journal.claim(entry(message, botId)))) {
|
|
193
|
+
logger.info(
|
|
194
|
+
{ channelId, messageId },
|
|
195
|
+
"message already taken in; not delivered again",
|
|
196
|
+
);
|
|
197
|
+
retry(message, botId);
|
|
198
|
+
return false;
|
|
199
|
+
}
|
|
200
|
+
await wait?.(channelId);
|
|
201
|
+
// Should the drain have begun meanwhile, routing refuses it, and `refused` leaves it.
|
|
202
|
+
return true;
|
|
203
|
+
} catch (error) {
|
|
204
|
+
unrecorded?.add(messageId);
|
|
205
|
+
logger.warn(
|
|
206
|
+
{ channelId, messageId, err: error },
|
|
207
|
+
"could not record an addressed message; delivered anyway",
|
|
208
|
+
);
|
|
209
|
+
return true;
|
|
210
|
+
}
|
|
211
|
+
};
|
|
212
|
+
const refused = async (message: InboundMessage, botId: string) => {
|
|
213
|
+
if (!notify || message.authorIsBot || message.integration) return false;
|
|
214
|
+
if (addressed(message))
|
|
215
|
+
await leave(message, botId, !unclaimed.delete(message.messageId));
|
|
216
|
+
else await tell("resend", message, botId);
|
|
217
|
+
return true;
|
|
218
|
+
};
|
|
219
|
+
return Object.assign(pass, { refused });
|
|
220
|
+
}
|
|
@@ -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
|
}
|
|
@@ -42,22 +54,62 @@ const migration: Migration = {
|
|
|
42
54
|
},
|
|
43
55
|
};
|
|
44
56
|
|
|
57
|
+
/** Marks a message left by a stopping process, so the next one answers it whatever the channel shows. */
|
|
58
|
+
const leftMigration: Migration = {
|
|
59
|
+
name: "discord-inbound-journal-left",
|
|
60
|
+
up: async (sql) => {
|
|
61
|
+
await sql`
|
|
62
|
+
ALTER TABLE discord_inbound_journal ADD COLUMN IF NOT EXISTS left_at timestamptz`;
|
|
63
|
+
},
|
|
64
|
+
};
|
|
65
|
+
|
|
45
66
|
/**
|
|
46
67
|
* The journal over the host's pool, built from closures rather than private fields, so a test
|
|
47
68
|
* proxy can carry it. One insert that does nothing on a conflict decides who records a message.
|
|
48
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
|
},
|