Skip to content

armgit / alook

Public Imported from GitHub
0

Multi-Agent Collaboration for Team and Friends

fix(web): keep message notify work alive (#436)

Genered33a2e92127
diff --git a/src/web/src/lib/community/message-handler.test.ts b/src/web/src/lib/community/message-handler.test.ts
index b81fb8d71..599b78629 100644
--- a/src/web/src/lib/community/message-handler.test.ts
+++ b/src/web/src/lib/community/message-handler.test.ts
@@ -828,6 +828,48 @@ describe("createCommunityMessage — private-channel mention scoping (no auto-ad
})
})
+ it("does not await a pending notify work on the normal delivery path", async () => {
+ mockGetMessage.mockResolvedValue(messageRow({ content: "hello" }))
+ mockResolveChannelRecipients.mockResolvedValueOnce(["author_1", "cara_1"])
+ mockDispatchMessageNotify.mockReturnValueOnce(new Promise<void>(() => {}))
+
+ const result = await createCommunityMessage({
+ db: {} as never,
+ authorId: "author_1",
+ target: { kind: "channel", channelId: "c1", serverId: "srv_1" },
+ body: { content: "hello" },
+ })
+
+ expect(result.ok).toBe(true)
+ expect(mockDispatchMessageNotify).toHaveBeenCalledWith(
+ {},
+ { authorName: "Author" },
+ { id: "msg_1", channelId: "c1" },
+ ["cara_1"],
+ expect.objectContaining({ mentionedUserIds: [] }),
+ )
+ })
+
+ it("starts notify only when a deferred broadcast thunk is invoked", async () => {
+ mockGetMessage.mockResolvedValue(messageRow({ content: "hello" }))
+ mockResolveChannelRecipients.mockResolvedValueOnce(["author_1", "cara_1"])
+ mockDispatchMessageNotify.mockReturnValueOnce(new Promise<void>(() => {}))
+
+ const result = await createCommunityMessage({
+ db: {} as never,
+ authorId: "author_1",
+ target: { kind: "channel", channelId: "c1", serverId: "srv_1" },
+ body: { content: "hello" },
+ deferBroadcast: true,
+ })
+
+ expect(result.ok).toBe(true)
+ if (!result.ok) return
+ expect(mockDispatchMessageNotify).not.toHaveBeenCalled()
+ await expect(result.broadcast?.()).resolves.toBeUndefined()
+ expect(mockDispatchMessageNotify).toHaveBeenCalledTimes(1)
+ })
+
it("suppressBroadcast (migration-backfill mode): STRUCTURAL core runs (enroll + mention rows), real-time delivery shell is fully dropped", async () => {
// The existing-data migration's atomic primitive needs a create that
// persists the message + enrolls participants + writes mention rows but
@@ -859,6 +901,7 @@ describe("createCommunityMessage — private-channel mention scoping (no auto-ad
})
// Real-time delivery shell FULLY dropped: no WS fan-out of any kind.
expect(mockFanOutToChannel).not.toHaveBeenCalled()
+ expect(mockDispatchMessageNotify).not.toHaveBeenCalled()
// ...and no deferred thunk handed back either (unlike deferBroadcast).
expect(result.ok).toBe(true)
if (result.ok) expect(result.broadcast).toBeUndefined()
diff --git a/src/web/src/lib/community/notify.test.ts b/src/web/src/lib/community/notify.test.ts
index 63a06e894..577643e83 100644
--- a/src/web/src/lib/community/notify.test.ts
+++ b/src/web/src/lib/community/notify.test.ts
@@ -1,138 +1,390 @@
-import { describe, it, expect, vi, beforeEach } from "vitest"
+import { beforeEach, describe, expect, it, vi } from "vitest"
+const mockInfo = vi.fn()
+const mockWarn = vi.fn()
+const mockWaitUntil = vi.fn()
+const mockGetCloudflareContext = vi.fn()
const mockResolveEffectiveLevelForUsers = vi.fn()
+
+vi.mock("@opennextjs/cloudflare", () => ({
+ getCloudflareContext: () => mockGetCloudflareContext(),
+}))
+
vi.mock("@alook/shared", async () => {
const actual = await vi.importActual<typeof import("@alook/shared")>("@alook/shared")
return {
...actual,
- createLogger: () => ({ info: vi.fn(), warn: vi.fn(), error: vi.fn(), debug: vi.fn() }),
+ createLogger: () => ({
+ info: (...args: unknown[]) => mockInfo(...args),
+ warn: (...args: unknown[]) => mockWarn(...args),
+ error: vi.fn(),
+ debug: vi.fn(),
+ }),
queries: {
communityNotificationSetting: {
- resolveEffectiveLevelForUsers: (...a: unknown[]) =>
- mockResolveEffectiveLevelForUsers(...(a as [unknown, string[], string])),
+ resolveEffectiveLevelForUsers: (...args: unknown[]) =>
+ mockResolveEffectiveLevelForUsers(...args),
},
},
}
})
-const mockBroadcastToUser = vi.fn(() => Promise.resolve())
+const mockBroadcastToUser = vi.fn()
vi.mock("../broadcast", () => ({
- broadcastToUser: (...a: unknown[]) => mockBroadcastToUser(...a),
+ broadcastToUser: (...args: unknown[]) => mockBroadcastToUser(...args),
}))
-import { dispatchMessageNotify, shouldDeliver } from "./notify"
+import {
+ dispatchMessageNotify,
+ settleNotifyTasks,
+ shouldDeliver,
+} from "./notify"
const db = {} as never
+const message = { id: "m1", channelId: "c1" }
+const notifyContext = { authorName: "Alice" }
-function bumpEvents() {
- return mockBroadcastToUser.mock.calls.map((c) => c[1]).filter((e: any) => e.type === "community:unread.bump")
+function deferred<T>() {
+ let resolve!: (value: T | PromiseLike<T>) => void
+ let reject!: (reason?: unknown) => void
+ const promise = new Promise<T>((resolvePromise, rejectPromise) => {
+ resolve = resolvePromise
+ reject = rejectPromise
+ })
+ return { promise, resolve, reject }
}
-function mentionEvents() {
- return mockBroadcastToUser.mock.calls.map((c) => c[1]).filter((e: any) => e.type === "community:mention.create")
+
+function eventsOfType(type: string): Record<string, unknown>[] {
+ return mockBroadcastToUser.mock.calls
+ .map((call) => call[1] as Record<string, unknown>)
+ .filter((event) => event.type === type)
}
describe("shouldDeliver", () => {
- it("all → always", () => {
+ it("delivers every all-level notification", () => {
expect(shouldDeliver("all", false)).toBe(true)
expect(shouldDeliver("all", true)).toBe(true)
})
- it("mentions → only when mentioned", () => {
+
+ it("delivers mentions-level notifications only when mentioned", () => {
expect(shouldDeliver("mentions", false)).toBe(false)
expect(shouldDeliver("mentions", true)).toBe(true)
})
- it("nothing → never", () => {
+
+ it("never delivers nothing-level notifications", () => {
expect(shouldDeliver("nothing", false)).toBe(false)
expect(shouldDeliver("nothing", true)).toBe(false)
})
})
+describe("settleNotifyTasks", () => {
+ it.each([0, 1, 3, 4, 1001])(
+ "settles %i tasks with at most three active",
+ async (taskCount) => {
+ let active = 0
+ let observedMaxActive = 0
+ const tasks = Array.from({ length: taskCount }, (_, index) => index)
+
+ const settled = await settleNotifyTasks(tasks, async () => {
+ active += 1
+ observedMaxActive = Math.max(observedMaxActive, active)
+ await Promise.resolve()
+ active -= 1
+ })
+
+ expect(settled.results).toHaveLength(taskCount)
+ expect(settled.results.every((result) => result.status === "fulfilled")).toBe(true)
+ expect(settled.maxActive).toBe(Math.min(taskCount, 3))
+ expect(observedMaxActive).toBe(Math.min(taskCount, 3))
+ },
+ )
+
+ it("starts the fourth task only after one of the first three settles", async () => {
+ const gates = Array.from({ length: 4 }, () => deferred<void>())
+ const started: number[] = []
+ const work = settleNotifyTasks([0, 1, 2, 3], async (index) => {
+ started.push(index)
+ await gates[index].promise
+ })
+
+ expect(started).toEqual([0, 1, 2])
+ gates[1].resolve(undefined)
+ await Promise.resolve()
+ await Promise.resolve()
+ expect(started).toEqual([0, 1, 2, 3])
+
+ gates[0].resolve(undefined)
+ gates[2].resolve(undefined)
+ gates[3].resolve(undefined)
+ await expect(work).resolves.toMatchObject({ maxActive: 3 })
+ })
+
+ it("keeps results aligned by input index when tasks settle out of order", async () => {
+ const gates = Array.from({ length: 3 }, () => deferred<void>())
+ const failure = new Error("task one failed")
+ const work = settleNotifyTasks([0, 1, 2], (index) => gates[index].promise)
+
+ gates[2].resolve(undefined)
+ gates[1].reject(failure)
+ gates[0].resolve(undefined)
+
+ const { results } = await work
+ expect(results[0]).toEqual({ status: "fulfilled", value: undefined })
+ expect(results[1]).toEqual({ status: "rejected", reason: failure })
+ expect(results[2]).toEqual({ status: "fulfilled", value: undefined })
+ })
+
+ it("continues with later tasks after a synchronous rejection", async () => {
+ const started: number[] = []
+ const failure = new Error("rejected")
+ const { results } = await settleNotifyTasks([0, 1, 2, 3], async (index) => {
+ started.push(index)
+ if (index === 1) throw failure
+ })
+
+ expect(started).toEqual([0, 1, 2, 3])
+ expect(results[1]).toEqual({ status: "rejected", reason: failure })
+ expect(results[3]).toEqual({ status: "fulfilled", value: undefined })
+ })
+})
+
describe("dispatchMessageNotify", () => {
- beforeEach(() => vi.clearAllMocks())
+ beforeEach(() => {
+ vi.clearAllMocks()
+ mockBroadcastToUser.mockReset()
+ mockBroadcastToUser.mockResolvedValue(undefined)
+ mockGetCloudflareContext.mockReturnValue({ ctx: { waitUntil: mockWaitUntil } })
+ })
- const msg = { id: "m1", channelId: "c1" }
- const ctx = { authorName: "Alice" }
+ it("registers the returned work before the level resolver settles", async () => {
+ const levels = deferred<Map<string, "all">>()
+ mockResolveEffectiveLevelForUsers.mockReturnValue(levels.promise)
- it("all-level recipient: gets a badge; a mentioned all-level recipient also gets the mention push", async () => {
- mockResolveEffectiveLevelForUsers.mockResolvedValue(
- new Map([["u_plain", "all"], ["u_mentioned", "all"]]),
- )
- await dispatchMessageNotify(db, ctx, msg, ["u_plain", "u_mentioned"], {
- mentionedUserIds: ["u_mentioned"],
+ const work = dispatchMessageNotify(db, notifyContext, message, ["u1"], {
+ mentionedUserIds: [],
})
- expect(bumpEvents().map((e: any) => e.userId).sort()).toEqual(["u_mentioned", "u_plain"])
- expect(mentionEvents().map((e: any) => e.userId)).toEqual(["u_mentioned"])
+
+ expect(mockWaitUntil).toHaveBeenCalledWith(work)
+ expect(mockBroadcastToUser).not.toHaveBeenCalled()
+ levels.resolve(new Map([["u1", "all"]]))
+ await work
+ expect(mockBroadcastToUser).toHaveBeenCalledTimes(1)
})
- it("mentions-level: plain recipient gets nothing; mentioned recipient gets badge + push", async () => {
- mockResolveEffectiveLevelForUsers.mockResolvedValue(
- new Map([["u_plain", "mentions"], ["u_mentioned", "mentions"]]),
+ it("keeps aggregate work pending until every lazily started leaf settles", async () => {
+ mockResolveEffectiveLevelForUsers.mockResolvedValue(new Map())
+ const gates = Array.from({ length: 4 }, () => deferred<void>())
+ mockBroadcastToUser.mockImplementation(() => {
+ const index = mockBroadcastToUser.mock.calls.length - 1
+ return gates[index].promise
+ })
+
+ const work = dispatchMessageNotify(
+ db,
+ notifyContext,
+ message,
+ ["u0", "u1", "u2", "u3"],
+ { mentionedUserIds: [] },
)
- await dispatchMessageNotify(db, ctx, msg, ["u_plain", "u_mentioned"], {
- mentionedUserIds: ["u_mentioned"],
+ let settled = false
+ void work.then(() => {
+ settled = true
})
- expect(bumpEvents().map((e: any) => e.userId)).toEqual(["u_mentioned"])
- expect(mentionEvents().map((e: any) => e.userId)).toEqual(["u_mentioned"])
- })
- it("@everyone counts as a mention: a mentions-level recipient in the mention set gets badge + push", async () => {
- // @everyone expands into mentionedUserIds upstream — no carve-out (Gener #28).
- mockResolveEffectiveLevelForUsers.mockResolvedValue(new Map([["u_e", "mentions"]]))
- await dispatchMessageNotify(db, ctx, msg, ["u_e"], { mentionedUserIds: ["u_e"] })
- expect(bumpEvents().map((e: any) => e.userId)).toEqual(["u_e"])
- expect(mentionEvents().map((e: any) => e.userId)).toEqual(["u_e"])
+ await Promise.resolve()
+ await Promise.resolve()
+ expect(mockBroadcastToUser).toHaveBeenCalledTimes(3)
+ expect(settled).toBe(false)
+
+ gates[0].resolve(undefined)
+ await Promise.resolve()
+ await Promise.resolve()
+ expect(mockBroadcastToUser).toHaveBeenCalledTimes(4)
+ expect(settled).toBe(false)
+
+ gates[1].resolve(undefined)
+ gates[2].resolve(undefined)
+ gates[3].resolve(undefined)
+ await work
+ expect(settled).toBe(true)
+ expect(mockWaitUntil).toHaveBeenCalledWith(work)
})
- it("nothing-level recipient (even mentioned): NO badge, NO push (mention ROW is written elsewhere, not here)", async () => {
- mockResolveEffectiveLevelForUsers.mockResolvedValue(new Map([["u_muted", "nothing"]]))
- await dispatchMessageNotify(db, ctx, msg, ["u_muted"], { mentionedUserIds: ["u_muted"] })
- expect(bumpEvents()).toEqual([])
- expect(mentionEvents()).toEqual([])
- // Never emits MESSAGE_CREATE — that's the caller's unconditional fan-out.
- const anyMessageCreate = mockBroadcastToUser.mock.calls.some(
- (c: any) => c[1]?.type === "community:message.create",
+ it("builds mention tasks before deduplicated unread tasks", async () => {
+ mockResolveEffectiveLevelForUsers.mockResolvedValue(new Map())
+
+ await dispatchMessageNotify(
+ db,
+ notifyContext,
+ message,
+ ["u_plain", "u_mentioned", "u_plain"],
+ { mentionedUserIds: ["u_mentioned", "u_extra", "u_mentioned"] },
+ )
+
+ expect(mockBroadcastToUser.mock.calls.map((call) => [
+ call[0],
+ (call[1] as { type: string }).type,
+ ])).toEqual([
+ ["u_mentioned", "community:mention.create"],
+ ["u_extra", "community:mention.create"],
+ ["u_plain", "community:unread.bump"],
+ ["u_mentioned", "community:unread.bump"],
+ ])
+ expect(mockInfo).toHaveBeenCalledWith(
+ "dispatch_message_notify_complete",
+ expect.objectContaining({
+ recipientCount: 2,
+ mentionedCount: 2,
+ leafTaskCount: 4,
+ mentionSuccess: 2,
+ mentionFailure: 0,
+ unreadSuccess: 2,
+ unreadFailure: 0,
+ maxActive: 3,
+ durationMs: expect.any(Number),
+ }),
)
- expect(anyMessageCreate).toBe(false)
})
- it("missing level defaults to 'all' (DM independence — resolver returns no row)", async () => {
+ it("isolates one rejected leaf and continues remaining deliveries", async () => {
mockResolveEffectiveLevelForUsers.mockResolvedValue(new Map())
- await dispatchMessageNotify(db, ctx, msg, ["u_dm"], { mentionedUserIds: [] })
- expect(bumpEvents().map((e: any) => e.userId)).toEqual(["u_dm"])
+ mockBroadcastToUser.mockImplementation((userId: string) => (
+ userId === "u1" ? Promise.reject(new Error("binding failed")) : Promise.resolve()
+ ))
+
+ await expect(dispatchMessageNotify(
+ db,
+ notifyContext,
+ message,
+ ["u0", "u1", "u2", "u3"],
+ { mentionedUserIds: [] },
+ )).resolves.toBeUndefined()
+
+ expect(mockBroadcastToUser).toHaveBeenCalledTimes(4)
+ expect(mockInfo).toHaveBeenCalledWith(
+ "dispatch_message_notify_complete",
+ expect.objectContaining({
+ unreadSuccess: 3,
+ unreadFailure: 1,
+ }),
+ )
})
- it("absorbs a resolver failure without throwing (send must not fail on a notify blip)", async () => {
- mockResolveEffectiveLevelForUsers.mockRejectedValue(new Error("d1 blip"))
- await expect(
- dispatchMessageNotify(db, ctx, msg, ["u1"], { mentionedUserIds: [] }),
- ).resolves.toBeUndefined()
- expect(bumpEvents()).toEqual([])
+ it("preserves all and mentions notification-level behavior", async () => {
+ mockResolveEffectiveLevelForUsers.mockResolvedValue(new Map([
+ ["u_all", "all"],
+ ["u_mentions_plain", "mentions"],
+ ["u_mentions_hit", "mentions"],
+ ]))
+
+ await dispatchMessageNotify(
+ db,
+ notifyContext,
+ message,
+ ["u_all", "u_mentions_plain", "u_mentions_hit"],
+ { mentionedUserIds: ["u_mentions_hit"] },
+ )
+
+ expect(eventsOfType("community:mention.create").map((event) => event.userId)).toEqual([
+ "u_mentions_hit",
+ ])
+ expect(eventsOfType("community:unread.bump").map((event) => event.userId)).toEqual([
+ "u_all",
+ "u_mentions_hit",
+ ])
})
- it("bump carries serverId + railChannelId when passed, and per-recipient isMention (inbox-dot)", async () => {
- mockResolveEffectiveLevelForUsers.mockResolvedValue(
- new Map([["u_plain", "all"], ["u_mentioned", "all"]]),
+ it("suppresses nothing-level deliveries without emitting message-create", async () => {
+ mockResolveEffectiveLevelForUsers.mockResolvedValue(new Map([["u_muted", "nothing"]]))
+
+ await dispatchMessageNotify(db, notifyContext, message, ["u_muted"], {
+ mentionedUserIds: ["u_muted"],
+ })
+
+ expect(mockBroadcastToUser).not.toHaveBeenCalled()
+ expect(mockInfo).toHaveBeenCalledWith(
+ "dispatch_message_notify_complete",
+ expect.objectContaining({ leafTaskCount: 0, maxActive: 0 }),
)
- await dispatchMessageNotify(db, ctx, msg, ["u_plain", "u_mentioned"], {
+ })
+
+ it("defaults a missing level to all", async () => {
+ mockResolveEffectiveLevelForUsers.mockResolvedValue(new Map())
+
+ await dispatchMessageNotify(db, notifyContext, message, ["u_dm"], {
+ mentionedUserIds: [],
+ })
+
+ expect(eventsOfType("community:unread.bump").map((event) => event.userId)).toEqual(["u_dm"])
+ })
+
+ it("preserves optional unread routing fields", async () => {
+ mockResolveEffectiveLevelForUsers.mockResolvedValue(new Map())
+
+ await dispatchMessageNotify(db, notifyContext, message, ["u_plain", "u_mentioned"], {
mentionedUserIds: ["u_mentioned"],
serverId: "srv_1",
- railChannelId: "parent_c1", // thread → parent row
+ railChannelId: "parent_c1",
})
- const bumps = bumpEvents()
- for (const b of bumps) {
- expect(b.serverId).toBe("srv_1")
- expect(b.railChannelId).toBe("parent_c1")
- expect(b.channelId).toBe("c1") // true message channel unchanged
+
+ const unreadEvents = eventsOfType("community:unread.bump")
+ for (const event of unreadEvents) {
+ expect(event.serverId).toBe("srv_1")
+ expect(event.railChannelId).toBe("parent_c1")
+ expect(event.channelId).toBe("c1")
}
- expect(bumps.find((b: any) => b.userId === "u_mentioned").isMention).toBe(true)
- expect(bumps.find((b: any) => b.userId === "u_plain").isMention).toBe(false)
+ expect(unreadEvents.find((event) => event.userId === "u_mentioned")?.isMention).toBe(true)
+ expect(unreadEvents.find((event) => event.userId === "u_plain")?.isMention).toBe(false)
+ })
+
+ it("omits optional unread routing fields for a direct message", async () => {
+ mockResolveEffectiveLevelForUsers.mockResolvedValue(new Map())
+
+ await dispatchMessageNotify(db, notifyContext, message, ["u_dm"], {
+ mentionedUserIds: [],
+ })
+
+ const [event] = eventsOfType("community:unread.bump")
+ expect(event.serverId).toBeUndefined()
+ expect(event.railChannelId).toBeUndefined()
+ expect(event.isMention).toBe(false)
+ })
+
+ it("absorbs a resolver failure and records its duration", async () => {
+ mockResolveEffectiveLevelForUsers.mockRejectedValue(new Error("d1 blip"))
+
+ const work = dispatchMessageNotify(db, notifyContext, message, ["u1"], {
+ mentionedUserIds: [],
+ })
+
+ expect(mockWaitUntil).toHaveBeenCalledWith(work)
+ await expect(work).resolves.toBeUndefined()
+ expect(mockBroadcastToUser).not.toHaveBeenCalled()
+ expect(mockWarn).toHaveBeenCalledWith(
+ "dispatch_message_notify_failed",
+ expect.objectContaining({
+ messageId: "m1",
+ err: "Error: d1 blip",
+ durationMs: expect.any(Number),
+ }),
+ )
})
- it("bump omits serverId/railChannelId when not passed (DM / backward-compatible frame)", async () => {
- mockResolveEffectiveLevelForUsers.mockResolvedValue(new Map([["u_dm", "all"]]))
- await dispatchMessageNotify(db, ctx, msg, ["u_dm"], { mentionedUserIds: [] })
- const [b] = bumpEvents()
- expect(b.serverId).toBeUndefined()
- expect(b.railChannelId).toBeUndefined()
- expect(b.isMention).toBe(false)
+ it("continues when Cloudflare context lookup is unavailable", async () => {
+ mockGetCloudflareContext.mockImplementation(() => {
+ throw new Error("not in a request context")
+ })
+ mockResolveEffectiveLevelForUsers.mockResolvedValue(new Map())
+
+ await expect(dispatchMessageNotify(
+ db,
+ notifyContext,
+ message,
+ ["u1"],
+ { mentionedUserIds: [] },
+ )).resolves.toBeUndefined()
+
+ expect(mockWaitUntil).not.toHaveBeenCalled()
+ expect(mockBroadcastToUser).toHaveBeenCalledTimes(1)
})
})
diff --git a/src/web/src/lib/community/notify.ts b/src/web/src/lib/community/notify.ts
index c442152e1..bd7b1b18c 100644
--- a/src/web/src/lib/community/notify.ts
+++ b/src/web/src/lib/community/notify.ts
@@ -32,11 +32,63 @@
* where "mentioned" = personal @ ∪ @everyone ∪ reply-to-me (the caller's full
* mention set — @everyone counts, no split; Gener #28).
*/
+import { getCloudflareContext } from "@opennextjs/cloudflare"
import { queries, WS_EVENTS, createLogger } from "@alook/shared"
-import type { Database, NotificationLevelValue } from "@alook/shared"
+import type { Database, NotificationLevelValue, WsMessage } from "@alook/shared"
import { broadcastToUser } from "../broadcast"
const log = createLogger({ service: "community-notify" })
+const notifyMaxActive = 3
+
+type NotifyLeafTask = {
+ kind: "mention" | "unread"
+ userId: string
+ event: WsMessage
+}
+
+type BoundedSettleResult = {
+ results: PromiseSettledResult<void>[]
+ maxActive: number
+}
+
+export async function settleNotifyTasks<T>(
+ tasks: readonly T[],
+ run: (task: T, index: number) => Promise<void>,
+): Promise<BoundedSettleResult> {
+ const results = new Array<PromiseSettledResult<void>>(tasks.length)
+ let nextIndex = 0
+ let active = 0
+ let maxActive = 0
+
+ const workers = Array.from(
+ { length: Math.min(notifyMaxActive, tasks.length) },
+ async () => {
+ while (nextIndex < tasks.length) {
+ const index = nextIndex
+ nextIndex += 1
+ active += 1
+ maxActive = Math.max(maxActive, active)
+ try {
+ await run(tasks[index], index)
+ results[index] = { status: "fulfilled", value: undefined }
+ } catch (reason) {
+ results[index] = { status: "rejected", reason }
+ } finally {
+ active -= 1
+ }
+ }
+ },
+ )
+
+ await Promise.all(workers)
+ return { results, maxActive }
+}
+
+function safeLog(write: () => void): void {
+ try {
+ write()
+ } catch {}
+}
export interface MessageNotifyContext {
/**
@@ -76,7 +128,7 @@ export function shouldDeliver(level: NotificationLevelValue, wasMentioned: boole
* expansion ∪ reply targets), already author-excluded — @everyone counts as a
* mention (Gener #28), no carve-out.
*/
-export async function dispatchMessageNotify(
+async function runMessageNotify(
db: Database,
ctx: MessageNotifyContext,
message: { id: string; channelId: string },
@@ -92,54 +144,111 @@ export async function dispatchMessageNotify(
railChannelId?: string
},
): Promise<void> {
+ const startedAt = Date.now()
try {
const { channelId } = message
- const mentioned = new Set(opts.mentionedUserIds)
+ const recipientIds = [...new Set(recipients)]
+ const mentionedIds = [...new Set(opts.mentionedUserIds)]
+ const mentioned = new Set(mentionedIds)
- const everyone = [...new Set([...recipients, ...opts.mentionedUserIds])]
+ const everyone = [...new Set([...recipientIds, ...mentionedIds])]
const levels = await queries.communityNotificationSetting.resolveEffectiveLevelForUsers(
db,
everyone,
channelId,
)
const levelOf = (userId: string): NotificationLevelValue => levels.get(userId) ?? "all"
+ const tasks: NotifyLeafTask[] = []
- // MENTION_CREATE live push — only to mentioned recipients whose level
- // delivers. A `nothing` mentioned recipient gets NO push, but their mention
- // ROW is still written by the caller.
- for (const userId of mentioned) {
+ for (const userId of mentionedIds) {
if (!shouldDeliver(levelOf(userId), true)) continue
- broadcastToUser(userId, {
- type: WS_EVENTS.MENTION_CREATE,
+ tasks.push({
+ kind: "mention",
userId,
- messageId: message.id,
- channelId,
- authorName: ctx.authorName,
- }).catch(() => {})
+ event: {
+ type: WS_EVENTS.MENTION_CREATE,
+ userId,
+ messageId: message.id,
+ channelId,
+ authorName: ctx.authorName,
+ },
+ })
}
- // Per-user UNREAD_BUMP badge — per-recipient (A muted, B not), so it rides a
- // per-user event, not a flag on the shared MESSAGE_CREATE payload.
- for (const userId of recipients) {
+ for (const userId of recipientIds) {
const isMention = mentioned.has(userId)
if (!shouldDeliver(levelOf(userId), isMention)) continue
- broadcastToUser(userId, {
- type: WS_EVENTS.UNREAD_BUMP,
+ tasks.push({
+ kind: "unread",
userId,
- channelId,
- // serverId + railChannelId let the client patch the RIGHT server tree
- // and the right (parent, for threads) sidebar row; isMention splits
- // +mention vs +unread. All optional — a client on an older frame falls
- // back to channelId + current-server behavior.
- ...(opts.serverId !== undefined ? { serverId: opts.serverId } : {}),
- ...(opts.railChannelId !== undefined ? { railChannelId: opts.railChannelId } : {}),
- isMention,
- }).catch(() => {})
+ event: {
+ type: WS_EVENTS.UNREAD_BUMP,
+ userId,
+ channelId,
+ ...(opts.serverId !== undefined ? { serverId: opts.serverId } : {}),
+ ...(opts.railChannelId !== undefined ? { railChannelId: opts.railChannelId } : {}),
+ isMention,
+ },
+ })
+ }
+
+ const { results, maxActive } = await settleNotifyTasks(
+ tasks,
+ (task) => broadcastToUser(task.userId, task.event),
+ )
+ let mentionSuccess = 0
+ let mentionFailure = 0
+ let unreadSuccess = 0
+ let unreadFailure = 0
+
+ for (const [index, result] of results.entries()) {
+ const succeeded = result.status === "fulfilled"
+ if (tasks[index].kind === "mention") {
+ if (succeeded) mentionSuccess += 1
+ else mentionFailure += 1
+ } else if (succeeded) {
+ unreadSuccess += 1
+ } else {
+ unreadFailure += 1
+ }
}
+
+ safeLog(() => log.info("dispatch_message_notify_complete", {
+ messageId: message.id,
+ recipientCount: recipientIds.length,
+ mentionedCount: mentionedIds.length,
+ leafTaskCount: tasks.length,
+ mentionSuccess,
+ mentionFailure,
+ unreadSuccess,
+ unreadFailure,
+ maxActive,
+ durationMs: Date.now() - startedAt,
+ }))
} catch (err) {
- log.warn("dispatch_message_notify_failed", {
+ safeLog(() => log.warn("dispatch_message_notify_failed", {
messageId: message.id,
err: String(err),
- })
+ durationMs: Date.now() - startedAt,
+ }))
}
}
+
+export function dispatchMessageNotify(
+ db: Database,
+ ctx: MessageNotifyContext,
+ message: { id: string; channelId: string },
+ recipients: string[],
+ opts: {
+ mentionedUserIds: string[]
+ serverId?: string
+ railChannelId?: string
+ },
+): Promise<void> {
+ const work = runMessageNotify(db, ctx, message, recipients, opts)
+ try {
+ const cloudflareContext = getCloudflareContext()
+ cloudflareContext.ctx.waitUntil(work)
+ } catch {}
+ return work
+}