Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
240 changes: 240 additions & 0 deletions apps/realtime/src/handlers/field-update-flush.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,240 @@
/**
* Collaborators edit the same field while an earlier edit is still being stored. Drives the real
* `subblock-update` and `variable-update` handlers against in-memory sockets: each edit may be
* reported only once its own write has finished, because a client drops an operation it is told is
* confirmed and never retries it.
*/
import { createDeferred } from '@sim/testing/helpers/deferred'
import { auditMock, auditMockFns } from '@sim/testing/mocks/audit.mock'
import {
databaseMock,
dbChainMockFns,
queueTableRows,
resetDbChainMock,
} from '@sim/testing/mocks/database.mock'
import { schemaMock } from '@sim/testing/mocks/schema.mock'
import { workflowAuthzMock, workflowAuthzMockFns } from '@sim/testing/mocks/workflow-authz.mock'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'

vi.mock('@sim/audit', () => auditMock)
vi.mock('@sim/db', () => databaseMock)
vi.mock('@sim/db/schema', () => schemaMock)
vi.mock('@sim/platform-authz/workflow', () => workflowAuthzMock)

import { setupSubblocksHandlers } from '@/handlers/subblocks'
import { setupVariablesHandlers } from '@/handlers/variables'
import type { IRoomManager } from '@/rooms'

const WORKFLOW_ID = 'workflow-1'
const TARGET_ID = 'target-1'
const DEBOUNCE_MS = 25

type Handler = (payload: unknown) => Promise<void>

/** A workflow room of in-memory clients, recording what each one is sent. */
function openRoom(socketIds: string[]) {
const outcomes: Record<string, string[]> = {}
const values: Record<string, unknown[]> = {}
for (const id of socketIds) {
outcomes[id] = []
values[id] = []
}
const deliver = (recipients: string[]) => ({
emit: (event: string, payload: { operationId?: string; value?: unknown }) => {
for (const id of recipients) {
if (payload.operationId) outcomes[id].push(`${event}:${payload.operationId}`)
else values[id].push(payload.value)
}
},
})
const roomManager = {
isReady: () => true,
getRoomForSocket: async () => ({ type: 'workflow', id: WORKFLOW_ID }),
getUserSession: async (id: string) => ({ userId: `user-${id}`, userName: id }),
hasRoom: async () => true,
getRoomUsers: async () =>
socketIds.map((id) => ({ socketId: id, userId: `user-${id}`, role: 'write' })),
updateUserActivity: async () => {},
io: {
to: (room: string) => ({
...deliver(room === WORKFLOW_ID ? socketIds : [room]),
except: (excluded: string[]) => deliver(socketIds.filter((id) => !excluded.includes(id))),
}),
},
} as unknown as IRoomManager

const handlers: Record<string, Record<string, Handler>> = {}
for (const id of socketIds) {
handlers[id] = {}
const socket = {
id,
on: (event: string, handler: Handler) => {
handlers[id][event] = handler
},
emit: () => {},
} as unknown as Parameters<typeof setupSubblocksHandlers>[0]
setupSubblocksHandlers(socket, roomManager)
setupVariablesHandlers(socket, roomManager)
}
return { handlers, outcomes, values }
}

