@hadoku/game-server 0.1.35 → 0.1.36

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.
@@ -0,0 +1,32 @@
1
+ import { type ArchivebotTarget } from '@wolffm/service-kernel/lifecycle';
2
+ import type { EventRecord, Events } from './events.js';
3
+ /** How an event reads on Discord. ArchiveBot caps `name` at 100 and `location` at 100, and cuts `description` at 1000. */
4
+ export interface DiscordEventShape {
5
+ name: string;
6
+ description: string;
7
+ location: string;
8
+ }
9
+ export interface DiscordEventsDeps extends ArchivebotTarget {
10
+ /** Names the idempotency keys and the `source` ArchiveBot logs. */
11
+ service: string;
12
+ events: Events;
13
+ /** How the event reads on Discord, or null when it must not be there (its room is gone, private or a test). */
14
+ shape: (event: EventRecord) => Promise<DiscordEventShape | null>;
15
+ log: (entry: Record<string, unknown>) => void;
16
+ now?: () => number;
17
+ }
18
+ export interface DiscordEvents {
19
+ /** Make Discord match the event's record now. Resolves when done; never rejects. */
20
+ sync(id: string): Promise<void>;
21
+ /** The organizer cancelled it: take it off Discord. Resolves when done; never rejects. */
22
+ cancel(event: EventRecord): Promise<void>;
23
+ /** `sync` every upcoming event. */
24
+ sweep(): Promise<void>;
25
+ }
26
+ /** How long the Discord event runs: Discord needs an end, and a pod's three rounds fit in this. */
27
+ export declare const DISCORD_EVENT_LENGTH_MS: number;
28
+ /** ArchiveBot's reminder in #events, this long before the start. */
29
+ export declare const DISCORD_REMIND_BEFORE_MS: number;
30
+ /** How often every upcoming event is synced with nobody asking. */
31
+ export declare const SWEEP_MS: number;
32
+ export declare function discordEvents(deps: DiscordEventsDeps): DiscordEvents;
@@ -0,0 +1,132 @@
1
+ /*
2
+ * The Discord server's Events tab mirrors the front page's calendar (`events.ts`): every upcoming
3
+ * event the game says may be shown there gets a Discord scheduled event, through ArchiveBot's
4
+ * signed `/api/events/create` and `/api/events/update` (contract and source:
5
+ * docs/requests/ARCHIVEBOT_DISCORD_INTEGRATION_REPLY.md, ArchiveBot `lib/eventWebhook.js`).
6
+ * ArchiveBot puts it in the app's own guild and posts its reminder and start in #events.
7
+ *
8
+ * One rule, `sync(id)`, makes Discord match the record, and everything goes through it:
9
+ *
10
+ * - shown and not on Discord → create, keyed `<service>-event-<id>`. ArchiveBot dedupes that key
11
+ * while its event is live, so a retry, or a reply lost after Discord made it, makes no second one.
12
+ * - shown, on Discord, but sent differently (a new start, the room renamed) → update, keyed by what
13
+ * it sends, since ArchiveBot drops an update whose key equals the last one it applied. An answer
14
+ * that the event is gone (someone deleted it in Discord) creates it afresh.
15
+ * - not shown any more (its room closed, or got a password) but on Discord → cancel.
16
+ * - a start already past is left alone: Discord ends it, and cancelling one being played is wrong.
17
+ *
18
+ * The organizer's own cancel (`cancel(event)`) removes the record first, so it cancels from the
19
+ * event it was handed. Calls for one event run one at a time, so a move made while its create is
20
+ * still out waits for the event id. `sweep()` syncs every upcoming event: at boot and every
21
+ * `SWEEP_MS`, it retries what failed and catches what changed without a call (a room renamed,
22
+ * closed or locked in the room itself). A failure is logged, never thrown, and never delays the
23
+ * request that caused it.
24
+ *
25
+ * Without the secret (PPE, local dev) every call is a no-op: only prod has a Discord calendar.
26
+ */
27
+ import { createHash } from 'node:crypto';
28
+ import { archivebotPost } from '@wolffm/service-kernel/lifecycle';
29
+ /** How long the Discord event runs: Discord needs an end, and a pod's three rounds fit in this. */
30
+ export const DISCORD_EVENT_LENGTH_MS = 3 * 60 * 60_000;
31
+ /** ArchiveBot's reminder in #events, this long before the start. */
32
+ export const DISCORD_REMIND_BEFORE_MS = 60 * 60_000;
33
+ /** A start closer than this is not sent: ArchiveBot refuses a start already past by the time it arrives. */
34
+ const START_MARGIN_MS = 60_000;
35
+ /** How often every upcoming event is synced with nobody asking. */
36
+ export const SWEEP_MS = 10 * 60_000;
37
+ /** ArchiveBot's answers that the event it was asked to update no longer exists on Discord. */
38
+ const GONE = new Set(['event_not_tracked', 'event_not_found']);
39
+ const short = (text) => createHash('sha256').update(text).digest('hex').slice(0, 16);
40
+ export function discordEvents(deps) {
41
+ const now = deps.now ?? Date.now;
42
+ const enabled = deps.secret !== '';
43
+ const queues = new Map();
44
+ /** Run `task` after every earlier one for the same event; never rejects. */
45
+ const queued = (id, task) => {
46
+ const run = (queues.get(id) ?? Promise.resolve()).then(task).catch((err) => {
47
+ deps.log({ event: 'discord-event', outcome: 'failed', id, error: err instanceof Error ? err.message : String(err) });
48
+ });
49
+ queues.set(id, run);
50
+ void run.then(() => {
51
+ if (queues.get(id) === run)
52
+ queues.delete(id);
53
+ });
54
+ return run;
55
+ };
56
+ const post = (path, payload) => archivebotPost(deps, path, JSON.stringify({ ...payload, timestamp: now(), source: deps.service }));
57
+ const fields = (event, shape) => ({
58
+ name: shape.name.slice(0, 100),
59
+ startTime: new Date(event.startsAt).toISOString(),
60
+ endTime: new Date(event.startsAt + DISCORD_EVENT_LENGTH_MS).toISOString(),
61
+ description: shape.description.slice(0, 1000),
62
+ location: shape.location.slice(0, 100),
63
+ remindBeforeMs: DISCORD_REMIND_BEFORE_MS,
64
+ });
65
+ const cancelOnDiscord = async (event, discord) => {
66
+ const res = await post('/api/events/update', { idempotencyKey: `${deps.service}-event-${event.id}-cancel-${discord.eventId}`, scheduledEventId: discord.eventId, cancel: true });
67
+ const gone = typeof res.answer.error === 'string' && GONE.has(res.answer.error);
68
+ if (!res.ok && !gone) {
69
+ deps.log({ event: 'discord-event', outcome: 'failed', act: 'cancel', id: event.id, eventId: discord.eventId, status: res.status, reply: res.raw.slice(0, 500) });
70
+ return false;
71
+ }
72
+ deps.log({ event: 'discord-event', outcome: gone ? 'already-gone' : 'cancelled', id: event.id, eventId: discord.eventId });
73
+ return true;
74
+ };
75
+ const create = async (event, sent, body) => {
76
+ const res = await post('/api/events/create', { idempotencyKey: `${deps.service}-event-${event.id}`, ...body });
77
+ const eventId = res.answer.eventId;
78
+ if (!res.ok || typeof eventId !== 'string') {
79
+ deps.log({ event: 'discord-event', outcome: 'failed', act: 'create', id: event.id, status: res.status, reply: res.raw.slice(0, 500) });
80
+ return;
81
+ }
82
+ deps.log({ event: 'discord-event', outcome: res.answer.deduped === true ? 'already-created' : 'created', id: event.id, eventId });
83
+ // Cancelled while the create was out: nothing will hold this id, so take it straight back off.
84
+ if (deps.events.get(event.id) === undefined)
85
+ await cancelOnDiscord(event, { eventId, sent });
86
+ else
87
+ deps.events.setDiscord(event.id, { eventId, sent });
88
+ };
89
+ const syncNow = async (id) => {
90
+ const event = deps.events.get(id);
91
+ if (event === undefined || event.startsAt <= now() + START_MARGIN_MS)
92
+ return;
93
+ const shape = await deps.shape(event);
94
+ if (shape === null) {
95
+ if (event.discord !== undefined && (await cancelOnDiscord(event, event.discord)))
96
+ deps.events.setDiscord(id, undefined);
97
+ return;
98
+ }
99
+ const body = fields(event, shape);
100
+ const sent = JSON.stringify(body);
101
+ if (event.discord === undefined)
102
+ return create(event, sent, body);
103
+ if (event.discord.sent === sent)
104
+ return;
105
+ const res = await post('/api/events/update', { idempotencyKey: `${deps.service}-event-${id}-${short(sent)}`, scheduledEventId: event.discord.eventId, ...body });
106
+ if (typeof res.answer.error === 'string' && GONE.has(res.answer.error)) {
107
+ deps.log({ event: 'discord-event', outcome: 'recreating', id, eventId: event.discord.eventId });
108
+ return create(event, sent, body);
109
+ }
110
+ if (!res.ok) {
111
+ deps.log({ event: 'discord-event', outcome: 'failed', act: 'update', id, eventId: event.discord.eventId, status: res.status, reply: res.raw.slice(0, 500) });
112
+ return;
113
+ }
114
+ deps.events.setDiscord(id, { eventId: event.discord.eventId, sent });
115
+ deps.log({ event: 'discord-event', outcome: 'updated', id, eventId: event.discord.eventId });
116
+ };
117
+ return {
118
+ sync: (id) => (enabled ? queued(id, () => syncNow(id)) : Promise.resolve()),
119
+ // Queued even with no Discord id yet, so it runs after a create still out, which then sees the record gone.
120
+ cancel: (event) => enabled && event.startsAt > now()
121
+ ? queued(event.id, async () => {
122
+ if (event.discord !== undefined)
123
+ await cancelOnDiscord(event, event.discord);
124
+ })
125
+ : Promise.resolve(),
126
+ sweep: async () => {
127
+ if (!enabled)
128
+ return;
129
+ await Promise.all(deps.events.upcoming(now()).map((e) => queued(e.id, () => syncNow(e.id))));
130
+ },
131
+ };
132
+ }
@@ -7,6 +7,10 @@ declare const EventRecordSchema: z.ZodObject<{
7
7
  organizerUserId: z.ZodOptional<z.ZodNullable<z.ZodString>>;
8
8
  organizerName: z.ZodOptional<z.ZodString>;
9
9
  formId: z.ZodOptional<z.ZodString>;
10
+ discord: z.ZodOptional<z.ZodObject<{
11
+ eventId: z.ZodString;
12
+ sent: z.ZodString;
13
+ }, z.core.$strip>>;
10
14
  createdAt: z.ZodNumber;
11
15
  }, z.core.$strip>;
