Skip to content

Commit 1d92d9e

Browse files
committed
fix(tlon): await durable invite side effects
1 parent 772f6a3 commit 1d92d9e

3 files changed

Lines changed: 260 additions & 88 deletions

File tree

‎extensions/tlon/src/monitor/approval-runtime.ts‎

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -49,7 +49,7 @@ export function createTlonApprovalRuntime(params: {
4949
refreshWatchedChannels,
5050
} = params;
5151

52-
const savePendingApprovals = async (): Promise<void> => {
52+
const savePendingApprovals = async (required = false): Promise<void> => {
5353
try {
5454
await api.poke({
5555
app: "settings",
@@ -65,6 +65,9 @@ export function createTlonApprovalRuntime(params: {
6565
});
6666
} catch (err) {
6767
runtime.error?.(`[tlon] Failed to save pending approvals: ${String(err)}`);
68+
if (required) {
69+
throw err;
70+
}
6871
}
6972
};
7073

@@ -225,13 +228,13 @@ export function createTlonApprovalRuntime(params: {
225228
runtime.log?.(
226229
`[tlon] Updated existing approval for ${approval.requestingShip} (${approval.type}) - re-sending notification`,
227230
);
228-
await savePendingApprovals();
231+
await savePendingApprovals(true);
229232
await sendOwnerNotification(formatApprovalRequest(existing));
230233
return;
231234
}
232235

233236
setPendingApprovals([...approvals, approval]);
234-
await savePendingApprovals();
237+
await savePendingApprovals(true);
235238
await sendOwnerNotification(formatApprovalRequest(approval));
236239
runtime.log?.(
237240
`[tlon] Queued approval request: ${approval.id} (${approval.type} from ${approval.requestingShip})`,

‎extensions/tlon/src/monitor/index.test.ts‎

Lines changed: 191 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -253,6 +253,197 @@ it("awaits cumulative Tlon discovery persistence and retries failed writes", asy
253253
}
254254
});
255255

256+
it.each([
257+
{ name: "owner", ship: "~nec", settings: {} },
258+
{
259+
name: "allowlisted",
260+
ship: "~bus",
261+
settings: { autoAcceptGroupInvites: true, groupInviteAllowlist: ["~bus"] },
262+
},
263+
])("awaits $name group invite acceptance and retries failed writes", async ({ ship, settings }) => {
264+
const controller = new AbortController();
265+
const runtime = { error: vi.fn(), exit: vi.fn(), log: vi.fn() } satisfies RuntimeEnv;
266+
authenticateMock.mockResolvedValueOnce("urbauth-~zod=proof");
267+
settingsManagerMock.load.mockResolvedValueOnce(settings);
268+
269+
const monitor = monitorTlonProvider({ abortSignal: controller.signal, runtime });
270+
try {
271+
await vi.waitFor(() => expect(sseClientMock.connect).toHaveBeenCalledOnce());
272+
const foreignsSubscription = sseClientMock.subscribe.mock.calls
273+
.map(([subscription]) => subscription)
274+
.find(({ app, path }) => app === "groups" && path === "/v1/foreigns");
275+
if (!foreignsSubscription) {
276+
throw new Error("expected foreigns subscription");
277+
}
278+
sseClientMock.poke.mockClear();
279+
280+
let releaseWrite = () => {};
281+
sseClientMock.poke.mockImplementationOnce(
282+
() =>
283+
new Promise<void>((resolve) => {
284+
releaseWrite = resolve;
285+
}),
286+
);
287+
let settled = false;
288+
const firstResult = foreignsSubscription.event({
289+
[`${ship}/first`]: { invites: [{ valid: true, from: ship }] },
290+
});
291+
expect(firstResult).toBeInstanceOf(Promise);
292+
const firstProcessing = Promise.resolve(firstResult).then(() => {
293+
settled = true;
294+
});
295+
await setImmediate();
296+
expect(sseClientMock.poke).toHaveBeenCalledOnce();
297+
expect(settled).toBe(false);
298+
299+
releaseWrite();
300+
await firstProcessing;
301+
expect(settled).toBe(true);
302+
303+
sseClientMock.poke.mockRejectedValueOnce(new Error("group join failed"));
304+
const retryEvent = {
305+
[`${ship}/retry`]: { invites: [{ valid: true, from: ship }] },
306+
};
307+
await expect(foreignsSubscription.event(retryEvent)).rejects.toThrow("group join failed");
308+
await foreignsSubscription.event(retryEvent);
309+
310+
expect(sseClientMock.poke).toHaveBeenCalledTimes(3);
311+
expect(sseClientMock.poke.mock.calls[2]?.[0]).toMatchObject({
312+
app: "groups",
313+
mark: "group-join",
314+
json: { flag: `${ship}/retry`, "join-all": true },
315+
});
316+
} finally {
317+
controller.abort();
318+
await monitor;
319+
}
320+
});
321+
322+
it.each([
323+
{ name: "owner", ship: "~nec", settings: {} },
324+
{
325+
name: "allowlisted",
326+
ship: "~bus",
327+
settings: { autoAcceptDmInvites: true, dmAllowlist: ["~bus"] },
328+
},
329+
])(
330+
"retries failed $name DM invite acceptance before acknowledgement",
331+
async ({ ship, settings }) => {
332+
const controller = new AbortController();
333+
const runtime = { error: vi.fn(), exit: vi.fn(), log: vi.fn() } satisfies RuntimeEnv;
334+
authenticateMock.mockResolvedValueOnce("urbauth-~zod=proof");
335+
settingsManagerMock.load.mockResolvedValueOnce(settings);
336+
337+
const monitor = monitorTlonProvider({ abortSignal: controller.signal, runtime });
338+
try {
339+
await vi.waitFor(() => expect(sseClientMock.connect).toHaveBeenCalledOnce());
340+
const chatSubscription = sseClientMock.subscribe.mock.calls
341+
.map(([subscription]) => subscription)
342+
.find(({ app, path }) => app === "chat" && path === "/v3");
343+
if (!chatSubscription) {
344+
throw new Error("expected chat subscription");
345+
}
346+
sseClientMock.poke.mockClear();
347+
ingressMock.receive
348+
.mockResolvedValueOnce({ kind: "ignored" })
349+
.mockResolvedValueOnce({ kind: "ignored" });
350+
351+
const inviteEvent = [{ ship }];
352+
sseClientMock.poke.mockRejectedValueOnce(new Error("DM invite write failed"));
353+
await expect(chatSubscription.event(inviteEvent)).rejects.toThrow("DM invite write failed");
354+
await chatSubscription.event(inviteEvent);
355+
356+
expect(sseClientMock.poke).toHaveBeenCalledTimes(2);
357+
expect(sseClientMock.poke.mock.calls[1]?.[0]).toMatchObject({
358+
app: "chat",
359+
mark: "chat-dm-rsvp",
360+
json: { ship, ok: true },
361+
});
362+
} finally {
363+
controller.abort();
364+
await monitor;
365+
}
366+
},
367+
);
368+
369+
it("persists group invite approval before notification and acknowledgement", async () => {
370+
const controller = new AbortController();
371+
const runtime = { error: vi.fn(), exit: vi.fn(), log: vi.fn() } satisfies RuntimeEnv;
372+
authenticateMock.mockResolvedValueOnce("urbauth-~zod=proof");
373+
374+
const monitor = monitorTlonProvider({ abortSignal: controller.signal, runtime });
375+
try {
376+
await vi.waitFor(() => expect(sseClientMock.connect).toHaveBeenCalledOnce());
377+
const foreignsSubscription = sseClientMock.subscribe.mock.calls
378+
.map(([subscription]) => subscription)
379+
.find(({ app, path }) => app === "groups" && path === "/v1/foreigns");
380+
if (!foreignsSubscription) {
381+
throw new Error("expected foreigns subscription");
382+
}
383+
sseClientMock.poke.mockClear();
384+
385+
const inviteEvent = {
386+
"~bus/private": { invites: [{ valid: true, from: "~bus" }] },
387+
};
388+
sseClientMock.poke.mockRejectedValueOnce(new Error("approval save failed"));
389+
await expect(foreignsSubscription.event(inviteEvent)).rejects.toThrow("approval save failed");
390+
await foreignsSubscription.event(inviteEvent);
391+
392+
const pendingWrites = sseClientMock.poke.mock.calls.filter(
393+
([payload]) => payload.json?.["put-entry"]?.["entry-key"] === "pendingApprovals",
394+
);
395+
expect(pendingWrites).toHaveLength(2);
396+
expect(sseClientMock.poke).toHaveBeenCalledTimes(3);
397+
expect(sseClientMock.poke.mock.calls[2]?.[0]).toMatchObject({
398+
app: "chat",
399+
mark: "chat-dm-action",
400+
});
401+
} finally {
402+
controller.abort();
403+
await monitor;
404+
}
405+
});
406+
407+
it("continues startup after an initial group invite write fails", async () => {
408+
const controller = new AbortController();
409+
const runtime = { error: vi.fn(), exit: vi.fn(), log: vi.fn() } satisfies RuntimeEnv;
410+
authenticateMock.mockResolvedValueOnce("urbauth-~zod=proof");
411+
settingsManagerMock.load.mockResolvedValueOnce({
412+
autoAcceptGroupInvites: true,
413+
autoDiscoverChannels: true,
414+
});
415+
sseClientMock.scry.mockImplementation(async (path) =>
416+
path === "/groups-ui/v6/init.json"
417+
? {
418+
foreigns: {
419+
"~nec/startup": { invites: [{ valid: true, from: "~nec" }] },
420+
},
421+
}
422+
: {},
423+
);
424+
sseClientMock.poke.mockImplementation(async (payload) => {
425+
if (payload.mark === "group-join") {
426+
throw new Error("initial group join failed");
427+
}
428+
});
429+
430+
const monitor = monitorTlonProvider({ abortSignal: controller.signal, runtime });
431+
try {
432+
await vi.waitFor(() => expect(sseClientMock.connect).toHaveBeenCalledOnce());
433+
expect(sseClientMock.subscribe.mock.calls.map(([subscription]) => subscription)).toEqual(
434+
expect.arrayContaining([expect.objectContaining({ app: "groups", path: "/v1/foreigns" })]),
435+
);
436+
expect(runtime.error).toHaveBeenCalledWith(
437+
expect.stringContaining("initial group join failed"),
438+
);
439+
} finally {
440+
controller.abort();
441+
await monitor;
442+
sseClientMock.scry.mockReset().mockResolvedValue({});
443+
sseClientMock.poke.mockReset().mockResolvedValue(undefined);
444+
}
445+
});
446+
256447
describe("monitorTlonProvider inbound media truth", () => {
257448
it.each([
258449
{

0 commit comments

Comments
 (0)