Skip to content

armgit / alook

Public Imported from GitHub
0

Multi-Agent Collaboration for Team and Friends

fix(ws-do): bound bulk fan-out concurrency

Generd6d185e51d0b
diff --git a/src/ws-do/src/routes/broadcast.test.ts b/src/ws-do/src/routes/broadcast.test.ts
index b645ab6dd..7b69d8aa3 100644
--- a/src/ws-do/src/routes/broadcast.test.ts
+++ b/src/ws-do/src/routes/broadcast.test.ts
@@ -164,6 +164,26 @@ describe("ws-do router", () => {
await expect(res.json()).resolves.toEqual({ sent: 0 })
expect(doMock.idFromName).not.toHaveBeenCalled()
expect(doMock.stubFetch).not.toHaveBeenCalled()
+ expect(loggerMocks.info).toHaveBeenCalledWith(
+ "bulk user broadcast complete",
+ expect.objectContaining({
+ targetCount: 0,
+ resultCount: 0,
+ successCount: 0,
+ failureCount: 0,
+ failureCounts: {
+ throw: 0,
+ "non-ok": 0,
+ "invalid-json": 0,
+ "invalid-sent": 0,
+ },
+ sent: 0,
+ maxActive: 0,
+ batchSize: 40,
+ batchCount: 0,
+ durationMs: expect.any(Number),
+ }),
+ )
})
it("returns sent zero when exclusion removes the only unique target", async () => {
@@ -252,6 +272,20 @@ describe("ws-do router", () => {
expect(maximum).toBe(Math.min(targetCount, 40))
if (targetCount > 40) expect(startedAfterCompleted[40]).toBe(40)
if (targetCount > 80) expect(startedAfterCompleted[80]).toBe(80)
+ expect(loggerMocks.info).toHaveBeenCalledWith(
+ "bulk user broadcast complete",
+ expect.objectContaining({
+ targetCount,
+ resultCount: targetCount,
+ successCount: targetCount,
+ failureCount: 0,
+ sent: targetCount,
+ maxActive: Math.min(targetCount, 40),
+ batchSize: 40,
+ batchCount: Math.ceil(targetCount / 40),
+ durationMs: expect.any(Number),
+ }),
+ )
},
)
@@ -284,7 +318,23 @@ describe("ws-do router", () => {
)
expect(loggerMocks.info).toHaveBeenCalledWith(
"bulk user broadcast complete",
- expect.objectContaining({ successCount: 2, failureCount: 4, sent: 5 }),
+ expect.objectContaining({
+ targetCount: 6,
+ resultCount: 6,
+ successCount: 2,
+ failureCount: 4,
+ failureCounts: {
+ throw: 1,
+ "non-ok": 1,
+ "invalid-json": 1,
+ "invalid-sent": 1,
+ },
+ sent: 5,
+ maxActive: 6,
+ batchSize: 40,
+ batchCount: 1,
+ durationMs: expect.any(Number),
+ }),
)
})
})
diff --git a/src/ws-do/src/routes/broadcast.ts b/src/ws-do/src/routes/broadcast.ts
index d4a46e79e..b40811719 100644
--- a/src/ws-do/src/routes/broadcast.ts
+++ b/src/ws-do/src/routes/broadcast.ts
@@ -1,5 +1,6 @@
import type { RouterContext } from "../router-context"
import { createInternalUserBroadcastRequest } from "../internal-user-broadcast"
+import { settleInBatches } from "../settle-in-batches"
const maxBulkUserIds = 1000
const bulkBatchSize = 40
@@ -14,6 +15,8 @@ type BulkTargetResult =
| { ok: true; sent: number }
| { ok: false; failureKind: "non-ok" | "invalid-json" | "invalid-sent"; status: number }
+type BulkFailureKind = "throw" | "non-ok" | "invalid-json" | "invalid-sent"
+
function isRecord(value: unknown): value is Record<string, unknown> {
return typeof value === "object" && value !== null && !Array.isArray(value)
}
@@ -115,38 +118,63 @@ export async function handleUsersBroadcast({ request, env, url, traceId, log }:
reqLog.debug("broadcasting to users")
const messageBody = JSON.stringify(body.message)
+ const startedAt = Date.now()
+ let active = 0
+ let maxActive = 0
let successCount = 0
let failureCount = 0
let sent = 0
+ const failureCounts: Record<BulkFailureKind, number> = {
+ throw: 0,
+ "non-ok": 0,
+ "invalid-json": 0,
+ "invalid-sent": 0,
+ }
- for (let start = 0; start < targetUserIds.length; start += bulkBatchSize) {
- const batch = targetUserIds.slice(start, start + bulkBatchSize)
- const results = await Promise.allSettled(
- batch.map((userId) => broadcastToBulkTarget(env, userId, messageBody)),
- )
- for (const [index, result] of results.entries()) {
- const userId = batch[index]
- if (result.status === "rejected") {
- failureCount += 1
- reqLog.warn("bulk user broadcast target failed", {
- userId,
- failureKind: "throw",
- err: String(result.reason),
- })
- } else if (!result.value.ok) {
- failureCount += 1
- reqLog.warn("bulk user broadcast target failed", {
- userId,
- failureKind: result.value.failureKind,
- status: result.value.status,
- })
- } else {
- successCount += 1
- sent += result.value.sent
- }
+ const results = await settleInBatches(targetUserIds, async (userId) => {
+ active += 1
+ maxActive = Math.max(maxActive, active)
+ try {
+ return await broadcastToBulkTarget(env, userId, messageBody)
+ } finally {
+ active -= 1
+ }
+ }, bulkBatchSize)
+
+ for (const [index, result] of results.entries()) {
+ const userId = targetUserIds[index]
+ if (result.status === "rejected") {
+ failureCount += 1
+ failureCounts.throw += 1
+ reqLog.warn("bulk user broadcast target failed", {
+ userId,
+ failureKind: "throw",
+ })
+ } else if (!result.value.ok) {
+ failureCount += 1
+ failureCounts[result.value.failureKind] += 1
+ reqLog.warn("bulk user broadcast target failed", {
+ userId,
+ failureKind: result.value.failureKind,
+ status: result.value.status,
+ })
+ } else {
+ successCount += 1
+ sent += result.value.sent
}
}
- reqLog.info("bulk user broadcast complete", { successCount, failureCount, sent })
+ reqLog.info("bulk user broadcast complete", {
+ targetCount: targetUserIds.length,
+ resultCount: results.length,
+ successCount,
+ failureCount,
+ failureCounts,
+ sent,
+ maxActive,
+ batchSize: bulkBatchSize,
+ batchCount: Math.ceil(targetUserIds.length / bulkBatchSize),
+ durationMs: Date.now() - startedAt,
+ })
return Response.json({ sent })
}
diff --git a/src/ws-do/src/routes/presence.test.ts b/src/ws-do/src/routes/presence.test.ts
index 4c43cd7c7..94c750d77 100644
--- a/src/ws-do/src/routes/presence.test.ts
+++ b/src/ws-do/src/routes/presence.test.ts
@@ -14,6 +14,16 @@ const mockGetActiveDoNamesForMachine = sharedMocks.getActiveDoNamesForMachine
const loggerMocks = {
child: sharedMocks.loggerChild,
debug: sharedMocks.loggerDebug,
+ info: sharedMocks.loggerInfo,
+ warn: sharedMocks.loggerWarn,
+}
+
+function deferred<T>() {
+ let resolve!: (value: T) => void
+ const promise = new Promise<T>((resolvePromise) => {
+ resolve = resolvePromise
+ })
+ return { promise, resolve }
}
describe("ws-do router", () => {
@@ -55,7 +65,31 @@ describe("ws-do router", () => {
expect(res.status).toBe(200)
expect(await res.json()).toEqual({ online: [] })
+ expect(doMock.idFromName).not.toHaveBeenCalled()
+ expect(doMock.get).not.toHaveBeenCalled()
expect(doMock.stubFetch).not.toHaveBeenCalled()
+ expect(loggerMocks.info).toHaveBeenCalledWith(
+ "bulk_presence_check_complete",
+ expect.objectContaining({
+ targetCount: 0,
+ resultCount: 0,
+ successCount: 0,
+ onlineCount: 0,
+ offlineCount: 0,
+ staleCount: 0,
+ failureCount: 0,
+ failureCounts: {
+ throw: 0,
+ "non-ok": 0,
+ "invalid-json": 0,
+ "invalid-body": 0,
+ },
+ maxActive: 0,
+ batchSize: 40,
+ batchCount: 0,
+ durationMs: expect.any(Number),
+ }),
+ )
})
it("returns only online ids from mixed responses", async () => {
@@ -76,7 +110,7 @@ describe("ws-do router", () => {
const body = await res.json() as { online: string[] }
expect(res.status).toBe(200)
- expect(body.online.sort()).toEqual(["u1", "u3"])
+ expect(body.online).toEqual(["u1", "u3"])
})
it("returns empty online list when all ids are offline", async () => {
@@ -160,12 +194,63 @@ describe("ws-do router", () => {
expect(res.status).toBe(400)
})
- it("tolerates a per-id DO fetch throwing — other ids still evaluated", async () => {
- let call = 0
- doMock.stubFetch.mockImplementation(() => {
- call++
- if (call === 1) return Promise.reject(new Error("boom"))
- return Promise.resolve(new Response(JSON.stringify({ online: true }), { status: 200 }))
+ it.each([1, 40, 41, 81, 1000])(
+ "limits %i presence targets to sequential batches of at most forty",
+ async (targetCount) => {
+ let active = 0
+ let completed = 0
+ let maximum = 0
+ const startedAfterCompleted: number[] = []
+ doMock.stubFetch.mockImplementation(async () => {
+ startedAfterCompleted.push(completed)
+ active += 1
+ maximum = Math.max(maximum, active)
+ await Promise.resolve()
+ active -= 1
+ completed += 1
+ return new Response(JSON.stringify({ online: false }), { status: 200 })
+ })
+ const ids = Array.from({ length: targetCount }, (_, index) => `u${index}`)
+
+ const res = await handler.fetch(new Request("http://localhost/presence/users", {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ ids }),
+ }), env as any)
+
+ expect(res.status).toBe(200)
+ await expect(res.json()).resolves.toEqual({ online: [] })
+ expect(maximum).toBe(Math.min(targetCount, 40))
+ if (targetCount > 40) expect(startedAfterCompleted[40]).toBe(40)
+ if (targetCount > 80) expect(startedAfterCompleted[80]).toBe(80)
+ expect(loggerMocks.info).toHaveBeenCalledWith(
+ "bulk_presence_check_complete",
+ expect.objectContaining({
+ targetCount,
+ resultCount: targetCount,
+ successCount: targetCount,
+ onlineCount: 0,
+ offlineCount: targetCount,
+ staleCount: 0,
+ failureCount: 0,
+ maxActive: Math.min(targetCount, 40),
+ batchSize: 40,
+ batchCount: Math.ceil(targetCount / 40),
+ durationMs: expect.any(Number),
+ }),
+ )
+ },
+ )
+
+ it("keeps online ids in input order when target responses settle out of order", async () => {
+ const gates = new Map([
+ ["u1", deferred<Response>()],
+ ["u2", deferred<Response>()],
+ ["u3", deferred<Response>()],
+ ])
+ doMock.stubFetch.mockImplementation((request: Request) => {
+ const userId = new URL(request.url).searchParams.get("userId")
+ return gates.get(userId ?? "")?.promise ?? Promise.reject(new Error("missing gate"))
})
const req = new Request("http://localhost/presence/users", {
@@ -173,11 +258,92 @@ describe("ws-do router", () => {
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ ids: ["u1", "u2", "u3"] }),
})
- const res = await handler.fetch(req, env as any)
- const body = await res.json() as { online: string[] }
+ const responsePromise = handler.fetch(req, env as any)
+
+ await vi.waitFor(() => expect(doMock.stubFetch).toHaveBeenCalledTimes(3))
+ gates.get("u3")?.resolve(Response.json({ online: true }))
+ gates.get("u2")?.resolve(Response.json({ online: false }))
+ gates.get("u1")?.resolve(Response.json({ online: true }))
+
+ const res = await responsePromise
expect(res.status).toBe(200)
- expect(body.online.sort()).toEqual(["u2", "u3"])
+ await expect(res.json()).resolves.toEqual({ online: ["u1", "u3"] })
+ })
+
+ it("classifies partial failures and continues evaluating every target", async () => {
+ doMock.stubFetch.mockImplementation(async () => {
+ const index = doMock.stubFetch.mock.calls.length - 1
+ if (index === 0) throw new Error("stub down")
+ if (index === 1) return new Response("unavailable", { status: 503 })
+ if (index === 2) return new Response("not-json", { status: 200 })
+ if (index === 3) return Response.json({ online: "yes" })
+ if (index === 4) return Response.json({ online: false, stale: true })
+ if (index === 5) return Response.json({ online: false })
+ return Response.json({ online: true })
+ })
+
+ const ids = [
+ "throws",
+ "non-ok",
+ "bad-json",
+ "bad-body",
+ "stale",
+ "offline",
+ "online-1",
+ "online-2",
+ ]
+ const res = await handler.fetch(new Request("http://localhost/presence/users", {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ ids }),
+ }), env as any)
+
+ expect(res.status).toBe(200)
+ await expect(res.json()).resolves.toEqual({ online: ["online-1", "online-2"] })
+ expect(doMock.stubFetch).toHaveBeenCalledTimes(ids.length)
+ expect(loggerMocks.warn.mock.calls.map(([, fields]) => (
+ fields as { failureKind?: string }
+ ).failureKind)).toEqual(["throw", "non-ok", "invalid-json", "invalid-body"])
+ expect(loggerMocks.info).toHaveBeenCalledWith(
+ "bulk_presence_check_complete",
+ expect.objectContaining({
+ targetCount: 8,
+ resultCount: 8,
+ successCount: 3,
+ onlineCount: 2,
+ offlineCount: 1,
+ staleCount: 1,
+ failureCount: 4,
+ failureCounts: {
+ throw: 1,
+ "non-ok": 1,
+ "invalid-json": 1,
+ "invalid-body": 1,
+ },
+ maxActive: 8,
+ batchSize: 40,
+ batchCount: 1,
+ durationMs: expect.any(Number),
+ }),
+ )
+ const completionFields = loggerMocks.info.mock.calls.find(
+ ([message]) => message === "bulk_presence_check_complete",
+ )?.[1] as Record<string, unknown>
+ expect(Object.keys(completionFields).sort()).toEqual([
+ "batchCount",
+ "batchSize",
+ "durationMs",
+ "failureCount",
+ "failureCounts",
+ "maxActive",
+ "offlineCount",
+ "onlineCount",
+ "resultCount",
+ "staleCount",
+ "successCount",
+ "targetCount",
+ ])
})
})
diff --git a/src/ws-do/src/routes/presence.ts b/src/ws-do/src/routes/presence.ts
index bf14259bb..092e6cd8b 100644
--- a/src/ws-do/src/routes/presence.ts
+++ b/src/ws-do/src/routes/presence.ts
@@ -1,4 +1,44 @@
import type { RouterContext } from "../router-context"
+import { settleInBatches } from "../settle-in-batches"
+
+const presenceBatchSize = 40
+
+type BatchPresenceTargetResult =
+ | { kind: "online" }
+ | { kind: "offline" }
+ | { kind: "stale" }
+ | { kind: "non-ok"; status: number }
+ | { kind: "invalid-json"; status: number }
+ | { kind: "invalid-body"; status: number }
+
+type BatchPresenceFailureKind = "throw" | "non-ok" | "invalid-json" | "invalid-body"
+
+function isRecord(value: unknown): value is Record<string, unknown> {
+ return typeof value === "object" && value !== null && !Array.isArray(value)
+}
+
+async function checkBatchPresenceTarget(env: Env, userId: string): Promise<BatchPresenceTargetResult> {
+ const doId = env.WS_DO.idFromName("user:" + userId)
+ const stub = env.WS_DO.get(doId)
+ const response = await stub.fetch(
+ new Request(`http://internal/check-user-online?userId=${encodeURIComponent(userId)}`),
+ )
+ if (!response.ok) return { kind: "non-ok", status: response.status }
+
+ let data: unknown
+ try {
+ data = await response.json()
+ } catch {
+ return { kind: "invalid-json", status: response.status }
+ }
+ if (
+ !isRecord(data)
+ || typeof data.online !== "boolean"
+ || (data.stale !== undefined && typeof data.stale !== "boolean")
+ ) return { kind: "invalid-body", status: response.status }
+ if (data.stale) return { kind: "stale" }
+ return data.online ? { kind: "online" } : { kind: "offline" }
+}
export async function handleBatchPresence({ request, env, url, traceId, log }: RouterContext): Promise<Response | null> {
// Bulk presence: fan out one DO fetch per id and return the online subset.
@@ -22,29 +62,70 @@ export async function handleBatchPresence({ request, env, url, traceId, log }: R
const reqLog = log.child({ traceId, count: ids.length })
reqLog.debug("bulk presence check")
- if (ids.length === 0) return Response.json({ online: [] })
-
- const results = await Promise.allSettled(
- ids.map((id) => {
- const doId = env.WS_DO.idFromName("user:" + id)
- const stub = env.WS_DO.get(doId)
- return stub.fetch(
- new Request(`http://internal/check-user-online?userId=${encodeURIComponent(id)}`),
- )
- }),
- )
- const online: string[] = []
- for (let i = 0; i < results.length; i++) {
- const r = results[i]
- if (r.status !== "fulfilled" || !r.value.ok) continue
+ const startedAt = Date.now()
+ let active = 0
+ let maxActive = 0
+ const results = await settleInBatches(ids, async (id) => {
+ active += 1
+ maxActive = Math.max(maxActive, active)
try {
- const data = await r.value.json() as { online?: boolean; stale?: boolean }
- // Skip stale responses — a fail-closed `online:false` from D1 must
- // not be surfaced as authoritative offline to fan-out callers.
- if (data.stale) continue
- if (data.online) online.push(ids[i])
- } catch { /* skip */ }
+ return await checkBatchPresenceTarget(env, id)
+ } finally {
+ active -= 1
+ }
+ }, presenceBatchSize)
+ const online: string[] = []
+ let offlineCount = 0
+ let staleCount = 0
+ let failureCount = 0
+ const failureCounts: Record<BatchPresenceFailureKind, number> = {
+ throw: 0,
+ "non-ok": 0,
+ "invalid-json": 0,
+ "invalid-body": 0,
}
+ for (const [index, result] of results.entries()) {
+ if (result.status === "rejected") {
+ failureCount += 1
+ failureCounts.throw += 1
+ reqLog.warn("bulk_presence_target_failed", {
+ userId: ids[index],
+ failureKind: "throw",
+ })
+ continue
+ }
+
+ if (result.value.kind === "online") {
+ online.push(ids[index])
+ } else if (result.value.kind === "offline") {
+ offlineCount += 1
+ } else if (result.value.kind === "stale") {
+ staleCount += 1
+ } else {
+ failureCount += 1
+ failureCounts[result.value.kind] += 1
+ reqLog.warn("bulk_presence_target_failed", {
+ userId: ids[index],
+ failureKind: result.value.kind,
+ status: result.value.status,
+ })
+ }
+ }
+
+ reqLog.info("bulk_presence_check_complete", {
+ targetCount: ids.length,
+ resultCount: results.length,
+ successCount: online.length + offlineCount,
+ onlineCount: online.length,
+ offlineCount,
+ staleCount,
+ failureCount,
+ failureCounts,
+ maxActive,
+ batchSize: presenceBatchSize,
+ batchCount: Math.ceil(ids.length / presenceBatchSize),
+ durationMs: Date.now() - startedAt,
+ })
return Response.json({ online })
}
diff --git a/src/ws-do/src/settle-in-batches.test.ts b/src/ws-do/src/settle-in-batches.test.ts
new file mode 100644
index 000000000..0b5f9de34
--- /dev/null
+++ b/src/ws-do/src/settle-in-batches.test.ts
@@ -0,0 +1,105 @@
+import { describe, expect, it, vi } from "vitest"
+import { settleInBatches } from "./settle-in-batches"
+
+function deferred<T>() {
+ let resolve!: (value: T) => void
+ let reject!: (reason: unknown) => void
+ const promise = new Promise<T>((resolvePromise, rejectPromise) => {
+ resolve = resolvePromise
+ reject = rejectPromise
+ })
+ return { promise, resolve, reject }
+}
+
+describe("settleInBatches", () => {
+ it.each([0, -1, 1.5, Number.NaN, Number.POSITIVE_INFINITY, Number.NEGATIVE_INFINITY])(
+ "throws synchronously for invalid batch size %s",
+ (batchSize) => {
+ const mapper = vi.fn(async (value: number) => value)
+
+ expect(() => settleInBatches([1], mapper, batchSize)).toThrow(RangeError)
+ expect(mapper).not.toHaveBeenCalled()
+ },
+ )
+
+ it.each([0, 1, 40, 41, 81, 1000])(
+ "settles %i inputs in input-index order",
+ async (inputCount) => {
+ const inputs = Array.from({ length: inputCount }, (_, index) => index)
+ let active = 0
+ let maxActive = 0
+ const mapper = vi.fn(async (value: number, index: number) => {
+ active += 1
+ maxActive = Math.max(maxActive, active)
+ await Promise.resolve()
+ active -= 1
+ return `${index}:${value}`
+ })
+
+ const results = await settleInBatches(inputs, mapper, 40)
+
+ expect(results).toEqual(inputs.map((value, index) => ({
+ status: "fulfilled",
+ value: `${index}:${value}`,
+ })))
+ expect(mapper).toHaveBeenCalledTimes(inputCount)
+ expect(maxActive).toBe(Math.min(inputCount, 40))
+ },
+ )
+
+ it("waits for every item in one batch before starting the next", async () => {
+ const gates = Array.from({ length: 41 }, () => deferred<number>())
+ const started: number[] = []
+ const execution = settleInBatches(gates, async (gate, index) => {
+ started.push(index)
+ return gate.promise
+ }, 40)
+
+ await vi.waitFor(() => expect(started).toEqual(Array.from({ length: 40 }, (_, index) => index)))
+ for (let index = 0; index < 39; index++) gates[index].resolve(index)
+ await Promise.resolve()
+ expect(started).toHaveLength(40)
+
+ gates[39].resolve(39)
+ await vi.waitFor(() => expect(started).toHaveLength(41))
+ gates[40].resolve(40)
+
+ await expect(execution).resolves.toEqual(Array.from({ length: 41 }, (_, index) => ({
+ status: "fulfilled",
+ value: index,
+ })))
+ })
+
+ it("preserves input indexes when items settle out of order", async () => {
+ const gates = Array.from({ length: 3 }, () => deferred<string>())
+ const execution = settleInBatches(gates, (gate) => gate.promise, 3)
+
+ gates[2].resolve("third")
+ gates[0].resolve("first")
+ gates[1].reject(new Error("second failed"))
+
+ const results = await execution
+
+ expect(results[0]).toEqual({ status: "fulfilled", value: "first" })
+ expect(results[1]).toEqual({ status: "rejected", reason: expect.any(Error) })
+ expect(results[2]).toEqual({ status: "fulfilled", value: "third" })
+ })
+
+ it("settles synchronous throws and rejections without blocking later items", async () => {
+ const mapper = vi.fn((value: number) => {
+ if (value === 1) throw new Error("sync")
+ if (value === 2) return Promise.reject(new Error("async"))
+ return Promise.resolve(value)
+ })
+
+ const results = await settleInBatches([0, 1, 2, 3], mapper, 2)
+
+ expect(results.map((result) => result.status)).toEqual([
+ "fulfilled",
+ "rejected",
+ "rejected",
+ "fulfilled",
+ ])
+ expect(mapper).toHaveBeenCalledTimes(4)
+ })
+})
diff --git a/src/ws-do/src/settle-in-batches.ts b/src/ws-do/src/settle-in-batches.ts
new file mode 100644
index 000000000..2b5d1ce33
--- /dev/null
+++ b/src/ws-do/src/settle-in-batches.ts
@@ -0,0 +1,29 @@
+export function settleInBatches<Input, Output>(
+ inputs: readonly Input[],
+ mapper: (input: Input, index: number) => Output | PromiseLike<Output>,
+ batchSize: number,
+): Promise<PromiseSettledResult<Awaited<Output>>[]> {
+ if (!Number.isFinite(batchSize) || !Number.isInteger(batchSize) || batchSize <= 0) {
+ throw new RangeError("batchSize must be a finite integer greater than zero")
+ }
+
+ return settleValidBatches(inputs, mapper, batchSize)
+}
+
+async function settleValidBatches<Input, Output>(
+ inputs: readonly Input[],
+ mapper: (input: Input, index: number) => Output | PromiseLike<Output>,
+ batchSize: number,
+): Promise<PromiseSettledResult<Awaited<Output>>[]> {
+ const results: PromiseSettledResult<Awaited<Output>>[] = []
+
+ for (let start = 0; start < inputs.length; start += batchSize) {
+ const batch = inputs.slice(start, start + batchSize)
+ const batchResults = await Promise.allSettled(
+ batch.map((input, offset) => Promise.resolve().then(() => mapper(input, start + offset))),
+ )
+ results.push(...batchResults)
+ }
+
+ return results
+}