12
16
  export type EventRecord = z.infer<typeof EventRecordSchema>;
@@ -42,6 +46,8 @@ export interface Events {
42
46
  create(event: NewEvent, now: number): EventRecord;
43
47
  reschedule(id: string, callerId: string, startsAt: number): EventChange;
44
48
  cancel(id: string, callerId: string): EventChange;
49
+ /** Record what Discord's calendar now holds for an event, or that it holds nothing (`undefined`). No-op for an event since cancelled. */
50
+ setDiscord(id: string, discord: EventRecord['discord']): void;
45
51
  /** Every attached form, oldest first. */
46
52
  forms(): FormRecord[];
47
53
  /** False when the form was already attached. */
@@ -23,6 +23,8 @@ const EventRecordSchema = z.object({
23
23
  organizerName: z.string().optional(),
24
24
  /** The Rally sign-up form it was made from: Rally counts who can make it (`EventView.signedUp`). */
25
25
  formId: z.string().optional(),
26
+ /** What the Discord server's calendar holds for it, as last sent (`discord-events.ts`): absent while it has none. */
27
+ discord: z.object({ eventId: z.string(), sent: z.string() }).optional(),
26
28
  createdAt: z.number(),
27
29
  });
28
30
  const FormRecordSchema = z.object({
@@ -119,6 +121,15 @@ export async function openEvents(file, log, now = Date.now) {
119
121
  void save();
120
122
  return found;
121
123
  },
124
+ setDiscord(id, discord) {
125
+ const found = events.find((e) => e.id === id);
126
+ if (found === undefined)
127
+ return;
128
+ const { discord: _, ...rest } = found;
129
+ const event = discord === undefined ? rest : { ...rest, discord };
130
+ events = events.map((e) => (e.id === id ? event : e));
131
+ void save();
132
+ },
122
133
  forms() {
123
134
  return forms;
124
135
  },
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@hadoku/game-server",
3
- "version": "0.1.35",
4
- "gitHead": "987c61565d0bf87332275f7f4b1f2d443376764b",
3
+ "version": "0.1.36",
4
+ "gitHead": "0042b4a6b48122971a996d7f469677d4b0e105ea",
5
5
  "type": "module",
6
6
  "license": "MIT",
7
7
  "description": "The server parts any hosted game shares, above the kernel: the app config and edge auth, the room core (identity, seats, sessions, membership, the room list, the generic room routes), match hosting (the host contract, local and remote JVMs, placement, the start queue, recordings, the in-process and relay runtimes), streams, erase, telemetry and usage. Knows no game; Magic plugs in from apps/server. MIT; imports only node built-ins, express, socket.io, @wolffm/* and the platform packages.",
@@ -16,9 +16,9 @@
16
16
  "play/remote/"
17
17
  ],
18
18
  "dependencies": {
19
- "@wolffm/host-wire": "npm:@hadoku/host-wire@0.1.35",
20
- "@wolffm/platform-wire": "npm:@hadoku/platform-wire@0.1.35",
21
- "@wolffm/service-kernel": "npm:@hadoku/service-kernel@0.1.68",
19
+ "@wolffm/host-wire": "npm:@hadoku/host-wire@0.1.36",
20
+ "@wolffm/platform-wire": "npm:@hadoku/platform-wire@0.1.36",
21
+ "@wolffm/service-kernel": "npm:@hadoku/service-kernel@0.1.69",
22
22
  "@wolffm/prefs-client": "npm:@hadoku/prefs-client@^1.1.27",
23
23
  "@wolffm/rooms-protocol": "npm:@hadoku/rooms-protocol@^0.45.109",
24
24
  "@wolffm/rooms-server": "npm:@hadoku/rooms-server@^0.45.109",