Skip to content

armgit / alook

Public Imported from GitHub
0

Multi-Agent Collaboration for Team and Friends

fix(community): retry transient D1 reads

Gener8d6ecaa542ff
diff --git a/src/web/src/app/api/community/daemon/resync-wakes/route.ts b/src/web/src/app/api/community/daemon/resync-wakes/route.ts
index e112993d3..3b6c59b81 100644
--- a/src/web/src/app/api/community/daemon/resync-wakes/route.ts
+++ b/src/web/src/app/api/community/daemon/resync-wakes/route.ts
@@ -1,5 +1,5 @@
import { NextResponse } from "next/server"
-import { queries, dispatchOneUnreadWake } from "@alook/shared"
+import { queries, dispatchOneUnreadWake, withD1Retry } from "@alook/shared"
import { getDb } from "@/lib/db"
import { withCommunityDaemonAuth } from "@/lib/middleware/community-daemon-auth"
@@ -24,11 +24,17 @@ import { withCommunityDaemonAuth } from "@/lib/middleware/community-daemon-auth"
*/
export const POST = withCommunityDaemonAuth(async (_req, ctx) => {
const db = getDb(ctx.env.DB)
- const bots = await queries.communityBot.listBotsForMachine(db, ctx.machineId)
+ const bots = await withD1Retry(
+ () => queries.communityBot.listBotsForMachine(db, ctx.machineId),
+ { route: "community/daemon/resync-wakes:list-bots" },
+ )
let woken = 0
for (const bot of bots) {
- const latest = await queries.communityAgentInbox.getLatestUnreadMessageForAgent(db, bot.id)
+ const latest = await withD1Retry(
+ () => queries.communityAgentInbox.getLatestUnreadMessageForAgent(db, bot.id),
+ { route: "community/daemon/resync-wakes:latest-unread" },
+ )
if (!latest) continue
const result = await dispatchOneUnreadWake(db, ctx.env, { messageId: latest.messageId, botUserId: bot.id })
if (result.outcome === "sent") woken++
diff --git a/src/web/src/app/api/community/servers/[id]/route.ts b/src/web/src/app/api/community/servers/[id]/route.ts
index cab852a9a..aecea3a03 100644
--- a/src/web/src/app/api/community/servers/[id]/route.ts
+++ b/src/web/src/app/api/community/servers/[id]/route.ts
@@ -10,6 +10,7 @@ import {
UNCATEGORIZED_CATEGORY_ID,
WS_EVENTS,
slugify,
+ withD1Retry,
} from "@alook/shared"
import { fanOutToServerMembers } from "@/lib/community/fanout"
import { logAudit } from "@/lib/community/audit"
@@ -24,9 +25,10 @@ export const GET = withAuth(async (_req, ctx) => {
const auth = await requireServerMember(db, serverId, ctx.userId)
if (!auth.ok) return writeError(auth.error, auth.status)
- const visibleChannelIds = await queries.communityChannel.listVisibleChannelIdsForUser(db, ctx.userId)
- const [server, rawChannels, categories, unreadRows] = await Promise.all([
- queries.communityServer.getServer(db, serverId),
+ const [server, rawChannels, categories, unreadRows] = await withD1Retry(async () => {
+ const visibleChannelIds = await queries.communityChannel.listVisibleChannelIdsForUser(db, ctx.userId)
+ return Promise.all([
+ queries.communityServer.getServer(db, serverId),
// Viewer-scoped: private-category channels are only returned if the viewer
// is the channel creator or an added member (admins get NO special
// visibility). Private category HEADERS still appear (below) so members can
@@ -36,8 +38,9 @@ export const GET = withAuth(async (_req, ctx) => {
where: (t, { eq }) => eq(t.serverId, serverId),
orderBy: (t, { asc }) => [asc(t.position)],
}),
- queries.communityInbox.listUnreadChannels(db, ctx.userId, visibleChannelIds),
- ])
+ queries.communityInbox.listUnreadChannels(db, ctx.userId, visibleChannelIds),
+ ])
+ }, { route: "community/servers/detail" })
if (!server) return writeError("server not found", 404)
diff --git a/src/web/src/app/api/community/servers/route.ts b/src/web/src/app/api/community/servers/route.ts
index 36c25a7b2..f661a82b4 100644
--- a/src/web/src/app/api/community/servers/route.ts
+++ b/src/web/src/app/api/community/servers/route.ts
@@ -8,6 +8,7 @@ import {
ROLES,
WS_EVENTS,
slugify,
+ withD1Retry,
} from "@alook/shared"
import { withCommunityActor, rejectBot } from "@/lib/middleware/community-actor"
import { fanOutToServerMembers } from "@/lib/community/fanout"
@@ -23,7 +24,10 @@ import { serverIconUrl } from "@/lib/community/storage"
*/
export const GET = withCommunityActor(async (_req, ctx) => {
const db = getDb(ctx.env.DB)
- const rows = await queries.communityServer.listUserServers(db, ctx.actor.userId)
+ const rows = await withD1Retry(
+ () => queries.communityServer.listUserServers(db, ctx.actor.userId),
+ { route: "community/servers:list" },
+ )
const servers = rows.map((row) => ({ ...row, icon: serverIconUrl(row) }))
return writeJSON({ servers })
})
diff --git a/src/web/src/lib/community/permissions.ts b/src/web/src/lib/community/permissions.ts
index 83e54c7ab..a5a07bc2b 100644
--- a/src/web/src/lib/community/permissions.ts
+++ b/src/web/src/lib/community/permissions.ts
@@ -1,4 +1,4 @@
-import { queries, canManageServer, canSeePrivateChannel } from "@alook/shared"
+import { queries, canManageServer, canSeePrivateChannel, withD1Retry } from "@alook/shared"
import type { Database } from "@alook/shared"
type PermissionError =
@@ -49,7 +49,10 @@ export async function requireChannelMember(
channelId: string,
userId: string,
): Promise<Result<NonNullable<Awaited<ReturnType<typeof queries.communityChannel.getChannelForMember>>>>> {
- const channel = await queries.communityChannel.getChannelForMember(db, channelId, userId)
+ const channel = await withD1Retry(
+ () => queries.communityChannel.getChannelForMember(db, channelId, userId),
+ { route: "community/permissions:channel-member" },
+ )
if (!channel) return err(403, "forbidden")
return ok(channel)
}
diff --git a/src/ws-do/src/ws-durable.test.ts b/src/ws-do/src/ws-durable.test.ts
index 4e3750c92..ea44ee280 100644
--- a/src/ws-do/src/ws-durable.test.ts
+++ b/src/ws-do/src/ws-durable.test.ts
@@ -273,6 +273,7 @@ vi.mock("@alook/shared", () => {
},
createDb: (d1: unknown) => mockCreateDb(d1),
createLogger: () => noopLogger,
+ withD1Retry: async <T>(fn: () => Promise<T>): Promise<T> => fn(),
// Real reach-trait impls — fanOutTyping's recipient split dispatches on
// channelReach (B2 reach axis single source) to route a thread/forum_post to
// the participant set, a dm to its members, else the access audience. Mirror
diff --git a/src/ws-do/src/ws-durable.ts b/src/ws-do/src/ws-durable.ts
index 939162fd9..f141bf4f8 100644
--- a/src/ws-do/src/ws-durable.ts
+++ b/src/ws-do/src/ws-durable.ts
@@ -19,6 +19,7 @@ import {
channelReach,
isStoredChannelType,
WS_EVENTS,
+ withD1Retry,
} from "@alook/shared"
import type { CommunityMachineRuntime, CommunityMachineSummary } from "@alook/shared"
@@ -892,7 +893,10 @@ export class WebSocketDurableObject extends DurableObject<Env> {
resolveBinding: () => queries.communityBot.getBotBinding(db, agentId),
isMatch: (binding) => binding.machineId === identity.machineId,
write: async () => {
- const prior = await queries.communityUserProfile.getProfile(db, agentId)
+ const prior = await withD1Retry(
+ () => queries.communityUserProfile.getProfile(db, agentId),
+ { route: "ws-do:agent-activity-profile-read" },
+ )
const priorEmoji = prior?.statusEmoji ?? null
// `status_text` defaults to "" (schema), so an unset status reads back
// as (null, "") not (null, null). Normalize "" → null so "no status"
@@ -920,10 +924,13 @@ export class WebSocketDurableObject extends DurableObject<Env> {
? { emoji: priorEmoji as string, text: priorText as string }
: pickBotActivityPreset(state, Math.random())
if (preset.emoji === priorEmoji && preset.text === priorText) return
- await queries.communityUserProfile.updateProfile(db, agentId, {
- statusEmoji: preset.emoji,
- statusText: preset.text,
- })
+ await withD1Retry(
+ () => queries.communityUserProfile.updateProfile(db, agentId, {
+ statusEmoji: preset.emoji,
+ statusText: preset.text,
+ }),
+ { route: "ws-do:agent-activity-profile" },
+ )
await this.broadcastToAudience(agentId, {
type: WS_EVENTS.STATUS_UPDATE,
userId: agentId,
@@ -950,7 +957,10 @@ export class WebSocketDurableObject extends DurableObject<Env> {
frameType: "agent_typing",
agentId,
machineId: identity.machineId,
- resolveBinding: () => queries.communityBot.getBotBindingWithOwner(db, agentId),
+ resolveBinding: () => withD1Retry(
+ () => queries.communityBot.getBotBindingWithOwner(db, agentId),
+ { route: "ws-do:agent-typing-binding" },
+ ),
isMatch: (binding) => binding.machineId === identity.machineId,
write: async (binding) => {
// Channel membership is enforced inside `fanOutTyping` — no need to
@@ -977,7 +987,10 @@ export class WebSocketDurableObject extends DurableObject<Env> {
frameType: "agent_typing_stop",
agentId,
machineId: identity.machineId,
- resolveBinding: () => queries.communityBot.getBotBindingWithOwner(db, agentId),
+ resolveBinding: () => withD1Retry(
+ () => queries.communityBot.getBotBindingWithOwner(db, agentId),
+ { route: "ws-do:agent-typing-stop-binding" },
+ ),
isMatch: (binding) => binding.machineId === identity.machineId,
// Channel membership enforced inside `fanOutTypingStop`.
write: () => this.fanOutTypingStop(agentId, channelId),
@@ -1015,7 +1028,10 @@ export class WebSocketDurableObject extends DurableObject<Env> {
agentId,
machineId: identity.machineId,
writeCategory: "ws_frame_dropped_write",
- resolveBinding: () => queries.communityBot.getBotBindingWithOwner(db, agentId),
+ resolveBinding: () => withD1Retry(
+ () => queries.communityBot.getBotBindingWithOwner(db, agentId),
+ { route: "ws-do:agent-session-binding" },
+ ),
isMatch: (binding) => binding.machineId === identity.machineId,
write: async (binding) => {
// Per-kind audit — nap and reset stay distinct kinds so my-bots reads
@@ -1112,7 +1128,10 @@ export class WebSocketDurableObject extends DurableObject<Env> {
// failures stay on the plain `ws_frame_dropped` category via the
// helper's default.
writeCategory: "ws_frame_dropped_write",
- resolveBinding: () => queries.communityBot.getBotBindingWithOwner(db, frame.agentId),
+ resolveBinding: () => withD1Retry(
+ () => queries.communityBot.getBotBindingWithOwner(db, frame.agentId),
+ { route: "ws-do:bot-audit-binding" },
+ ),
isMatch: (binding) => binding.machineId === identity.machineId,
write: async (binding) => {
const inserted = await queries.communityBotAuditLog.insertBotActivityEventAndPrune(db, {
@@ -1536,14 +1555,20 @@ export class WebSocketDurableObject extends DurableObject<Env> {
// channel — same authz the HTTP layer enforces via requireChannelMember
// (src/web/src/lib/community/permissions.ts). For a DM (type=dm) it
// resolves via the sender's relation='access' member row.
- const membership = await queries.communityChannel.getChannelForMember(db, channelId, senderUserId)
+ const membership = await withD1Retry(
+ () => queries.communityChannel.getChannelForMember(db, channelId, senderUserId),
+ { route: "ws-do:agent-typing-membership" },
+ )
if (!membership) {
log.warn("fanOutTyping: sender not a channel member", { senderUserId, channelId })
return
}
// Recipient set — the shared reach recipient-split (same as message
// fan-out), then exclude the sender.
- recipientUserIds = await this.typingRecipientUserIds(db, channelId)
+ recipientUserIds = await withD1Retry(
+ () => this.typingRecipientUserIds(db, channelId),
+ { route: "ws-do:agent-typing-recipients" },
+ )
recipientUserIds = recipientUserIds.filter((id) => id !== senderUserId)
if (recipientUserIds.length === 0) return
@@ -1574,12 +1599,18 @@ export class WebSocketDurableObject extends DurableObject<Env> {
channelId: string,
): Promise<void> {
const db = createDb(this.env.DB)
- const membership = await queries.communityChannel.getChannelForMember(db, channelId, senderUserId)
+ const membership = await withD1Retry(
+ () => queries.communityChannel.getChannelForMember(db, channelId, senderUserId),
+ { route: "ws-do:agent-typing-stop-membership" },
+ )
if (!membership) {
log.warn("fanOutTypingStop: sender not a channel member", { senderUserId, channelId })
return
}
- let recipientUserIds = await this.typingRecipientUserIds(db, channelId)
+ let recipientUserIds = await withD1Retry(
+ () => this.typingRecipientUserIds(db, channelId),
+ { route: "ws-do:agent-typing-stop-recipients" },
+ )
recipientUserIds = recipientUserIds.filter((id) => id !== senderUserId)
if (recipientUserIds.length === 0) return
const body = JSON.stringify({