pi-roundtable 0.51.2 → 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 +22 -0
- package/docs/plugins.md +43 -0
- package/package.json +1 -1
- package/src/core/builtin/discord.ts +46 -1
- package/src/core/config/adapters.ts +19 -0
- package/src/core/contract/channels.ts +6 -0
- 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 +134 -0
- package/src/core/discord/catch-up-reader.ts +121 -0
- package/src/core/discord/catch-up-service.ts +142 -0
- package/src/core/discord/catch-up.ts +385 -0
- package/src/core/discord/discord-surface.ts +18 -2
- package/src/core/discord/message-changes.ts +33 -4
- package/src/core/host/define-roundtable.ts +1 -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
|
@@ -0,0 +1,121 @@
|
|
|
1
|
+
import {
|
|
2
|
+
type Client,
|
|
3
|
+
type Message,
|
|
4
|
+
PermissionFlagsBits,
|
|
5
|
+
type TextBasedChannel,
|
|
6
|
+
} from "discord.js";
|
|
7
|
+
import type {
|
|
8
|
+
CatchUpChannel,
|
|
9
|
+
CatchUpReader,
|
|
10
|
+
ScannedMessage,
|
|
11
|
+
} from "./catch-up.ts";
|
|
12
|
+
import { timeOf } from "./catch-up.ts";
|
|
13
|
+
import type { PostedNotice } from "./catch-up-gate.ts";
|
|
14
|
+
import { toInbound } from "./inbound-message.ts";
|
|
15
|
+
|
|
16
|
+
/** What the bot needs in a server channel to read what was said there before. */
|
|
17
|
+
const READ = [
|
|
18
|
+
PermissionFlagsBits.ViewChannel,
|
|
19
|
+
PermissionFlagsBits.ReadMessageHistory,
|
|
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
|
+
|
|
27
|
+
function channelView(
|
|
28
|
+
channel: TextBasedChannel,
|
|
29
|
+
): CatchUpChannel<Message & ScannedMessage> {
|
|
30
|
+
return {
|
|
31
|
+
id: channel.id,
|
|
32
|
+
direct: channel.isDMBased(),
|
|
33
|
+
lastMessageAt: channel.lastMessageId
|
|
34
|
+
? timeOf(channel.lastMessageId)
|
|
35
|
+
: undefined,
|
|
36
|
+
read: async (before, limit) => [
|
|
37
|
+
...(await channel.messages.fetch({ before, limit })).values(),
|
|
38
|
+
],
|
|
39
|
+
};
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/**
|
|
43
|
+
* Catch-up's view of a ready client. The server channels, threads and forum posts come from the
|
|
44
|
+
* client's cache, which Discord fills as the connection becomes ready, with each channel's last
|
|
45
|
+
* message: choosing what to read costs no request. A message's author is fetched as a member
|
|
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.
|
|
48
|
+
*/
|
|
49
|
+
export function clientCatchUpReader(
|
|
50
|
+
client: Client,
|
|
51
|
+
): CatchUpReader<Message & ScannedMessage> {
|
|
52
|
+
const bot = client.user;
|
|
53
|
+
const readyAt = client.readyTimestamp;
|
|
54
|
+
if (!bot || readyAt === null)
|
|
55
|
+
throw new Error("catch-up needs a ready Discord connection");
|
|
56
|
+
const identity = { botId: bot.id, applicationId: client.application?.id };
|
|
57
|
+
return {
|
|
58
|
+
botId: bot.id,
|
|
59
|
+
applicationId: client.application?.id,
|
|
60
|
+
readyAt,
|
|
61
|
+
channels: () => {
|
|
62
|
+
const found: CatchUpChannel<Message & ScannedMessage>[] = [];
|
|
63
|
+
for (const channel of client.channels.cache.values()) {
|
|
64
|
+
if (!channel.isTextBased()) continue;
|
|
65
|
+
if (channel.isThread() && channel.archived) continue;
|
|
66
|
+
if (!channel.isDMBased() && !channel.permissionsFor(bot)?.has(READ))
|
|
67
|
+
continue;
|
|
68
|
+
found.push(channelView(channel));
|
|
69
|
+
}
|
|
70
|
+
return found;
|
|
71
|
+
},
|
|
72
|
+
direct: async (channelId) => {
|
|
73
|
+
const channel = await client.channels.fetch(channelId);
|
|
74
|
+
return channel?.isDMBased() && channel.isTextBased()
|
|
75
|
+
? channelView(channel)
|
|
76
|
+
: undefined;
|
|
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
|
+
},
|
|
88
|
+
inbound: async (message) => {
|
|
89
|
+
if (message.inGuild() && !message.member)
|
|
90
|
+
await message.guild.members
|
|
91
|
+
.fetch(message.author.id)
|
|
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
|
+
});
|
|
97
|
+
return toInbound(message, identity);
|
|
98
|
+
},
|
|
99
|
+
};
|
|
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
|
+
}
|
|
@@ -0,0 +1,385 @@
|
|
|
1
|
+
import type { InboundMessage } from "../contract/channels.ts";
|
|
2
|
+
import { ConfigError } from "../domain/errors.ts";
|
|
3
|
+
import type { Logger } from "../kernel/log.ts";
|
|
4
|
+
import type { InboundJournal } from "./catch-up-journal.ts";
|
|
5
|
+
|
|
6
|
+
/** What `discord.catchUp` takes. */
|
|
7
|
+
export interface CatchUpOptions {
|
|
8
|
+
/** How far back, in minutes before the connection is ready, a missed message is still answered: 1 to 1440. Default 10. */
|
|
9
|
+
windowMinutes?: number;
|
|
10
|
+
/** The most missed messages answered after one restart, the newest; 1 to 100. Default 20. */
|
|
11
|
+
maxMessages?: number;
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
/** `CatchUpOptions` with the defaults filled in. */
|
|
15
|
+
export type CatchUpSettings = Required<CatchUpOptions>;
|
|
16
|
+
|
|
17
|
+
const DEFAULT_WINDOW_MINUTES = 10;
|
|
18
|
+
const DEFAULT_MAX_MESSAGES = 20;
|
|
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
|
+
/** The most remembered direct-message channels fetched to see whether they had a message lately. */
|
|
22
|
+
const DIRECT_PROBES = 25;
|
|
23
|
+
/** The most channels whose messages one catch-up reads, one request each. */
|
|
24
|
+
const MAX_CHANNEL_READS = 50;
|
|
25
|
+
/** The messages read before the ready time in each channel, one page. */
|
|
26
|
+
const PAGE = 100;
|
|
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;
|
|
30
|
+
const DISCORD_EPOCH = 1_420_070_400_000n;
|
|
31
|
+
|
|
32
|
+
const whole = (value: number | undefined, low: number, high: number) =>
|
|
33
|
+
value === undefined ||
|
|
34
|
+
(Number.isInteger(value) && value >= low && value <= high);
|
|
35
|
+
|
|
36
|
+
/** The settings of `discord.catchUp`; throws a `ConfigError` for a value out of range. */
|
|
37
|
+
export function catchUpSettings(options: CatchUpOptions): CatchUpSettings {
|
|
38
|
+
if (!whole(options.windowMinutes, 1, 1440))
|
|
39
|
+
throw new ConfigError(
|
|
40
|
+
"discord.catchUp.windowMinutes must be a whole number from 1 to 1440",
|
|
41
|
+
);
|
|
42
|
+
if (!whole(options.maxMessages, 1, 100))
|
|
43
|
+
throw new ConfigError(
|
|
44
|
+
"discord.catchUp.maxMessages must be a whole number from 1 to 100",
|
|
45
|
+
);
|
|
46
|
+
return {
|
|
47
|
+
windowMinutes: options.windowMinutes ?? DEFAULT_WINDOW_MINUTES,
|
|
48
|
+
maxMessages: options.maxMessages ?? DEFAULT_MAX_MESSAGES,
|
|
49
|
+
};
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/** The first snowflake Discord could assign at `ms`, as a bound for reading messages before it. */
|
|
53
|
+
export const snowflakeAt = (ms: number): string =>
|
|
54
|
+
((BigInt(ms) - DISCORD_EPOCH) << 22n).toString();
|
|
55
|
+
|
|
56
|
+
/** When Discord assigned a snowflake, in epoch milliseconds. */
|
|
57
|
+
export const timeOf = (id: string): number =>
|
|
58
|
+
Number((BigInt(id) >> 22n) + DISCORD_EPOCH);
|
|
59
|
+
|
|
60
|
+
/** A person's message to the bot: a direct message, a mention, or a reply to it; never a bot's or a webhook's. */
|
|
61
|
+
export function addressed(message: InboundMessage): boolean {
|
|
62
|
+
return (
|
|
63
|
+
!message.authorIsBot &&
|
|
64
|
+
!message.integration &&
|
|
65
|
+
(message.isDirect || message.mentionsBot || message.repliesToBot)
|
|
66
|
+
);
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/** The parts of a Discord message catch-up reads before it reads the message in full; a discord.js `Message` has them. */
|
|
70
|
+
export interface ScannedMessage {
|
|
71
|
+
id: string;
|
|
72
|
+
createdTimestamp: number;
|
|
73
|
+
author: { id: string; bot: boolean };
|
|
74
|
+
webhookId: string | null;
|
|
75
|
+
applicationId: string | null;
|
|
76
|
+
system: boolean;
|
|
77
|
+
mentions: {
|
|
78
|
+
users: { has(id: string): boolean };
|
|
79
|
+
repliedUser: { id: string } | null;
|
|
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
|
+
};
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/** A channel catch-up may read. */
|
|
90
|
+
export interface CatchUpChannel<M extends ScannedMessage> {
|
|
91
|
+
id: string;
|
|
92
|
+
direct: boolean;
|
|
93
|
+
/** When its last message was posted, as the client knows it; undefined for none. */
|
|
94
|
+
lastMessageAt: number | undefined;
|
|
95
|
+
/** Up to `limit` of its messages before the snowflake `before`, in any order. */
|
|
96
|
+
read(before: string, limit: number): Promise<M[]>;
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
/** Discord as catch-up reads it, once the connection is ready. */
|
|
100
|
+
export interface CatchUpReader<M extends ScannedMessage> {
|
|
101
|
+
botId: string;
|
|
102
|
+
applicationId: string | undefined;
|
|
103
|
+
/** When the connection became ready: from then on the gateway delivers each message. */
|
|
104
|
+
readyAt: number;
|
|
105
|
+
/** The server channels, threads and forum posts the bot can read, and the direct messages the client holds, without a request. */
|
|
106
|
+
channels(): CatchUpChannel<M>[];
|
|
107
|
+
/** A direct-message channel by its id; undefined when it is not one. */
|
|
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>;
|
|
111
|
+
/** The message as the live gateway would deliver it. */
|
|
112
|
+
inbound(message: M): Promise<InboundMessage | undefined>;
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
export interface CatchUpDeps<M extends ScannedMessage> {
|
|
116
|
+
reader: CatchUpReader<M>;
|
|
117
|
+
journal: InboundJournal;
|
|
118
|
+
/** Hands a message to routing, as the live gateway does. */
|
|
119
|
+
deliver(message: InboundMessage): void;
|
|
120
|
+
settings: CatchUpSettings;
|
|
121
|
+
logger: Logger;
|
|
122
|
+
/** True once the host shuts down: nothing more is delivered. */
|
|
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;
|
|
128
|
+
now?: () => number;
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
/** What one catch-up did, in counts; logged, never the messages. */
|
|
132
|
+
export interface CatchUpReport {
|
|
133
|
+
channels: number;
|
|
134
|
+
unread: number;
|
|
135
|
+
missed: number;
|
|
136
|
+
replied: number;
|
|
137
|
+
overCap: number;
|
|
138
|
+
handled: number;
|
|
139
|
+
failed: number;
|
|
140
|
+
delivered: number;
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
/**
|
|
144
|
+
* The channels to read: those the client knows of, and the remembered direct messages, whose last
|
|
145
|
+
* message falls in the window, the most recently active first, at most `MAX_CHANNEL_READS`.
|
|
146
|
+
*/
|
|
147
|
+
async function channelsToRead<M extends ScannedMessage>(
|
|
148
|
+
deps: CatchUpDeps<M>,
|
|
149
|
+
since: number,
|
|
150
|
+
now: number,
|
|
151
|
+
leftIn: string[],
|
|
152
|
+
): Promise<CatchUpChannel<M>[]> {
|
|
153
|
+
const { reader, journal, logger } = deps;
|
|
154
|
+
const known = reader.channels();
|
|
155
|
+
const ids = new Set(known.map((channel) => channel.id));
|
|
156
|
+
const directs = await journal
|
|
157
|
+
.directChannels(
|
|
158
|
+
reader.botId,
|
|
159
|
+
new Date(now - JOURNAL_DAYS * DAY_MS),
|
|
160
|
+
DIRECT_PROBES,
|
|
161
|
+
)
|
|
162
|
+
.catch((error: unknown) => {
|
|
163
|
+
logger.warn({ err: error }, "catch-up could not list direct messages");
|
|
164
|
+
return [];
|
|
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
|
+
]);
|
|
174
|
+
for (const id of directs) {
|
|
175
|
+
if (ids.has(id)) continue;
|
|
176
|
+
const channel = await reader.direct(id).catch(() => undefined);
|
|
177
|
+
if (channel) known.push(channel);
|
|
178
|
+
}
|
|
179
|
+
return known
|
|
180
|
+
.filter((channel) => (channel.lastMessageAt ?? 0) >= since)
|
|
181
|
+
.toSorted((a, b) => (b.lastMessageAt ?? 0) - (a.lastMessageAt ?? 0))
|
|
182
|
+
.slice(0, MAX_CHANNEL_READS);
|
|
183
|
+
}
|
|
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
|
+
|
|
201
|
+
/**
|
|
202
|
+
* Answers the messages addressed to the bot that came while the host was down: after the
|
|
203
|
+
* connection is ready, reads the channels active in the window and hands routing each person's
|
|
204
|
+
* mention, reply to the bot, or direct message from the window that the bot did not answer and
|
|
205
|
+
* that no one recorded, oldest first, marked `caughtUp`. A message is recorded in the journal
|
|
206
|
+
* before it is handed on, so a second restart, or a crash during its turn, never answers it again.
|
|
207
|
+
* Never rejects; reports its counts.
|
|
208
|
+
*/
|
|
209
|
+
export async function catchUp<M extends ScannedMessage>(
|
|
210
|
+
deps: CatchUpDeps<M>,
|
|
211
|
+
): Promise<CatchUpReport> {
|
|
212
|
+
const { reader, journal, settings, logger } = deps;
|
|
213
|
+
const now = deps.now?.() ?? Date.now();
|
|
214
|
+
const { readyAt, botId } = reader;
|
|
215
|
+
const since = readyAt - settings.windowMinutes * 60_000;
|
|
216
|
+
const report: CatchUpReport = {
|
|
217
|
+
channels: 0,
|
|
218
|
+
unread: 0,
|
|
219
|
+
missed: 0,
|
|
220
|
+
replied: 0,
|
|
221
|
+
overCap: 0,
|
|
222
|
+
handled: 0,
|
|
223
|
+
failed: 0,
|
|
224
|
+
delivered: 0,
|
|
225
|
+
};
|
|
226
|
+
const own = reader.applicationId ?? botId;
|
|
227
|
+
const byBot = (message: M) =>
|
|
228
|
+
message.author.id === botId ||
|
|
229
|
+
(message.webhookId !== null && message.applicationId === own);
|
|
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) {
|
|
274
|
+
if (deps.stopping?.()) return report;
|
|
275
|
+
report.channels += 1;
|
|
276
|
+
let messages: M[];
|
|
277
|
+
try {
|
|
278
|
+
messages = await channel.read(snowflakeAt(readyAt), PAGE);
|
|
279
|
+
} catch (error) {
|
|
280
|
+
report.unread += 1;
|
|
281
|
+
logger.warn(
|
|
282
|
+
{ channelId: channel.id, err: error },
|
|
283
|
+
"catch-up could not read a channel",
|
|
284
|
+
);
|
|
285
|
+
continue;
|
|
286
|
+
}
|
|
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);
|
|
299
|
+
for (const message of messages) {
|
|
300
|
+
const { author, mentions } = message;
|
|
301
|
+
if (
|
|
302
|
+
leftIds.has(message.id) ||
|
|
303
|
+
message.createdTimestamp < since ||
|
|
304
|
+
message.createdTimestamp >= readyAt ||
|
|
305
|
+
author.bot ||
|
|
306
|
+
message.webhookId !== null ||
|
|
307
|
+
message.system ||
|
|
308
|
+
!(
|
|
309
|
+
channel.direct ||
|
|
310
|
+
mentions.users.has(botId) ||
|
|
311
|
+
mentions.repliedUser?.id === botId
|
|
312
|
+
)
|
|
313
|
+
)
|
|
314
|
+
continue;
|
|
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;
|
|
323
|
+
else missed.push({ message, channel });
|
|
324
|
+
}
|
|
325
|
+
}
|
|
326
|
+
missed.sort((a, b) => (BigInt(a.message.id) < BigInt(b.message.id) ? -1 : 1));
|
|
327
|
+
report.missed = missed.length;
|
|
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))) {
|
|
332
|
+
if (deps.stopping?.()) break;
|
|
333
|
+
if (deps.passedLive?.(message.id)) {
|
|
334
|
+
report.handled += 1;
|
|
335
|
+
continue;
|
|
336
|
+
}
|
|
337
|
+
try {
|
|
338
|
+
const inbound = await reader.inbound(message);
|
|
339
|
+
if (!inbound) continue;
|
|
340
|
+
const first = await journal.claim({
|
|
341
|
+
botId,
|
|
342
|
+
messageId: message.id,
|
|
343
|
+
channelId: channel.id,
|
|
344
|
+
direct: channel.direct,
|
|
345
|
+
});
|
|
346
|
+
if (!first) {
|
|
347
|
+
report.handled += 1;
|
|
348
|
+
continue;
|
|
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
|
+
}
|
|
367
|
+
deps.deliver({ ...inbound, caughtUp: true });
|
|
368
|
+
report.delivered += 1;
|
|
369
|
+
} catch (error) {
|
|
370
|
+
// Unrecorded, it is not answered: a second answer is worse than none.
|
|
371
|
+
report.failed += 1;
|
|
372
|
+
logger.warn(
|
|
373
|
+
{ channelId: channel.id, messageId: message.id, err: error },
|
|
374
|
+
"catch-up skipped a missed message it could not read or record",
|
|
375
|
+
);
|
|
376
|
+
}
|
|
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
|
+
);
|
|
383
|
+
logger.info({ ...report }, "discord catch-up done");
|
|
384
|
+
return report;
|
|
385
|
+
}
|
|
@@ -53,7 +53,11 @@ import {
|
|
|
53
53
|
listenForJoins,
|
|
54
54
|
memberIntents,
|
|
55
55
|
} from "./member-events.ts";
|
|
56
|
-
import {
|
|
56
|
+
import {
|
|
57
|
+
type InboundGate,
|
|
58
|
+
listenForMessages,
|
|
59
|
+
reportChanges,
|
|
60
|
+
} from "./message-changes.ts";
|
|
57
61
|
import type { CardChannel, LateTurn } from "./owner-cards.ts";
|
|
58
62
|
import { DiscordOwnerOps } from "./owner-discord.ts";
|
|
59
63
|
import { showStopPanel } from "./stop-button.ts";
|
|
@@ -81,6 +85,10 @@ export interface DiscordSurfaceOptions {
|
|
|
81
85
|
formatting?: string | false;
|
|
82
86
|
/** Where the agents' message cards keep their whole texts for the open button; without it a card posts as text. */
|
|
83
87
|
intercomTexts?: IntercomTexts;
|
|
88
|
+
/** Decides whether each live message is handed on, such as catch-up's journal; without it every one is. */
|
|
89
|
+
inboundGate?: InboundGate;
|
|
90
|
+
/** `ChatSurface.refuseStopping`, such as catch-up's; without it routing tells the channel. */
|
|
91
|
+
refuseStopping?: (message: InboundMessage) => Promise<boolean>;
|
|
84
92
|
/** Reads the channel context of an addressed message; without it the surface has none. */
|
|
85
93
|
channelContext?: (
|
|
86
94
|
message: InboundMessage,
|
|
@@ -114,8 +122,11 @@ export class DiscordSurface
|
|
|
114
122
|
#interactions: ComposedCommands = { commands: [], modules: [] };
|
|
115
123
|
#onMessage: ((message: InboundMessage) => void) | undefined;
|
|
116
124
|
|
|
125
|
+
readonly refuseStopping?: (message: InboundMessage) => Promise<boolean>;
|
|
126
|
+
|
|
117
127
|
constructor(options: DiscordSurfaceOptions) {
|
|
118
128
|
this.#options = options;
|
|
129
|
+
if (options.refuseStopping) this.refuseStopping = options.refuseStopping;
|
|
119
130
|
this.#client = new Client({
|
|
120
131
|
intents: [
|
|
121
132
|
GatewayIntentBits.Guilds,
|
|
@@ -274,7 +285,12 @@ export class DiscordSurface
|
|
|
274
285
|
const { logger, token } = this.#options;
|
|
275
286
|
this.#onMessage = onMessage;
|
|
276
287
|
if (events) reportChanges(this.#client, events, logger);
|
|
277
|
-
listenForMessages(
|
|
288
|
+
listenForMessages(
|
|
289
|
+
this.#client,
|
|
290
|
+
onMessage,
|
|
291
|
+
logger,
|
|
292
|
+
this.#options.inboundGate,
|
|
293
|
+
);
|
|
278
294
|
this.#client.on(Events.InteractionCreate, (interaction) => {
|
|
279
295
|
void this.#dispatch(interaction);
|
|
280
296
|
});
|