describe.each([
{
event: 'subblock-update',
field: { blockId: TARGET_ID, subblockId: 'code' },
auditedUsers: [],
},
{
event: 'variable-update',
field: { variableId: TARGET_ID, field: 'value' },
auditedUsers: ['user-alice', 'user-bob'],
},
])('$event while an earlier one is being stored', ({ event, field, auditedUsers }) => {
beforeEach(() => {
vi.useFakeTimers()
resetDbChainMock()
workflowAuthzMockFns.mockAuthorizeWorkflowByWorkspacePermission.mockResolvedValue({
allowed: true,
workspacePermission: 'write',
})
for (let read = 0; read < 6; read++) {
queueTableRows(schemaMock.workflow, [
{ id: WORKFLOW_ID, variables: { [TARGET_ID]: { id: TARGET_ID, value: '' } } },
])
}
for (let read = 0; read < 3; read++) {
queueTableRows(schemaMock.workflowBlocks, [
{ id: TARGET_ID, subBlocks: {}, locked: false, data: {} },
])
}
dbChainMockFns.returning.mockResolvedValue([{ id: TARGET_ID }])
})

afterEach(() => {
vi.useRealTimers()
})

/** Alice's edit is mid-write when Bob's arrives; `release` lets her write finish. */
async function overlappingEdits() {
const room = openRoom(['alice', 'bob', 'carol'])
const write = createDeferred<void>()
dbChainMockFns.transaction.mockImplementationOnce(async (run) => {
await write.promise
return run(databaseMock.db)
})
const send = (socketId: string, value: string, operationId = `op-${socketId}`) =>
room.handlers[socketId][event]({
workflowId: WORKFLOW_ID,
...field,
value,
timestamp: Date.now(),
operationId,
})

await send('alice', 'from alice')
await vi.advanceTimersByTimeAsync(DEBOUNCE_MS)
await send('bob', 'from bob')
return {
...room,
send,
release: async () => {
write.resolve()
await vi.advanceTimersByTimeAsync(0)
},
}
}

it('reports the second edit as failed, never confirmed, when its own write fails', async () => {
const { outcomes, release } = await overlappingEdits()
await release()
expect(outcomes).toEqual({ alice: ['operation-confirmed:op-alice'], bob: [], carol: [] })

dbChainMockFns.transaction.mockRejectedValueOnce(new Error('connection lost'))
await vi.advanceTimersByTimeAsync(DEBOUNCE_MS)
expect(outcomes).toEqual({
alice: ['operation-confirmed:op-alice'],
bob: ['operation-failed:op-bob'],
carol: [],
})
})

it('sends the stored value to the first client and no superseded value to the second', async () => {
const { values, release } = await overlappingEdits()
await release()
await vi.advanceTimersByTimeAsync(DEBOUNCE_MS)

expect(values).toEqual({ alice: ['from bob'], bob: [], carol: ['from alice', 'from bob'] })
})

it('audits each edit as the user who made it', async () => {
const { release } = await overlappingEdits()
await release()
await vi.advanceTimersByTimeAsync(DEBOUNCE_MS)

const actors = auditMockFns.mockRecordAudit.mock.calls.map(([entry]) => entry.actorId)
expect(actors).toEqual(auditedUsers)
})

it('stores and sends the edits in order when the second is due before the first is stored', async () => {
const { outcomes, values, release } = await overlappingEdits()
await vi.advanceTimersByTimeAsync(DEBOUNCE_MS)
expect(outcomes).toEqual({ alice: [], bob: [], carol: [] })
await release()

expect(values).toEqual({ alice: ['from bob'], bob: [], carol: ['from alice', 'from bob'] })
})

it('does not echo an edit to its sender when it joined one already waiting its turn', async () => {
const { outcomes, values, send, release } = await overlappingEdits()
await vi.advanceTimersByTimeAsync(DEBOUNCE_MS)
await send('carol', 'from carol')
await vi.advanceTimersByTimeAsync(DEBOUNCE_MS)
await release()

expect(outcomes.carol).toEqual(['operation-confirmed:op-carol'])
expect(values.carol).toEqual([])
})

it('keeps an edit made after the first is stored behind the second still being stored', async () => {
const { outcomes, send, release } = await overlappingEdits()
await release()
const write = createDeferred<void>()
dbChainMockFns.transaction.mockImplementationOnce(async (run) => {
await write.promise
return run(databaseMock.db)
})
await vi.advanceTimersByTimeAsync(DEBOUNCE_MS)
await send('carol', 'from carol')
await vi.advanceTimersByTimeAsync(DEBOUNCE_MS)
expect(outcomes).toEqual({ alice: ['operation-confirmed:op-alice'], bob: [], carol: [] })

write.resolve()
await vi.advanceTimersByTimeAsync(0)
expect(outcomes).toEqual({
alice: ['operation-confirmed:op-alice'],
bob: ['operation-confirmed:op-bob'],
carol: ['operation-confirmed:op-carol'],
})
})

it('answers a third edit that arrives while the second is being stored', async () => {
const { outcomes, send, release } = await overlappingEdits()
await release()
const write = createDeferred<void>()
dbChainMockFns.transaction.mockImplementationOnce(async (run) => {
await write.promise
return run(databaseMock.db)
})
await vi.advanceTimersByTimeAsync(DEBOUNCE_MS)
await send('alice', 'from alice again', 'op-alice-2')
write.resolve()
await vi.advanceTimersByTimeAsync(DEBOUNCE_MS)

expect(outcomes).toEqual({
alice: ['operation-confirmed:op-alice', 'operation-confirmed:op-alice-2'],
bob: ['operation-confirmed:op-bob'],
carol: [],
})
})
})
76 changes: 40 additions & 36 deletions apps/realtime/src/handlers/subblocks.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,9 +17,13 @@ const logger = createLogger('SubblocksHandlers')
const DEBOUNCE_INTERVAL_MS = 25

type PendingSubblock = {
latest: { blockId: string; subblockId: string; value: any; timestamp: number }
timeout: NodeJS.Timeout
// Map operationId -> socketId to emit confirmations/failures to correct clients
/** Newest value, until a flush takes it. */
latest?: { blockId: string; subblockId: string; value: any; timestamp: number }
timeout?: NodeJS.Timeout
/** Settles with the last flush due, so one field's flushes run one at a time, in order. */
lastFlush: Promise<void>
// Map operationId -> socketId to emit confirmations/failures to correct clients.
// Holds only operations no flush has taken yet.
opToSocket: Map<string, string>
}

Expand Down Expand Up @@ -188,31 +192,23 @@ export function setupSubblocksHandlers(socket: AuthenticatedSocket, roomManager:

// Server-side debounce/coalesce by workflowId+blockId+subblockId
const debouncedKey = `${workflowId}:${blockId}:${subblockId}`
const existing = pendingSubblockUpdates.get(debouncedKey)
if (existing) {
clearTimeout(existing.timeout)
existing.latest = { blockId, subblockId, value, timestamp }
if (operationId) existing.opToSocket.set(operationId, socket.id)
existing.timeout = setTimeout(async () => {
await flushSubblockUpdate(workflowId, existing, roomManager)
pendingSubblockUpdates.delete(debouncedKey)
}, DEBOUNCE_INTERVAL_MS)
} else {
const opToSocket = new Map<string, string>()
if (operationId) opToSocket.set(operationId, socket.id)
const timeout = setTimeout(async () => {
const pending = pendingSubblockUpdates.get(debouncedKey)
if (pending) {
await flushSubblockUpdate(workflowId, pending, roomManager)
pendingSubblockUpdates.delete(debouncedKey)
}
}, DEBOUNCE_INTERVAL_MS)
pendingSubblockUpdates.set(debouncedKey, {
latest: { blockId, subblockId, value, timestamp },
timeout,
opToSocket,
})
const pending: PendingSubblock = pendingSubblockUpdates.get(debouncedKey) ?? {
opToSocket: new Map(),
lastFlush: Promise.resolve(),
}
pendingSubblockUpdates.set(debouncedKey, pending)
pending.latest = { blockId, subblockId, value, timestamp }
if (operationId) pending.opToSocket.set(operationId, socket.id)
clearTimeout(pending.timeout)
const timeout = setTimeout(async () => {
pending.lastFlush = pending.lastFlush.then(() =>
flushSubblockUpdate(workflowId, pending, roomManager)
)
await pending.lastFlush
// A newer update has its own timer and still needs this entry.
if (pending.timeout === timeout) pendingSubblockUpdates.delete(debouncedKey)
}, DEBOUNCE_INTERVAL_MS)
pending.timeout = timeout
} catch (error) {
logger.error('Error handling subblock update:', error)

Expand Down Expand Up @@ -241,7 +237,14 @@ async function flushSubblockUpdate(
pending: PendingSubblock,
roomManager: IRoomManager
) {
const { blockId, subblockId, value, timestamp } = pending.latest
// Take the value with its own operations: one that arrives while this is being stored belongs to
// the next flush, and must not be answered before its value is persisted.
const { latest, opToSocket: operations } = pending
if (!latest) return
pending.latest = undefined
pending.opToSocket = new Map()

const { blockId, subblockId, value, timestamp } = latest
const io = roomManager.io

try {
Expand All @@ -253,7 +256,7 @@ async function flushSubblockUpdate(
.limit(1)

if (workflowExists.length === 0) {
pending.opToSocket.forEach((socketId, opId) => {
operations.forEach((socketId, opId) => {
io.to(socketId).emit('operation-failed', {
operationId: opId,
error: 'Workflow not found',
Expand All @@ -267,7 +270,7 @@ async function flushSubblockUpdate(
await assertWorkflowMutable(workflowId)
} catch (error) {
if (error instanceof WorkflowLockedError) {
pending.opToSocket.forEach((socketId, opId) => {
operations.forEach((socketId, opId) => {
io.to(socketId).emit('operation-failed', {
operationId: opId,
error: error.message,
Expand Down Expand Up @@ -342,8 +345,9 @@ async function flushSubblockUpdate(
})

if (updateSuccessful) {
// Broadcast to room excluding all senders (works cross-pod via Redis adapter)
const senderSocketIds = [...pending.opToSocket.values()]
// Broadcast to room excluding all senders (works cross-pod via Redis adapter), and those whose
// newer value is waiting for the next flush, which would not send it back to them
const senderSocketIds = [...operations.values(), ...pending.opToSocket.values()]
const broadcastPayload = {
workflowId,
blockId,
Expand All @@ -358,21 +362,21 @@ async function flushSubblockUpdate(
}

// Confirm all coalesced operationIds (io.to(socketId) works cross-pod)
pending.opToSocket.forEach((socketId, opId) => {
operations.forEach((socketId, opId) => {
io.to(socketId).emit('operation-confirmed', {
operationId: opId,
serverTimestamp: Date.now(),
})
})
} else if (blockLocked) {
pending.opToSocket.forEach((socketId, opId) => {
operations.forEach((socketId, opId) => {
io.to(socketId).emit('operation-confirmed', {
operationId: opId,
serverTimestamp: Date.now(),
})
})
} else {
pending.opToSocket.forEach((socketId, opId) => {
operations.forEach((socketId, opId) => {
io.to(socketId).emit('operation-failed', {
operationId: opId,
error: 'Block no longer exists',
Expand All @@ -382,7 +386,7 @@ async function flushSubblockUpdate(
}
} catch (error) {
logger.error('Error flushing subblock update:', error)
pending.opToSocket.forEach((socketId, opId) => {
operations.forEach((socketId, opId) => {
io.to(socketId).emit('operation-failed', {
operationId: opId,
error: getErrorMessage(error, 'Unknown error'),
Expand Down
Loading