diff --git a/docs/timeline-architecture.md b/docs/timeline-architecture.md index 34034b96ce..1c2fe36293 100644 --- a/docs/timeline-architecture.md +++ b/docs/timeline-architecture.md @@ -2,9 +2,11 @@ ## Core Principle: Events Are Canonical, Groups Are Derived -All event data lives in a **single module-level singleton** (`grouped-event-buffer.ts`). -Events are stored once, in a flat array indexed by `eventId - 1`. Groups are not -stored at all — they are described by lightweight records and built on demand. +Each `WorkflowHistoryController` owns a **buffer instance** created by +`createGroupedEventBuffer()` (`grouped-event-buffer.ts`) and an `EventBufferView` +exposed as `history`. Events are stored once, in a flat array indexed by +`eventId - 1`. Groups are not stored at all — they are described by lightweight +records and built on demand. The flat array works because Temporal event IDs are a gapless sequence from 1, so the ID _is_ the position. That buys more than storage: a follower references its @@ -17,7 +19,7 @@ skips empty slots — costing memory rather than correctness. flowchart LR API["Bidirectional fetch
+ live poll"] -->|ingestHistoryEvent| BUF - subgraph BUF["grouped-event-buffer.ts (singleton, plain TS)"] + subgraph BUF["grouped-event-buffer.ts (controller-owned instance, plain TS)"] direction TB EV["events[]
slot = eventId - 1, one copy"] HG["headGroup: Int32Array
head slot → record"] @@ -29,7 +31,7 @@ flowchart LR BUF -->|getEventArray| FLAT["Flat event consumers"] BUF -->|onChange| FACADE["grouped-event-buffer.svelte.ts"] - FACADE -->|eventBuffer.*| VIEW + FACADE -->|controller.history.*| VIEW ``` ### Key tenets @@ -113,15 +115,16 @@ flowchart TD W["ingestHistoryEvent / setPendingMetadata / reset"] -->|notifyChanged| OC["onChange listeners"] OC --> FV["EventBufferView.scheduleUpdate()"] FV -->|coalesce onto a microtask| VER["_version++ ($state)"] - VER --> D1["eventBuffer.lazyGroupsWithoutWorkflowTasks"] - VER --> D2["eventBuffer.events"] - VER --> D3["bufferVersion store (legacy derived stores)"] + VER --> D1["history.lazyGroupsWithoutWorkflowTasks"] + VER --> D2["history.events"] + VER --> D3["history.event(id) / history.eventGroup(id, opts)"] ``` Consumers read a value: ```svelte -const lazyGroups = $derived(eventBuffer.lazyGroupsWithoutWorkflowTasks); +const lazyGroups = +$derived(historyController.history.lazyGroupsWithoutWorkflowTasks); ``` No subscribe / throttle / re-read effect at the call site, and **producers never @@ -133,8 +136,13 @@ announce their own writes** — the buffer reports them. leave a run opened in a background tab with an empty history until focused. - **`reset` propagates immediately** rather than coalescing, so navigating between runs cannot leave the previous run's groups on screen for a tick. -- **`bufferVersion`** survives as a store mirror of `eventBuffer.version`, for the - pre-runes `derived()` stores in `$lib/stores/events`. Prefer `eventBuffer` in new code. +- **`_version` is private to the view**, with no public version getter or store + mirror. Reactive reads use the controller's `history` surface; disposing the + view unsubscribes it and prevents queued microtasks from updating it. +- **`history.event(id)` and `history.eventGroup(id, opts)` use indexed lookups** + through the buffer's `getEvent` and `getEventGroup`, without flattening events + or listing every group. Both track `_version`; group lookups materialize only + the matching group and retain per-group version memoization. ### The identity invariant diff --git a/src/lib/components/activity/activity-command-controls.svelte b/src/lib/components/activity/activity-command-controls.svelte new file mode 100644 index 0000000000..f3e186eb16 --- /dev/null +++ b/src/lib/components/activity/activity-command-controls.svelte @@ -0,0 +1,128 @@ + + +
+ + + + + + + + + +
+ + + + + + + + +{#key optionsUpdateDrawerOpen} + +{/key} diff --git a/src/lib/components/activity/activity-commands.svelte b/src/lib/components/activity/activity-commands.svelte index 69843f3444..4134e2a88d 100644 --- a/src/lib/components/activity/activity-commands.svelte +++ b/src/lib/components/activity/activity-commands.svelte @@ -1,174 +1,119 @@ - -
- - - - - - - - - -
- - - - - + const onUpdateOptions = async (options: ActivityOptions) => { + const refresh = onRefresh; + await updateActivityOptions({ + namespace: workflowExecutionIdentity.namespace, + execution, + id: activity.activityId, + activityOptions: options, + identity, + }); + await refresh(Action.Update); + }; + - -{#key optionsUpdateDrawerOpen} - -{/key} +{/if} diff --git a/src/lib/components/activity/activity-options-form.svelte b/src/lib/components/activity/activity-options-form.svelte index 7adc2a35fa..d6f342ecba 100644 --- a/src/lib/components/activity/activity-options-form.svelte +++ b/src/lib/components/activity/activity-options-form.svelte @@ -102,7 +102,7 @@ // NOT reset reactively if the activity prop changes while the user is // mid-edit — untrack() captures the initial values intentionally. Re-seeding // on each open comes from the {#key} around the drawer in - // activity-commands.svelte, which remounts this form. + // activity-command-controls.svelte, which remounts this form. const initialData: z.infer = untrack(() => ({ taskQueue: initialOptions?.taskQueue?.name ?? '', scheduleToCloseTimeout: String( diff --git a/src/lib/components/activity/activity-options-update-drawer.svelte b/src/lib/components/activity/activity-options-update-drawer.svelte deleted file mode 100644 index 1a857e5e50..0000000000 --- a/src/lib/components/activity/activity-options-update-drawer.svelte +++ /dev/null @@ -1,41 +0,0 @@ - - - diff --git a/src/lib/components/event/event-card.svelte b/src/lib/components/event/event-card.svelte index 1bd36ea74f..b0bbf11a59 100644 --- a/src/lib/components/event/event-card.svelte +++ b/src/lib/components/event/event-card.svelte @@ -1,6 +1,4 @@ @@ -393,6 +397,7 @@ container-class="min-w-0" > + import type { Snippet } from 'svelte'; + import type { EventGroup } from '$lib/models/event-groups/event-groups'; import { resolveSystemNexusEvent } from '$lib/system-nexus-endpoints'; - import type { WorkflowEvent } from '$lib/types/events'; + import type { PendingActivity, WorkflowEvent } from '$lib/types/events'; + import type { + WorkflowExecution, + WorkflowExecutionIdentity, + } from '$lib/types/workflows'; + import { isActivityTaskScheduledEvent } from '$lib/utilities/is-event-type'; import PendingActivityCard from '../workflow/pending-activity/pending-activity-card.svelte'; import PendingNexusOperationCard from '../workflow/pending-nexus-operation/pending-nexus-operation-card.svelte'; @@ -13,12 +20,18 @@ event = undefined, lazy = false, groupRow = false, + workflowExecutionIdentity, + workflow, + activityActions, }: { group?: EventGroup; event?: WorkflowEvent; lazy?: boolean; /** The row that opened this represents the whole group, not one event. */ groupRow?: boolean; + workflowExecutionIdentity: WorkflowExecutionIdentity; + workflow: WorkflowExecution | null; + activityActions?: Snippet<[PendingActivity]>; } = $props(); const pendingEvent = $derived( @@ -45,13 +58,21 @@ {#if showEventGroup}
- {#if group?.pendingActivity} - + {#if group?.pendingActivity && workflow} + {:else if group?.pendingNexusOperation} {/if} {#each group?.eventList ?? [] as groupEvent (groupEvent.id)} {:else if event} - + {/if} diff --git a/src/lib/components/event/event-details-link.svelte b/src/lib/components/event/event-details-link.svelte index 02089c4c42..413de8e035 100644 --- a/src/lib/components/event/event-details-link.svelte +++ b/src/lib/components/event/event-details-link.svelte @@ -1,7 +1,6 @@ - -
-
- - All - Compact - JSON - -
-
-{#if $eventViewType === 'json'} -
- -
-{:else} -
- -
-{/if} diff --git a/src/lib/components/event/pending-activity-summary-row.svelte b/src/lib/components/event/pending-activity-summary-row.svelte index aa26cd8a93..334fff3d29 100644 --- a/src/lib/components/event/pending-activity-summary-row.svelte +++ b/src/lib/components/event/pending-activity-summary-row.svelte @@ -1,5 +1,5 @@ - -{#snippet dot( - point: [number, number], - eventClassification: EventClassification | 'pending' | undefined, -)} - {@const colors = dotColors(eventClassification)} - -{/snippet} - -{#snippet line(opts: { - startPoint: [number, number]; - endPoint: [number, number]; - category?: EventTypeCategory | 'pending' | 'retry'; - pending?: boolean; -})} - {@const { - startPoint, - endPoint, - category: lineCategory, - pending = false, - } = opts} - -{/snippet} - - - {#if connectLine} - {@render line({ - startPoint: [canvasWidth, centerY], - endPoint: [canvasWidth - horizontalOffset - RADIUS, centerY], - })} - {/if} - {#if !reverseSort} - {@render dot([canvasWidth - horizontalOffset, centerY], classification)} - {/if} - {#if zoomNextDistance} - {@render line({ - startPoint: [ - canvasWidth - horizontalOffset - RADIUS / 2 + strokeWidth, - centerY + RADIUS + strokeWidth / 2, - ], - endPoint: [ - canvasWidth - horizontalOffset - RADIUS / 2 + strokeWidth, - centerY + zoomNextDistance + RADIUS, - ], - category: group?.pendingActivity - ? Number(group.pendingActivity.attempt) > 1 - ? 'retry' - : 'pending' - : category, - pending: nextIsPending, - })} - {/if} - {#if reverseSort} - {@render dot([canvasWidth - horizontalOffset, centerY], classification)} - {/if} - - - diff --git a/src/lib/components/lines-and-dots/history-graph/history-graph.svelte b/src/lib/components/lines-and-dots/history-graph/history-graph.svelte deleted file mode 100644 index 7d3060f1ca..0000000000 --- a/src/lib/components/lines-and-dots/history-graph/history-graph.svelte +++ /dev/null @@ -1,87 +0,0 @@ - - - diff --git a/src/lib/components/lines-and-dots/history-graph/positioning.ts b/src/lib/components/lines-and-dots/history-graph/positioning.ts deleted file mode 100644 index cbbdaedd6c..0000000000 --- a/src/lib/components/lines-and-dots/history-graph/positioning.ts +++ /dev/null @@ -1,125 +0,0 @@ -import type { - EventGroup, - EventGroups, -} from '$lib/models/event-groups/event-groups'; -import { isEvent } from '$lib/models/event-history'; -import type { EventSortOrder } from '$lib/stores/event-view'; -import type { - WorkflowEvent, - WorkflowEventWithPending, -} from '$lib/types/events'; -import { getGroupForEventOrPendingEvent } from '$lib/utilities/pending-activities'; - -export const isMiddleEvent = ( - event: WorkflowEvent, - groups: EventGroups | Map, -): boolean => { - const group = - groups instanceof Map - ? groups.get(event.id) - : groups.find((candidate) => - candidate.eventList.some((listEvent) => listEvent.id === event.id), - ); - if (!group) return false; - return ( - group.eventList.findIndex((listEvent) => listEvent.id === event.id) === 1 && - group.eventList.length === 3 - ); -}; - -const pairIsConsecutive = (firstId: string, secondId: string): boolean => { - return parseInt(firstId) === parseInt(secondId) - 1; -}; - -const isConsecutiveGroup = (group: EventGroup): boolean => { - const { eventList } = group; - if (eventList.length === 1) return true; - if (eventList.length === 2) - return pairIsConsecutive(eventList[0].id, eventList[1].id); - if (eventList.length === 3) { - return ( - pairIsConsecutive(eventList[0].id, eventList[1].id) && - pairIsConsecutive(eventList[1].id, eventList[2].id) - ); - } - return false; -}; - -const getOpenGroups = ( - event: WorkflowEventWithPending, - groups: EventGroups, -): number => { - const group = getGroupForEventOrPendingEvent(groups, event); - if (!group) return 0; - if (group.level !== undefined) return group.level; - - const pendingGroups = groups - .filter((other) => other.isPending && other.id !== group.id) - .filter( - (other) => - parseInt(other.initialEvent.id) < parseInt(group.initialEvent.id), - ); - - const nonPendingGroups = groups - .filter( - (other) => - other.eventList.length > 1 && !other.isPending && other.id !== group.id, - ) - .filter( - (other) => - parseInt(other.initialEvent.id) < parseInt(group.initialEvent.id), - ) - .filter( - (other) => parseInt(other.lastEvent.id) > parseInt(group.initialEvent.id), - ); - - const openGroups = [...pendingGroups, ...nonPendingGroups]; - - if (!openGroups.length && isConsecutiveGroup(group)) { - group.level = 0; - } - group.level = openGroups.length + 1; - return group.level; -}; - -export const getNextDistanceAndOffset = ( - history: WorkflowEventWithPending[], - event: WorkflowEventWithPending, - groups: EventGroups, - height: number, - sort: EventSortOrder, -): { nextDistance: number; offset: number } => { - const group = getGroupForEventOrPendingEvent(groups, event); - let nextDistance = 0; - let offset = 0; - - if (!group) { - return { nextDistance, offset }; - } - - if (group.eventList.length === 1 && !group.isPending) { - return { nextDistance, offset }; - } - - const currentIndex = isEvent(event) ? group.eventList.indexOf(event) : -1; - const nextEvent = isEvent(event) - ? group.eventList[currentIndex + 1] - : undefined; - if (!isEvent(event) || event.category !== 'workflow') { - offset = getOpenGroups(event, groups); - } - - if (!nextEvent && !group.isPending) { - return { nextDistance, offset }; - } - - let diff = 0; - if (nextEvent && isEvent(event)) { - diff = parseInt(nextEvent.id) - parseInt(event.id); - } else if (group.isPending && isEvent(event)) { - diff = history.length - parseInt(event.id) + 2; - } - const distance = diff * height; - nextDistance = sort === 'ascending' ? distance : -distance; - return { nextDistance, offset }; -}; diff --git a/src/lib/components/lines-and-dots/timeline-graph/graph-widget.svelte b/src/lib/components/lines-and-dots/timeline-graph/graph-widget.svelte index ec6bd1dba6..a2ba534346 100644 --- a/src/lib/components/lines-and-dots/timeline-graph/graph-widget.svelte +++ b/src/lib/components/lines-and-dots/timeline-graph/graph-widget.svelte @@ -4,6 +4,8 @@ import { groupEvents } from '$lib/models/event-groups'; import type { EventGroups } from '$lib/models/event-groups/event-groups'; import { fetchAllEvents } from '$lib/services/events-service'; + import { materializeGroup } from '$lib/services/grouped-event-buffer'; + import type { ExecutionHistory } from '$lib/services/grouped-event-buffer.svelte'; import { fetchWorkflow } from '$lib/services/workflow-service'; import type { WorkflowExecution } from '$lib/types/workflows'; import { getValidTimeMs } from '$lib/utilities/format-time'; @@ -33,12 +35,15 @@ let snapshot = $state<{ workflow: WorkflowExecution; groups: EventGroups; + history: ExecutionHistory; + namespace: string; latestEventTimeMs: number | undefined; }>(); const getWorkflowAndEventHistory = async () => { if (!workflowId || !runId) return; + const executionNamespace = namespace; const [{ workflow }, history] = await Promise.all([ fetchWorkflow({ namespace, workflowId, runId }), fetchAllEvents({ namespace, workflowId, runId }), @@ -53,8 +58,13 @@ ? lastEventTimeMs : Math.max(firstEventTimeMs, lastEventTimeMs ?? firstEventTimeMs); return { + namespace: executionNamespace, workflow, groups: groupEvents(history, 'ascending', pendingActivities), + history: { + events: history, + materializeGroup, + }, latestEventTimeMs, }; }; @@ -85,11 +95,15 @@ class="cursor-pointer overflow-auto {className}" style:max-height="{viewportHeight}px" > - + {#key JSON.stringify( [snapshot.namespace, snapshot.workflow.id, snapshot.workflow.runId], )} + + {/key}
{/if} diff --git a/src/lib/components/lines-and-dots/timeline-graph/group-details-row-client-test-runner-entry.ts b/src/lib/components/lines-and-dots/timeline-graph/group-details-row-client-test-runner-entry.ts index a6f42bb6a8..a6f779de93 100644 --- a/src/lib/components/lines-and-dots/timeline-graph/group-details-row-client-test-runner-entry.ts +++ b/src/lib/components/lines-and-dots/timeline-graph/group-details-row-client-test-runner-entry.ts @@ -1,6 +1,7 @@ import { flushSync, mount, unmount } from 'svelte'; import type { EventGroup } from '$lib/models/event-groups/event-groups'; +import type { WorkflowExecution } from '$lib/types/workflows'; import GroupDetailsRow from './group-details-row.svelte'; @@ -26,7 +27,20 @@ export function render(group: EventGroup) { mounted.push( mount(GroupDetailsRow, { target, - props: { group, canvasWidth: 600, y: 0 }, + props: { + group, + canvasWidth: 600, + y: 0, + workflowExecutionIdentity: { + namespace: 'test-namespace', + workflowId: 'test-workflow', + runId: 'test-run', + }, + workflow: { + id: 'test-workflow', + runId: 'test-run', + } as WorkflowExecution, + }, }), ); flushSync(); diff --git a/src/lib/components/lines-and-dots/timeline-graph/group-details-row.svelte b/src/lib/components/lines-and-dots/timeline-graph/group-details-row.svelte index 14454c91e8..db5895a280 100644 --- a/src/lib/components/lines-and-dots/timeline-graph/group-details-row.svelte +++ b/src/lib/components/lines-and-dots/timeline-graph/group-details-row.svelte @@ -1,7 +1,5 @@ @@ -62,7 +68,7 @@
{translate('workers.no-worker-heartbeats')}
{#if currentSdk} {@const { href, sdk, version } = currentSdk} - {#if !minimumVersionRequired(version, $sdkInfo.version)} + {#if !minimumVersionRequired(version, sdkInfo.version)}

{translate('workers.worker-heartbeats-sdk-link-preface')} diff --git a/src/lib/components/workers/workers-table/workers-table.svelte b/src/lib/components/workers/workers-table/workers-table.svelte index b793c0c716..7bd36675a9 100644 --- a/src/lib/components/workers/workers-table/workers-table.svelte +++ b/src/lib/components/workers/workers-table/workers-table.svelte @@ -12,6 +12,7 @@ import { workerSearchAttributes } from '$lib/stores/search-attributes'; import { workflowRun } from '$lib/stores/workflow-run'; import type { WorkerHeartbeat, WorkerListInfo } from '$lib/types'; + import type { getSDKandVersion } from '$lib/utilities/get-sdk-version'; import { isRunningWithNoWorkers } from '$lib/utilities/is-running-with-no-workers'; import type { TableSort, TableSortColumn } from '$lib/utilities/table-sort'; @@ -27,6 +28,7 @@ interface Props { filterable?: boolean; + sdkInfo?: ReturnType; namespace: string; onFetch: () => Promise>; onError?: (err: unknown) => void; @@ -36,6 +38,7 @@ let { filterable = false, + sdkInfo, namespace, onFetch, onError, @@ -117,7 +120,7 @@ {:else if runningWithNoWorkers} {:else} - + {/if} {/snippet} diff --git a/src/lib/components/workflow-actions.svelte b/src/lib/components/workflow-actions.svelte index c0f0ce15d7..52372c51e2 100644 --- a/src/lib/components/workflow-actions.svelte +++ b/src/lib/components/workflow-actions.svelte @@ -17,9 +17,8 @@ import Menu from '$lib/holocene/menu/menu.svelte'; import { translate } from '$lib/i18n/translate'; import { isCloud } from '$lib/stores/advanced-visibility'; - import { resetEvents } from '$lib/stores/events'; import { temporalVersion } from '$lib/stores/versions'; - import type { WorkflowEvent } from '$lib/types/events'; + import type { WorkflowEvents } from '$lib/types/events'; import type { WorkflowExecution } from '$lib/types/workflows'; import { isWorkflowDelayed } from '$lib/utilities/delayed-workflows'; import { routeForWorkflowStart } from '$lib/utilities/route-for'; @@ -33,13 +32,21 @@ import { workflowUpdateEnabled } from '$lib/utilities/workflow-update-enabled'; interface Props { workflow: WorkflowExecution; + resetEvents: WorkflowEvents; namespace: string; cancelInProgress: boolean; first?: string; next?: string; } - let { workflow, namespace, cancelInProgress, first, next }: Props = $props(); + let { + workflow, + resetEvents, + namespace, + cancelInProgress, + first, + next, + }: Props = $props(); const isRunning = $derived(workflow?.isRunning); const isPaused = $derived(workflow?.isPaused); @@ -81,7 +88,7 @@ let resetEnabled = $derived( resetAuthorized && canResetWithPendingChildWorkflows && - $resetEvents.length > 0, + resetEvents.length > 0, ); let startWorkflowDisabled = $derived( @@ -103,7 +110,7 @@ }: { resetAuthorized: boolean; canResetWithPendingChildWorkflows: boolean; - resetEvents: WorkflowEvent[]; + resetEvents: WorkflowEvents; }) => { if (!resetAuthorized) { return translate('workflows.reset-disabled-unauthorized'); @@ -123,7 +130,7 @@ getResetDescription({ resetAuthorized, canResetWithPendingChildWorkflows, - resetEvents: $resetEvents, + resetEvents, }), ); @@ -323,6 +330,7 @@ {#if resetEnabled} - {#each $resetEvents as event (event.eventId)} + {#each resetEvents as event (event.eventId)} {/each} diff --git a/src/lib/components/workflow/input-and-results.svelte b/src/lib/components/workflow/input-and-results.svelte index b011168f34..438eabc73b 100644 --- a/src/lib/components/workflow/input-and-results.svelte +++ b/src/lib/components/workflow/input-and-results.svelte @@ -4,8 +4,8 @@ createDecodedPayload, type DecodedPayloadState, } from '$lib/runes/decoded-payload.svelte'; - import { fullEventHistory } from '$lib/stores/events'; import { workflowRun } from '$lib/stores/workflow-run'; + import type { WorkflowEvents } from '$lib/types/events'; import { isParsedPayload } from '$lib/utilities/decode-payload'; import { getWorkflowStartedCompletedAndTaskFailedEvents, @@ -16,8 +16,10 @@ import InputAndResultsPayload from './input-and-results-payload.svelte'; import PayloadPreview from './payload-preview.svelte'; + let { events }: { events: WorkflowEvents } = $props(); + const workflowEvents = $derived( - getWorkflowStartedCompletedAndTaskFailedEvents($fullEventHistory), + getWorkflowStartedCompletedAndTaskFailedEvents(events), ); const isPending = $derived( $workflowRun.workflow?.isRunning || diff --git a/src/lib/components/workflow/pending-activity/pending-activity-card.svelte b/src/lib/components/workflow/pending-activity/pending-activity-card.svelte index e920a590d9..b7f40c8bf4 100644 --- a/src/lib/components/workflow/pending-activity/pending-activity-card.svelte +++ b/src/lib/components/workflow/pending-activity/pending-activity-card.svelte @@ -2,9 +2,6 @@ import { omit } from 'es-toolkit'; import type { Snippet } from 'svelte'; - import { page } from '$app/state'; - - import ActivityCommands from '$lib/components/activity/activity-commands.svelte'; import EventStatusBadge from '$lib/components/event/event-status-badge.svelte'; import PayloadCodeBlock from '$lib/components/payload/payload-code-block.svelte'; import { timestamp } from '$lib/components/timestamp.svelte'; @@ -12,11 +9,8 @@ import CodeBlock from '$lib/holocene/code-block.svelte'; import { translate } from '$lib/i18n/translate'; import { BadgeCount } from '$lib/io/badge-count'; - import { eventBuffer } from '$lib/services/grouped-event-buffer.svelte'; - import { coreUserStore } from '$lib/stores/core-user'; - import { workflowRun } from '$lib/stores/workflow-run'; - import type { PendingActivity } from '$lib/types/events'; - import { activityCommandsEnabled } from '$lib/utilities/activity-commands-enabled'; + import type { PendingActivity, WorkflowEvent } from '$lib/types/events'; + import type { WorkflowExecution } from '$lib/types/workflows'; import { getUpdatedActivityOptions } from '$lib/utilities/activity-options-diff'; import { formatAttemptsLeft, @@ -30,35 +24,26 @@ let { activity, totalPending, + scheduledEvent, + workflow, + actions, }: { activity: PendingActivity; totalPending?: number; + scheduledEvent?: WorkflowEvent; + workflow: WorkflowExecution; + actions?: Snippet<[PendingActivity]>; } = $props(); const failed = $derived( (activity.attempt ?? 0) > 1 && !!activity.lastFailure, ); - const isRunning = $derived($workflowRun?.workflow?.isRunning); - const isPaused = $derived($workflowRun?.workflow?.isPaused); - const scheduledEvent = $derived( - eventBuffer.pendingActivityScheduledEvent(activity.activityId), - ); const updatedOptions = $derived( getUpdatedActivityOptions( activity.activityOptions, scheduledEvent?.activityTaskScheduledEventAttributes, ), ); - - let coreUser = coreUserStore(); - let showActivityCommands = $derived( - activityCommandsEnabled( - page.data.settings, - $coreUser, - page.params.namespace, - ) && - (isRunning || isPaused), - );

{activity.activityType}

- {#if showActivityCommands} - - {/if} + {@render actions?.(activity)}
@@ -94,7 +77,7 @@ {#if activity.scheduledTime} {@const timeDifference = toTimeDifference({ date: activity.scheduledTime, - now: getWorkflowCurrentTime($workflowRun?.workflow), + now: getWorkflowCurrentTime(workflow), negativeDefault: '', })} {#if timeDifference} @@ -114,7 +97,7 @@ activity.maximumAttempts ?? 0, formatDuration( getDuration({ - start: getWorkflowCurrentTime($workflowRun?.workflow), + start: getWorkflowCurrentTime(workflow), end: activity.expirationTime, }) ?? '', ), diff --git a/src/lib/components/workflow/relationships/workflow-family-node-tree.svelte b/src/lib/components/workflow/relationships/workflow-family-node-tree.svelte index 6c9a295cbe..1d45cfa2b2 100644 --- a/src/lib/components/workflow/relationships/workflow-family-node-tree.svelte +++ b/src/lib/components/workflow/relationships/workflow-family-node-tree.svelte @@ -6,8 +6,8 @@ import { translate } from '$lib/i18n/translate'; import { IconTemporalSchedules } from '$lib/io/icon'; import type { RootNode } from '$lib/services/workflow-service'; - import { fullEventHistory } from '$lib/stores/events'; import { workflowRun } from '$lib/stores/workflow-run'; + import type { WorkflowEvents } from '$lib/types/events'; import type { WorkflowExecution } from '$lib/types/workflows'; import { getWorkflowRelationships } from '$lib/utilities/get-workflow-relationships'; import { @@ -21,6 +21,7 @@ interface Props { root: RootNode; + events: WorkflowEvents; width: number; height: number; zoomLevel: number; @@ -35,6 +36,7 @@ let { root, + events, width, height, zoomLevel, @@ -52,11 +54,7 @@ const namespace = $derived(page.params.namespace); const fullWorkflow = $derived($workflowRun.workflow); const workflowRelationships = $derived( - getWorkflowRelationships( - fullWorkflow, - $fullEventHistory, - page.data.namespace, - ), + getWorkflowRelationships(fullWorkflow, events, page.data.namespace), ); const first = $derived(workflowRelationships.first); const next = $derived(workflowRelationships.next); @@ -170,6 +168,7 @@ {#if child.children.length && isExpanded(child)} (undefined); @@ -86,6 +88,7 @@ {#snippet graph({ width, height, zoomLevel })} import AccordionLight from '$lib/holocene/accordion/accordion-light.svelte'; - import { fullEventHistory } from '$lib/stores/events'; + import type { WorkflowEvent } from '$lib/types/events'; import type { Callback } from '$lib/types/nexus'; import WorkflowCallback from './workflow-callback.svelte'; - let { callbacks }: { callbacks: Callback[] } = $props(); - - const initialEvent = $derived($fullEventHistory[0]); + let { + callbacks, + initialEvent, + }: { callbacks: Callback[]; initialEvent?: WorkflowEvent } = $props(); const link = $derived(initialEvent?.links?.[0]); const firstCallback = $derived(callbacks[0]); diff --git a/src/lib/components/workflow/workflow-common-errors.svelte b/src/lib/components/workflow/workflow-common-errors.svelte index 1f892235eb..6adddff4e0 100644 --- a/src/lib/components/workflow/workflow-common-errors.svelte +++ b/src/lib/components/workflow/workflow-common-errors.svelte @@ -11,16 +11,17 @@ - +
{#if workflowTaskFailedError} {/if} {#if workflow?.callbacks?.length} - + {/if}
@@ -292,7 +286,9 @@ - + {:else}
- + + {#snippet activityActions(activity)} + {#if workflow} + + {/if} + {/snippet} +
{/if}
diff --git a/src/lib/layouts/workflow-history-provider.svelte b/src/lib/layouts/workflow-history-provider.svelte new file mode 100644 index 0000000000..5ee62561f0 --- /dev/null +++ b/src/lib/layouts/workflow-history-provider.svelte @@ -0,0 +1,18 @@ + + +{#key controller} + +{/key} diff --git a/src/lib/layouts/workflow-history-scope.svelte b/src/lib/layouts/workflow-history-scope.svelte new file mode 100644 index 0000000000..f6d1f4e64f --- /dev/null +++ b/src/lib/layouts/workflow-history-scope.svelte @@ -0,0 +1,19 @@ + + +{@render children()} diff --git a/src/lib/layouts/workflow-run-layout.svelte b/src/lib/layouts/workflow-run-layout.svelte index ee67387b13..a8ec2840ef 100644 --- a/src/lib/layouts/workflow-run-layout.svelte +++ b/src/lib/layouts/workflow-run-layout.svelte @@ -1,39 +1,27 @@ @@ -418,9 +315,40 @@
{:else if workflowError} -{:else if !$workflowRun.workflow} +{:else if !$workflowRun.workflow || !historyController} {:else} - - {@render children()} + + + {#if historyController.error} + {@const error = historyController.error} + {@const errorDetail = + error.message?.trim() || + ('statusText' in error ? error.statusText?.trim() : '')} + +
+
+

{translate('workflows.history-load-error-description')}

+ {#if errorDetail} +

{errorDetail}

+ {/if} +
+ +
+
+ {/if} + {@render children()} +
{/if} diff --git a/src/lib/layouts/workflow-timeline-layout.svelte b/src/lib/layouts/workflow-timeline-layout.svelte index d2bc8a5d03..de8d3a0799 100644 --- a/src/lib/layouts/workflow-timeline-layout.svelte +++ b/src/lib/layouts/workflow-timeline-layout.svelte @@ -1,9 +1,10 @@ - +
{#if workflowTaskFailedError} {/if} {#if workflow?.callbacks?.length} - + {/if}
@@ -294,8 +291,8 @@ :last-child_.menu-button-anchor>button]:rounded-r' : 'empty:hidden max-xl:[&_.menu-button-anchor>button]:rounded max-xl:[&_.menu-button-anchor>button]:border-l'} > - + {#snippet toggle()} {#if hasTimelineEventGroups} {#if workflow} + > + {#snippet activityActions(activity)} + + {/snippet} + {/if} diff --git a/src/lib/pages/standalone-activity-workers.svelte b/src/lib/pages/standalone-activity-workers.svelte index a1bd3ea80e..b5ffd8bb3e 100644 --- a/src/lib/pages/standalone-activity-workers.svelte +++ b/src/lib/pages/standalone-activity-workers.svelte @@ -4,6 +4,7 @@ import WorkersTable from '$lib/components/workers/workers-table/task-queue-workers-table.svelte'; import { activityWorkerCount } from '$lib/stores/activities'; import { parseSearchAttributes } from '$lib/utilities/decode-payload'; + import { formatSDKName } from '$lib/utilities/get-sdk-version'; import { activityExecution } from '$lib/utilities/standalone-activity-poller.svelte'; interface Props { @@ -15,6 +16,10 @@ const searchAttributes = $derived($activityExecution?.info?.searchAttributes); const taskQueue = $derived($activityExecution?.info?.taskQueue ?? ''); + const sdkInfo = $derived({ + sdk: formatSDKName($activityExecution?.info?.sdkName), + version: $activityExecution?.info?.sdkVersion ?? '', + }); const workerHeartbeatsEnabled = $derived( !!page.data.namespace.namespaceInfo?.capabilities?.workerHeartbeats, ); @@ -28,6 +33,7 @@ {namespace} {taskQueue} searchAttributes={decodedSearchAttributes} + {sdkInfo} useFallback={!workerHeartbeatsEnabled || useFallback} onCount={(count) => ($activityWorkerCount = count)} /> diff --git a/src/lib/pages/workflow-history-event.svelte b/src/lib/pages/workflow-history-event.svelte index f10c8ee7df..fa626a4a22 100644 --- a/src/lib/pages/workflow-history-event.svelte +++ b/src/lib/pages/workflow-history-event.svelte @@ -1,91 +1,47 @@ +{#snippet activityActions(activity: PendingActivity)} + {#if workflow} + + {/if} +{/snippet} +
- {#each visibleItems as event, index} + {#each visibleItems as event, index (event.id)} {/each} @@ -142,7 +116,9 @@ size="xs" LeadingIcon={IconArrowDown} onclick={loadNext} - disabled={ids[ids.length - 1] === lastEventId || loading} + disabled={!ids.length || + ids[ids.length - 1] === String(lastEventId) || + loading} data-testid="load-next">Show Next 10 diff --git a/src/lib/pages/workflow-history-json.svelte b/src/lib/pages/workflow-history-json.svelte index 8774e1573a..7839707647 100644 --- a/src/lib/pages/workflow-history-json.svelte +++ b/src/lib/pages/workflow-history-json.svelte @@ -2,19 +2,17 @@ import WorkflowJsonNavigator from '$lib/components/workflow/workflow-json-navigator.svelte'; import ToggleSwitch from '$lib/holocene/toggle-switch.svelte'; import { translate } from '$lib/i18n/translate'; - import { decodeEventHistory, filteredEventHistory } from '$lib/stores/events'; + import { decodeEventHistory } from '$lib/stores/events'; import type { WorkflowEvent } from '$lib/types/events'; interface Props { - events?: WorkflowEvent[]; + events: WorkflowEvent[]; } let { events }: Props = $props(); - - const resolvedEvents = $derived(events ?? $filteredEventHistory); - + {#snippet decode()} isSystemNexusScheduledEvent(event)), ), ); - const inboundLinks = getVisibleInboundNexusLinkEvents( - () => $fullEventHistory, - ); + const inboundLinks = getVisibleInboundNexusLinkEvents(() => events); const inboundLinkEvents = $derived(inboundLinks.events); const counts = $derived({ diff --git a/src/lib/pages/workflow-pending-activities.svelte b/src/lib/pages/workflow-pending-activities.svelte index 0dc45b3c39..d5f9137477 100644 --- a/src/lib/pages/workflow-pending-activities.svelte +++ b/src/lib/pages/workflow-pending-activities.svelte @@ -1,8 +1,13 @@
- {#if pendingActivities.length} + {#if workflow && pendingActivities.length}
{#each pendingActivities as activity (activity.id)} + {workflow} + scheduledEvent={historyController.history.pendingActivityScheduledEvent( + activity.activityId, + )} + > + {#snippet actions(actionActivity)} + {#if workflow} + + {/if} + {/snippet} + {/each}
{:else} diff --git a/src/lib/services/events-service.ts b/src/lib/services/events-service.ts index c2ba0f5514..18f543d4ad 100644 --- a/src/lib/services/events-service.ts +++ b/src/lib/services/events-service.ts @@ -2,7 +2,6 @@ import { throttle } from 'es-toolkit'; import { toEventHistory } from '$lib/models/event-history'; import type { EventSortOrder } from '$lib/stores/event-view'; -import { fullEventHistory } from '$lib/stores/events'; import { triggerRefresh } from '$lib/stores/workflow-run'; import type { WorkflowAPIRoutePath } from '$lib/types/api'; import type { @@ -103,17 +102,12 @@ export const fetchAllEvents = async ({ signal, historySize, }: FetchEventsParameters): Promise => { - const onStart = () => { - if (!signal) return; - fullEventHistory.set([]); - }; - const onUpdate = ( - full: WithoutNextPageToken, + _full: WithoutNextPageToken, current: WithoutNextPageToken, ) => { if (!signal) return; - fullEventHistory.set([...toEventHistory(full.history?.events)]); + const next = current?.history?.events; const hasNewHistory = historySize && @@ -147,7 +141,7 @@ export const fetchAllEvents = async ({ })) ?? { history: { events: [] } } ); }, - { onStart, onUpdate, onComplete }, + { onUpdate, onComplete }, ); if (!response?.history) return []; diff --git a/src/lib/services/fetch-bidirectional.test.ts b/src/lib/services/fetch-bidirectional.test.ts index bead2db7c7..520c5d3d90 100644 --- a/src/lib/services/fetch-bidirectional.test.ts +++ b/src/lib/services/fetch-bidirectional.test.ts @@ -1,6 +1,13 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; -import { fetchBidirectional } from './fetch-bidirectional'; +import { + handleError, + handleUnauthorizedOrForbiddenError, +} from '$lib/utilities/handle-error'; +import type { ErrorCallback } from '$lib/utilities/request-from-api'; + +import { fetchBidirectional, type PauseHandle } from './fetch-bidirectional'; +import { createGroupedEventBuffer } from './grouped-event-buffer'; // --------------------------------------------------------------------------- // Mocks @@ -10,6 +17,11 @@ vi.mock('$lib/utilities/route-for-api', () => ({ routeForApi: (key: string) => (key === 'events.ascending' ? 'asc' : 'desc'), })); +vi.mock('$lib/utilities/handle-error', () => ({ + handleError: vi.fn(), + handleUnauthorizedOrForbiddenError: vi.fn(), +})); + vi.mock('$lib/utilities/request-from-api', () => ({ requestFromAPI: vi.fn(), })); @@ -18,7 +30,7 @@ let requestFromAPI: ReturnType; beforeEach(async () => { const mod = await import('$lib/utilities/request-from-api'); - requestFromAPI = mod.requestFromAPI as ReturnType; + requestFromAPI = vi.mocked(mod.requestFromAPI); }); afterEach(() => { @@ -49,7 +61,7 @@ function descPage(ids: number[], tok = '') { return { history: { events: ids.map(makeEvent) }, nextPageToken: tok }; } -/** Empty page breaks a cursor immediately without affecting the gap. */ +/** Empty terminal page ends a cursor without affecting the gap. */ const emptyPage = { history: { events: [] }, nextPageToken: '' }; // --------------------------------------------------------------------------- @@ -57,30 +69,43 @@ const emptyPage = { history: { events: [] }, nextPageToken: '' }; // --------------------------------------------------------------------------- describe('fetchBidirectional onRawPage', () => { - it('delivers all ascending events via onRawPage with isAscending=true', async () => { - const received: { id: string; asc: boolean }[] = []; - requestFromAPI.mockImplementation((url: string) => { - if (url === 'asc') return Promise.resolve(ascPage([1, 2, 3])); - return Promise.resolve(emptyPage); - }); + it('retains each event once when cursor pages overlap', async () => { + const buffer = createGroupedEventBuffer(); + requestFromAPI.mockImplementation((url: string) => + Promise.resolve(url === 'asc' ? ascPage([1, 2, 3]) : descPage([3, 2, 1])), + ); await fetchBidirectional({ namespace: 'ns', workflowId: 'wf', runId: 'run', - onRawPage: (evts, isAsc) => { - for (const e of evts) received.push({ id: e.eventId, asc: isAsc }); + onRawPage: (events) => { + for (const event of events) buffer.ingestHistoryEvent(event); }, }); - expect(received.every((r) => r.asc)).toBe(true); - expect(received.map((r) => r.id)).toEqual(['1', '2', '3']); + expect(buffer.getEventArray().map((event) => event.id)).toEqual([ + '1', + '2', + '3', + ]); }); +}); + +// --------------------------------------------------------------------------- +// Multi-page ascending fetch +// --------------------------------------------------------------------------- - it('delivers descending events via onRawPage with isAscending=false', async () => { - const received: { id: string; asc: boolean }[] = []; +describe('fetchBidirectional multi-page ascending', () => { + it('follows ascending nextPageToken across pages', async () => { + let ascCall = 0; + const allReceived: string[] = []; requestFromAPI.mockImplementation((url: string) => { - if (url === 'desc') return Promise.resolve(descPage([3, 2, 1])); + if (url === 'asc') { + ascCall++; + if (ascCall === 1) return Promise.resolve(ascPage([1, 2], 'tok1')); + return Promise.resolve(ascPage([3, 4])); + } return Promise.resolve(emptyPage); }); @@ -88,119 +113,573 @@ describe('fetchBidirectional onRawPage', () => { namespace: 'ns', workflowId: 'wf', runId: 'run', - onRawPage: (evts, isAsc) => { - for (const e of evts) received.push({ id: e.eventId, asc: isAsc }); + onRawPage: (evts) => { + for (const e of evts) allReceived.push(e.eventId); }, }); - const descEvents = received.filter((r) => !r.asc); - expect(descEvents.length).toBeGreaterThan(0); - expect(descEvents.every((r) => !r.asc)).toBe(true); + expect(ascCall).toBe(2); + expect(allReceived).toEqual(['1', '2', '3', '4']); }); +}); - it('deduplicates events that both cursors return', async () => { - // Ascending: events 1-3. Descending: events 3-1 (overlap at 3). - const received: string[] = []; - let ascCall = 0; - requestFromAPI.mockImplementation((url: string) => { - if (url === 'asc') { - ascCall++; - if (ascCall === 1) return Promise.resolve(ascPage([1, 2, 3])); - return Promise.resolve(emptyPage); - } - return Promise.resolve(descPage([3, 2, 1])); +describe('fetchBidirectional progress', () => { + it('reports zero descending bounds until a descending page arrives', async () => { + const onProgress = vi.fn(); + requestFromAPI.mockImplementation((url: string) => + Promise.resolve(url === 'asc' ? ascPage([1, 2, 3]) : emptyPage), + ); + + await fetchBidirectional({ + namespace: 'ns', + workflowId: 'wf', + runId: 'run', + onRawPage: () => {}, + onProgress, + }); + expect(onProgress).toHaveBeenCalledExactlyOnceWith({ + totalEstimated: 0, + descMinId: 0, }); + }); + + it('reports descending bounds even when the raw page overlaps', async () => { + const onProgress = vi.fn(); + requestFromAPI.mockImplementation((url: string) => + Promise.resolve(url === 'asc' ? ascPage([1, 2, 3]) : descPage([3, 2, 1])), + ); await fetchBidirectional({ namespace: 'ns', workflowId: 'wf', runId: 'run', - onRawPage: (evts) => { - for (const e of evts) received.push(e.eventId); - }, + onRawPage: () => {}, + onProgress, }); - // Event 3 should only appear once (deduped by the `seen` set). - const countOf3 = received.filter((id) => id === '3').length; - expect(countOf3).toBe(1); + expect(onProgress).toHaveBeenLastCalledWith({ + totalEstimated: 3, + descMinId: 1, + }); }); }); // --------------------------------------------------------------------------- -// Multi-page ascending fetch +// Abort // --------------------------------------------------------------------------- -describe('fetchBidirectional multi-page ascending', () => { - it('follows ascending nextPageToken across pages', async () => { - let ascCall = 0; - const allReceived: string[] = []; - requestFromAPI.mockImplementation((url: string) => { - if (url === 'asc') { - ascCall++; - if (ascCall === 1) return Promise.resolve(ascPage([1, 2], 'tok1')); - return Promise.resolve(ascPage([3, 4])); - } - return Promise.resolve(emptyPage); - }); +function deferred() { + let resolve: (value: T) => void = () => { + throw new Error('Deferred promise is not initialized.'); + }; + let reject: (error: Error) => void = () => { + throw new Error('Deferred promise is not initialized.'); + }; + const promise = new Promise((resolvePromise, rejectPromise) => { + resolve = resolvePromise; + reject = rejectPromise; + }); + return { promise, resolve, reject }; +} +describe('fetchBidirectional request error policy', () => { + it('delegates request errors to auth handling and rethrows without global reporting', async () => { + const callbacks: ErrorCallback[] = []; + requestFromAPI.mockImplementation( + ( + _url: string, + init: { handleError: ErrorCallback; notifyOnError?: boolean }, + ) => { + expect(init.notifyOnError).not.toBe(false); + callbacks.push(init.handleError); + return Promise.resolve(emptyPage); + }, + ); await fetchBidirectional({ namespace: 'ns', workflowId: 'wf', runId: 'run', - onRawPage: (evts) => { - for (const e of evts) allReceived.push(e.eventId); - }, + onRawPage: vi.fn(), }); + expect(callbacks).toHaveLength(2); + const error = { + status: 403, + statusCode: 403, + statusText: 'Request failed', + response: new Response(), + message: 'History request failed', + body: { + code: 403, + message: 'History request failed', + details: [], + }, + }; - expect(ascCall).toBe(2); - expect(allReceived).toContain('1'); - expect(allReceived).toContain('4'); + for (const callback of callbacks) { + await expect(Promise.resolve().then(() => callback(error))).rejects.toBe( + error, + ); + } + + expect(handleUnauthorizedOrForbiddenError).toHaveBeenCalledWith(error); + expect(handleError).not.toHaveBeenCalled(); }); }); -// --------------------------------------------------------------------------- -// BidirectionalStats shape -// --------------------------------------------------------------------------- +describe('fetchBidirectional failure recovery', () => { + it.each(['asc', 'desc'])( + 'drains the healthy cursor when %s fails', + async (failedDirection) => { + const received: string[] = []; + let healthyCalls = 0; + requestFromAPI.mockImplementation((url: string) => { + if (url === failedDirection) + return Promise.reject(new Error('page failed')); + healthyCalls++; + const ids = + failedDirection === 'asc' + ? [ + [6, 5], + [4, 3], + [2, 1], + ] + : [ + [1, 2], + [3, 4], + [5, 6], + ]; + return Promise.resolve( + ascPage( + ids[healthyCalls - 1], + healthyCalls < 3 ? `page-${healthyCalls}` : '', + ), + ); + }); + + await fetchBidirectional({ + namespace: 'ns', + workflowId: 'wf', + runId: 'run', + onRawPage: (events) => + received.push(...events.map((event) => event.eventId)), + }); + + expect(healthyCalls).toBe(3); + expect(received.toSorted()).toEqual(['1', '2', '3', '4', '5', '6']); + expect( + requestFromAPI.mock.calls.filter(([url]) => url === failedDirection), + ).toHaveLength(1); + }, + ); + + it('stops the healthy cursor at the pause threshold after a failure', async () => { + const error = new Error('ascending failed'); + let descendingCalls = 0; + requestFromAPI.mockImplementation((url: string) => { + if (url === 'asc') return Promise.reject(error); + descendingCalls++; + return Promise.resolve( + descPage( + descendingCalls === 1 ? [6, 5] : [4, 3], + `d${descendingCalls + 1}`, + ), + ); + }); + const onPause = vi.fn(); + + await expect( + fetchBidirectional({ + namespace: 'ns', + workflowId: 'wf', + runId: 'run', + pauseAfterPages: 2, + onPause, + onRawPage: vi.fn(), + }), + ).rejects.toBe(error); + expect(descendingCalls).toBe(2); + expect(onPause).toHaveBeenCalledTimes(1); + }); -describe('fetchBidirectional stats', () => { - it('returns winner=ascending when ascending completes in fewer pages', async () => { + it('lets the healthy cursor finish after a failure when the pause is released immediately', async () => { + let descendingCalls = 0; + const pages = [ + [6, 5], + [4, 3], + [2, 1], + ]; requestFromAPI.mockImplementation((url: string) => { - if (url === 'asc') return Promise.resolve(ascPage([1, 2, 3])); - return Promise.resolve(emptyPage); + if (url === 'asc') return Promise.reject(new Error('ascending failed')); + const ids = pages[descendingCalls]; + descendingCalls++; + return Promise.resolve( + descPage( + ids, + descendingCalls < pages.length ? `d${descendingCalls + 1}` : '', + ), + ); }); + const received: string[] = []; - const stats = await fetchBidirectional({ + await fetchBidirectional({ namespace: 'ns', workflowId: 'wf', runId: 'run', - onRawPage: () => {}, + pauseAfterPages: 2, + onPause: (handle) => handle.resume(), + onRawPage: (events) => + received.push(...events.map((event) => event.eventId)), }); - expect(stats.totalEvents).toBe(3); - expect(typeof stats.durationMs).toBe('number'); - expect(['ascending', 'descending', 'tie']).toContain(stats.winner); + expect(descendingCalls).toBe(3); + expect(received).toEqual(['6', '5', '4', '3', '2', '1']); + }); + + it('rejects after both directions fail with a gap, retaining delivered pages', async () => { + const error = new Error('ascending failed'); + const received: string[] = []; + requestFromAPI.mockImplementation( + (url: string, init: { token?: string }) => { + if (init.token) + return Promise.reject( + url === 'asc' ? error : new Error('descending failed'), + ); + return Promise.resolve( + url === 'asc' ? ascPage([1, 2], 'a2') : descPage([10, 9], 'd2'), + ); + }, + ); + + await expect( + fetchBidirectional({ + namespace: 'ns', + workflowId: 'wf', + runId: 'run', + onRawPage: (events) => + received.push(...events.map((event) => event.eventId)), + }), + ).rejects.toBe(error); + + expect(received).toEqual(['1', '2', '10', '9']); }); - it('counts overlap when both cursors return the same events', async () => { + it('succeeds when recovery closes the gap without reaching a terminal token', async () => { + const received: string[] = []; + const onProgress = vi.fn(); + requestFromAPI.mockImplementation( + (url: string, init: { token?: string }) => { + if (url === 'desc') { + return init.token + ? Promise.reject(new Error('descending failed')) + : Promise.resolve(descPage([10, 9], 'd2')); + } + const firstId = init.token ? Number(init.token) : 1; + return Promise.resolve( + ascPage([firstId, firstId + 1], String(firstId + 2)), + ); + }, + ); + + await expect( + fetchBidirectional({ + namespace: 'ns', + workflowId: 'wf', + runId: 'run', + onRawPage: (events) => + received.push(...events.map((event) => event.eventId)), + onProgress, + }), + ).resolves.toBeUndefined(); + expect(received.toSorted((a, b) => Number(a) - Number(b))).toEqual( + Array.from({ length: 10 }, (_, index) => String(index + 1)), + ); + expect(onProgress).toHaveBeenLastCalledWith({ + totalEstimated: 10, + descMinId: 9, + }); + }); + + it('preserves NetworkError failures', async () => { + const error = { + statusCode: 503, + statusText: 'Unavailable', + response: new Response(), + message: 'history unavailable', + }; + requestFromAPI.mockRejectedValue(error); + + await expect( + fetchBidirectional({ + namespace: 'ns', + workflowId: 'wf', + runId: 'run', + onRawPage: vi.fn(), + }), + ).rejects.toBe(error); + }); + + it('normalizes other failures to Error', async () => { + requestFromAPI.mockRejectedValue({ message: 'invalid history' }); + + await expect( + fetchBidirectional({ + namespace: 'ns', + workflowId: 'wf', + runId: 'run', + onRawPage: vi.fn(), + }), + ).rejects.toThrow('invalid history'); + }); + + it('rejects when the chosen winner fails after cancelling its sibling', async () => { + const error = new Error('winning page failed'); + let descendingSignal: AbortSignal | undefined; + requestFromAPI.mockImplementation( + ( + url: string, + init: { token?: string; options: { signal: AbortSignal } }, + ) => { + if (url === 'desc') { + descendingSignal = init.options.signal; + return Promise.resolve(descPage([5, 4], 'd2')); + } + if (init.token) { + expect(descendingSignal?.aborted).toBe(true); + return Promise.reject(error); + } + return Promise.resolve(ascPage([1, 2], 'a2')); + }, + ); + + await expect( + fetchBidirectional({ + namespace: 'ns', + workflowId: 'wf', + runId: 'run', + onRawPage: vi.fn(), + }), + ).rejects.toBe(error); + }); + + it('stops a paused cursor and rejects when the other cursor fails', async () => { + const failingPage = deferred>(); + const paused = deferred(); + const onPause = vi.fn(() => paused.resolve()); + const onRawPage = vi.fn(); + let descendingCalls = 0; requestFromAPI.mockImplementation((url: string) => { - if (url === 'asc') return Promise.resolve(ascPage([1, 2, 3])); - return Promise.resolve(descPage([3, 2, 1])); + if (url === 'asc') return failingPage.promise; + descendingCalls++; + return Promise.resolve( + descendingCalls === 1 ? descPage([4, 3], 'd2') : descPage([2, 1]), + ); }); - const stats = await fetchBidirectional({ + const done = fetchBidirectional({ namespace: 'ns', workflowId: 'wf', runId: 'run', - onRawPage: () => {}, + onRawPage, + pauseAfterPages: 1, + onPause, }); + await paused.promise; + const error = new Error('ascending failed while descending paused'); + failingPage.reject(error); + + await expect(done).rejects.toBe(error); + expect( + onRawPage.mock.calls.flatMap(([events]) => + events.map((event: ReturnType) => event.eventId), + ), + ).toEqual(['4', '3']); + expect(descendingCalls).toBe(1); + expect(onPause).toHaveBeenCalledTimes(1); + }); + + it.each(['onRawPage', 'onProgress', 'onPause'])( + 'propagates %s errors, aborting both requests and suppressing late callbacks', + async (callback) => { + const error = new Error('callback failed'); + const latePage = deferred>(); + const signals: AbortSignal[] = []; + requestFromAPI.mockImplementation( + (url: string, init: { options: { signal: AbortSignal } }) => { + signals.push(init.options.signal); + return url === 'asc' + ? Promise.resolve(ascPage([1, 2], 'a2')) + : latePage.promise; + }, + ); + const callbacks = { + onRawPage: vi.fn(), + onProgress: vi.fn(), + onPause: vi.fn(), + }; + for (const [name, handler] of Object.entries(callbacks)) { + if (name === callback) + handler.mockImplementation(() => { + throw error; + }); + } + + await expect( + fetchBidirectional({ + namespace: 'ns', + workflowId: 'wf', + runId: 'run', + pauseAfterPages: 1, + ...callbacks, + }), + ).rejects.toBe(error); + expect(signals).toHaveLength(2); + expect(signals.every((signal) => signal.aborted)).toBe(true); + latePage.resolve(descPage([10, 9])); + await latePage.promise; + expect(callbacks.onRawPage).toHaveBeenCalledTimes(1); + expect(callbacks.onProgress).toHaveBeenCalledTimes( + callback === 'onRawPage' ? 0 : 1, + ); + expect(callbacks.onPause).toHaveBeenCalledTimes( + callback === 'onPause' ? 1 : 0, + ); + expect(requestFromAPI).toHaveBeenCalledTimes(2); + }, + ); +}); + +describe('fetchBidirectional empty pages', () => { + it.each(['asc', 'desc'])( + 'follows an empty %s page continuation before establishing completion', + async (direction) => { + const received: string[] = []; + requestFromAPI.mockImplementation( + (url: string, init: { token?: string }) => { + if (url !== direction) + return Promise.reject(new Error('other direction failed')); + return Promise.resolve( + init.token ? ascPage([1]) : ascPage([], 'next'), + ); + }, + ); + + await expect( + fetchBidirectional({ + namespace: 'ns', + workflowId: 'wf', + runId: 'run', + onRawPage: (events) => + received.push(...events.map((event) => event.eventId)), + }), + ).resolves.toBeUndefined(); + expect(received).toEqual(['1']); + expect(requestFromAPI).toHaveBeenCalledWith( + direction, + expect.objectContaining({ token: 'next' }), + ); + }, + ); + + it('rejects if the continuation after an empty page fails before coverage', async () => { + const error = new Error('continuation failed'); + requestFromAPI.mockImplementation( + (url: string, init: { token?: string }) => { + if (url === 'desc' || init.token) return Promise.reject(error); + return Promise.resolve(ascPage([], 'next')); + }, + ); + + await expect( + fetchBidirectional({ + namespace: 'ns', + workflowId: 'wf', + runId: 'run', + onRawPage: vi.fn(), + }), + ).rejects.toBe(error); + expect(requestFromAPI).toHaveBeenCalledWith( + 'asc', + expect.objectContaining({ token: 'next' }), + ); + }); - expect(stats.overlap).toBeGreaterThan(0); + it('accepts an empty terminal page as completed pagination', async () => { + const onRawPage = vi.fn(); + requestFromAPI.mockImplementation((url: string) => + url === 'asc' + ? Promise.resolve(emptyPage) + : Promise.reject(new Error('descending failed')), + ); + await expect( + fetchBidirectional({ + namespace: 'ns', + workflowId: 'wf', + runId: 'run', + onRawPage, + }), + ).resolves.toBeUndefined(); + expect(onRawPage).not.toHaveBeenCalled(); + expect(requestFromAPI).toHaveBeenCalledTimes(2); + }); + + it('does not treat a missing response as completed pagination', async () => { + requestFromAPI.mockResolvedValue(undefined); + await expect( + fetchBidirectional({ + namespace: 'ns', + workflowId: 'wf', + runId: 'run', + onRawPage: vi.fn(), + }), + ).rejects.toThrow('Missing workflow history response.'); }); }); -// --------------------------------------------------------------------------- -// Abort -// --------------------------------------------------------------------------- +describe('fetchBidirectional pause', () => { + it('pauses both cursors at the threshold, resumes once, and lets the winner cancel its sibling', async () => { + const paused = deferred(); + let resume = () => {}; + const onPause = vi.fn((handle: PauseHandle) => { + resume = handle.resume; + paused.resolve(); + }); + const signals: AbortSignal[] = []; + const received: string[] = []; + requestFromAPI.mockImplementation( + ( + url: string, + init: { token?: string; options: { signal: AbortSignal } }, + ) => { + signals.push(init.options.signal); + if (init.token) { + expect(url).toBe('asc'); + expect(signals[1].aborted).toBe(true); + return Promise.resolve(ascPage([3, 4], 'a3')); + } + return Promise.resolve( + url === 'asc' ? ascPage([1, 2], 'a2') : descPage([6, 5], 'd2'), + ); + }, + ); + const done = fetchBidirectional({ + namespace: 'ns', + workflowId: 'wf', + runId: 'run', + pauseAfterPages: 1, + onPause, + onRawPage: (events) => + received.push(...events.map((event) => event.eventId)), + }); + await paused.promise; + expect(requestFromAPI).toHaveBeenCalledTimes(2); + resume(); + await expect(done).resolves.toBeUndefined(); + resume(); + expect(onPause).toHaveBeenCalledTimes(1); + expect(requestFromAPI).toHaveBeenCalledTimes(3); + expect(received.toSorted()).toEqual(['1', '2', '3', '4', '5', '6']); + }); +}); describe('fetchBidirectional abort', () => { it('exits cleanly when signal is pre-aborted', async () => { @@ -218,4 +697,67 @@ describe('fetchBidirectional abort', () => { expect(onRawPage).not.toHaveBeenCalled(); }); + + it('settles an externally aborted paused fetch without resume', async () => { + const controller = new AbortController(); + const paused = deferred(); + requestFromAPI.mockImplementation((url: string) => + Promise.resolve( + url === 'asc' ? ascPage([1, 2], 'a2') : descPage([10, 9], 'd2'), + ), + ); + const onRawPage = vi.fn(); + const done = fetchBidirectional({ + namespace: 'ns', + workflowId: 'wf', + runId: 'run', + signal: controller.signal, + onRawPage, + pauseAfterPages: 1, + onPause: () => paused.resolve(), + }); + await paused.promise; + controller.abort(); + await done; + expect(requestFromAPI).toHaveBeenCalledTimes(2); + expect(onRawPage).toHaveBeenCalledTimes(2); + }); + + it('suppresses every callback from responses delivered after external abort', async () => { + const controller = new AbortController(); + const ascending = deferred>(); + const descending = deferred>(); + const started = deferred(); + const signals: AbortSignal[] = []; + requestFromAPI.mockImplementation( + (url: string, init: { options: { signal: AbortSignal } }) => { + signals.push(init.options.signal); + if (signals.length === 2) started.resolve(); + return url === 'asc' ? ascending.promise : descending.promise; + }, + ); + const onRawPage = vi.fn(); + const onProgress = vi.fn(); + const onPause = vi.fn(); + const done = fetchBidirectional({ + namespace: 'ns', + workflowId: 'wf', + runId: 'run', + signal: controller.signal, + onRawPage, + onProgress, + onPause, + pauseAfterPages: 1, + }); + await started.promise; + controller.abort(); + ascending.resolve(ascPage([1, 2])); + descending.resolve(descPage([10, 9])); + await done; + + expect(signals.every((signal) => signal.aborted)).toBe(true); + expect(onRawPage).not.toHaveBeenCalled(); + expect(onProgress).not.toHaveBeenCalled(); + expect(onPause).not.toHaveBeenCalled(); + }); }); diff --git a/src/lib/services/fetch-bidirectional.ts b/src/lib/services/fetch-bidirectional.ts index 7bcd1b471e..b9959b2aae 100644 --- a/src/lib/services/fetch-bidirectional.ts +++ b/src/lib/services/fetch-bidirectional.ts @@ -2,28 +2,19 @@ import type { GetWorkflowExecutionHistoryResponse, HistoryEvent, } from '$lib/types/events'; -import { requestFromAPI } from '$lib/utilities/request-from-api'; +import type { NetworkError } from '$lib/types/global'; +import { getErrorMessage } from '$lib/utilities/error-message'; +import { handleUnauthorizedOrForbiddenError } from '$lib/utilities/handle-error'; +import { isNetworkError } from '$lib/utilities/is-network-error'; +import { + type ErrorCallback, + requestFromAPI, +} from '$lib/utilities/request-from-api'; import { routeForApi } from '$lib/utilities/route-for-api'; type BidirectionalProgress = { - ascEvents: number; - descEvents: number; - ascPages: number; - descPages: number; - elapsedMs: number; - ascMaxId: number; - descMinId: number; totalEstimated: number; -}; - -type BidirectionalStats = { - durationMs: number; - totalEvents: number; - overlap: number; - ascPages: number; - descPages: number; - eventsPerSecond: number; - winner: 'ascending' | 'descending' | 'tie'; + descMinId: number; }; export type PauseHandle = { @@ -37,13 +28,7 @@ export type FetchBidirectionalParams = { runId: string; signal?: AbortSignal; onProgress?: (p: BidirectionalProgress) => void; - /** Fires after every page with that page's raw events and direction flag. - * Feed directly into processEvent() to resolve buffer Promises live. */ - onRawPage: (events: HistoryEvent[], isAscending: boolean) => void; - /** Fires once with the raw events from the first descending page — the most - * recent events in the history. Use to call setFailedEvent() before the - * ascending cursor processes events that affect billableActions. */ - onFirstDescPage?: (events: HistoryEvent[]) => void; + onRawPage: (events: HistoryEvent[]) => void; maximumPageSize?: number; /** After this many total pages (asc + desc combined), pause both cursors and * call onPause with a handle whose resume() continues the fetch. */ @@ -59,44 +44,31 @@ export const fetchBidirectional = async ({ signal, onProgress, onRawPage, - onFirstDescPage, maximumPageSize, pauseAfterPages, onPause, -}: FetchBidirectionalParams): Promise => { - if (signal?.aborted) { - return { - durationMs: 0, - totalEvents: 0, - overlap: 0, - ascPages: 0, - descPages: 0, - eventsPerSecond: 0, - winner: 'tie', - }; - } +}: FetchBidirectionalParams): Promise => { + if (signal?.aborted) return; - const t0 = performance.now(); + const handlePageError: ErrorCallback = (error) => { + handleUnauthorizedOrForbiddenError(error); + throw error; + }; + const rootCtrl = new AbortController(); const ascCtrl = new AbortController(); const descCtrl = new AbortController(); - const onAbort = () => { - ascCtrl.abort(); - descCtrl.abort(); - }; - signal?.addEventListener('abort', onAbort); let ascMaxId = 0; let descMinId = Infinity; let descMaxId = 0; - let ascPages = 0; - let descPages = 0; + let pages = 0; let observedPageSize = 0; let winnerChosen = false; - let totalEvents = 0; - let pauseFired = false; - const seen = new Set(); + let pauseFired = false; + let failure: Error | NetworkError | null = null; + let reachedEnd = false; const gap = () => Math.max(0, descMinId - ascMaxId - 1); @@ -105,8 +77,42 @@ export const fetchBidirectional = async ({ // onPause is called. resume() resolves it, unblocking both loops. let pauseLatch: Promise | null = null; - const checkPause = async () => { - if (pauseLatch) await pauseLatch; + let resumePause: (() => void) | undefined; + + const releasePause = () => { + pauseLatch = null; + resumePause?.(); + resumePause = undefined; + }; + + const isPaused = () => pauseLatch !== null; + + const stopCursors = () => { + ascCtrl.abort(); + descCtrl.abort(); + }; + + const onAbort = () => { + rootCtrl.abort(); + stopCursors(); + releasePause(); + }; + signal?.addEventListener('abort', onAbort); + + const checkPause = async (cursorSignal: AbortSignal) => { + if (!pauseLatch || cursorSignal.aborted) return; + let onCursorAbort = () => {}; + try { + await Promise.race([ + pauseLatch, + new Promise((resolve) => { + onCursorAbort = resolve; + cursorSignal.addEventListener('abort', onCursorAbort, { once: true }); + }), + ]); + } finally { + cursorSignal.removeEventListener('abort', onCursorAbort); + } }; const maybePause = () => { @@ -114,28 +120,21 @@ export const fetchBidirectional = async ({ !pauseFired && pauseAfterPages !== undefined && onPause && - ascPages + descPages >= pauseAfterPages + pages >= pauseAfterPages ) { pauseFired = true; pauseLatch = new Promise((resolve) => { - onPause({ - resume: () => { - pauseLatch = null; - resolve(); - }, - }); + resumePause = resolve; }); + onPause({ resume: releasePause }); + if (failure && isPaused()) { + stopCursors(); + } } }; const reportProgress = () => { onProgress?.({ - ascEvents: ascMaxId, - descEvents: totalEvents - descMinId + 1, - ascPages, - descPages, - elapsedMs: performance.now() - t0, - ascMaxId, descMinId: descMinId === Infinity ? 0 : descMinId, totalEstimated: descMaxId, }); @@ -143,162 +142,122 @@ export const fetchBidirectional = async ({ type Token = string | undefined; - const runAscending = async () => { - const route = routeForApi('events.ascending', { namespace, workflowId }); - let token: Token; - while (!ascCtrl.signal.aborted) { - await checkPause(); - if (ascCtrl.signal.aborted) break; - const g = gap(); - if (g <= 0) { - descCtrl.abort(); - break; - } - if (observedPageSize > 0 && g <= observedPageSize && !winnerChosen) { - winnerChosen = true; - descCtrl.abort(); - } - - let response: GetWorkflowExecutionHistoryResponse | undefined; - try { - response = await requestFromAPI( - route, - { - token, - request: fetch, - params: { - 'execution.runId': runId, - waitNewEvent: 'false', - ...(maximumPageSize && { - maximumPageSize: String(maximumPageSize), - }), - }, - options: { signal: ascCtrl.signal }, + const fetchPage = async ( + route: string, + controller: AbortController, + token: Token, + ): Promise => { + try { + const response = + await requestFromAPI(route, { + token, + request: fetch, + params: { + 'execution.runId': runId, + waitNewEvent: 'false', + ...(maximumPageSize && { + maximumPageSize: String(maximumPageSize), + }), }, - ); - } catch { - break; - } - - const events = (response?.history?.events ?? []) as HistoryEvent[]; - if (!events.length) break; - - ascPages++; - observedPageSize = Math.max(observedPageSize, events.length); - - const fresh: HistoryEvent[] = []; - for (const e of events) { - const id = parseInt(e.eventId); - if (id > ascMaxId) ascMaxId = id; - if (!seen.has(id)) { - seen.add(id); - fresh.push(e); - } - } - if (fresh.length) onRawPage(fresh, true); - reportProgress(); - maybePause(); - - if (!response?.nextPageToken || gap() <= 0) { - descCtrl.abort(); - break; + options: { signal: controller.signal }, + handleError: handlePageError, + }); + if (!response) throw new Error('Missing workflow history response.'); + return response; + } catch (error) { + if (controller.signal.aborted) return; + failure ??= + error instanceof Error || isNetworkError(error) + ? error + : new Error(getErrorMessage(error)); + if (pauseLatch) { + stopCursors(); } - token = response.nextPageToken as unknown as string; } }; - const runDescending = async () => { - const route = routeForApi('events.descending', { namespace, workflowId }); + const runCursor = async ({ + direction, + controller, + sibling, + updateBounds, + }: { + direction: 'ascending' | 'descending'; + controller: AbortController; + sibling: AbortController; + updateBounds: (id: number) => void; + }) => { + const route = routeForApi(`events.${direction}`, { namespace, workflowId }); let token: Token; - while (!descCtrl.signal.aborted) { - await checkPause(); - if (descCtrl.signal.aborted) break; + while (!controller.signal.aborted) { + await checkPause(controller.signal); + if (controller.signal.aborted) break; const g = gap(); if (g <= 0) { - ascCtrl.abort(); + sibling.abort(); break; } if (observedPageSize > 0 && g <= observedPageSize && !winnerChosen) { winnerChosen = true; - ascCtrl.abort(); + sibling.abort(); } - let response: GetWorkflowExecutionHistoryResponse | undefined; - try { - response = await requestFromAPI( - route, - { - token, - request: fetch, - params: { - 'execution.runId': runId, - waitNewEvent: 'false', - ...(maximumPageSize && { - maximumPageSize: String(maximumPageSize), - }), - }, - options: { signal: descCtrl.signal }, - }, - ); - } catch { + const response = await fetchPage(route, controller, token); + if (!response || rootCtrl.signal.aborted) break; + + const events = response.history?.events ?? []; + if (!events.length) { + if (response.nextPageToken) { + token = String(response.nextPageToken); + continue; + } + reachedEnd = true; break; } - const events = (response?.history?.events ?? []) as HistoryEvent[]; - if (!events.length) break; - - descPages++; + pages++; observedPageSize = Math.max(observedPageSize, events.length); - - const fresh: HistoryEvent[] = []; - for (const e of events) { - const id = parseInt(e.eventId); - if (id < descMinId) descMinId = id; - if (id > descMaxId) { - descMaxId = id; - totalEvents = id; - } - if (!seen.has(id)) { - seen.add(id); - fresh.push(e); - } - } - if (fresh.length) onRawPage(fresh, false); - if (descPages === 1) onFirstDescPage?.(fresh); + for (const event of events) updateBounds(parseInt(event.eventId)); + onRawPage(events); + if (rootCtrl.signal.aborted) break; reportProgress(); + if (rootCtrl.signal.aborted) break; maybePause(); - if (!response?.nextPageToken || gap() <= 0) { - ascCtrl.abort(); + if (!response.nextPageToken) reachedEnd = true; + if (!response.nextPageToken || gap() <= 0) { + sibling.abort(); break; } - token = response.nextPageToken as unknown as string; + token = String(response.nextPageToken); } }; - await Promise.allSettled([runAscending(), runDescending()]); - signal?.removeEventListener('abort', onAbort); - - const durationMs = performance.now() - t0; - const total = seen.size; - const fetched = - ascPages * (observedPageSize || 1) + descPages * (observedPageSize || 1); - const overlap = Math.max(0, fetched - total); - - const winner: BidirectionalStats['winner'] = - ascPages === descPages - ? 'tie' - : ascPages > descPages - ? 'ascending' - : 'descending'; - - return { - durationMs, - totalEvents: total, - overlap, - ascPages, - descPages, - eventsPerSecond: Math.round(total / (durationMs / 1000)), - winner, - }; + try { + await Promise.all([ + runCursor({ + direction: 'ascending', + controller: ascCtrl, + sibling: descCtrl, + updateBounds: (id) => { + ascMaxId = Math.max(ascMaxId, id); + }, + }), + runCursor({ + direction: 'descending', + controller: descCtrl, + sibling: ascCtrl, + updateBounds: (id) => { + descMinId = Math.min(descMinId, id); + descMaxId = Math.max(descMaxId, id); + }, + }), + ]); + if (!signal?.aborted && failure && !reachedEnd && gap() > 0) { + throw failure; + } + } finally { + onAbort(); + signal?.removeEventListener('abort', onAbort); + } }; diff --git a/src/lib/services/grouped-event-buffer.svelte.test.ts b/src/lib/services/grouped-event-buffer.svelte.test.ts new file mode 100644 index 0000000000..8966dc1443 --- /dev/null +++ b/src/lib/services/grouped-event-buffer.svelte.test.ts @@ -0,0 +1,113 @@ +import { flushSync } from 'svelte'; +import { afterEach, describe, expect, it, vi } from 'vitest'; + +import type { EventGroup } from '$lib/models/event-groups/event-groups'; +import type { WorkflowEvent } from '$lib/types/events'; + +import { createGroupedEventBuffer } from './grouped-event-buffer'; +import { + makeActivityGroup, + makeTimerGroup, + makeWorkflowTaskGroup, +} from './test-helpers/synthetic-events'; + +import { EventBufferView } from './grouped-event-buffer.svelte'; + +const cleanups: (() => void)[] = []; + +afterEach(() => { + for (const cleanup of cleanups.splice(0)) cleanup(); + vi.restoreAllMocks(); +}); + +describe('EventBufferView direct lookups', () => { + it('reacts to head and follower arrivals, pending metadata, and reset without flattening', async () => { + const buffer = createGroupedEventBuffer(); + buffer.reset(20); + const history = new EventBufferView(buffer); + cleanups.push(() => history.dispose()); + const events = vi.spyOn(buffer, 'getEventArray'); + const groups = vi.spyOn(buffer, 'getGroupArray'); + const lazyGroups = vi.spyOn(buffer, 'getLazyGroups'); + const snapshots: { + event: WorkflowEvent | undefined; + group: EventGroup | undefined; + }[] = []; + cleanups.push( + $effect.root(() => { + $effect(() => { + snapshots.push({ + event: history.event('2'), + group: history.eventGroup('2', { excludeWorkflowTasks: true }), + }); + }); + }), + ); + flushSync(); + expect(snapshots).toEqual([{ event: undefined, group: undefined }]); + const [head, started, completed] = makeActivityGroup(1); + buffer.ingestHistoryEvent(started); + await Promise.resolve(); + flushSync(); + expect(snapshots).toHaveLength(2); + expect(snapshots.at(-1)?.event?.id).toBe('2'); + expect(snapshots.at(-1)?.group).toBeUndefined(); + buffer.ingestHistoryEvent(head); + await Promise.resolve(); + flushSync(); + expect(snapshots.at(-1)?.group?.eventCount).toBe(2); + buffer.setPendingMetadata( + [{ id: '1', activityId: '1', state: 'Started' }], + [], + ); + await Promise.resolve(); + flushSync(); + expect(snapshots.at(-1)?.group?.isPending).toBe(true); + buffer.ingestHistoryEvent(completed); + await Promise.resolve(); + flushSync(); + expect(snapshots.at(-1)?.group?.eventCount).toBe(3); + expect(snapshots.at(-1)?.group?.isPending).toBe(false); + const beforeUnrelated = snapshots.at(-1); + for (const event of makeTimerGroup(10)) buffer.ingestHistoryEvent(event); + await Promise.resolve(); + flushSync(); + expect(snapshots).toHaveLength(6); + expect(snapshots.at(-1)?.event).toBe(beforeUnrelated?.event); + expect(snapshots.at(-1)?.group).toBe(beforeUnrelated?.group); + buffer.reset(20); + flushSync(); + expect(snapshots.at(-1)).toEqual({ event: undefined, group: undefined }); + expect(events).not.toHaveBeenCalled(); + expect(groups).not.toHaveBeenCalled(); + expect(lazyGroups).not.toHaveBeenCalled(); + }); + + it('forwards filtering and isolates views', async () => { + const buffer = createGroupedEventBuffer(); + const otherBuffer = createGroupedEventBuffer(); + buffer.reset(3); + otherBuffer.reset(3); + const history = new EventBufferView(buffer); + const other = new EventBufferView(otherBuffer); + cleanups.push( + () => history.dispose(), + () => other.dispose(), + ); + for (const event of makeWorkflowTaskGroup(1)) + buffer.ingestHistoryEvent(event); + for (const event of makeTimerGroup(1)) + otherBuffer.ingestHistoryEvent(event); + await Promise.resolve(); + expect(history.event('2')?.eventType).toBe('WorkflowTaskStarted'); + expect(history.eventGroup('2')?.id).toBe('1'); + expect( + history.eventGroup('2', { excludeWorkflowTasks: true }), + ).toBeUndefined(); + expect(other.event('2')?.eventType).toBe('TimerFired'); + expect(other.eventGroup('2')?.category).toBe('timer'); + buffer.reset(0); + expect(history.event('2')).toBeUndefined(); + expect(other.event('2')?.eventType).toBe('TimerFired'); + }); +}); diff --git a/src/lib/services/grouped-event-buffer.svelte.ts b/src/lib/services/grouped-event-buffer.svelte.ts index 47d3188186..099157ff04 100644 --- a/src/lib/services/grouped-event-buffer.svelte.ts +++ b/src/lib/services/grouped-event-buffer.svelte.ts @@ -1,31 +1,22 @@ -import { readonly, writable } from 'svelte/store'; - import type { EventGroup } from '$lib/models/event-groups/event-groups'; import type { EventGroupKey } from '$lib/models/event-history/event-group-markers'; import type { TimelineEventGroup } from '$lib/models/event-history/timeline-event-groups'; import type { WorkflowEvent } from '$lib/types/events'; +import { getSDKandVersion } from '$lib/utilities/get-sdk-version'; +import { + isResetEvent, + isWorkflowTaskCompletedEvent, +} from '$lib/utilities/is-event-type'; import { type EventGroupMatcher, type EventGroupOption, - getEventArray, - getEventGroupMatcher, - getEventGroupOptions, - getGroupArray, - getLatestEventTimeMs, - getLazyGroups, - getPendingActivityScheduledEvent, - getTimelineEventGroups, - getWorkflowTaskFailedEvent, - hasTimelineEventGroups, - hasUserDefinedEventGroups, + type GroupArrayOptions, + type GroupedEventBuffer, type LazyGroup, materializeGroup, - onChange, } from './grouped-event-buffer'; -const versionStore = writable(0); - /** * Reactive read surface over the grouped-event-buffer. * @@ -39,21 +30,34 @@ const versionStore = writable(0); * requestAnimationFrame — that never fires in a hidden tab, which would leave a * run opened in a background tab with an empty event history until focused. */ -class EventBufferView { +export class EventBufferView { private _version = $state(0); private pending = false; + private disposed = false; + private readonly buffer: GroupedEventBuffer; + private readonly unsubscribe: () => void; + + constructor(buffer: GroupedEventBuffer) { + this.buffer = buffer; + this.unsubscribe = buffer.onChange((immediate) => + this.scheduleUpdate(immediate), + ); + } - constructor() { - onChange((immediate) => this.scheduleUpdate(immediate)); + dispose(): void { + if (this.disposed) return; + this.disposed = true; + this.pending = false; + this.unsubscribe(); } private bump(): void { this.pending = false; this._version++; - versionStore.update((current) => current + 1); } private scheduleUpdate(immediate: boolean): void { + if (this.disposed) return; if (immediate) { this.bump(); return; @@ -61,18 +65,13 @@ class EventBufferView { if (this.pending) return; this.pending = true; queueMicrotask(() => { - if (this.pending) this.bump(); + if (!this.disposed && this.pending) this.bump(); }); } - /** Bumped once per batch of buffer writes. */ - get version(): number { - return this._version; - } - get latestEventTimeMs(): number | undefined { void this._version; - return getLatestEventTimeMs(); + return this.buffer.getLatestEventTimeMs(); } /** @@ -91,7 +90,7 @@ class EventBufferView { */ pendingActivityScheduledEvent(activityId: string): WorkflowEvent | undefined { void this._version; - return getPendingActivityScheduledEvent(activityId); + return this.buffer.getPendingActivityScheduledEvent(activityId); } /** @@ -100,7 +99,7 @@ class EventBufferView { */ readonly lazyGroupsWithoutWorkflowTasks: LazyGroup[] = $derived.by(() => { void this._version; - return getLazyGroups({ excludeWorkflowTasks: true }); + return this.buffer.getLazyGroups({ excludeWorkflowTasks: true }); }); /** @@ -109,29 +108,29 @@ class EventBufferView { */ readonly groupsWithoutWorkflowTasks: EventGroup[] = $derived.by(() => { void this._version; - return getGroupArray({ excludeWorkflowTasks: true }); + return this.buffer.getGroupArray({ excludeWorkflowTasks: true }); }); /** Every event group in the run, in order of first appearance. */ readonly eventGroupOptions: EventGroupOption[] = $derived.by(() => { void this._version; - return getEventGroupOptions(); + return this.buffer.getEventGroupOptions(); }); readonly hasTimelineEventGroups: boolean = $derived.by(() => { void this._version; - return hasTimelineEventGroups(); + return this.buffer.hasTimelineEventGroups(); }); readonly hasUserDefinedEventGroups: boolean = $derived.by(() => { void this._version; - return hasUserDefinedEventGroups(); + return this.buffer.hasUserDefinedEventGroups(); }); readonly timelineEventGroups: TimelineEventGroup[] = $derived.by( () => { void this._version; - return getTimelineEventGroups(); + return this.buffer.getTimelineEventGroups(); }, ); @@ -143,27 +142,48 @@ class EventBufferView { keys: readonly EventGroupKey[], ): EventGroupMatcher | undefined { void this._version; - return getEventGroupMatcher(keys); + return this.buffer.getEventGroupMatcher(keys); + } + + event(eventId: string): WorkflowEvent | undefined { + void this._version; + return this.buffer.getEvent(eventId); + } + + eventGroup( + eventId: string, + opts?: GroupArrayOptions, + ): EventGroup | undefined { + void this._version; + return this.buffer.getEventGroup(eventId, opts); } readonly events: WorkflowEvent[] = $derived.by(() => { void this._version; - return getEventArray(); + return this.buffer.getEventArray(); + }); + + readonly initialEvent = $derived.by(() => { + void this._version; + return this.buffer.getInitialEvent(); }); + readonly resetEvents = $derived(this.events.filter(isResetEvent)); + + readonly sdkInfo = $derived( + getSDKandVersion(this.events.filter(isWorkflowTaskCompletedEvent)), + ); + /** The active WorkflowTaskFailed/TimedOut event, if the run has one. */ readonly workflowTaskFailedEvent: WorkflowEvent | undefined = $derived.by( () => { void this._version; - return getWorkflowTaskFailedEvent(); + return this.buffer.getWorkflowTaskFailedEvent(); }, ); } -export const eventBuffer = new EventBufferView(); - -/** - * Store mirror of `eventBuffer.version`, for the derived stores in - * $lib/stores/events that predate runes. Prefer `eventBuffer` in new code. - */ -export const bufferVersion = readonly(versionStore); +export type ExecutionHistory = Pick< + EventBufferView, + 'events' | 'materializeGroup' +>; diff --git a/src/lib/services/grouped-event-buffer.test.ts b/src/lib/services/grouped-event-buffer.test.ts index 54d0f20bb1..f8ef633b20 100644 --- a/src/lib/services/grouped-event-buffer.test.ts +++ b/src/lib/services/grouped-event-buffer.test.ts @@ -1,10 +1,22 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; -import { groupEvents } from '$lib/models/event-groups'; +import { + buildGroupIndex, + groupEvents, + groupWorkflowTaskEvents, +} from '$lib/models/event-groups'; +import { + createEventGroup, + createWorkflowTaskGroup, +} from '$lib/models/event-groups/create-event-group'; import type { EventGroup } from '$lib/models/event-groups/event-groups'; import { toEvent, toEventHistory } from '$lib/models/event-history'; import { createTimelineEventGroup } from '$lib/models/event-history/timeline-event-groups'; -import type { HistoryEvent } from '$lib/types/events'; +import type { + HistoryEvent, + PendingActivity, + PendingNexusOperation, +} from '$lib/types/events'; vi.mock('$lib/models/event-history', async (importOriginal) => { const actual = @@ -12,25 +24,27 @@ vi.mock('$lib/models/event-history', async (importOriginal) => { return { ...actual, toEvent: vi.fn(actual.toEvent) }; }); +vi.mock( + '$lib/models/event-groups/create-event-group', + async (importOriginal) => { + const actual = + await importOriginal< + typeof import('$lib/models/event-groups/create-event-group') + >(); + return { + ...actual, + createEventGroup: vi.fn(actual.createEventGroup), + createWorkflowTaskGroup: vi.fn(actual.createWorkflowTaskGroup), + }; + }, +); + import { - getEventArray, - getEventGroupMatcher, - getEventGroupOptions, - getGroupArray, - getLatestEventTimeMs, - getLazyGroups, - getPendingActivityScheduledEvent, - getTimelineEventGroups, - getWorkflowTaskFailedEvent, - hasTimelineEventGroups, - hasUserDefinedEventGroups, - ingestHistoryEvent, + createGroupedEventBuffer, + type GroupedEventBuffer, isWorkflowTaskGroup, type LazyGroup, materializeGroup, - reset, - setFailedEvent, - setPendingMetadata, } from './grouped-event-buffer'; import { SHARED_WITH_EVENT_GROUP } from './test-helpers/lazy-group-fields'; import { @@ -62,15 +76,17 @@ import { /** Load all events ascending (simulates asc-cursor-wins scenario). */ function loadAll(events: ReturnType) { - for (const e of events) ingestHistoryEvent(e); + for (const e of events) buffer.ingestHistoryEvent(e); } // --------------------------------------------------------------------------- // Setup / teardown // --------------------------------------------------------------------------- +let buffer: GroupedEventBuffer; + beforeEach(() => { - reset(0); + buffer = createGroupedEventBuffer(); }); afterEach(() => { @@ -81,15 +97,333 @@ afterEach(() => { // 1. Correctness: output equivalence with groupEvents // --------------------------------------------------------------------------- +describe('direct event lookups', () => { + const invalidIds = [ + '', + '0', + '-1', + '1.5', + '01', + '+1', + ' 1', + '1 ', + '1.0', + '1e0', + '0x1', + 'NaN', + 'Infinity', + '9007199254740992', + '1suffix', + '1e000000-0000-4000-8000-000000000000', + ]; + + it.each(invalidIds)('rejects noncanonical or invalid ID %j', (id) => { + buffer.reset(3); + loadAll(makeActivityGroup(1)); + expect(buffer.getEvent(id)).toBeUndefined(); + expect(buffer.getEventGroup(id)).toBeUndefined(); + }); + + it('rejects a stored event whose ID does not match its numeric slot', () => { + buffer.reset(3); + buffer.ingestHistoryEvent({ ...makeActivityScheduled(1), eventId: '01' }); + expect(buffer.getEvent('1')).toBeUndefined(); + expect(buffer.getEventGroup('1')).toBeUndefined(); + expect(buffer.getEvent('01')).toBeUndefined(); + expect(buffer.getEventGroup('01')).toBeUndefined(); + }); + + it('reads sparse event slots without flattening or creating groups', () => { + buffer.reset(1); + const event = makeActivityScheduled(100); + buffer.ingestHistoryEvent(event); + const createGroup = vi.mocked(createEventGroup).mockClear(); + const createWft = vi.mocked(createWorkflowTaskGroup).mockClear(); + const flatten = vi.spyOn(buffer, 'getEventArray'); + expect(buffer.getEvent('1')).toBeUndefined(); + expect(buffer.getEvent('99')).toBeUndefined(); + expect(buffer.getEvent('101')).toBeUndefined(); + expect(buffer.getEvent('100')).toEqual(toEvent(event)); + expect(buffer.getEvent('100')).toBe(buffer.getEvent('100')); + expect(flatten).not.toHaveBeenCalled(); + expect(createGroup).not.toHaveBeenCalled(); + expect(createWft).not.toHaveBeenCalled(); + }); + + it.each([false, true])( + 'matches the legacy group index with excludeWorkflowTasks=%s', + (excludeWorkflowTasks) => { + const signal: HistoryEvent = { + ...makeWorkflowStarted(22), + eventType: 'WorkflowExecutionSignaled', + workflowExecutionSignaledEventAttributes: { signalName: 'signal' }, + }; + const marker: HistoryEvent = { + ...makeLocalActivityMarker(23), + markerRecordedEventAttributes: { markerName: 'Version', details: {} }, + }; + const externalSignal: HistoryEvent = { + ...makeWorkflowStarted(24), + eventType: 'SignalExternalWorkflowExecutionInitiated', + signalExternalWorkflowExecutionInitiatedEventAttributes: { + signalName: 'external', + workflowExecution: { workflowId: 'other', runId: 'run' }, + }, + }; + const signalDelivered: HistoryEvent = { + ...makeWorkflowStarted(25), + eventType: 'ExternalWorkflowExecutionSignaled', + externalWorkflowExecutionSignaledEventAttributes: { + initiatedEventId: '24', + workflowExecution: { workflowId: 'other', runId: 'run' }, + }, + }; + const raw = [ + makeWorkflowStarted(1), + ...makeActivityGroup(2), + ...makeTimerGroup(5), + ...makeChildWorkflowGroup(7), + ...makeLocalActivityGroup(10), + ...makeWorkflowUpdateGroup(11), + ...makeNexusOperationGroup(13), + ...makeWorkflowTaskGroup(16), + makeWorkflowCompleted(19), + signal, + marker, + externalSignal, + signalDelivered, + ]; + buffer.reset(25); + loadAll(raw); + const events = toEventHistory(raw); + const groups = groupEvents(events); + const expected = buildGroupIndex( + excludeWorkflowTasks + ? groups + : [...groups, ...groupWorkflowTaskEvents(events)], + ); + expect(new Set(groups.map((group) => group.category))).toEqual( + new Set([ + 'activity', + 'timer', + 'child-workflow', + 'local-activity', + 'update', + 'nexus', + 'signal', + 'other', + ]), + ); + for (const event of events) { + expect(buffer.getEvent(event.id)).toEqual(event); + expect( + buffer.getEventGroup(event.id, { excludeWorkflowTasks }), + ).toEqual(expected.get(event.id)); + } + for (const group of new Set(expected.values())) { + for (const event of group.eventList) { + expect(buffer.getEventGroup(event.id, { excludeWorkflowTasks })).toBe( + buffer.getEventGroup(group.initialEvent.id, { + excludeWorkflowTasks, + }), + ); + } + } + }, + ); + + it('exposes descending followers only after their head arrives', () => { + buffer.reset(10); + const [head, started, completed] = makeActivityGroup(1); + buffer.ingestHistoryEvent(completed); + buffer.ingestHistoryEvent(started); + expect(buffer.getEvent('3')?.id).toBe('3'); + expect(buffer.getEventGroup('1')).toBeUndefined(); + expect(buffer.getEventGroup('2')).toBeUndefined(); + expect(buffer.getEventGroup('3')).toBeUndefined(); + buffer.ingestHistoryEvent(head); + const expected = buildGroupIndex( + groupEvents(toEventHistory([head, started, completed])), + ); + expect(buffer.getEventGroup('3')).toEqual(expected.get('3')); + expect(buffer.getEventGroup('2')).toBe(buffer.getEventGroup('1')); + }); + + it('does not create groups for missing events, absent heads, solo events, or excluded WFTs', () => { + buffer.reset(20); + buffer.ingestHistoryEvent(makeWorkflowStarted(1)); + buffer.ingestHistoryEvent(makeActivityStarted(3, 1)); + buffer.ingestHistoryEvent(makeActivityStarted(5, 4)); + loadAll(makeWorkflowTaskGroup(6)); + const createGroup = vi.mocked(createEventGroup).mockClear(); + const createWft = vi.mocked(createWorkflowTaskGroup).mockClear(); + for (const id of ['1', '2', '3', '4', '5', '99']) { + expect(buffer.getEventGroup(id)).toBeUndefined(); + } + for (const id of ['6', '7', '8']) { + expect( + buffer.getEventGroup(id, { excludeWorkflowTasks: true }), + ).toBeUndefined(); + } + expect(createGroup).not.toHaveBeenCalled(); + expect(createWft).not.toHaveBeenCalled(); + expect(buffer.getEventGroup('8')?.id).toBe('6'); + }); + + it('materializes only the requested record and shares its cache with array reads', () => { + buffer.reset(100); + loadAll(makeActivityGroup(1)); + loadAll(makeTimerGroup(4)); + loadAll(makeNexusOperationGroup(6)); + const createGroup = vi.mocked(createEventGroup).mockClear(); + const createWft = vi.mocked(createWorkflowTaskGroup).mockClear(); + const first = buffer.getEventGroup('2'); + expect(first?.id).toBe('1'); + expect(createGroup).toHaveBeenCalledTimes(1); + expect(createWft).not.toHaveBeenCalled(); + expect(buffer.getEventGroup('3')).toBe(first); + buffer.ingestHistoryEvent(makeWorkflowCompleted(50)); + expect(buffer.getEventGroup('1')).toBe(first); + expect(createGroup).toHaveBeenCalledTimes(1); + expect(buffer.getGroupArray()[0]).toBe(first); + expect(createGroup).toHaveBeenCalledTimes(3); + }); + + it('invalidates only the record whose members or pending metadata changed', () => { + buffer.reset(20); + const [scheduled, started, completed] = makeActivityGroup(1); + const [nexusScheduled, nexusStarted, nexusCompleted] = + makeNexusOperationGroup(4); + loadAll([ + scheduled, + started, + nexusScheduled, + nexusStarted, + ...makeTimerGroup(7), + ]); + const activity: PendingActivity = { + id: '1', + activityId: '1', + state: 'Started', + activityType: 'TestActivity', + }; + const nexus: PendingNexusOperation = { + scheduledEventId: '4', + scheduleToStartTimeout: null, + startToCloseTimeout: null, + }; + const timer = buffer.getEventGroup('8'); + const before = buffer.getEventGroup('2'); + buffer.setPendingMetadata([activity], [nexus]); + const pendingActivity = buffer.getEventGroup('2'); + const pendingNexus = buffer.getEventGroup('5'); + expect(pendingActivity).not.toBe(before); + expect(pendingActivity?.pendingActivity).toEqual(activity); + expect(pendingNexus?.pendingNexusOperation).toEqual(nexus); + expect(pendingActivity?.isPending).toBe(true); + expect(pendingNexus?.isPending).toBe(true); + const expected = buildGroupIndex( + groupEvents( + toEventHistory([scheduled, started, nexusScheduled, nexusStarted]), + 'ascending', + [activity], + [nexus], + ), + ); + expect(pendingActivity).toEqual(expected.get('2')); + expect(pendingNexus).toEqual(expected.get('5')); + buffer.setPendingMetadata([activity], [nexus]); + expect(buffer.getEventGroup('1')).toBe(pendingActivity); + expect(buffer.getEventGroup('4')).toBe(pendingNexus); + buffer.setPendingMetadata( + [{ ...activity, state: 'CancelRequested' }], + [nexus], + ); + expect(buffer.getEventGroup('2')).not.toBe(pendingActivity); + expect(buffer.getEventGroup('5')).toBe(pendingNexus); + buffer.ingestHistoryEvent(completed); + expect(buffer.getEventGroup('3')?.pendingActivity).toBeUndefined(); + expect(buffer.getEventGroup('3')?.isPending).toBe(false); + expect(buffer.getEventGroup('5')).toBe(pendingNexus); + buffer.ingestHistoryEvent(nexusCompleted); + expect(buffer.getEventGroup('6')).not.toBe(pendingNexus); + expect(buffer.getEventGroup('6')?.pendingNexusOperation).toBeUndefined(); + expect(buffer.getEventGroup('6')?.isPending).toBe(false); + expect(buffer.getEventGroup('8')).toBe(timer); + expect(pendingActivity?.pendingActivity).toEqual(activity); + expect(pendingNexus?.pendingNexusOperation).toEqual(nexus); + }); + + it('reads pending metadata that predates heads and refreshes nexus updates and removal', () => { + buffer.reset(10); + const activity: PendingActivity = { + id: '1', + activityId: '1', + state: 'Scheduled', + }; + const nexus: PendingNexusOperation = { + scheduledEventId: '4', + endpoint: 'before', + scheduleToStartTimeout: null, + startToCloseTimeout: null, + }; + buffer.setPendingMetadata([activity], [nexus]); + expect(buffer.getEventGroup('1')).toBeUndefined(); + expect(buffer.getEventGroup('4')).toBeUndefined(); + buffer.ingestHistoryEvent(makeActivityScheduled(1)); + buffer.ingestHistoryEvent(makeNexusOperationGroup(4)[0]); + const activityGroup = buffer.getEventGroup('1'); + const nexusGroup = buffer.getEventGroup('4'); + expect(activityGroup?.pendingActivity).toEqual(activity); + expect(nexusGroup?.pendingNexusOperation).toEqual(nexus); + const updatedNexus = { ...nexus, endpoint: 'after' }; + buffer.setPendingMetadata([activity], [updatedNexus]); + expect(buffer.getEventGroup('1')).toBe(activityGroup); + expect(buffer.getEventGroup('4')).not.toBe(nexusGroup); + expect(buffer.getEventGroup('4')?.pendingNexusOperation).toEqual( + updatedNexus, + ); + expect(nexusGroup?.pendingNexusOperation).toEqual(nexus); + buffer.setPendingMetadata([], []); + expect(buffer.getEventGroup('1')?.pendingActivity).toBeUndefined(); + expect(buffer.getEventGroup('4')?.pendingNexusOperation).toBeUndefined(); + expect(buffer.getEventGroup('1')?.isPending).toBe(false); + expect(buffer.getEventGroup('4')?.isPending).toBe(false); + }); + + it('isolates buffers and discards events and cached groups on reset', () => { + buffer.reset(3); + loadAll(makeActivityGroup(1)); + const other = createGroupedEventBuffer(); + other.reset(3); + for (const event of makeActivityGroup(1, 'Other')) + other.ingestHistoryEvent(event); + const previousEvent = buffer.getEvent('1'); + const previousGroup = buffer.getEventGroup('1'); + const otherGroup = other.getEventGroup('1'); + expect(otherGroup).not.toBe(previousGroup); + buffer.reset(3); + expect(buffer.getEvent('1')).toBeUndefined(); + expect(buffer.getEventGroup('3')).toBeUndefined(); + expect(other.getEventGroup('1')).toBe(otherGroup); + loadAll(makeTimerGroup(1)); + expect(buffer.getEvent('1')).not.toBe(previousEvent); + expect(buffer.getEventGroup('1')).not.toBe(previousGroup); + expect(buffer.getEventGroup('2')?.category).toBe('timer'); + expect(buffer.getEvent('3')).toBeUndefined(); + expect(buffer.getEventGroup('3')).toBeUndefined(); + }); +}); + describe('output equivalence with groupEvents', () => { it('matches groupEvents for a small ascending load', async () => { const events = makeSyntheticEvents(30); - reset(30); + buffer.reset(30); loadAll(events); const workflowEvents = toEventHistory(events); const expected = groupEvents(workflowEvents, 'ascending'); - const actual = getGroupArray(); + const actual = buffer.getGroupArray(); expect(actual.map((g) => g.id)).toEqual(expected.map((g) => g.id)); expect(actual.map((g) => g.eventList.length)).toEqual( @@ -99,10 +433,10 @@ describe('output equivalence with groupEvents', () => { it('includes WorkflowTask groups when present', async () => { const events = makeSyntheticEventsWithWorkflowTasks(30); - reset(30); + buffer.reset(30); loadAll(events); - const actual = getGroupArray(); + const actual = buffer.getGroupArray(); const wftGroups = actual.filter(isWorkflowTaskGroup); expect(wftGroups.length).toBeGreaterThan(0); }); @@ -114,18 +448,18 @@ describe('output equivalence with groupEvents', () => { describe('follower before head', () => { it('desc-cursor followers arriving before the asc-cursor head land in the group', () => { - reset(10); + buffer.reset(10); const [head, started, completed] = makeActivityGroup(1); // Desc cursor delivers completed & started before head - ingestHistoryEvent(completed); - ingestHistoryEvent(started); - expect(getGroupArray()).toHaveLength(0); + buffer.ingestHistoryEvent(completed); + buffer.ingestHistoryEvent(started); + expect(buffer.getGroupArray()).toHaveLength(0); // Asc cursor delivers the head - ingestHistoryEvent(head); + buffer.ingestHistoryEvent(head); - const groups = getGroupArray(); + const groups = buffer.getGroupArray(); expect(groups).toHaveLength(1); expect(groups[0].eventList).toHaveLength(3); }); @@ -138,19 +472,19 @@ describe('follower before head', () => { describe('non-terminal workflow: new events beyond initial historyLength', () => { it('new events extend the slot arrays beyond the initial allocation', () => { const initialEvents = makeSyntheticEvents(9); // 9 events → 3 groups - reset(9); + buffer.reset(9); loadAll(initialEvents); - const initialGroupCount = getGroupArray().length; + const initialGroupCount = buffer.getGroupArray().length; expect(initialGroupCount).toBeGreaterThan(0); // New activity arrives at IDs 10-12 const [newHead, newStarted, newCompleted] = makeActivityGroup(10); - ingestHistoryEvent(newHead); - ingestHistoryEvent(newStarted); - ingestHistoryEvent(newCompleted); + buffer.ingestHistoryEvent(newHead); + buffer.ingestHistoryEvent(newStarted); + buffer.ingestHistoryEvent(newCompleted); - const groups = getGroupArray(); + const groups = buffer.getGroupArray(); expect(groups).toHaveLength(initialGroupCount + 1); const newGroup = groups.find((group) => group.id === '10'); @@ -165,56 +499,59 @@ describe('non-terminal workflow: new events beyond initial historyLength', () => describe('latest received event time', () => { it('keeps the maximum across out-of-order arrivals and clears it for the next run', () => { const latestTime = '2027-11-09T12:08:00.000Z'; - expect(getLatestEventTimeMs()).toBeUndefined(); + expect(buffer.getLatestEventTimeMs()).toBeUndefined(); - ingestHistoryEvent({ ...makeWorkflowStarted(2), eventTime: latestTime }); - ingestHistoryEvent({ + buffer.ingestHistoryEvent({ + ...makeWorkflowStarted(2), + eventTime: latestTime, + }); + buffer.ingestHistoryEvent({ ...makeWorkflowStarted(1), eventTime: '2027-11-09T12:02:00.000Z', }); - ingestHistoryEvent({ + buffer.ingestHistoryEvent({ ...makeWorkflowStarted(3), eventTime: '2027-11-09T12:05:00.000Z', }); - expect(getLatestEventTimeMs()).toBe(Date.parse(latestTime)); + expect(buffer.getLatestEventTimeMs()).toBe(Date.parse(latestTime)); - reset(0); - expect(getLatestEventTimeMs()).toBeUndefined(); + buffer.reset(0); + expect(buffer.getLatestEventTimeMs()).toBeUndefined(); const nextRunStartTime = '2026-11-09T12:00:00.000Z'; - ingestHistoryEvent({ + buffer.ingestHistoryEvent({ ...makeWorkflowStarted(1), eventTime: nextRunStartTime, }); - expect(getLatestEventTimeMs()).toBe(Date.parse(nextRunStartTime)); + expect(buffer.getLatestEventTimeMs()).toBe(Date.parse(nextRunStartTime)); }); }); describe('navigation reset', () => { it('reset() zeroes pool entries and reuses them for the next workflow', async () => { const events1 = makeSyntheticEvents(30); - reset(30); + buffer.reset(30); loadAll(events1); - const firstGroupCount = getGroupArray().length; + const firstGroupCount = buffer.getGroupArray().length; - reset(15); + buffer.reset(15); const events2 = makeSyntheticEvents(15); loadAll(events2); // Pool was re-used — no double allocation - expect(getGroupArray().length).toBeLessThanOrEqual(firstGroupCount); - expect(getGroupArray().length).toBeGreaterThan(0); + expect(buffer.getGroupArray().length).toBeLessThanOrEqual(firstGroupCount); + expect(buffer.getGroupArray().length).toBeGreaterThan(0); }); it('groups from the previous workflow do not survive reset()', () => { - reset(30); + buffer.reset(30); loadAll(makeSyntheticEvents(30)); - expect(getGroupArray().length).toBeGreaterThan(0); + expect(buffer.getGroupArray().length).toBeGreaterThan(0); - reset(9); // navigate away - expect(getGroupArray()).toHaveLength(0); + buffer.reset(9); // navigate away + expect(buffer.getGroupArray()).toHaveLength(0); loadAll(makeSyntheticEvents(9)); - const ids = getGroupArray().map((group) => Number(group.id)); + const ids = buffer.getGroupArray().map((group) => Number(group.id)); expect(Math.max(...ids)).toBeLessThanOrEqual(9); }); }); @@ -228,26 +565,26 @@ describe('navigation reset', () => { describe('compact view: getGroupArray excludeWorkflowTasks regression', () => { it('returns no WFT groups when excludeWorkflowTasks is true, even with interleaved events', () => { - reset(30); + buffer.reset(30); // Interleave WFT groups and activity groups to simulate a real workflow - for (const e of makeWorkflowTaskGroup(1)) ingestHistoryEvent(e); - for (const e of makeActivityGroup(4)) ingestHistoryEvent(e); - for (const e of makeWorkflowTaskGroup(7)) ingestHistoryEvent(e); - for (const e of makeActivityGroup(10)) ingestHistoryEvent(e); - for (const e of makeWorkflowTaskGroup(13)) ingestHistoryEvent(e); + for (const e of makeWorkflowTaskGroup(1)) buffer.ingestHistoryEvent(e); + for (const e of makeActivityGroup(4)) buffer.ingestHistoryEvent(e); + for (const e of makeWorkflowTaskGroup(7)) buffer.ingestHistoryEvent(e); + for (const e of makeActivityGroup(10)) buffer.ingestHistoryEvent(e); + for (const e of makeWorkflowTaskGroup(13)) buffer.ingestHistoryEvent(e); - const compactGroups = getGroupArray({ excludeWorkflowTasks: true }); + const compactGroups = buffer.getGroupArray({ excludeWorkflowTasks: true }); expect(compactGroups.every((g) => !isWorkflowTaskGroup(g))).toBe(true); expect(compactGroups).toHaveLength(2); // only the two activity groups }); it('includes WFT groups in unfiltered output (for All events view)', () => { - reset(20); - for (const e of makeWorkflowTaskGroup(1)) ingestHistoryEvent(e); - for (const e of makeActivityGroup(4)) ingestHistoryEvent(e); + buffer.reset(20); + for (const e of makeWorkflowTaskGroup(1)) buffer.ingestHistoryEvent(e); + for (const e of makeActivityGroup(4)) buffer.ingestHistoryEvent(e); - const allGroups = getGroupArray(); + const allGroups = buffer.getGroupArray(); const wftGroups = allGroups.filter(isWorkflowTaskGroup); expect(wftGroups.length).toBeGreaterThan(0); @@ -260,28 +597,28 @@ describe('compact view: getGroupArray excludeWorkflowTasks regression', () => { describe('boundary dedup', () => { it('write-once guard prevents double group registration for the same head slot', () => { - reset(10); + buffer.reset(10); const [head] = makeActivityGroup(1); - ingestHistoryEvent(head); // asc cursor - ingestHistoryEvent(head); // desc cursor — same event, same slot + buffer.ingestHistoryEvent(head); // asc cursor + buffer.ingestHistoryEvent(head); // desc cursor — same event, same slot - expect(getGroupArray().length).toBe(1); + expect(buffer.getGroupArray().length).toBe(1); }); it('a redelivered head does not corrupt an already-built group', () => { - reset(10); + buffer.reset(10); const [head, started, completed] = makeActivityGroup(1); - ingestHistoryEvent(head); - ingestHistoryEvent(started); - ingestHistoryEvent(completed); + buffer.ingestHistoryEvent(head); + buffer.ingestHistoryEvent(started); + buffer.ingestHistoryEvent(completed); // Simulate boundary overlap: desc cursor also writes the head - ingestHistoryEvent(head); + buffer.ingestHistoryEvent(head); - expect(getGroupArray()).toHaveLength(1); - expect(getGroupArray()[0].eventList).toHaveLength(3); + expect(buffer.getGroupArray()).toHaveLength(1); + expect(buffer.getGroupArray()[0].eventList).toHaveLength(3); }); }); @@ -291,27 +628,27 @@ describe('boundary dedup', () => { describe('solo event orphan cleanup', () => { it('WorkflowExecutionStarted is not registered as a group', () => { - reset(10); - ingestHistoryEvent(makeWorkflowStarted(1)); - expect(getGroupArray().length).toBe(0); + buffer.reset(10); + buffer.ingestHistoryEvent(makeWorkflowStarted(1)); + expect(buffer.getGroupArray().length).toBe(0); }); it('WorkflowExecutionCompleted is not registered as a group', () => { - reset(10); - ingestHistoryEvent(makeWorkflowCompleted(5)); - expect(getGroupArray().length).toBe(0); + buffer.reset(10); + buffer.ingestHistoryEvent(makeWorkflowCompleted(5)); + expect(buffer.getGroupArray().length).toBe(0); }); it('followers of a solo head form no group but stay in the event list', () => { - reset(10); + buffer.reset(10); // A follower that references slot 0 (eventId "1") as its head, where slot 0 // turns out to be a WorkflowExecutionStarted — solo, not a group head. - ingestHistoryEvent(makeActivityStarted(2, 1)); - ingestHistoryEvent(makeWorkflowStarted(1)); + buffer.ingestHistoryEvent(makeActivityStarted(2, 1)); + buffer.ingestHistoryEvent(makeWorkflowStarted(1)); - expect(getGroupArray()).toHaveLength(0); - expect(getEventArray().map((event) => event.id)).toEqual(['1', '2']); + expect(buffer.getGroupArray()).toHaveLength(0); + expect(buffer.getEventArray().map((event) => event.id)).toEqual(['1', '2']); }); }); @@ -321,18 +658,18 @@ describe('solo event orphan cleanup', () => { describe('setFailedEvent', () => { it('can be set to null without error', () => { - reset(10); - setFailedEvent(null); - expect(getGroupArray()).toHaveLength(0); + buffer.reset(10); + buffer.setFailedEvent(null); + expect(buffer.getGroupArray()).toHaveLength(0); }); it('can be set to a HistoryEvent before ingestHistoryEvent calls', () => { - reset(10); + buffer.reset(10); const events = makeSyntheticEvents(9); // Simulate desc first-page hook - setFailedEvent(null); + buffer.setFailedEvent(null); loadAll(events); - expect(getGroupArray().length).toBeGreaterThan(0); + expect(buffer.getGroupArray().length).toBeGreaterThan(0); }); }); @@ -348,64 +685,63 @@ describe('marker billable actions', () => { const toEventSpy = vi.mocked(toEvent); const totalBillableActions = () => - getEventArray().reduce( - (sum, event) => sum + (event.billableActions ?? 0), - 0, - ); + buffer + .getEventArray() + .reduce((sum, event) => sum + (event.billableActions ?? 0), 0); // IDs 11-13, all emitted by the workflow task completed at event 10. const markers = [11, 12, 13].map((id) => makeLocalActivityMarker(id, 10)); it('bills one workflow task once in ascending id order', () => { - reset(20); - for (const marker of markers) ingestHistoryEvent(marker); + buffer.reset(20); + for (const marker of markers) buffer.ingestHistoryEvent(marker); expect(totalBillableActions()).toBe(1); }); it('bills one workflow task once in descending id order', () => { - reset(20); + buffer.reset(20); for (const marker of markers.toReversed()) { - ingestHistoryEvent(marker); + buffer.ingestHistoryEvent(marker); } expect(totalBillableActions()).toBe(1); }); it('bills one workflow task once when its markers interleave', () => { - reset(20); - ingestHistoryEvent(markers[2]); - ingestHistoryEvent(markers[0]); - ingestHistoryEvent(markers[1]); + buffer.reset(20); + buffer.ingestHistoryEvent(markers[2]); + buffer.ingestHistoryEvent(markers[0]); + buffer.ingestHistoryEvent(markers[1]); expect(totalBillableActions()).toBe(1); }); it('bills distinct workflow tasks separately', () => { - reset(20); - ingestHistoryEvent(makeLocalActivityMarker(11, 10)); - ingestHistoryEvent(makeLocalActivityMarker(13, 12)); + buffer.reset(20); + buffer.ingestHistoryEvent(makeLocalActivityMarker(11, 10)); + buffer.ingestHistoryEvent(makeLocalActivityMarker(13, 12)); expect(totalBillableActions()).toBe(2); }); // Both cursors can deliver the same event. Conversion is what charges, so the // write-once guard has to reject a redelivery before toWorkflowEvent runs. it('converts a redelivered event once, so it bills once', () => { - reset(20); + buffer.reset(20); toEventSpy.mockClear(); const scheduled = makeActivityScheduled(1, 'Act'); - expect(ingestHistoryEvent(scheduled)).toBe(true); - expect(ingestHistoryEvent(scheduled)).toBe(false); + expect(buffer.ingestHistoryEvent(scheduled)).toBe(true); + expect(buffer.ingestHistoryEvent(scheduled)).toBe(false); expect(toEventSpy).toHaveBeenCalledTimes(1); expect(totalBillableActions()).toBe(1); }); it('converts a redelivered marker once, so its task stays charged', () => { - reset(20); + buffer.reset(20); toEventSpy.mockClear(); - ingestHistoryEvent(markers[0]); - ingestHistoryEvent(markers[0]); - ingestHistoryEvent(markers[1]); + buffer.ingestHistoryEvent(markers[0]); + buffer.ingestHistoryEvent(markers[0]); + buffer.ingestHistoryEvent(markers[1]); expect(toEventSpy).toHaveBeenCalledTimes(2); expect(totalBillableActions()).toBe(1); @@ -424,9 +760,9 @@ describe('memory overhead smoke test', () => { globalThis.gc(); const before = process.memoryUsage().heapUsed; - reset(50_000); + buffer.reset(50_000); loadAll(events); - getGroupArray(); + buffer.getGroupArray(); globalThis.gc(); const after = process.memoryUsage().heapUsed; @@ -444,28 +780,28 @@ describe('memory overhead smoke test', () => { describe('activity group integrity', () => { it('group has all 3 events when loaded ascending', async () => { - reset(10); + buffer.reset(10); const [scheduled, started, completed] = makeActivityGroup(1); - ingestHistoryEvent(scheduled); - ingestHistoryEvent(started); - ingestHistoryEvent(completed); + buffer.ingestHistoryEvent(scheduled); + buffer.ingestHistoryEvent(started); + buffer.ingestHistoryEvent(completed); - const [group] = getGroupArray(); + const [group] = buffer.getGroupArray(); expect(group.eventList.length).toBe(3); expect(group.id).toBe('1'); }); it('group has all 3 events when followers arrive before head', async () => { - reset(10); + buffer.reset(10); const [scheduled, started, completed] = makeActivityGroup(1); // Desc cursor delivers completion and start first - ingestHistoryEvent(completed); - ingestHistoryEvent(started); + buffer.ingestHistoryEvent(completed); + buffer.ingestHistoryEvent(started); // Asc cursor delivers head - ingestHistoryEvent(scheduled); + buffer.ingestHistoryEvent(scheduled); - const [group] = getGroupArray(); + const [group] = buffer.getGroupArray(); expect(group.eventList.length).toBe(3); }); @@ -475,14 +811,14 @@ describe('activity group integrity', () => { // (lower ID). insertEventById must keep the list in ascending ID order so // that isMiddleEvent, isConsecutiveGroup, and the detail panel all see // [Scheduled, Started, Completed] rather than [Scheduled, Completed, Started]. - reset(10); + buffer.reset(10); const [scheduled, started, completed] = makeActivityGroup(1); - ingestHistoryEvent(scheduled); // asc cursor: head arrives first - ingestHistoryEvent(completed); // desc cursor: Completed arrives before Started - ingestHistoryEvent(started); // desc cursor: Started arrives last despite lower ID + buffer.ingestHistoryEvent(scheduled); // asc cursor: head arrives first + buffer.ingestHistoryEvent(completed); // desc cursor: Completed arrives before Started + buffer.ingestHistoryEvent(started); // desc cursor: Started arrives last despite lower ID - const [group] = getGroupArray(); + const [group] = buffer.getGroupArray(); expect(group.eventList.map((e) => e.id)).toEqual([ String(scheduled.eventId), String(started.eventId), @@ -491,16 +827,16 @@ describe('activity group integrity', () => { }); it('multiple groups maintain correct event membership', async () => { - reset(20); + buffer.reset(20); const group1Events = makeActivityGroup(1); const group2Events = makeActivityGroup(4); const group3Events = makeTimerGroup(7); for (const e of [...group1Events, ...group2Events, ...group3Events]) { - ingestHistoryEvent(e); + buffer.ingestHistoryEvent(e); } - const groups = getGroupArray(); + const groups = buffer.getGroupArray(); expect(groups[0].eventList.length).toBe(3); // activity expect(groups[1].eventList.length).toBe(3); // activity expect(groups[2].eventList.length).toBe(2); // timer @@ -516,33 +852,33 @@ describe('activity group integrity', () => { describe('setPendingMetadata', () => { it('sets pendingActivity on an in-flight activity group (1 event)', async () => { - reset(10); - ingestHistoryEvent(makeActivityScheduled(1, 'MyActivity')); + buffer.reset(10); + buffer.ingestHistoryEvent(makeActivityScheduled(1, 'MyActivity')); const pendingActivities = [ { activityId: '1', state: 'Started', activityType: 'MyActivity' }, - ] as Parameters[0]; + ] as Parameters[0]; - setPendingMetadata(pendingActivities, []); + buffer.setPendingMetadata(pendingActivities, []); - const [group] = getGroupArray(); + const [group] = buffer.getGroupArray(); expect(group.pendingActivity).toBeDefined(); expect(group.pendingActivity?.activityId).toBe('1'); }); it('swaps in a fresh group reference when pending state changes', () => { - reset(10); - ingestHistoryEvent(makeActivityScheduled(1, 'MyActivity')); - const before = getGroupArray().find((g) => g.id === '1'); + buffer.reset(10); + buffer.ingestHistoryEvent(makeActivityScheduled(1, 'MyActivity')); + const before = buffer.getGroupArray().find((g) => g.id === '1'); - setPendingMetadata( + buffer.setPendingMetadata( [ { activityId: '1', state: 'Started', activityType: 'MyActivity' }, - ] as Parameters[0], + ] as Parameters[0], [], ); - const after = getGroupArray().find((g) => g.id === '1'); + const after = buffer.getGroupArray().find((g) => g.id === '1'); // Reference-tracking views only re-derive when the object identity changes; // a pause/unpause appends no history event, so the ref swap is the signal. expect(after).not.toBe(before); @@ -556,135 +892,135 @@ describe('setPendingMetadata', () => { }); it('reuses the group reference when pending state is unchanged', () => { - reset(10); - ingestHistoryEvent(makeActivityScheduled(1, 'MyActivity')); + buffer.reset(10); + buffer.ingestHistoryEvent(makeActivityScheduled(1, 'MyActivity')); const pending = [ { activityId: '1', state: 'Started', activityType: 'MyActivity' }, - ] as Parameters[0]; + ] as Parameters[0]; - setPendingMetadata(pending, []); - const first = getGroupArray().find((g) => g.id === '1'); - setPendingMetadata(pending, []); - const second = getGroupArray().find((g) => g.id === '1'); + buffer.setPendingMetadata(pending, []); + const first = buffer.getGroupArray().find((g) => g.id === '1'); + buffer.setPendingMetadata(pending, []); + const second = buffer.getGroupArray().find((g) => g.id === '1'); expect(second).toBe(first); }); it('does not set pendingActivity on a completed activity group (3 events)', async () => { - reset(10); + buffer.reset(10); const [s, st, c] = makeActivityGroup(1); - ingestHistoryEvent(s); - ingestHistoryEvent(st); - ingestHistoryEvent(c); + buffer.ingestHistoryEvent(s); + buffer.ingestHistoryEvent(st); + buffer.ingestHistoryEvent(c); const pendingActivities = [ { activityId: '1', state: 'Started', activityType: 'TestActivity' }, - ] as Parameters[0]; + ] as Parameters[0]; - setPendingMetadata(pendingActivities, []); + buffer.setPendingMetadata(pendingActivities, []); - const [group] = getGroupArray(); + const [group] = buffer.getGroupArray(); expect(group.pendingActivity).toBeUndefined(); }); it('clears a previously set pendingActivity when no longer pending', async () => { - reset(10); + buffer.reset(10); const [s, st, c] = makeActivityGroup(1); - ingestHistoryEvent(s); - ingestHistoryEvent(st); - ingestHistoryEvent(c); + buffer.ingestHistoryEvent(s); + buffer.ingestHistoryEvent(st); + buffer.ingestHistoryEvent(c); // First enrichment marks it pending const pa = [{ activityId: '1', state: 'Started' }] as Parameters< - typeof setPendingMetadata + typeof buffer.setPendingMetadata >[0]; - setPendingMetadata(pa, []); + buffer.setPendingMetadata(pa, []); // Second enrichment with empty array (activity completed server-side) - setPendingMetadata([], []); + buffer.setPendingMetadata([], []); - const [group] = getGroupArray(); + const [group] = buffer.getGroupArray(); expect(group.pendingActivity).toBeUndefined(); }); it('clears pendingActivity when live completion extends an existing group', async () => { - reset(10); + buffer.reset(10); const [scheduled, started, completed] = makeActivityGroup(1); - ingestHistoryEvent(scheduled); - ingestHistoryEvent(started); + buffer.ingestHistoryEvent(scheduled); + buffer.ingestHistoryEvent(started); - setPendingMetadata( + buffer.setPendingMetadata( [ { activityId: '1', state: 'Started', activityType: 'TestActivity', }, - ] as Parameters[0], + ] as Parameters[0], [], ); - let [group] = getGroupArray(); + let [group] = buffer.getGroupArray(); expect(group.pendingActivity).toBeDefined(); expect(group.isPending).toBe(true); - expect(ingestHistoryEvent(completed)).toBe(true); + expect(buffer.ingestHistoryEvent(completed)).toBe(true); - [group] = getGroupArray(); + [group] = buffer.getGroupArray(); expect(group.eventList).toHaveLength(3); expect(group.pendingActivity).toBeUndefined(); expect(group.isPending).toBe(false); }); it('clears pendingActivity when a live timeout resolves a short activity group', async () => { - reset(10); + buffer.reset(10); const [scheduled, timedOut] = makeActivityTimeoutGroup(1); - ingestHistoryEvent(scheduled); + buffer.ingestHistoryEvent(scheduled); - setPendingMetadata( + buffer.setPendingMetadata( [ { activityId: '1', state: 'Started', activityType: 'TestActivity', }, - ] as Parameters[0], + ] as Parameters[0], [], ); - let [group] = getGroupArray(); + let [group] = buffer.getGroupArray(); expect(group.pendingActivity).toBeDefined(); expect(group.isPending).toBe(true); - expect(ingestHistoryEvent(timedOut)).toBe(true); + expect(buffer.ingestHistoryEvent(timedOut)).toBe(true); - [group] = getGroupArray(); + [group] = buffer.getGroupArray(); expect(group.eventList.map((event) => event.id)).toEqual(['1', '2']); expect(group.pendingActivity).toBeUndefined(); expect(group.isPending).toBe(false); }); it('annotates live-only activity and nexus groups with pending metadata', () => { - reset(20); - ingestHistoryEvent(makeActivityScheduled(1, 'MyActivity')); - ingestHistoryEvent(makeNexusOperationGroup(4)[0]); + buffer.reset(20); + buffer.ingestHistoryEvent(makeActivityScheduled(1, 'MyActivity')); + buffer.ingestHistoryEvent(makeNexusOperationGroup(4)[0]); - setPendingMetadata( + buffer.setPendingMetadata( [ { activityId: '1', state: 'Started', activityType: 'MyActivity', }, - ] as Parameters[0], + ] as Parameters[0], [ { scheduledEventId: '4', }, - ] as Parameters[1], + ] as Parameters[1], ); - const groups = getGroupArray(); + const groups = buffer.getGroupArray(); expect( groups.find((group) => group.id === '1')?.pendingActivity, ).toBeDefined(); @@ -694,28 +1030,28 @@ describe('setPendingMetadata', () => { }); it('ignores activities not in the pending list', async () => { - reset(10); - ingestHistoryEvent(makeActivityScheduled(1, 'MyActivity')); - setPendingMetadata([], []); + buffer.reset(10); + buffer.ingestHistoryEvent(makeActivityScheduled(1, 'MyActivity')); + buffer.setPendingMetadata([], []); - const [group] = getGroupArray(); + const [group] = buffer.getGroupArray(); expect(group.pendingActivity).toBeUndefined(); }); it('does not touch non-activity groups', async () => { - reset(10); + buffer.reset(10); const [ts, tf] = makeTimerGroup(1); - ingestHistoryEvent(ts); - ingestHistoryEvent(tf); + buffer.ingestHistoryEvent(ts); + buffer.ingestHistoryEvent(tf); - setPendingMetadata( + buffer.setPendingMetadata( [{ activityId: '1', state: 'Started' }] as Parameters< - typeof setPendingMetadata + typeof buffer.setPendingMetadata >[0], [], ); - const [group] = getGroupArray(); + const [group] = buffer.getGroupArray(); expect(group.pendingActivity).toBeUndefined(); }); }); @@ -726,117 +1062,117 @@ describe('setPendingMetadata', () => { describe('getWorkflowTaskFailedEvent (buffer)', () => { it('returns undefined when no WFT groups exist', () => { - reset(10); - ingestHistoryEvent(makeActivityScheduled(1)); - expect(getWorkflowTaskFailedEvent()).toBeUndefined(); + buffer.reset(10); + buffer.ingestHistoryEvent(makeActivityScheduled(1)); + expect(buffer.getWorkflowTaskFailedEvent()).toBeUndefined(); }); it('returns undefined when WFT group completed normally', () => { - reset(10); - for (const e of makeWorkflowTaskGroup(1)) ingestHistoryEvent(e); - expect(getWorkflowTaskFailedEvent()).toBeUndefined(); + buffer.reset(10); + for (const e of makeWorkflowTaskGroup(1)) buffer.ingestHistoryEvent(e); + expect(buffer.getWorkflowTaskFailedEvent()).toBeUndefined(); }); it('returns the failed event when a WFT group has no subsequent completion', () => { - reset(10); + buffer.reset(10); // WFT: Scheduled(1), Started(2), Failed(3) - ingestHistoryEvent(makeWorkflowTaskScheduled(1)); - ingestHistoryEvent(makeWorkflowTaskStarted(2, 1)); - ingestHistoryEvent(makeWorkflowTaskFailed(3, 1)); + buffer.ingestHistoryEvent(makeWorkflowTaskScheduled(1)); + buffer.ingestHistoryEvent(makeWorkflowTaskStarted(2, 1)); + buffer.ingestHistoryEvent(makeWorkflowTaskFailed(3, 1)); - const failed = getWorkflowTaskFailedEvent(); + const failed = buffer.getWorkflowTaskFailedEvent(); expect(failed).toBeDefined(); expect(failed?.eventType).toBe('WorkflowTaskFailed'); }); it('returns undefined when a later WFT completed after the failure (workflow recovered)', () => { - reset(20); + buffer.reset(20); // First WFT: fails - ingestHistoryEvent(makeWorkflowTaskScheduled(1)); - ingestHistoryEvent(makeWorkflowTaskStarted(2, 1)); - ingestHistoryEvent(makeWorkflowTaskFailed(3, 1)); + buffer.ingestHistoryEvent(makeWorkflowTaskScheduled(1)); + buffer.ingestHistoryEvent(makeWorkflowTaskStarted(2, 1)); + buffer.ingestHistoryEvent(makeWorkflowTaskFailed(3, 1)); // Second WFT: completes successfully (workflow recovered) - ingestHistoryEvent(makeWorkflowTaskScheduled(4)); - ingestHistoryEvent(makeWorkflowTaskStarted(5, 4)); - ingestHistoryEvent(makeWorkflowTaskCompleted(6, 4)); + buffer.ingestHistoryEvent(makeWorkflowTaskScheduled(4)); + buffer.ingestHistoryEvent(makeWorkflowTaskStarted(5, 4)); + buffer.ingestHistoryEvent(makeWorkflowTaskCompleted(6, 4)); - expect(getWorkflowTaskFailedEvent()).toBeUndefined(); + expect(buffer.getWorkflowTaskFailedEvent()).toBeUndefined(); }); it('returns undefined for ResetWorkflow cause (not a real failure)', () => { - reset(10); - ingestHistoryEvent(makeWorkflowTaskScheduled(1)); - ingestHistoryEvent(makeWorkflowTaskStarted(2, 1)); - ingestHistoryEvent(makeWorkflowTaskFailed(3, 1, 'ResetWorkflow')); + buffer.reset(10); + buffer.ingestHistoryEvent(makeWorkflowTaskScheduled(1)); + buffer.ingestHistoryEvent(makeWorkflowTaskStarted(2, 1)); + buffer.ingestHistoryEvent(makeWorkflowTaskFailed(3, 1, 'ResetWorkflow')); - expect(getWorkflowTaskFailedEvent()).toBeUndefined(); + expect(buffer.getWorkflowTaskFailedEvent()).toBeUndefined(); }); it('returns the most recent failure when multiple WFT groups fail', () => { - reset(20); + buffer.reset(20); // First WFT fails - ingestHistoryEvent(makeWorkflowTaskScheduled(1)); - ingestHistoryEvent(makeWorkflowTaskStarted(2, 1)); - ingestHistoryEvent(makeWorkflowTaskFailed(3, 1)); + buffer.ingestHistoryEvent(makeWorkflowTaskScheduled(1)); + buffer.ingestHistoryEvent(makeWorkflowTaskStarted(2, 1)); + buffer.ingestHistoryEvent(makeWorkflowTaskFailed(3, 1)); // Second WFT also fails (eventId 6 > 3) - ingestHistoryEvent(makeWorkflowTaskScheduled(4)); - ingestHistoryEvent(makeWorkflowTaskStarted(5, 4)); - ingestHistoryEvent(makeWorkflowTaskFailed(6, 4)); + buffer.ingestHistoryEvent(makeWorkflowTaskScheduled(4)); + buffer.ingestHistoryEvent(makeWorkflowTaskStarted(5, 4)); + buffer.ingestHistoryEvent(makeWorkflowTaskFailed(6, 4)); - const failed = getWorkflowTaskFailedEvent(); + const failed = buffer.getWorkflowTaskFailedEvent(); expect(failed?.eventType).toBe('WorkflowTaskFailed'); expect(failed?.id).toBe('6'); }); it('returns a WFT failure whose group arrives entirely via the live poll', () => { - reset(10); - ingestHistoryEvent(makeWorkflowTaskScheduled(1)); - ingestHistoryEvent(makeWorkflowTaskStarted(2, 1)); - expect(getWorkflowTaskFailedEvent()).toBeUndefined(); + buffer.reset(10); + buffer.ingestHistoryEvent(makeWorkflowTaskScheduled(1)); + buffer.ingestHistoryEvent(makeWorkflowTaskStarted(2, 1)); + expect(buffer.getWorkflowTaskFailedEvent()).toBeUndefined(); - expect(ingestHistoryEvent(makeWorkflowTaskFailed(3, 1))).toBe(true); + expect(buffer.ingestHistoryEvent(makeWorkflowTaskFailed(3, 1))).toBe(true); - const failed = getWorkflowTaskFailedEvent(); + const failed = buffer.getWorkflowTaskFailedEvent(); expect(failed?.eventType).toBe('WorkflowTaskFailed'); expect(failed?.id).toBe('3'); }); it('returns a live WFT failure appended to a WFT head already in the pool', () => { - reset(10); - ingestHistoryEvent(makeWorkflowTaskScheduled(1)); - ingestHistoryEvent(makeWorkflowTaskStarted(2, 1)); - expect(getWorkflowTaskFailedEvent()).toBeUndefined(); + buffer.reset(10); + buffer.ingestHistoryEvent(makeWorkflowTaskScheduled(1)); + buffer.ingestHistoryEvent(makeWorkflowTaskStarted(2, 1)); + expect(buffer.getWorkflowTaskFailedEvent()).toBeUndefined(); - expect(ingestHistoryEvent(makeWorkflowTaskFailed(3, 1))).toBe(true); + expect(buffer.ingestHistoryEvent(makeWorkflowTaskFailed(3, 1))).toBe(true); - const failed = getWorkflowTaskFailedEvent(); + const failed = buffer.getWorkflowTaskFailedEvent(); expect(failed?.eventType).toBe('WorkflowTaskFailed'); expect(failed?.id).toBe('3'); }); it('clears the WFT failure when a later WFT completes via the live poll', () => { - reset(20); - ingestHistoryEvent(makeWorkflowTaskScheduled(1)); - ingestHistoryEvent(makeWorkflowTaskStarted(2, 1)); - ingestHistoryEvent(makeWorkflowTaskFailed(3, 1)); - expect(getWorkflowTaskFailedEvent()?.id).toBe('3'); + buffer.reset(20); + buffer.ingestHistoryEvent(makeWorkflowTaskScheduled(1)); + buffer.ingestHistoryEvent(makeWorkflowTaskStarted(2, 1)); + buffer.ingestHistoryEvent(makeWorkflowTaskFailed(3, 1)); + expect(buffer.getWorkflowTaskFailedEvent()?.id).toBe('3'); // Workflow recovers: a new WFT completes, delivered live. - ingestHistoryEvent(makeWorkflowTaskScheduled(4)); - ingestHistoryEvent(makeWorkflowTaskStarted(5, 4)); - ingestHistoryEvent(makeWorkflowTaskCompleted(6, 4)); + buffer.ingestHistoryEvent(makeWorkflowTaskScheduled(4)); + buffer.ingestHistoryEvent(makeWorkflowTaskStarted(5, 4)); + buffer.ingestHistoryEvent(makeWorkflowTaskCompleted(6, 4)); - expect(getWorkflowTaskFailedEvent()).toBeUndefined(); + expect(buffer.getWorkflowTaskFailedEvent()).toBeUndefined(); }); it('does not double-count a live WFT group once the fetch claims its head', () => { - reset(10); + buffer.reset(10); // Failure lands live first, then the bidirectional fetch reaches the head. - ingestHistoryEvent(makeWorkflowTaskScheduled(1)); - ingestHistoryEvent(makeWorkflowTaskFailed(3, 1)); - ingestHistoryEvent(makeWorkflowTaskScheduled(1)); + buffer.ingestHistoryEvent(makeWorkflowTaskScheduled(1)); + buffer.ingestHistoryEvent(makeWorkflowTaskFailed(3, 1)); + buffer.ingestHistoryEvent(makeWorkflowTaskScheduled(1)); - const failed = getWorkflowTaskFailedEvent(); + const failed = buffer.getWorkflowTaskFailedEvent(); expect(failed?.eventType).toBe('WorkflowTaskFailed'); expect(failed?.id).toBe('3'); }); @@ -848,44 +1184,44 @@ describe('getWorkflowTaskFailedEvent (buffer)', () => { describe('getGroupArray', () => { it('returns groups sorted by eventId ascending', () => { - reset(20); + buffer.reset(20); // Load in non-sequential order (simulates interleaved cursors) const [s2, st2, c2] = makeActivityGroup(4); const [s1, st1, c1] = makeActivityGroup(1); - for (const e of [s2, st2, c2]) ingestHistoryEvent(e); // desc cursor - for (const e of [s1, st1, c1]) ingestHistoryEvent(e); // asc cursor + for (const e of [s2, st2, c2]) buffer.ingestHistoryEvent(e); // desc cursor + for (const e of [s1, st1, c1]) buffer.ingestHistoryEvent(e); // asc cursor - const groups = getGroupArray(); + const groups = buffer.getGroupArray(); expect(groups.length).toBe(2); expect(Number(groups[0].id)).toBeLessThan(Number(groups[1].id)); }); it('excludeWorkflowTasks filters WFT groups', () => { - reset(20); - for (const e of makeWorkflowTaskGroup(1)) ingestHistoryEvent(e); - for (const e of makeActivityGroup(4)) ingestHistoryEvent(e); + buffer.reset(20); + for (const e of makeWorkflowTaskGroup(1)) buffer.ingestHistoryEvent(e); + for (const e of makeActivityGroup(4)) buffer.ingestHistoryEvent(e); - const all = getGroupArray(); - const noWft = getGroupArray({ excludeWorkflowTasks: true }); + const all = buffer.getGroupArray(); + const noWft = buffer.getGroupArray({ excludeWorkflowTasks: true }); expect(all.length).toBe(2); expect(noWft.length).toBe(1); expect(noWft[0].initialEvent.eventType).toBe('ActivityTaskScheduled'); }); it('is stable across multiple calls', () => { - reset(10); - for (const e of makeActivityGroup(1)) ingestHistoryEvent(e); + buffer.reset(10); + for (const e of makeActivityGroup(1)) buffer.ingestHistoryEvent(e); - const a = getGroupArray(); - const b = getGroupArray(); + const a = buffer.getGroupArray(); + const b = buffer.getGroupArray(); expect(a.length).toBe(b.length); expect(a[0].id).toBe(b[0].id); }); it('returns empty array when no groups loaded', () => { - reset(10); - ingestHistoryEvent(makeWorkflowStarted(1)); - expect(getGroupArray()).toHaveLength(0); + buffer.reset(10); + buffer.ingestHistoryEvent(makeWorkflowStarted(1)); + expect(buffer.getGroupArray()).toHaveLength(0); }); }); @@ -903,45 +1239,47 @@ describe('getGroupArray', () => { describe('ingestHistoryEvent boolean return', () => { beforeEach(() => { - reset(10); + buffer.reset(10); }); it('returns true for a genuinely new live event', () => { // Event 11 was never in the initial fetch — it is a new live event. const newEvent = makeWorkflowCompleted(11); - expect(ingestHistoryEvent(newEvent)).toBe(true); + expect(buffer.ingestHistoryEvent(newEvent)).toBe(true); }); it('returns false when the same event is appended a second time (duplicate)', () => { const ev = makeWorkflowCompleted(11); - ingestHistoryEvent(ev); + buffer.ingestHistoryEvent(ev); // Second call with the same eventId must be a no-op. - expect(ingestHistoryEvent(ev)).toBe(false); + expect(buffer.ingestHistoryEvent(ev)).toBe(false); }); it('returns false for a different object with the same eventId (duplicate by ID)', () => { const ev1 = makeWorkflowCompleted(11); const ev2 = makeWorkflowCompleted(11); // distinct object, same ID - ingestHistoryEvent(ev1); - expect(ingestHistoryEvent(ev2)).toBe(false); + buffer.ingestHistoryEvent(ev1); + expect(buffer.ingestHistoryEvent(ev2)).toBe(false); }); it('returns false for a grouped event already seen in the initial fetch', () => { const group = makeActivityGroup(2); // eventIds 2, 3, 4 - reset(5); - for (const e of group) ingestHistoryEvent(e); + buffer.reset(5); + for (const e of group) buffer.ingestHistoryEvent(e); - expect(ingestHistoryEvent(group[0])).toBe(false); + expect(buffer.ingestHistoryEvent(group[0])).toBe(false); }); it('only returns true for grouped events that are actually new in a mixed batch', () => { // An activity group (events 1-3) stands in for the initial fetch's events. const existing = makeActivityGroup(1); // eventIds 1, 2, 3 - reset(6); - for (const e of existing) ingestHistoryEvent(e); + buffer.reset(6); + for (const e of existing) buffer.ingestHistoryEvent(e); const newEv = makeActivityScheduled(4); - const results = [...existing, newEv].map((e) => ingestHistoryEvent(e)); + const results = [...existing, newEv].map((e) => + buffer.ingestHistoryEvent(e), + ); // Events 1-3 were already ingested → all false expect(results.slice(0, 3).every((r) => r === false)).toBe(true); @@ -961,29 +1299,29 @@ describe('ingestHistoryEvent boolean return', () => { describe('concurrent live poll and bidirectional fetch', () => { beforeEach(() => { - reset(10); + buffer.reset(10); }); it('events only in live poll (genuinely new) appear in getEventArray()', () => { // Bidirectional has not started — buffer is empty. // Live poll delivers a brand-new event (not in the initial fetch). const newEv = makeActivityScheduled(1); - ingestHistoryEvent(newEv); + buffer.ingestHistoryEvent(newEv); - const ids = getEventArray().map((e) => e.id); + const ids = buffer.getEventArray().map((e) => e.id); expect(ids).toContain('1'); }); it('an event delivered by both producers is not double-counted in getEventArray()', () => { const group = makeActivityGroup(2); // eventIds 2, 3, 4 - reset(5); + buffer.reset(5); // Live poll wins the race, then the bidirectional fetch redelivers. - for (const ev of group) ingestHistoryEvent(ev); - for (const ev of group) ingestHistoryEvent(ev); + for (const ev of group) buffer.ingestHistoryEvent(ev); + for (const ev of group) buffer.ingestHistoryEvent(ev); // getEventArray() must return each event exactly once. - const allIds = getEventArray().map((e) => e.id); + const allIds = buffer.getEventArray().map((e) => e.id); const unique = new Set(allIds); expect(allIds.length).toBe(unique.size); @@ -1004,15 +1342,15 @@ describe('concurrent live poll and bidirectional fetch', () => { 'keeps live %s followers visible when bidirectional fetch later claims the head', (_, buildGroup) => { const group = buildGroup(); - reset(10); + buffer.reset(10); - for (const ev of group) ingestHistoryEvent(ev); - expect(getGroupArray()).toHaveLength(1); - expect(getGroupArray()[0].eventList).toHaveLength(group.length); + for (const ev of group) buffer.ingestHistoryEvent(ev); + expect(buffer.getGroupArray()).toHaveLength(1); + expect(buffer.getGroupArray()[0].eventList).toHaveLength(group.length); - ingestHistoryEvent(group[0]); + buffer.ingestHistoryEvent(group[0]); - const groups = getGroupArray(); + const groups = buffer.getGroupArray(); expect(groups).toHaveLength(1); expect(groups[0].id).toBe(group[0].eventId); expect(groups[0].eventList.map((event) => event.id)).toEqual( @@ -1032,14 +1370,14 @@ describe('concurrent live poll and bidirectional fetch', () => { 'flushes live %s followers parked before the history head arrives', (_, buildGroup) => { const group = buildGroup(); - reset(10); + buffer.reset(10); - for (const ev of group.slice(1)) ingestHistoryEvent(ev); - expect(getGroupArray()).toHaveLength(0); + for (const ev of group.slice(1)) buffer.ingestHistoryEvent(ev); + expect(buffer.getGroupArray()).toHaveLength(0); - ingestHistoryEvent(group[0]); + buffer.ingestHistoryEvent(group[0]); - const groups = getGroupArray(); + const groups = buffer.getGroupArray(); expect(groups).toHaveLength(1); expect(groups[0].id).toBe(group[0].eventId); expect(groups[0].eventList.map((event) => event.id)).toEqual( @@ -1059,12 +1397,12 @@ describe('concurrent live poll and bidirectional fetch', () => { 'attaches live %s followers to an existing history group head', (_, buildGroup) => { const group = buildGroup(); - reset(10); + buffer.reset(10); - ingestHistoryEvent(group[0]); - for (const ev of group.slice(1)) ingestHistoryEvent(ev); + buffer.ingestHistoryEvent(group[0]); + for (const ev of group.slice(1)) buffer.ingestHistoryEvent(ev); - const groups = getGroupArray(); + const groups = buffer.getGroupArray(); expect(groups).toHaveLength(1); expect(groups[0].id).toBe(group[0].eventId); expect(groups[0].eventList.map((event) => event.id)).toEqual( @@ -1074,32 +1412,32 @@ describe('concurrent live poll and bidirectional fetch', () => { ); it('does not duplicate a far-ahead live follower when history later processes it', () => { - reset(5); + buffer.reset(5); const scheduled = makeActivityScheduled(1); const started = makeActivityStarted(100, 1); - ingestHistoryEvent(scheduled); - expect(ingestHistoryEvent(started)).toBe(true); - ingestHistoryEvent(started); + buffer.ingestHistoryEvent(scheduled); + expect(buffer.ingestHistoryEvent(started)).toBe(true); + buffer.ingestHistoryEvent(started); - const groups = getGroupArray(); + const groups = buffer.getGroupArray(); expect(groups).toHaveLength(1); expect(groups[0].eventList.map((event) => event.id)).toEqual(['1', '100']); - expect(getEventArray().filter((event) => event.id === '100')).toHaveLength( - 1, - ); + expect( + buffer.getEventArray().filter((event) => event.id === '100'), + ).toHaveLength(1); }); it('new events from live poll remain after bidirectional fetch completes', () => { // Bidirectional loads events 1-6; live poll delivers event 7 (new). const existing = makeSyntheticEvents(6); - reset(8); - for (const ev of existing) ingestHistoryEvent(ev); + buffer.reset(8); + for (const ev of existing) buffer.ingestHistoryEvent(ev); const newEv = makeActivityScheduled(7); - ingestHistoryEvent(newEv); + buffer.ingestHistoryEvent(newEv); - const ids = getEventArray().map((e) => e.id); + const ids = buffer.getEventArray().map((e) => e.id); // Events 1-6 from bidirectional + event 7 from live poll. expect(ids).toContain('7'); // Events from bidirectional still present. @@ -1110,15 +1448,15 @@ describe('concurrent live poll and bidirectional fetch', () => { // Simulate: live poll delivers events 1-5 before the bidirectional fetch // has processed any of them. Then the bidirectional processes all 5. const events = makeSyntheticEvents(5); - reset(5); + buffer.reset(5); // Live poll wins the race and ingests all 5 events. - for (const ev of events) ingestHistoryEvent(ev); + for (const ev of events) buffer.ingestHistoryEvent(ev); // Bidirectional catches up and redelivers the same 5 events. - for (const ev of events) ingestHistoryEvent(ev); + for (const ev of events) buffer.ingestHistoryEvent(ev); - const allIds = getEventArray().map((e) => e.id); + const allIds = buffer.getEventArray().map((e) => e.id); const unique = new Set(allIds); expect(allIds.length).toBe(unique.size); }); @@ -1127,14 +1465,14 @@ describe('concurrent live poll and bidirectional fetch', () => { // When the bidirectional fetch has already loaded events 1-3, // a live-poll batch of [2 (dup), 3 (dup), 4 (new)] should count added=1. const group = makeActivityGroup(1); // eventIds 1, 2, 3 - reset(5); - for (const ev of group) ingestHistoryEvent(ev); + buffer.reset(5); + for (const ev of group) buffer.ingestHistoryEvent(ev); const results = [ - ingestHistoryEvent(group[0]), // eventId 1 → duplicate → false - ingestHistoryEvent(group[1]), // eventId 2 → duplicate → false - ingestHistoryEvent(group[2]), // eventId 3 → duplicate → false - ingestHistoryEvent(makeActivityScheduled(4)), // new → true + buffer.ingestHistoryEvent(group[0]), // eventId 1 → duplicate → false + buffer.ingestHistoryEvent(group[1]), // eventId 2 → duplicate → false + buffer.ingestHistoryEvent(group[2]), // eventId 3 → duplicate → false + buffer.ingestHistoryEvent(makeActivityScheduled(4)), // new → true ]; const added = results.filter(Boolean).length; @@ -1153,31 +1491,31 @@ describe('concurrent live poll and bidirectional fetch', () => { describe('followers ingested before their head', () => { beforeEach(() => { - reset(10); + buffer.reset(10); }); it('follower before head: nothing visible in getGroupArray until head arrives', () => { const [, started] = makeActivityGroup(1); - const before = getGroupArray().length; - ingestHistoryEvent(started); // head not yet seen - expect(getGroupArray().length).toBe(before); // no partial stub rendered + const before = buffer.getGroupArray().length; + buffer.ingestHistoryEvent(started); // head not yet seen + expect(buffer.getGroupArray().length).toBe(before); // no partial stub rendered }); it('multiple followers before head: still nothing visible', () => { const [, started, completed] = makeActivityGroup(1); - const before = getGroupArray().length; - ingestHistoryEvent(started); - ingestHistoryEvent(completed); - expect(getGroupArray().length).toBe(before); + const before = buffer.getGroupArray().length; + buffer.ingestHistoryEvent(started); + buffer.ingestHistoryEvent(completed); + expect(buffer.getGroupArray().length).toBe(before); }); it('head last: group is complete with all followers', () => { const [scheduled, started, completed] = makeActivityGroup(1); - ingestHistoryEvent(started); - ingestHistoryEvent(completed); - ingestHistoryEvent(scheduled); // head arrives last + buffer.ingestHistoryEvent(started); + buffer.ingestHistoryEvent(completed); + buffer.ingestHistoryEvent(scheduled); // head arrives last - const groups = getGroupArray(); + const groups = buffer.getGroupArray(); const g = groups.find((g) => g.id === '1'); expect(g).toBeDefined(); expect(g?.eventList).toHaveLength(3); @@ -1186,21 +1524,21 @@ describe('followers ingested before their head', () => { it('head first: later followers extend the group', () => { const [scheduled, started, completed] = makeActivityGroup(1); - ingestHistoryEvent(scheduled); // head first - ingestHistoryEvent(started); - ingestHistoryEvent(completed); + buffer.ingestHistoryEvent(scheduled); // head first + buffer.ingestHistoryEvent(started); + buffer.ingestHistoryEvent(completed); - const g = getGroupArray().find((g) => g.id === '1'); + const g = buffer.getGroupArray().find((g) => g.id === '1'); expect(g?.eventList).toHaveLength(3); }); it('head from the fetch cursor: earlier live followers are picked up', () => { const [scheduled, started, completed] = makeActivityGroup(1); - ingestHistoryEvent(started); - ingestHistoryEvent(completed); - ingestHistoryEvent(scheduled); // head arrives from the desc cursor + buffer.ingestHistoryEvent(started); + buffer.ingestHistoryEvent(completed); + buffer.ingestHistoryEvent(scheduled); // head arrives from the desc cursor - const g = getGroupArray().find((g) => g.id === '1'); + const g = buffer.getGroupArray().find((g) => g.id === '1'); expect(g).toBeDefined(); expect(g?.eventList).toHaveLength(3); expect(g?.eventList.map((e) => e.id)).toEqual(['1', '2', '3']); @@ -1208,23 +1546,23 @@ describe('followers ingested before their head', () => { it('live follower extends a group whose head came from the fetch', () => { const [scheduled, started] = makeActivityGroup(1); - ingestHistoryEvent(scheduled); // head from the fetch - ingestHistoryEvent(started); // follower from the live poll + buffer.ingestHistoryEvent(scheduled); // head from the fetch + buffer.ingestHistoryEvent(started); // follower from the live poll - const g = getGroupArray().find((g) => g.id === '1'); + const g = buffer.getGroupArray().find((g) => g.id === '1'); expect(g?.eventList).toHaveLength(2); expect(g?.eventList[1].id).toBe('2'); }); it('no duplicate events when both producers deliver the same followers', () => { const [scheduled, started, completed] = makeActivityGroup(1); - ingestHistoryEvent(started); - ingestHistoryEvent(completed); - ingestHistoryEvent(scheduled); - ingestHistoryEvent(started); - ingestHistoryEvent(completed); + buffer.ingestHistoryEvent(started); + buffer.ingestHistoryEvent(completed); + buffer.ingestHistoryEvent(scheduled); + buffer.ingestHistoryEvent(started); + buffer.ingestHistoryEvent(completed); - const allIds = getEventArray().map((e) => e.id); + const allIds = buffer.getEventArray().map((e) => e.id); const unique = new Set(allIds); expect(allIds.length).toBe(unique.size); expect(unique.has('1')).toBe(true); @@ -1234,11 +1572,11 @@ describe('followers ingested before their head', () => { it('duplicate calls for the same follower are ignored', () => { const [scheduled, started] = makeActivityGroup(1); - ingestHistoryEvent(started); - ingestHistoryEvent(started); // second call for same event - ingestHistoryEvent(scheduled); + buffer.ingestHistoryEvent(started); + buffer.ingestHistoryEvent(started); // second call for same event + buffer.ingestHistoryEvent(scheduled); - const g = getGroupArray().find((g) => g.id === '1'); + const g = buffer.getGroupArray().find((g) => g.id === '1'); expect(g?.eventList).toHaveLength(2); // not 3 }); }); @@ -1256,31 +1594,31 @@ describe('followers ingested before their head', () => { describe('group reference identity', () => { beforeEach(() => { - reset(10); + buffer.reset(10); }); it('returns the identical reference for a group that has not changed', () => { - ingestHistoryEvent(makeActivityScheduled(1, 'Act')); - const first = getGroupArray()[0]; + buffer.ingestHistoryEvent(makeActivityScheduled(1, 'Act')); + const first = buffer.getGroupArray()[0]; - ingestHistoryEvent(makeActivityScheduled(5, 'Other')); - const second = getGroupArray().find((group) => group.id === '1'); + buffer.ingestHistoryEvent(makeActivityScheduled(5, 'Other')); + const second = buffer.getGroupArray().find((group) => group.id === '1'); expect(second).toBe(first); }); it('hands back a fresh reference when a live completion extends a group', () => { const [scheduled, started, completed] = makeActivityGroup(1); - ingestHistoryEvent(scheduled); - ingestHistoryEvent(started); + buffer.ingestHistoryEvent(scheduled); + buffer.ingestHistoryEvent(started); - const before = getGroupArray()[0]; + const before = buffer.getGroupArray()[0]; expect(before.eventList).toHaveLength(2); expect(before.finalClassification).toBe('Started'); - expect(ingestHistoryEvent(completed)).toBe(true); + expect(buffer.ingestHistoryEvent(completed)).toBe(true); - const after = getGroupArray()[0]; + const after = buffer.getGroupArray()[0]; expect(after).not.toBe(before); expect(after.eventList).toHaveLength(3); expect(after.finalClassification).toBe('Completed'); @@ -1288,52 +1626,52 @@ describe('group reference identity', () => { it('leaves the previous reference as an intact snapshot of the old state', () => { const [scheduled, started, completed] = makeActivityGroup(1); - ingestHistoryEvent(scheduled); - ingestHistoryEvent(started); - const before = getGroupArray()[0]; + buffer.ingestHistoryEvent(scheduled); + buffer.ingestHistoryEvent(started); + const before = buffer.getGroupArray()[0]; - ingestHistoryEvent(completed); + buffer.ingestHistoryEvent(completed); expect(before.eventList).toHaveLength(2); expect(before.finalClassification).toBe('Started'); }); it('hands back a fresh reference when enrich changes pending metadata', () => { - ingestHistoryEvent(makeActivityScheduled(1, 'Act')); - const before = getGroupArray()[0]; + buffer.ingestHistoryEvent(makeActivityScheduled(1, 'Act')); + const before = buffer.getGroupArray()[0]; - setPendingMetadata( + buffer.setPendingMetadata( [ { activityId: '1', state: 'Started', activityType: 'Act' }, - ] as Parameters[0], + ] as Parameters[0], [], ); - const after = getGroupArray()[0]; + const after = buffer.getGroupArray()[0]; expect(after).not.toBe(before); expect(after.pendingActivity).toBeDefined(); }); it('keeps references stable across repeated reads with no writes', () => { - for (const event of makeActivityGroup(1)) ingestHistoryEvent(event); - for (const event of makeTimerGroup(4)) ingestHistoryEvent(event); + for (const event of makeActivityGroup(1)) buffer.ingestHistoryEvent(event); + for (const event of makeTimerGroup(4)) buffer.ingestHistoryEvent(event); - const first = getGroupArray(); - const second = getGroupArray(); + const first = buffer.getGroupArray(); + const second = buffer.getGroupArray(); expect(second).toBe(first); - expect(getGroupArray({ excludeWorkflowTasks: true })).toEqual(first); + expect(buffer.getGroupArray({ excludeWorkflowTasks: true })).toEqual(first); }); it('swaps only the groups that changed', () => { - for (const event of makeActivityGroup(1)) ingestHistoryEvent(event); + for (const event of makeActivityGroup(1)) buffer.ingestHistoryEvent(event); const [scheduled, started, completed] = makeActivityGroup(4); - ingestHistoryEvent(scheduled); - ingestHistoryEvent(started); + buffer.ingestHistoryEvent(scheduled); + buffer.ingestHistoryEvent(started); - const before = getGroupArray(); - ingestHistoryEvent(completed); - const after = getGroupArray(); + const before = buffer.getGroupArray(); + buffer.ingestHistoryEvent(completed); + const after = buffer.getGroupArray(); expect(after[0]).toBe(before[0]); expect(after[1]).not.toBe(before[1]); @@ -1351,33 +1689,33 @@ describe('group reference identity', () => { describe('arrival-order independence', () => { const pending = [ { activityId: '1', state: 'Started', activityType: 'Act' }, - ] as Parameters[0]; + ] as Parameters[0]; it('drops pending metadata when the completion arrives after enrich', () => { - reset(10); + buffer.reset(10); const [scheduled, started, completed] = makeActivityGroup(1); - ingestHistoryEvent(scheduled); - setPendingMetadata(pending, []); - expect(getGroupArray()[0].isPending).toBe(true); + buffer.ingestHistoryEvent(scheduled); + buffer.setPendingMetadata(pending, []); + expect(buffer.getGroupArray()[0].isPending).toBe(true); - ingestHistoryEvent(started); - ingestHistoryEvent(completed); + buffer.ingestHistoryEvent(started); + buffer.ingestHistoryEvent(completed); - const group = getGroupArray()[0]; + const group = buffer.getGroupArray()[0]; expect(group.pendingActivity).toBeUndefined(); expect(group.isPending).toBe(false); }); it('applies pending metadata to a head that arrives afterwards', () => { - reset(10); + buffer.reset(10); // The run refresh can list an activity before its ActivityTaskScheduled has // been ingested; the buffer holds the metadata and applies it on arrival. - setPendingMetadata(pending, []); - expect(getLazyGroups()).toHaveLength(0); + buffer.setPendingMetadata(pending, []); + expect(buffer.getLazyGroups()).toHaveLength(0); - ingestHistoryEvent(makeActivityScheduled(1, 'Act')); + buffer.ingestHistoryEvent(makeActivityScheduled(1, 'Act')); - const [lazy] = getLazyGroups(); + const [lazy] = buffer.getLazyGroups(); expect(lazy.pendingActivity).toBeDefined(); expect(lazy.isPending).toBe(true); expect(materializeGroup(lazy).isPending).toBe(true); @@ -1387,39 +1725,39 @@ describe('arrival-order independence', () => { // disagreement hoists a finished activity to the top. Nothing re-enriches // here on purpose — a closed run stops refreshing. it('agrees on isPending when the completion lands after the metadata', () => { - reset(10); + buffer.reset(10); const [scheduled, started, completed] = makeActivityGroup(1); - ingestHistoryEvent(scheduled); - setPendingMetadata(pending, []); - expect(getLazyGroups()[0].isPending).toBe(true); + buffer.ingestHistoryEvent(scheduled); + buffer.setPendingMetadata(pending, []); + expect(buffer.getLazyGroups()[0].isPending).toBe(true); - ingestHistoryEvent(started); - ingestHistoryEvent(completed); + buffer.ingestHistoryEvent(started); + buffer.ingestHistoryEvent(completed); - const [lazy] = getLazyGroups(); + const [lazy] = buffer.getLazyGroups(); expect(lazy.isPending).toBe(false); expect(lazy.isPending).toBe(materializeGroup(lazy).isPending); expect(lazy.pendingActivity).toBeUndefined(); }); it('ignores a stale pending entry for an already-completed activity', () => { - reset(10); - for (const event of makeActivityGroup(1)) ingestHistoryEvent(event); + buffer.reset(10); + for (const event of makeActivityGroup(1)) buffer.ingestHistoryEvent(event); // The run still lists it — the history says otherwise and wins. - setPendingMetadata(pending, []); + buffer.setPendingMetadata(pending, []); - const [lazy] = getLazyGroups(); + const [lazy] = buffer.getLazyGroups(); expect(lazy.isPending).toBe(false); expect(materializeGroup(lazy).isPending).toBe(false); }); it('drops pending metadata when enrich runs after the completion', () => { - reset(10); - for (const event of makeActivityGroup(1)) ingestHistoryEvent(event); - setPendingMetadata(pending, []); + buffer.reset(10); + for (const event of makeActivityGroup(1)) buffer.ingestHistoryEvent(event); + buffer.setPendingMetadata(pending, []); - const group = getGroupArray()[0]; + const group = buffer.getGroupArray()[0]; expect(group.pendingActivity).toBeUndefined(); expect(group.isPending).toBe(false); }); @@ -1429,12 +1767,12 @@ describe('arrival-order independence', () => { // followers landing before their head still produce the right failure state — // is the same guarantee. it('keeps a timed-out activity failed when its head arrives last', () => { - reset(10); - ingestHistoryEvent(makeActivityStarted(2, 1)); - ingestHistoryEvent(makeActivityTimedOut(3, 1)); - ingestHistoryEvent(makeActivityScheduled(1)); + buffer.reset(10); + buffer.ingestHistoryEvent(makeActivityStarted(2, 1)); + buffer.ingestHistoryEvent(makeActivityTimedOut(3, 1)); + buffer.ingestHistoryEvent(makeActivityScheduled(1)); - const [lazy] = getLazyGroups(); + const [lazy] = buffer.getLazyGroups(); const group = materializeGroup(lazy); expect(group.eventList.map((event) => event.id)).toEqual(['1', '2', '3']); expect(group.isFailureOrTimedOut).toBe(true); @@ -1444,13 +1782,13 @@ describe('arrival-order independence', () => { it('groups events identically whichever cursor delivers them', () => { const group = makeActivityGroup(1); - reset(10); - for (const event of group) ingestHistoryEvent(event); - const ascending = getGroupArray()[0]; + buffer.reset(10); + for (const event of group) buffer.ingestHistoryEvent(event); + const ascending = buffer.getGroupArray()[0]; - reset(10); - for (const event of group.toReversed()) ingestHistoryEvent(event); - const descending = getGroupArray()[0]; + buffer.reset(10); + for (const event of group.toReversed()) buffer.ingestHistoryEvent(event); + const descending = buffer.getGroupArray()[0]; expect(descending.eventList.map((event) => event.id)).toEqual( ascending.eventList.map((event) => event.id), @@ -1491,12 +1829,12 @@ describe('lazy and materialized group agreement', () => { const events = build(1); for (let count = 1; count <= events.length; count++) { - reset(20); + buffer.reset(20); for (const event of events.slice(0, count)) { - ingestHistoryEvent(event); + buffer.ingestHistoryEvent(event); } - const [lazy] = getLazyGroups(); + const [lazy] = buffer.getLazyGroups(); const group = materializeGroup(lazy); for (const field of SHARED_FIELDS) { @@ -1510,55 +1848,55 @@ describe('lazy and materialized group agreement', () => { }); it('agrees on isPending once pending metadata is attached', () => { - reset(10); - ingestHistoryEvent(makeActivityScheduled(1, 'Act')); - setPendingMetadata( + buffer.reset(10); + buffer.ingestHistoryEvent(makeActivityScheduled(1, 'Act')); + buffer.setPendingMetadata( [ { activityId: '1', state: 'Started', activityType: 'Act' }, - ] as Parameters[0], + ] as Parameters[0], [], ); - const [lazy] = getLazyGroups(); + const [lazy] = buffer.getLazyGroups(); expect(lazy.isPending).toBe(true); expect(lazy.isPending).toBe(materializeGroup(lazy).isPending); }); it('exposes no lazy for an event that heads no group', () => { - reset(10); - ingestHistoryEvent(makeWorkflowStarted(1)); - expect(getLazyGroups()).toHaveLength(0); - expect(getEventArray()).toHaveLength(1); + buffer.reset(10); + buffer.ingestHistoryEvent(makeWorkflowStarted(1)); + expect(buffer.getLazyGroups()).toHaveLength(0); + expect(buffer.getEventArray()).toHaveLength(1); }); it('matches getGroupArray one-for-one', () => { - reset(40); + buffer.reset(40); for (const event of makeSyntheticEventsWithWorkflowTasks(30)) { - ingestHistoryEvent(event); + buffer.ingestHistoryEvent(event); } - const lazyGroups = getLazyGroups({ excludeWorkflowTasks: true }); - const groups = getGroupArray({ excludeWorkflowTasks: true }); + const lazyGroups = buffer.getLazyGroups({ excludeWorkflowTasks: true }); + const groups = buffer.getGroupArray({ excludeWorkflowTasks: true }); expect(lazyGroups.map((lazy) => lazy.id)).toEqual(groups.map((g) => g.id)); expect(lazyGroups.map(materializeGroup)).toEqual(groups); }); it('passes an already-materialized group straight through', () => { - reset(10); - for (const event of makeActivityGroup(1)) ingestHistoryEvent(event); + buffer.reset(10); + for (const event of makeActivityGroup(1)) buffer.ingestHistoryEvent(event); - const group = materializeGroup(getLazyGroups()[0]); + const group = materializeGroup(buffer.getLazyGroups()[0]); // Views may be handed groups built outside the buffer, which already // satisfy LazyGroup — materializing one again must be a no-op. expect(materializeGroup(group)).toBe(group); }); it('returns the identical group for an unchanged lazy', () => { - reset(10); - for (const event of makeActivityGroup(1)) ingestHistoryEvent(event); + buffer.reset(10); + for (const event of makeActivityGroup(1)) buffer.ingestHistoryEvent(event); - const [lazy] = getLazyGroups(); + const [lazy] = buffer.getLazyGroups(); expect(materializeGroup(lazy)).toBe(materializeGroup(lazy)); }); }); @@ -1572,74 +1910,74 @@ describe('getPendingActivityScheduledEvent', () => { activityType: 'MyActivity', ...overrides, }, - ] as Parameters[0]; + ] as Parameters[0]; it('returns the head event of a pending activity group', () => { - reset(10); - ingestHistoryEvent(makeActivityScheduled(1, 'MyActivity')); - setPendingMetadata(pending(), []); + buffer.reset(10); + buffer.ingestHistoryEvent(makeActivityScheduled(1, 'MyActivity')); + buffer.setPendingMetadata(pending(), []); - const scheduled = getPendingActivityScheduledEvent('1'); + const scheduled = buffer.getPendingActivityScheduledEvent('1'); expect(scheduled?.id).toBe('1'); expect(scheduled?.eventType).toBe('ActivityTaskScheduled'); }); it('is undefined until the head event is ingested', () => { - reset(10); - setPendingMetadata(pending(), []); - expect(getPendingActivityScheduledEvent('1')).toBeUndefined(); + buffer.reset(10); + buffer.setPendingMetadata(pending(), []); + expect(buffer.getPendingActivityScheduledEvent('1')).toBeUndefined(); - ingestHistoryEvent(makeActivityScheduled(1, 'MyActivity')); - expect(getPendingActivityScheduledEvent('1')?.id).toBe('1'); + buffer.ingestHistoryEvent(makeActivityScheduled(1, 'MyActivity')); + expect(buffer.getPendingActivityScheduledEvent('1')?.id).toBe('1'); }); it('is undefined for an activity the history has resolved', () => { - reset(10); + buffer.reset(10); const [scheduled, timedOut] = makeActivityTimeoutGroup(1); - ingestHistoryEvent(scheduled); - setPendingMetadata(pending(), []); - expect(getPendingActivityScheduledEvent('1')).toBeDefined(); + buffer.ingestHistoryEvent(scheduled); + buffer.setPendingMetadata(pending(), []); + expect(buffer.getPendingActivityScheduledEvent('1')).toBeDefined(); - ingestHistoryEvent(timedOut); - expect(getPendingActivityScheduledEvent('1')).toBeUndefined(); + buffer.ingestHistoryEvent(timedOut); + expect(buffer.getPendingActivityScheduledEvent('1')).toBeUndefined(); }); it('is undefined once the activity is no longer pending', () => { - reset(10); - ingestHistoryEvent(makeActivityScheduled(1, 'MyActivity')); - setPendingMetadata(pending(), []); - setPendingMetadata([], []); + buffer.reset(10); + buffer.ingestHistoryEvent(makeActivityScheduled(1, 'MyActivity')); + buffer.setPendingMetadata(pending(), []); + buffer.setPendingMetadata([], []); - expect(getPendingActivityScheduledEvent('1')).toBeUndefined(); + expect(buffer.getPendingActivityScheduledEvent('1')).toBeUndefined(); }); it('is cleared by reset', () => { - reset(10); - ingestHistoryEvent(makeActivityScheduled(1, 'MyActivity')); - setPendingMetadata(pending(), []); + buffer.reset(10); + buffer.ingestHistoryEvent(makeActivityScheduled(1, 'MyActivity')); + buffer.setPendingMetadata(pending(), []); - reset(10); - expect(getPendingActivityScheduledEvent('1')).toBeUndefined(); + buffer.reset(10); + expect(buffer.getPendingActivityScheduledEvent('1')).toBeUndefined(); }); it('bumps the lazy group version without changing its identity when only the options change', () => { - reset(10); - ingestHistoryEvent(makeActivityScheduled(1, 'MyActivity')); - setPendingMetadata( + buffer.reset(10); + buffer.ingestHistoryEvent(makeActivityScheduled(1, 'MyActivity')); + buffer.setPendingMetadata( pending({ activityOptions: { retryPolicy: { maximumAttempts: 3 } } }), [], ); - const [lazyBefore] = getLazyGroups(); + const [lazyBefore] = buffer.getLazyGroups(); const versionBefore = lazyBefore.version; const groupBefore = materializeGroup(lazyBefore); - setPendingMetadata( + buffer.setPendingMetadata( pending({ activityOptions: { retryPolicy: { maximumAttempts: 10 } } }), [], ); - const [lazyAfter] = getLazyGroups(); + const [lazyAfter] = buffer.getLazyGroups(); // The record identity is stable for the life of the run, so consumers that // derive off the lazy group alone must compare version, not reference. expect(lazyAfter).toBe(lazyBefore); @@ -1668,10 +2006,10 @@ describe('event group labels', () => { it('resolves a label from an event ingested later', () => { const [started, fired] = makeTimerGroup(1); - ingestHistoryEvent(withMarker(fired, { id: 'group-1' })); - ingestHistoryEvent(withMarker(started, { id: 'group-1', label })); + buffer.ingestHistoryEvent(withMarker(fired, { id: 'group-1' })); + buffer.ingestHistoryEvent(withMarker(started, { id: 'group-1', label })); - expect(getEventArray().map((event) => event.eventGroups)).toEqual([ + expect(buffer.getEventArray().map((event) => event.eventGroups)).toEqual([ [{ key: 'label:group-1', kind: 'label', id: 'group-1', label }], [{ key: 'label:group-1', kind: 'label', id: 'group-1', label }], ]); @@ -1679,12 +2017,12 @@ describe('event group labels', () => { it('does not carry labels across a reset', () => { const [started, fired] = makeTimerGroup(1); - ingestHistoryEvent(withMarker(started, { id: 'group-1', label })); + buffer.ingestHistoryEvent(withMarker(started, { id: 'group-1', label })); - reset(0); - ingestHistoryEvent(withMarker(fired, { id: 'group-1' })); + buffer.reset(0); + buffer.ingestHistoryEvent(withMarker(fired, { id: 'group-1' })); - expect(getEventArray()[0].eventGroups).toEqual([ + expect(buffer.getEventArray()[0].eventGroups).toEqual([ { key: 'label:group-1', kind: 'label', id: 'group-1' }, ]); }); @@ -1700,18 +2038,22 @@ describe('event group index', () => { it('lists event groups in order of their first event with event counts', () => { const [scheduled, started, completed] = makeActivityGroup(5); const [timerStarted, timerFired] = makeTimerGroup(1); - ingestHistoryEvent(withMarkers(scheduled, [marker('b'), marker('a')])); - ingestHistoryEvent(started); - ingestHistoryEvent(completed); - ingestHistoryEvent(withMarkers(timerStarted, [marker('a')])); - ingestHistoryEvent(timerFired); + buffer.ingestHistoryEvent( + withMarkers(scheduled, [marker('b'), marker('a')]), + ); + buffer.ingestHistoryEvent(started); + buffer.ingestHistoryEvent(completed); + buffer.ingestHistoryEvent(withMarkers(timerStarted, [marker('a')])); + buffer.ingestHistoryEvent(timerFired); expect( - getEventGroupOptions().map(({ group, eventCount, firstEventId }) => ({ - key: group.key, - eventCount, - firstEventId, - })), + buffer + .getEventGroupOptions() + .map(({ group, eventCount, firstEventId }) => ({ + key: group.key, + eventCount, + firstEventId, + })), ).toEqual([ { key: 'label:a', eventCount: 2, firstEventId: 1 }, { key: 'label:b', eventCount: 1, firstEventId: 5 }, @@ -1721,18 +2063,19 @@ describe('event group index', () => { it('matches whole lifecycle groups that contain a marked event', () => { const [scheduled, started, completed] = makeActivityGroup(1); const [timerStarted, timerFired] = makeTimerGroup(4); - ingestHistoryEvent(withMarkers(scheduled, [marker('a')])); - ingestHistoryEvent(started); - ingestHistoryEvent(completed); - ingestHistoryEvent(timerStarted); - ingestHistoryEvent(timerFired); + buffer.ingestHistoryEvent(withMarkers(scheduled, [marker('a')])); + buffer.ingestHistoryEvent(started); + buffer.ingestHistoryEvent(completed); + buffer.ingestHistoryEvent(timerStarted); + buffer.ingestHistoryEvent(timerFired); - const matcher = getEventGroupMatcher(['label:a'])!; + const matcher = buffer.getEventGroupMatcher(['label:a'])!; expect(matcher.hasGroup('1')).toBe(true); expect(matcher.hasGroup('4')).toBe(false); expect( - getEventArray() + buffer + .getEventArray() .filter((event) => matcher.hasEvent(event)) .map(({ id }) => id), ).toEqual(['1', '2', '3']); @@ -1741,12 +2084,12 @@ describe('event group index', () => { it('matches any of the selected event groups', () => { const [timerStarted, timerFired] = makeTimerGroup(1); const [otherStarted, otherFired] = makeTimerGroup(3); - ingestHistoryEvent(withMarkers(timerStarted, [marker('a')])); - ingestHistoryEvent(timerFired); - ingestHistoryEvent(withMarkers(otherStarted, [marker('b')])); - ingestHistoryEvent(otherFired); + buffer.ingestHistoryEvent(withMarkers(timerStarted, [marker('a')])); + buffer.ingestHistoryEvent(timerFired); + buffer.ingestHistoryEvent(withMarkers(otherStarted, [marker('b')])); + buffer.ingestHistoryEvent(otherFired); - const matcher = getEventGroupMatcher(['label:a', 'label:b'])!; + const matcher = buffer.getEventGroupMatcher(['label:a', 'label:b'])!; expect(matcher.hasGroup('1')).toBe(true); expect(matcher.hasGroup('3')).toBe(true); @@ -1754,68 +2097,70 @@ describe('event group index', () => { it('ignores selected keys that are not in the run', () => { const [timerStarted, timerFired] = makeTimerGroup(1); - ingestHistoryEvent(withMarkers(timerStarted, [marker('a')])); - ingestHistoryEvent(timerFired); + buffer.ingestHistoryEvent(withMarkers(timerStarted, [marker('a')])); + buffer.ingestHistoryEvent(timerFired); - expect(getEventGroupMatcher(['label:missing'])).toBeUndefined(); - expect(getEventGroupMatcher([])).toBeUndefined(); + expect(buffer.getEventGroupMatcher(['label:missing'])).toBeUndefined(); + expect(buffer.getEventGroupMatcher([])).toBeUndefined(); expect( - getEventGroupMatcher(['label:missing', 'label:a'])?.hasGroup('1'), + buffer.getEventGroupMatcher(['label:missing', 'label:a'])?.hasGroup('1'), ).toBe(true); }); it('indexes events that arrive before their lifecycle group head', () => { const [timerStarted, timerFired] = makeTimerGroup(1); - ingestHistoryEvent(withMarkers(timerFired, [marker('a')])); - ingestHistoryEvent(timerStarted); + buffer.ingestHistoryEvent(withMarkers(timerFired, [marker('a')])); + buffer.ingestHistoryEvent(timerStarted); - expect(getEventGroupMatcher(['label:a'])?.hasGroup('1')).toBe(true); + expect(buffer.getEventGroupMatcher(['label:a'])?.hasGroup('1')).toBe(true); }); it('clears the index on reset', () => { const [timerStarted] = makeTimerGroup(1); - ingestHistoryEvent(withMarkers(timerStarted, [marker('a')])); + buffer.ingestHistoryEvent(withMarkers(timerStarted, [marker('a')])); - reset(0); + buffer.reset(0); - expect(getEventGroupOptions()).toEqual([]); - expect(getEventGroupMatcher(['label:a'])).toBeUndefined(); + expect(buffer.getEventGroupOptions()).toEqual([]); + expect(buffer.getEventGroupMatcher(['label:a'])).toBeUndefined(); }); describe('getTimelineEventGroups', () => { it('renames a row when its signal event is ingested after the row was built', () => { const [timerStarted, timerFired] = makeTimerGroup(4); const signalMarker = { inboundEvent: { inboundEventId: 3 } }; - ingestHistoryEvent({ + buffer.ingestHistoryEvent({ ...timerStarted, eventGroupMarkers: [signalMarker], } as unknown as HistoryEvent); - ingestHistoryEvent(timerFired); - expect(getTimelineEventGroups()[0].displayName).toBe('3'); + buffer.ingestHistoryEvent(timerFired); + expect(buffer.getTimelineEventGroups()[0].displayName).toBe('3'); - ingestHistoryEvent({ + buffer.ingestHistoryEvent({ eventId: '3', eventTime: timerStarted.eventTime, eventType: 'WorkflowExecutionSignaled', workflowExecutionSignaledEventAttributes: { signalName: 'launchHold' }, } as unknown as HistoryEvent); - expect(getTimelineEventGroups()[0].displayName).toBe('launchHold (3)'); + expect(buffer.getTimelineEventGroups()[0].displayName).toBe( + 'launchHold (3)', + ); }); it('builds one row per event group spanning its lifecycle groups', () => { const [scheduled, started, completed] = makeActivityGroup(1); const [timerStarted, timerFired] = makeTimerGroup(4); const [otherStarted, otherFired] = makeTimerGroup(6); - ingestHistoryEvent(withMarkers(scheduled, [marker('a')])); - ingestHistoryEvent(started); - ingestHistoryEvent(completed); - ingestHistoryEvent(withMarkers(timerStarted, [marker('a')])); - ingestHistoryEvent(timerFired); - ingestHistoryEvent(withMarkers(otherStarted, [marker('b')])); - ingestHistoryEvent(otherFired); + buffer.ingestHistoryEvent(withMarkers(scheduled, [marker('a')])); + buffer.ingestHistoryEvent(started); + buffer.ingestHistoryEvent(completed); + buffer.ingestHistoryEvent(withMarkers(timerStarted, [marker('a')])); + buffer.ingestHistoryEvent(timerFired); + buffer.ingestHistoryEvent(withMarkers(otherStarted, [marker('b')])); + buffer.ingestHistoryEvent(otherFired); expect( - getTimelineEventGroups().map((group) => ({ + buffer.getTimelineEventGroups().map((group) => ({ id: group.id, key: group.key, eventCount: group.eventCount, @@ -1850,19 +2195,18 @@ describe('event group index', () => { const [wftScheduled, wftStarted, wftCompleted] = makeWorkflowTaskGroup(1); const [bStarted, bFired] = makeTimerGroup(4); const [aStarted, aFired] = makeTimerGroup(6); - ingestHistoryEvent(wftScheduled); - ingestHistoryEvent(wftStarted); - ingestHistoryEvent(withMarkers(wftCompleted, [marker('a')])); - ingestHistoryEvent(withMarkers(bStarted, [marker('b')])); - ingestHistoryEvent(bFired); - ingestHistoryEvent(withMarkers(aStarted, [marker('a')])); - ingestHistoryEvent(aFired); - - expect(getEventGroupOptions().map(({ group }) => group.key)).toEqual([ - 'label:a', - 'label:b', - ]); - expect(getTimelineEventGroups().map(({ key }) => key)).toEqual([ + buffer.ingestHistoryEvent(wftScheduled); + buffer.ingestHistoryEvent(wftStarted); + buffer.ingestHistoryEvent(withMarkers(wftCompleted, [marker('a')])); + buffer.ingestHistoryEvent(withMarkers(bStarted, [marker('b')])); + buffer.ingestHistoryEvent(bFired); + buffer.ingestHistoryEvent(withMarkers(aStarted, [marker('a')])); + buffer.ingestHistoryEvent(aFired); + + expect( + buffer.getEventGroupOptions().map(({ group }) => group.key), + ).toEqual(['label:a', 'label:b']); + expect(buffer.getTimelineEventGroups().map(({ key }) => key)).toEqual([ 'label:b', 'label:a', ]); @@ -1871,32 +2215,32 @@ describe('event group index', () => { it('counts only events in the lifecycle groups it shows', () => { const [wftScheduled, wftStarted, wftCompleted] = makeWorkflowTaskGroup(1); const [timerStarted, timerFired] = makeTimerGroup(4); - ingestHistoryEvent(withMarkers(wftScheduled, [marker('a')])); - ingestHistoryEvent(withMarkers(wftStarted, [marker('a')])); - ingestHistoryEvent(withMarkers(wftCompleted, [marker('a')])); - ingestHistoryEvent(withMarkers(timerStarted, [marker('a')])); - ingestHistoryEvent(timerFired); - - expect(getEventGroupOptions()[0].eventCount).toBe(4); - expect(getTimelineEventGroups()[0].eventCount).toBe(2); + buffer.ingestHistoryEvent(withMarkers(wftScheduled, [marker('a')])); + buffer.ingestHistoryEvent(withMarkers(wftStarted, [marker('a')])); + buffer.ingestHistoryEvent(withMarkers(wftCompleted, [marker('a')])); + buffer.ingestHistoryEvent(withMarkers(timerStarted, [marker('a')])); + buffer.ingestHistoryEvent(timerFired); + + expect(buffer.getEventGroupOptions()[0].eventCount).toBe(4); + expect(buffer.getTimelineEventGroups()[0].eventCount).toBe(2); }); it('follows pending metadata from the workflow run', () => { const [scheduled, started, completed] = makeActivityGroup(1); - ingestHistoryEvent(withMarkers(scheduled, [marker('a')])); - ingestHistoryEvent(started); - expect(getTimelineEventGroups()[0].isPending).toBe(false); + buffer.ingestHistoryEvent(withMarkers(scheduled, [marker('a')])); + buffer.ingestHistoryEvent(started); + expect(buffer.getTimelineEventGroups()[0].isPending).toBe(false); - setPendingMetadata( + buffer.setPendingMetadata( [ { activityId: '1', state: 'Started', activityType: 'TestActivity' }, - ] as Parameters[0], + ] as Parameters[0], [], ); - expect(getTimelineEventGroups()[0].isPending).toBe(true); + expect(buffer.getTimelineEventGroups()[0].isPending).toBe(true); - ingestHistoryEvent(completed); - expect(getTimelineEventGroups()[0].isPending).toBe(false); + buffer.ingestHistoryEvent(completed); + expect(buffer.getTimelineEventGroups()[0].isPending).toBe(false); }); it('matches a from-scratch rebuild whatever order events arrive in', () => { @@ -1925,9 +2269,9 @@ describe('event group index', () => { const shuffled = [...history].sort(() => random() - 0.5); const expectMatchesRebuild = () => { - const lazyGroups = getLazyGroups({ excludeWorkflowTasks: true }); - for (const group of getTimelineEventGroups()) { - const matcher = getEventGroupMatcher([group.key])!; + const lazyGroups = buffer.getLazyGroups({ excludeWorkflowTasks: true }); + for (const group of buffer.getTimelineEventGroups()) { + const matcher = buffer.getEventGroupMatcher([group.key])!; const expected = createTimelineEventGroup({ label: group.eventGroupLabel, lifecycleGroups: lazyGroups.filter(({ id }) => @@ -1955,34 +2299,36 @@ describe('event group index', () => { }; shuffled.forEach((event, index) => { - ingestHistoryEvent(event); + buffer.ingestHistoryEvent(event); if (index % 10 === 0) expectMatchesRebuild(); }); expectMatchesRebuild(); - expect(getTimelineEventGroups().map(({ key }) => key)).toHaveLength(4); + expect( + buffer.getTimelineEventGroups().map(({ key }) => key), + ).toHaveLength(4); }); it('is pending while any lifecycle group is pending', () => { const [timerStarted, timerFired] = makeTimerGroup(1); - ingestHistoryEvent(withMarkers(timerStarted, [marker('a')])); + buffer.ingestHistoryEvent(withMarkers(timerStarted, [marker('a')])); - expect(getTimelineEventGroups()[0].isPending).toBe(true); + expect(buffer.getTimelineEventGroups()[0].isPending).toBe(true); - ingestHistoryEvent(timerFired); + buffer.ingestHistoryEvent(timerFired); - expect(getTimelineEventGroups()[0].isPending).toBe(false); + expect(buffer.getTimelineEventGroups()[0].isPending).toBe(false); }); it('keeps an unchanged event group as the same reference', () => { const [timerStarted, timerFired] = makeTimerGroup(1); const [otherStarted, otherFired] = makeTimerGroup(3); - ingestHistoryEvent(withMarkers(timerStarted, [marker('a')])); - ingestHistoryEvent(timerFired); - ingestHistoryEvent(withMarkers(otherStarted, [marker('b')])); + buffer.ingestHistoryEvent(withMarkers(timerStarted, [marker('a')])); + buffer.ingestHistoryEvent(timerFired); + buffer.ingestHistoryEvent(withMarkers(otherStarted, [marker('b')])); - const [a, b] = getTimelineEventGroups(); - ingestHistoryEvent(otherFired); - const [nextA, nextB] = getTimelineEventGroups(); + const [a, b] = buffer.getTimelineEventGroups(); + buffer.ingestHistoryEvent(otherFired); + const [nextA, nextB] = buffer.getTimelineEventGroups(); expect(nextA).toBe(a); expect(nextB).not.toBe(b); @@ -1992,52 +2338,52 @@ describe('event group index', () => { it('skips event groups whose events are only in WorkflowTask groups', () => { const [wftScheduled, wftStarted, wftCompleted] = makeWorkflowTaskGroup(1); - ingestHistoryEvent(wftScheduled); - ingestHistoryEvent(wftStarted); - ingestHistoryEvent(withMarkers(wftCompleted, [marker('a')])); + buffer.ingestHistoryEvent(wftScheduled); + buffer.ingestHistoryEvent(wftStarted); + buffer.ingestHistoryEvent(withMarkers(wftCompleted, [marker('a')])); - expect(getEventGroupOptions()).toHaveLength(1); - expect(getTimelineEventGroups()).toEqual([]); - expect(hasTimelineEventGroups()).toBe(false); + expect(buffer.getEventGroupOptions()).toHaveLength(1); + expect(buffer.getTimelineEventGroups()).toEqual([]); + expect(buffer.hasTimelineEventGroups()).toBe(false); }); it('clears on reset', () => { const [timerStarted] = makeTimerGroup(1); - ingestHistoryEvent(withMarkers(timerStarted, [marker('a')])); - expect(getTimelineEventGroups()).toHaveLength(1); - expect(hasTimelineEventGroups()).toBe(true); + buffer.ingestHistoryEvent(withMarkers(timerStarted, [marker('a')])); + expect(buffer.getTimelineEventGroups()).toHaveLength(1); + expect(buffer.hasTimelineEventGroups()).toBe(true); - reset(0); + buffer.reset(0); - expect(getTimelineEventGroups()).toEqual([]); - expect(hasTimelineEventGroups()).toBe(false); + expect(buffer.getTimelineEventGroups()).toEqual([]); + expect(buffer.hasTimelineEventGroups()).toBe(false); }); it('reports user-defined event groups only for label markers', () => { const [timerStarted] = makeTimerGroup(1); const [otherTimerStarted] = makeTimerGroup(3); - ingestHistoryEvent({ + buffer.ingestHistoryEvent({ ...timerStarted, eventGroupMarkers: [{ inboundEvent: { inboundEventId: 1 } }], } as unknown as HistoryEvent); - expect(hasTimelineEventGroups()).toBe(true); - expect(hasUserDefinedEventGroups()).toBe(false); + expect(buffer.hasTimelineEventGroups()).toBe(true); + expect(buffer.hasUserDefinedEventGroups()).toBe(false); - ingestHistoryEvent(withMarkers(otherTimerStarted, [marker('a')])); - expect(hasUserDefinedEventGroups()).toBe(true); + buffer.ingestHistoryEvent(withMarkers(otherTimerStarted, [marker('a')])); + expect(buffer.hasUserDefinedEventGroups()).toBe(true); - reset(0); - expect(hasUserDefinedEventGroups()).toBe(false); + buffer.reset(0); + expect(buffer.hasUserDefinedEventGroups()).toBe(false); }); it('reports timeline event groups once a marked lifecycle head arrives', () => { const [timerStarted, timerFired] = makeTimerGroup(1); - ingestHistoryEvent(withMarkers(timerFired, [marker('a')])); - expect(hasTimelineEventGroups()).toBe(false); + buffer.ingestHistoryEvent(withMarkers(timerFired, [marker('a')])); + expect(buffer.hasTimelineEventGroups()).toBe(false); - ingestHistoryEvent(timerStarted); - expect(hasTimelineEventGroups()).toBe(true); - expect(getTimelineEventGroups()).toHaveLength(1); + buffer.ingestHistoryEvent(timerStarted); + expect(buffer.hasTimelineEventGroups()).toBe(true); + expect(buffer.getTimelineEventGroups()).toHaveLength(1); }); }); }); diff --git a/src/lib/services/grouped-event-buffer.ts b/src/lib/services/grouped-event-buffer.ts index 1366a62a51..d1525214b3 100644 --- a/src/lib/services/grouped-event-buffer.ts +++ b/src/lib/services/grouped-event-buffer.ts @@ -24,6 +24,7 @@ import type { PendingActivity, PendingNexusOperation, WorkflowEvent, + WorkflowExecutionStartedEvent, } from '$lib/types/events'; import { getValidTimeMs } from '$lib/utilities/format-time'; import { @@ -42,6 +43,7 @@ import { isNexusOperationFailedEvent, isNexusOperationScheduledEvent, isNexusOperationTimedOutEvent, + isWorkflowExecutionStartedEvent, } from '$lib/utilities/is-event-type'; /** @@ -138,7 +140,13 @@ class GroupRecord implements LazyGroup { syncedPending = false; private lastSlot = -1; - constructor(readonly headSlot: number) { + constructor( + readonly headSlot: number, + private readonly applyPendingMetadata: (record: GroupRecord) => boolean, + private readonly materializeRecord: ( + record: GroupRecord, + ) => EventGroup | null, + ) { this.id = String(headSlot + 1); } @@ -156,10 +164,14 @@ class GroupRecord implements LazyGroup { this.headsGroup = isGroupHeadEvent(event as CommonHistoryEvent); } // A head arriving picks pending metadata up; a terminal event drops it. - applyPendingMetadataTo(this); + this.applyPendingMetadata(this); this.version++; } + materialize(): EventGroup | null { + return this.materializeRecord(this); + } + get eventCount(): number { return this.slots.length; } @@ -210,718 +222,789 @@ export type GroupArrayOptions = { excludeWorkflowTasks?: boolean; }; -// --------------------------------------------------------------------------- -// Module state (reset between workflows via reset()) -// --------------------------------------------------------------------------- - -let events: (WorkflowEvent | null)[] = []; -let headGroup = new Int32Array(0); // head slot -> record index + 1 (0 = none) -let records: GroupRecord[] = []; -let maxSlot = -1; -let latestEventTimeMs: number | undefined; - -let failedEvent: HistoryEvent | null = null; - -// Accumulated WFT IDs for marker billable-action dedup. Shared by both cursors -// and the live poll — the direction an event arrives from is a fetch detail, -// and one workflow task's markers bill once however they were loaded. -const processedWorkflowTaskIds = new Set(); -const createLabelRegistry = () => - createEventGroupLabelRegistry({ - onLabelChange: (key) => dirtyTimelineEventGroupKeys.add(key), - }); -let eventGroupLabels = createLabelRegistry(); - -// Event group key -> the events carrying that marker and the lifecycle groups -// they belong to, so the event group filter is a set lookup per row. -let eventGroupIndex = new Map(); -let cachedEventGroupOptions: EventGroupOption[] | null = null; -let cachedEventGroupOptionsRevision = -1; -let timelineEventGroupsByKey = new Map< - EventGroupKey, - TimelineEventGroup ->(); -const dirtyTimelineEventGroupKeys = new Set(); -let timelineEventGroupCount = 0; -let userDefinedEventGroupFound = false; -let cachedTimelineEventGroups: TimelineEventGroup[] | null = null; -let cachedTimelineEventGroupsRevision = -1; - -// Bumped by every write. Read caches hold the revision they were built at, so -// invalidation is a single counter rather than scattered cache-busting calls. -let revision = 0; - -let cachedGroups: EventGroup[] | null = null; -let cachedGroupsRevision = -1; -let cachedGroupsNoWFT: EventGroup[] | null = null; -let cachedGroupsNoWFTRevision = -1; -let cachedEvents: WorkflowEvent[] | null = null; -let cachedEventsRevision = -1; -let cachedLazyGroups: LazyGroup[] | null = null; -let cachedLazyGroupsRevision = -1; -let cachedLazyGroupsNoWFT: LazyGroup[] | null = null; -let cachedLazyGroupsNoWFTRevision = -1; -let cachedWftFailed: WorkflowEvent | undefined; -let cachedWftFailedRevision = -1; - -const changeListeners = new Set(); - -// Pending metadata from the workflow run, held so a head event arriving later -// can pick its own up. Records currently carrying some are tracked so a walk is -// only needed when there is something to set or clear. -let pendingByActivityId = new Map(); -let pendingByNexusScheduledId = new Map(); -const enrichedRecords = new Set(); - -// Head event of each currently-pending activity's group, keyed by activityId. -// Maintained alongside enrichedRecords so a pending-activity card can diff its -// current options against the ones it was scheduled with without scanning. The -// head is always ActivityTaskScheduled: that is the only branch in -// applyPendingMetadataTo that assigns pendingActivity. -const scheduledEventByActivityId = new Map(); - -/** Returns whether the record's pending metadata changed. */ -function applyPendingMetadataTo(record: GroupRecord): boolean { - const head = record.initialEvent; - if (!head) return false; - - let pendingActivity: PendingActivity | undefined; - let pendingNexusOperation: PendingNexusOperation | undefined; - - // The run can still list an activity the history has already resolved, so a - // terminal event wins. This is the only writer of the record's pending - // fields, so gating here covers the lazy and materialized readings alike. - if (!record.hasTerminalActivity && isActivityTaskScheduledEvent(head)) { - pendingActivity = pendingByActivityId.get( - head.activityTaskScheduledEventAttributes?.activityId ?? '', - ); - } else if (!record.hasTerminalNexus && isNexusOperationScheduledEvent(head)) { - pendingNexusOperation = pendingByNexusScheduledId.get(head.id); - } +function isTerminalActivityEvent(event: WorkflowEvent): boolean { + return ( + isActivityTaskCompletedEvent(event) || + isActivityTaskFailedEvent(event) || + isActivityTaskCanceledEvent(event) || + isActivityTaskTimedOutEvent(event) + ); +} - if ( - record.pendingActivity === pendingActivity && - record.pendingNexusOperation === pendingNexusOperation - ) { - return false; - } +function isTerminalNexusEvent(event: WorkflowEvent): boolean { + return ( + isNexusOperationCompletedEvent(event) || + isNexusOperationFailedEvent(event) || + isNexusOperationCanceledEvent(event) || + isNexusOperationTimedOutEvent(event) + ); +} - const previousActivityId = record.pendingActivity?.activityId; - record.pendingActivity = pendingActivity; - record.pendingNexusOperation = pendingNexusOperation; - if ( - previousActivityId && - previousActivityId !== pendingActivity?.activityId - ) { - scheduledEventByActivityId.delete(previousActivityId); - } - if (pendingActivity) { - scheduledEventByActivityId.set(pendingActivity.activityId, head); - } - if (pendingActivity || pendingNexusOperation) { - enrichedRecords.add(record); - } else { - enrichedRecords.delete(record); - } - record.version++; - return true; +export function isWorkflowTaskGroup(group: EventGroup | LazyGroup): boolean { + return group.initialEvent.eventType === 'WorkflowTaskScheduled'; } -// --------------------------------------------------------------------------- -// Internal helpers -// --------------------------------------------------------------------------- +const NO_EVENT_GROUP_KEYS: readonly EventGroupKey[] = []; -function notifyChanged(immediate = false): void { - for (const listener of changeListeners) listener(immediate); +function isTimelineLifecycle(record: GroupRecord): boolean { + return record.headsGroup && !isWorkflowTaskGroup(record); } -function grow(slot: number): void { - if (slot < events.length) return; - const size = slot + Math.ceil(slot * 0.25) + 16; - events.length = size; - const grown = new Int32Array(size); - grown.set(headGroup); - headGroup = grown; +function isLaterEvent( + event: WorkflowEvent, + than: WorkflowEvent | undefined, +): boolean { + return !than || Number(event.id) > Number(than.id); } -function shouldNotAddBillableAction(event: WorkflowEvent): boolean { - if (!failedEvent) return false; - return Number(event.id) < Number(failedEvent.eventId); +/** + * The full EventGroup for a lazy group, memoized on its content version: an + * unchanged lazy group returns the identical object, a changed one a new object. + * + * Idempotent — an already-materialized EventGroup passes straight through, so + * views can accept either lazy groups or groups built elsewhere (e.g. + * groupEvents() in graph-widget) without branching at every use site. + */ +export function materializeGroup(lazy: LazyGroup): EventGroup { + if (lazy instanceof GroupRecord) { + return lazy.materialize() as EventGroup; + } + return lazy as EventGroup; } -function toWorkflowEvent(raw: HistoryEvent): WorkflowEvent { - return toEvent(raw, { - shouldNotAddBillableAction, - processedWorkflowTaskIds, - eventGroupLabels, - }); -} +export function createGroupedEventBuffer() { + // --------------------------------------------------------------------------- + // Buffer state (reset between workflows via reset()) + // --------------------------------------------------------------------------- + + let events: (WorkflowEvent | null)[] = []; + let headGroup = new Int32Array(0); // head slot -> record index + 1 (0 = none) + let records: GroupRecord[] = []; + let maxSlot = -1; + + let failedEvent: HistoryEvent | null = null; + let initialEvent: WorkflowExecutionStartedEvent | undefined; + let latestEventTimeMs: number | undefined; + + // Accumulated WFT IDs for marker billable-action dedup. Shared by both cursors + // and the live poll — the direction an event arrives from is a fetch detail, + // and one workflow task's markers bill once however they were loaded. + const processedWorkflowTaskIds = new Set(); + const createLabelRegistry = () => + createEventGroupLabelRegistry({ + onLabelChange: (key) => dirtyTimelineEventGroupKeys.add(key), + }); + let eventGroupLabels = createLabelRegistry(); + + // Event group key -> the events carrying that marker and the lifecycle groups + // they belong to, so the event group filter is a set lookup per row. + let eventGroupIndex = new Map(); + let cachedEventGroupOptions: EventGroupOption[] | null = null; + let cachedEventGroupOptionsRevision = -1; + let timelineEventGroupsByKey = new Map< + EventGroupKey, + TimelineEventGroup + >(); + const dirtyTimelineEventGroupKeys = new Set(); + let timelineEventGroupCount = 0; + let userDefinedEventGroupFound = false; + let cachedTimelineEventGroups: TimelineEventGroup[] | null = null; + let cachedTimelineEventGroupsRevision = -1; + + // Bumped by every write. Read caches hold the revision they were built at, so + // invalidation is a single counter rather than scattered cache-busting calls. + let revision = 0; + + let cachedGroups: EventGroup[] | null = null; + let cachedGroupsRevision = -1; + let cachedGroupsNoWFT: EventGroup[] | null = null; + let cachedGroupsNoWFTRevision = -1; + let cachedEvents: WorkflowEvent[] | null = null; + let cachedEventsRevision = -1; + let cachedLazyGroups: LazyGroup[] | null = null; + let cachedLazyGroupsRevision = -1; + let cachedLazyGroupsNoWFT: LazyGroup[] | null = null; + let cachedLazyGroupsNoWFTRevision = -1; + let cachedWftFailed: WorkflowEvent | undefined; + let cachedWftFailedRevision = -1; + + const changeListeners = new Set(); + + // Pending metadata from the workflow run, held so a head event arriving later + // can pick its own up. Records currently carrying some are tracked so a walk is + // only needed when there is something to set or clear. + let pendingByActivityId = new Map(); + let pendingByNexusScheduledId = new Map(); + const enrichedRecords = new Set(); + + // Head event of each currently-pending activity's group, keyed by activityId. + // Maintained alongside enrichedRecords so a pending-activity card can diff its + // current options against the ones it was scheduled with without scanning. The + // head is always ActivityTaskScheduled: that is the only branch in + // applyPendingMetadataTo that assigns pendingActivity. + const scheduledEventByActivityId = new Map(); + + /** Returns whether the record's pending metadata changed. */ + function applyPendingMetadataTo(record: GroupRecord): boolean { + const head = record.initialEvent; + if (!head) return false; + + let pendingActivity: PendingActivity | undefined; + let pendingNexusOperation: PendingNexusOperation | undefined; + + // The run can still list an activity the history has already resolved, so a + // terminal event wins. This is the only writer of the record's pending + // fields, so gating here covers the lazy and materialized readings alike. + if (!record.hasTerminalActivity && isActivityTaskScheduledEvent(head)) { + pendingActivity = pendingByActivityId.get( + head.activityTaskScheduledEventAttributes?.activityId ?? '', + ); + } else if ( + !record.hasTerminalNexus && + isNexusOperationScheduledEvent(head) + ) { + pendingNexusOperation = pendingByNexusScheduledId.get(head.id); + } -function updateLatestEventTime(event: WorkflowEvent): void { - const eventTimeMs = getValidTimeMs(event.eventTime); - if (eventTimeMs === undefined) { - return; + if ( + record.pendingActivity === pendingActivity && + record.pendingNexusOperation === pendingNexusOperation + ) { + return false; + } + + const previousActivityId = record.pendingActivity?.activityId; + record.pendingActivity = pendingActivity; + record.pendingNexusOperation = pendingNexusOperation; + if ( + previousActivityId && + previousActivityId !== pendingActivity?.activityId + ) { + scheduledEventByActivityId.delete(previousActivityId); + } + if (pendingActivity) { + scheduledEventByActivityId.set(pendingActivity.activityId, head); + } + if (pendingActivity || pendingNexusOperation) { + enrichedRecords.add(record); + } else { + enrichedRecords.delete(record); + } + record.version++; + return true; } - if (latestEventTimeMs !== undefined && eventTimeMs <= latestEventTimeMs) { - return; + // --------------------------------------------------------------------------- + // Internal helpers + // --------------------------------------------------------------------------- + + function notifyChanged(immediate = false): void { + for (const listener of changeListeners) listener(immediate); } - latestEventTimeMs = eventTimeMs; -} + function grow(slot: number): void { + if (slot < events.length) return; + const size = slot + Math.ceil(slot * 0.25) + 16; + events.length = size; + const grown = new Int32Array(size); + grown.set(headGroup); + headGroup = grown; + } -// An event whose head is unknown (malformed attributes) heads its own group. -function headSlotFor(event: WorkflowEvent, slot: number): number { - const parsedHeadSlot = parseInt(getGroupId(event as CommonHistoryEvent)) - 1; - return parsedHeadSlot >= 0 ? parsedHeadSlot : slot; -} + function shouldNotAddBillableAction(event: WorkflowEvent): boolean { + if (!failedEvent) return false; + return Number(event.id) < Number(failedEvent.eventId); + } -const NO_EVENT_GROUP_KEYS: readonly EventGroupKey[] = []; + function toWorkflowEvent(raw: HistoryEvent): WorkflowEvent { + return toEvent(raw, { + shouldNotAddBillableAction, + processedWorkflowTaskIds, + eventGroupLabels, + }); + } -function indexEventGroups( - event: WorkflowEvent, - slot: number, - record: GroupRecord, -): readonly EventGroupKey[] { - if (!event.eventGroups) return NO_EVENT_GROUP_KEYS; - const eventId = slot + 1; - let linkedKeys: EventGroupKey[] | undefined; - for (const group of event.eventGroups) { - let entry = eventGroupIndex.get(group.key); - if (!entry) { - entry = { - group, - eventCount: 0, - firstEventId: eventId, - headSlots: new Set(), - lifecycle: [], - lifecycleSorted: true, - lifecycleEventCount: 0, - lifecycleVersion: 0, - pendingCount: 0, - initialEvent: undefined, - lastEvent: undefined, - }; - eventGroupIndex.set(group.key, entry); + function updateLatestEventTime(event: WorkflowEvent): void { + const eventTimeMs = getValidTimeMs(event.eventTime); + if (eventTimeMs === undefined) { + return; } - entry.eventCount++; - if (eventId < entry.firstEventId) entry.firstEventId = eventId; - if (!entry.headSlots.has(record.headSlot)) { - entry.headSlots.add(record.headSlot); - (record.eventGroupKeys ??= []).push(group.key); - (linkedKeys ??= []).push(group.key); - } - } - return linkedKeys ?? NO_EVENT_GROUP_KEYS; -} -function isTimelineLifecycle(record: GroupRecord): boolean { - return record.headsGroup && !isWorkflowTaskGroup(record); -} + if (latestEventTimeMs !== undefined && eventTimeMs <= latestEventTimeMs) { + return; + } -function addLifecycle(entry: EventGroupIndexEntry, record: GroupRecord): void { - const last = entry.lifecycle[entry.lifecycle.length - 1]; - if (last && last.headSlot > record.headSlot) entry.lifecycleSorted = false; - if (!last) { - timelineEventGroupCount++; - if (entry.group.kind === 'label') userDefinedEventGroupFound = true; + latestEventTimeMs = eventTimeMs; } - entry.lifecycle.push(record); -} -function isLaterEvent( - event: WorkflowEvent, - than: WorkflowEvent | undefined, -): boolean { - return !than || Number(event.id) > Number(than.id); -} + // An event whose head is unknown (malformed attributes) heads its own group. + function headSlotFor(event: WorkflowEvent, slot: number): number { + const parsedHeadSlot = + parseInt(getGroupId(event as CommonHistoryEvent)) - 1; + return parsedHeadSlot >= 0 ? parsedHeadSlot : slot; + } -function syncEventGroupTotals( - record: GroupRecord, - linkedKeys: readonly EventGroupKey[] = NO_EVENT_GROUP_KEYS, -): void { - const keys = record.eventGroupKeys; - if (!keys || !isTimelineLifecycle(record)) return; - - const eventCount = record.eventCount; - const isPending = record.isPending; - for (const key of keys) { - const entry = eventGroupIndex.get(key); - if (!entry) continue; - - if (!record.syncedVersion || linkedKeys.includes(key)) { - addLifecycle(entry, record); - entry.lifecycleEventCount += eventCount; - entry.lifecycleVersion += record.version + 1; - entry.pendingCount += Number(isPending); - if ( - !entry.initialEvent || - Number(record.initialEvent.id) < Number(entry.initialEvent.id) - ) { - entry.initialEvent = record.initialEvent; + function indexEventGroups( + event: WorkflowEvent, + slot: number, + record: GroupRecord, + ): readonly EventGroupKey[] { + if (!event.eventGroups) return NO_EVENT_GROUP_KEYS; + const eventId = slot + 1; + let linkedKeys: EventGroupKey[] | undefined; + for (const group of event.eventGroups) { + let entry = eventGroupIndex.get(group.key); + if (!entry) { + entry = { + group, + eventCount: 0, + firstEventId: eventId, + headSlots: new Set(), + lifecycle: [], + lifecycleSorted: true, + lifecycleEventCount: 0, + lifecycleVersion: 0, + pendingCount: 0, + initialEvent: undefined, + lastEvent: undefined, + }; + eventGroupIndex.set(group.key, entry); + } + entry.eventCount++; + if (eventId < entry.firstEventId) entry.firstEventId = eventId; + if (!entry.headSlots.has(record.headSlot)) { + entry.headSlots.add(record.headSlot); + (record.eventGroupKeys ??= []).push(group.key); + (linkedKeys ??= []).push(group.key); } - } else { - entry.lifecycleEventCount += eventCount - record.syncedEventCount; - entry.lifecycleVersion += record.version - record.syncedVersion; - entry.pendingCount += Number(isPending) - Number(record.syncedPending); - } - if (isLaterEvent(record.lastEvent, entry.lastEvent)) { - entry.lastEvent = record.lastEvent; } - dirtyTimelineEventGroupKeys.add(key); + return linkedKeys ?? NO_EVENT_GROUP_KEYS; } - record.syncedVersion = record.version; - record.syncedEventCount = eventCount; - record.syncedPending = isPending; -} + function addLifecycle( + entry: EventGroupIndexEntry, + record: GroupRecord, + ): void { + const last = entry.lifecycle[entry.lifecycle.length - 1]; + if (last && last.headSlot > record.headSlot) entry.lifecycleSorted = false; + if (!last) { + timelineEventGroupCount++; + if (entry.group.kind === 'label') userDefinedEventGroupFound = true; + } + entry.lifecycle.push(record); + } -function recordFor(headSlot: number): GroupRecord { - const existing = headGroup[headSlot]; - if (existing !== 0) return records[existing - 1]; + function syncEventGroupTotals( + record: GroupRecord, + linkedKeys: readonly EventGroupKey[] = NO_EVENT_GROUP_KEYS, + ): void { + const keys = record.eventGroupKeys; + if (!keys || !isTimelineLifecycle(record)) return; + + const eventCount = record.eventCount; + const isPending = record.isPending; + for (const key of keys) { + const entry = eventGroupIndex.get(key); + if (!entry) continue; + + if (!record.syncedVersion || linkedKeys.includes(key)) { + addLifecycle(entry, record); + entry.lifecycleEventCount += eventCount; + entry.lifecycleVersion += record.version + 1; + entry.pendingCount += Number(isPending); + if ( + !entry.initialEvent || + Number(record.initialEvent.id) < Number(entry.initialEvent.id) + ) { + entry.initialEvent = record.initialEvent; + } + } else { + entry.lifecycleEventCount += eventCount - record.syncedEventCount; + entry.lifecycleVersion += record.version - record.syncedVersion; + entry.pendingCount += Number(isPending) - Number(record.syncedPending); + } + if (isLaterEvent(record.lastEvent, entry.lastEvent)) { + entry.lastEvent = record.lastEvent; + } + dirtyTimelineEventGroupKeys.add(key); + } - const record = new GroupRecord(headSlot); - records.push(record); - headGroup[headSlot] = records.length; - return record; -} + record.syncedVersion = record.version; + record.syncedEventCount = eventCount; + record.syncedPending = isPending; + } -function isTerminalActivityEvent(event: WorkflowEvent): boolean { - return ( - isActivityTaskCompletedEvent(event) || - isActivityTaskFailedEvent(event) || - isActivityTaskCanceledEvent(event) || - isActivityTaskTimedOutEvent(event) - ); -} + function recordFor(headSlot: number): GroupRecord { + const existing = headGroup[headSlot]; + if (existing !== 0) return records[existing - 1]; -function isTerminalNexusEvent(event: WorkflowEvent): boolean { - return ( - isNexusOperationCompletedEvent(event) || - isNexusOperationFailedEvent(event) || - isNexusOperationCanceledEvent(event) || - isNexusOperationTimedOutEvent(event) - ); -} + const record = new GroupRecord( + headSlot, + applyPendingMetadataTo, + materializeEventGroup, + ); + records.push(record); + headGroup[headSlot] = records.length; + return record; + } -// Pending metadata is applied as a derived read rather than stored on the -// group, so a terminal event and a stale pending entry can arrive in either -// order without leaving the group reporting isPending alongside a completion. -function applyPendingMetadata(group: EventGroup, record: GroupRecord): void { - // Copies rather than re-deciding — the record is already correct. - group.pendingActivity = record.pendingActivity; - group.pendingNexusOperation = record.pendingNexusOperation; -} + // Pending metadata is applied as a derived read rather than stored on the + // group, so a terminal event and a stale pending entry can arrive in either + // order without leaving the group reporting isPending alongside a completion. + function applyPendingMetadata(group: EventGroup, record: GroupRecord): void { + // Copies rather than re-deciding — the record is already correct. + group.pendingActivity = record.pendingActivity; + group.pendingNexusOperation = record.pendingNexusOperation; + } -/** - * Build the EventGroup for a record, or null when it has no head event yet or - * its head event doesn't form a group (e.g. WorkflowExecutionStarted). - * Memoized on the record's version — callers may rely on an unchanged record - * returning the identical object. - */ -function materializeEventGroup(record: GroupRecord): EventGroup | null { - if (record.cachedVersion === record.version) return record.cached; - record.cachedVersion = record.version; - record.cached = null; + /** + * Build the EventGroup for a record, or null when it has no head event yet or + * its head event doesn't form a group (e.g. WorkflowExecutionStarted). + * Memoized on the record's version — callers may rely on an unchanged record + * returning the identical object. + */ + function materializeEventGroup(record: GroupRecord): EventGroup | null { + if (record.cachedVersion === record.version) return record.cached; + record.cachedVersion = record.version; + record.cached = null; + + const head = events[record.headSlot]; + if (!head) return null; + + const group = + createEventGroup(head as CommonHistoryEvent) ?? + createWorkflowTaskGroup(head as CommonHistoryEvent); + if (!group) return null; + + const followers: WorkflowEvent[] = []; + for (const slot of record.slots) { + if (slot === record.headSlot) continue; + const event = events[slot]; + if (event) followers.push(event); + } + followers.sort((a, b) => Number(a.id) - Number(b.id)); - const head = events[record.headSlot]; - if (!head) return null; + for (const event of followers) { + group.eventList.push(event); + group.timestamp = event.timestamp; + addEventToGroup(group, event); + } - const group = - createEventGroup(head as CommonHistoryEvent) ?? - createWorkflowTaskGroup(head as CommonHistoryEvent); - if (!group) return null; + applyPendingMetadata(group, record); - const followers: WorkflowEvent[] = []; - for (const slot of record.slots) { - if (slot === record.headSlot) continue; - const event = events[slot]; - if (event) followers.push(event); + record.cached = group; + return group; } - followers.sort((a, b) => Number(a.id) - Number(b.id)); - for (const event of followers) { - group.eventList.push(event); - group.timestamp = event.timestamp; - addEventToGroup(group, event); - } + // --------------------------------------------------------------------------- + // Public API + // --------------------------------------------------------------------------- - applyPendingMetadata(group, record); + /** + * (Re)initialise the buffer for a new workflow run. + * Call before starting the bidirectional fetch. + */ + function reset(historyLength: number): void { + const size = Math.max(historyLength + 16, 16); + + events = new Array(size).fill(null); + headGroup = new Int32Array(size); + records = []; + enrichedRecords.clear(); + scheduledEventByActivityId.clear(); + pendingByActivityId = new Map(); + pendingByNexusScheduledId = new Map(); + maxSlot = -1; + + failedEvent = null; + initialEvent = undefined; + latestEventTimeMs = undefined; + processedWorkflowTaskIds.clear(); + eventGroupLabels = createLabelRegistry(); + eventGroupIndex = new Map(); + cachedEventGroupOptions = null; + timelineEventGroupsByKey = new Map(); + dirtyTimelineEventGroupKeys.clear(); + timelineEventGroupCount = 0; + userDefinedEventGroupFound = false; + cachedTimelineEventGroups = null; + + revision++; + cachedGroups = null; + cachedGroupsNoWFT = null; + cachedEvents = null; + cachedLazyGroups = null; + cachedLazyGroupsNoWFT = null; + + notifyChanged(true); + } - record.cached = group; - return group; -} + /** + * The reset point past which events stop counting toward billableActions. + * Currently unwired — no production caller supplies it. + */ + function setFailedEvent(raw: HistoryEvent | null): void { + failedEvent = raw; + } -// --------------------------------------------------------------------------- -// Public API -// --------------------------------------------------------------------------- + /** + * Add one raw HistoryEvent from either fetch cursor or the live poll. + * Returns false when the event was already present. + */ + function ingestHistoryEvent(raw: HistoryEvent): boolean { + const slot = parseInt(raw.eventId) - 1; + if (!(slot >= 0)) return false; -/** - * (Re)initialise the buffer for a new workflow run. - * Call before starting the bidirectional fetch. - */ -export function reset(historyLength: number): void { - const size = Math.max(historyLength + 16, 16); - - events = new Array(size).fill(null); - headGroup = new Int32Array(size); - records = []; - enrichedRecords.clear(); - scheduledEventByActivityId.clear(); - pendingByActivityId = new Map(); - pendingByNexusScheduledId = new Map(); - maxSlot = -1; - latestEventTimeMs = undefined; - - failedEvent = null; - processedWorkflowTaskIds.clear(); - eventGroupLabels = createLabelRegistry(); - eventGroupIndex = new Map(); - cachedEventGroupOptions = null; - timelineEventGroupsByKey = new Map(); - dirtyTimelineEventGroupKeys.clear(); - timelineEventGroupCount = 0; - userDefinedEventGroupFound = false; - cachedTimelineEventGroups = null; - - revision++; - cachedGroups = null; - cachedGroupsNoWFT = null; - cachedEvents = null; - cachedLazyGroups = null; - cachedLazyGroupsNoWFT = null; - - notifyChanged(true); -} + grow(slot); + if (events[slot]) return false; -/** - * The reset point past which events stop counting toward billableActions. - * Currently unwired — no production caller supplies it. - */ -export function setFailedEvent(raw: HistoryEvent | null): void { - failedEvent = raw; -} + const event = toWorkflowEvent(raw); + if (!initialEvent && isWorkflowExecutionStartedEvent(event)) { + initialEvent = event; + } + events[slot] = event; + if (slot > maxSlot) maxSlot = slot; -/** - * Add one raw HistoryEvent from either fetch cursor or the live poll. - * Returns false when the event was already present. - */ -export function ingestHistoryEvent(raw: HistoryEvent): boolean { - const slot = parseInt(raw.eventId) - 1; - if (!(slot >= 0)) return false; + const headSlot = headSlotFor(event, slot); + grow(headSlot); - grow(slot); - if (events[slot]) return false; + const record = recordFor(headSlot); + record.addMember(slot, event); + syncEventGroupTotals(record, indexEventGroups(event, slot, record)); + updateLatestEventTime(event); + revision++; - const event = toWorkflowEvent(raw); - events[slot] = event; - if (slot > maxSlot) maxSlot = slot; + notifyChanged(); + return true; + } - const headSlot = headSlotFor(event, slot); - grow(headSlot); + function getLatestEventTimeMs(): number | undefined { + return latestEventTimeMs; + } - const record = recordFor(headSlot); - record.addMember(slot, event); - syncEventGroupTotals(record, indexEventGroups(event, slot, record)); - updateLatestEventTime(event); - revision++; + /** + * Annotate activity and nexus groups with pending metadata from the workflow + * run. Safe to call repeatedly — groups whose pending entry is unchanged keep + * their existing reference. + */ + function setPendingMetadata( + pendingActivities: PendingActivity[], + pendingNexusOperations: PendingNexusOperation[], + ): void { + pendingByActivityId = new Map( + pendingActivities.map((pending) => [pending.activityId, pending]), + ); + pendingByNexusScheduledId = new Map( + pendingNexusOperations.map((pending) => [ + String(pending.scheduledEventId), + pending, + ]), + ); - notifyChanged(); - return true; -} + const nothingPending = + pendingByActivityId.size === 0 && pendingByNexusScheduledId.size === 0; + if (nothingPending && enrichedRecords.size === 0) return; + + let changed = false; + for (const record of records) { + if (!record.headsGroup) continue; + if (applyPendingMetadataTo(record)) { + syncEventGroupTotals(record); + revision++; + changed = true; + } + } -export function getLatestEventTimeMs(): number | undefined { - return latestEventTimeMs; -} + if (changed) notifyChanged(); + } -/** - * Annotate activity and nexus groups with pending metadata from the workflow - * run. Safe to call repeatedly — groups whose pending entry is unchanged keep - * their existing reference. - */ -export function setPendingMetadata( - pendingActivities: PendingActivity[], - pendingNexusOperations: PendingNexusOperation[], -): void { - pendingByActivityId = new Map( - pendingActivities.map((pending) => [pending.activityId, pending]), - ); - pendingByNexusScheduledId = new Map( - pendingNexusOperations.map((pending) => [ - String(pending.scheduledEventId), - pending, - ]), - ); + /** + * The ActivityTaskScheduled event that started a currently-pending activity, or + * undefined when that event has not been ingested yet. Only pending activities + * are indexed: a resolved one drops out with its pending metadata. + */ + function getPendingActivityScheduledEvent( + activityId: string, + ): WorkflowEvent | undefined { + return scheduledEventByActivityId.get(activityId); + } - const nothingPending = - pendingByActivityId.size === 0 && pendingByNexusScheduledId.size === 0; - if (nothingPending && enrichedRecords.size === 0) return; - - let changed = false; - for (const record of records) { - if (!record.headsGroup) continue; - if (applyPendingMetadataTo(record)) { - syncEventGroupTotals(record); - revision++; - changed = true; - } + /** + * Subscribe to buffer writes. Fires once per ingested event and once per + * pending-metadata change, so subscribers are expected to coalesce. `immediate` + * is true for reset, which subscribers should apply without coalescing so a + * navigation cannot leave the previous run's groups on screen. + * Returns an unsubscribe function. + */ + function onChange(listener: ChangeListener): () => void { + changeListeners.add(listener); + return () => changeListeners.delete(listener); } - if (changed) notifyChanged(); -} + /** + * Sorted LazyGroup[] in ascending event-id order, without building a single + * EventGroup. Cached until the next write; lazy groups are the records themselves, + * so a rebuild allocates only the array. + */ + function getLazyGroups(opts?: GroupArrayOptions): LazyGroup[] { + const excludeWFT = Boolean(opts?.excludeWorkflowTasks); -/** - * The ActivityTaskScheduled event that started a currently-pending activity, or - * undefined when that event has not been ingested yet. Only pending activities - * are indexed: a resolved one drops out with its pending metadata. - */ -export function getPendingActivityScheduledEvent( - activityId: string, -): WorkflowEvent | undefined { - return scheduledEventByActivityId.get(activityId); -} + if (excludeWFT) { + if (cachedLazyGroupsNoWFT && cachedLazyGroupsNoWFTRevision === revision) { + return cachedLazyGroupsNoWFT; + } + } else if (cachedLazyGroups && cachedLazyGroupsRevision === revision) { + return cachedLazyGroups; + } -/** - * Subscribe to buffer writes. Fires once per ingested event and once per - * pending-metadata change, so subscribers are expected to coalesce. `immediate` - * is true for reset, which subscribers should apply without coalescing so a - * navigation cannot leave the previous run's groups on screen. - * Returns an unsubscribe function. - */ -export function onChange(listener: ChangeListener): () => void { - changeListeners.add(listener); - return () => changeListeners.delete(listener); -} + // headGroup is indexed by head slot, so scanning it yields groups already in + // ascending event-id order — no sort needed. + const result: LazyGroup[] = new Array(records.length); + let count = 0; + for (let slot = 0; slot <= maxSlot; slot++) { + const recordIdx = headGroup[slot]; + if (recordIdx === 0) continue; + const record = records[recordIdx - 1]; + if (!record.headsGroup) continue; + if (excludeWFT && isWorkflowTaskGroup(record)) continue; + result[count++] = record; + } + result.length = count; -export function isWorkflowTaskGroup(group: EventGroup | LazyGroup): boolean { - return group.initialEvent.eventType === 'WorkflowTaskScheduled'; -} + if (excludeWFT) { + cachedLazyGroupsNoWFT = result; + cachedLazyGroupsNoWFTRevision = revision; + } else { + cachedLazyGroups = result; + cachedLazyGroupsRevision = revision; + } + return result; + } -/** - * Sorted LazyGroup[] in ascending event-id order, without building a single - * EventGroup. Cached until the next write; lazy groups are the records themselves, - * so a rebuild allocates only the array. - */ -export function getLazyGroups(opts?: GroupArrayOptions): LazyGroup[] { - const excludeWFT = Boolean(opts?.excludeWorkflowTasks); + /** + * Sorted EventGroup[] in ascending event-id order — materializes every group. + * Prefer getLazyGroups + materializeGroup so only rendered groups are built. + */ + function getGroupArray(opts?: GroupArrayOptions): EventGroup[] { + const excludeWFT = Boolean(opts?.excludeWorkflowTasks); - if (excludeWFT) { - if (cachedLazyGroupsNoWFT && cachedLazyGroupsNoWFTRevision === revision) { - return cachedLazyGroupsNoWFT; + if (excludeWFT) { + if (cachedGroupsNoWFT && cachedGroupsNoWFTRevision === revision) { + return cachedGroupsNoWFT; + } + } else if (cachedGroups && cachedGroupsRevision === revision) { + return cachedGroups; } - } else if (cachedLazyGroups && cachedLazyGroupsRevision === revision) { - return cachedLazyGroups; - } - - // headGroup is indexed by head slot, so scanning it yields groups already in - // ascending event-id order — no sort needed. - const result: LazyGroup[] = new Array(records.length); - let count = 0; - for (let slot = 0; slot <= maxSlot; slot++) { - const recordIdx = headGroup[slot]; - if (recordIdx === 0) continue; - const record = records[recordIdx - 1]; - if (!record.headsGroup) continue; - if (excludeWFT && isWorkflowTaskGroup(record)) continue; - result[count++] = record; - } - result.length = count; - - if (excludeWFT) { - cachedLazyGroupsNoWFT = result; - cachedLazyGroupsNoWFTRevision = revision; - } else { - cachedLazyGroups = result; - cachedLazyGroupsRevision = revision; - } - return result; -} -/** - * The full EventGroup for a lazy group, memoized on its content version: an - * unchanged lazy group returns the identical object, a changed one a new object. - * - * Idempotent — an already-materialized EventGroup passes straight through, so - * views can accept either lazy groups or groups built elsewhere (e.g. - * groupEvents() in graph-widget) without branching at every use site. - */ -export function materializeGroup(lazy: LazyGroup): EventGroup { - if (lazy instanceof GroupRecord) { - return materializeEventGroup(lazy) as EventGroup; - } - return lazy as EventGroup; -} - -/** - * Sorted EventGroup[] in ascending event-id order — materializes every group. - * Prefer getLazyGroups + materializeGroup so only rendered groups are built. - */ -export function getGroupArray(opts?: GroupArrayOptions): EventGroup[] { - const excludeWFT = Boolean(opts?.excludeWorkflowTasks); + const result = getLazyGroups(opts).map(materializeGroup); - if (excludeWFT) { - if (cachedGroupsNoWFT && cachedGroupsNoWFTRevision === revision) { - return cachedGroupsNoWFT; + if (excludeWFT) { + cachedGroupsNoWFT = result; + cachedGroupsNoWFTRevision = revision; + } else { + cachedGroups = result; + cachedGroupsRevision = revision; } - } else if (cachedGroups && cachedGroupsRevision === revision) { - return cachedGroups; + return result; } - const result = getLazyGroups(opts).map(materializeGroup); + /** Every event group in the run, in order of the first event carrying it. */ + function getEventGroupOptions(): EventGroupOption[] { + if ( + cachedEventGroupOptions && + cachedEventGroupOptionsRevision === revision + ) { + return cachedEventGroupOptions; + } - if (excludeWFT) { - cachedGroupsNoWFT = result; - cachedGroupsNoWFTRevision = revision; - } else { - cachedGroups = result; - cachedGroupsRevision = revision; + const result = [...eventGroupIndex.values()] + .map(({ group, eventCount, firstEventId }) => ({ + group, + eventCount, + firstEventId, + })) + .sort((a, b) => a.firstEventId - b.firstEventId); + + cachedEventGroupOptions = result; + cachedEventGroupOptionsRevision = revision; + return result; } - return result; -} -/** Every event group in the run, in order of the first event carrying it. */ -export function getEventGroupOptions(): EventGroupOption[] { - if (cachedEventGroupOptions && cachedEventGroupOptionsRevision === revision) { - return cachedEventGroupOptions; + function hasTimelineEventGroups(): boolean { + return timelineEventGroupCount > 0; } - const result = [...eventGroupIndex.values()] - .map(({ group, eventCount, firstEventId }) => ({ - group, - eventCount, - firstEventId, - })) - .sort((a, b) => a.firstEventId - b.firstEventId); + function hasUserDefinedEventGroups(): boolean { + return userDefinedEventGroupFound; + } - cachedEventGroupOptions = result; - cachedEventGroupOptionsRevision = revision; - return result; -} + function getTimelineEventGroups(): TimelineEventGroup[] { + if ( + cachedTimelineEventGroups && + (cachedTimelineEventGroupsRevision === revision || + !dirtyTimelineEventGroupKeys.size) + ) { + cachedTimelineEventGroupsRevision = revision; + return cachedTimelineEventGroups; + } -export function hasTimelineEventGroups(): boolean { - return timelineEventGroupCount > 0; -} + for (const key of dirtyTimelineEventGroupKeys) { + const entry = eventGroupIndex.get(key); + if (!entry?.initialEvent || !entry.lastEvent) continue; + const previous = timelineEventGroupsByKey.get(key); + if (!entry.lifecycleSorted) { + entry.lifecycle.sort((a, b) => a.headSlot - b.headSlot); + entry.lifecycleSorted = true; + } + const lifecycleGroups: LazyGroup[] = + previous?.lifecycleGroups.length !== entry.lifecycle.length + ? entry.lifecycle.slice() + : previous.lifecycleGroups; + timelineEventGroupsByKey.set( + key, + toTimelineEventGroup(entry.group, lifecycleGroups, { + initialEvent: entry.initialEvent, + lastEvent: entry.lastEvent, + eventCount: entry.lifecycleEventCount, + isPending: entry.pendingCount > 0, + version: entry.lifecycleVersion, + }), + ); + } + dirtyTimelineEventGroupKeys.clear(); -export function hasUserDefinedEventGroups(): boolean { - return userDefinedEventGroupFound; -} + const result = [...timelineEventGroupsByKey.values()].sort( + (a, b) => + Number(a.initialEvent.id) - Number(b.initialEvent.id) || + a.key.localeCompare(b.key), + ); -export function getTimelineEventGroups(): TimelineEventGroup[] { - if ( - cachedTimelineEventGroups && - (cachedTimelineEventGroupsRevision === revision || - !dirtyTimelineEventGroupKeys.size) - ) { + cachedTimelineEventGroups = result; cachedTimelineEventGroupsRevision = revision; - return cachedTimelineEventGroups; + return result; } - for (const key of dirtyTimelineEventGroupKeys) { - const entry = eventGroupIndex.get(key); - if (!entry?.initialEvent || !entry.lastEvent) continue; - const previous = timelineEventGroupsByKey.get(key); - if (!entry.lifecycleSorted) { - entry.lifecycle.sort((a, b) => a.headSlot - b.headSlot); - entry.lifecycleSorted = true; + /** + * Matches lifecycle groups, and the events in them, that contain an event + * carrying any of `keys`. Keys not in this run are ignored; returns undefined + * when none remain, so a stale selection never hides the whole history. + */ + function getEventGroupMatcher( + keys: readonly EventGroupKey[], + ): EventGroupMatcher | undefined { + const headSlots = new Set(); + for (const key of keys) { + for (const headSlot of eventGroupIndex.get(key)?.headSlots ?? []) { + headSlots.add(headSlot); + } } - const lifecycleGroups: LazyGroup[] = - previous?.lifecycleGroups.length !== entry.lifecycle.length - ? entry.lifecycle.slice() - : previous.lifecycleGroups; - timelineEventGroupsByKey.set( - key, - toTimelineEventGroup(entry.group, lifecycleGroups, { - initialEvent: entry.initialEvent, - lastEvent: entry.lastEvent, - eventCount: entry.lifecycleEventCount, - isPending: entry.pendingCount > 0, - version: entry.lifecycleVersion, - }), - ); + if (!headSlots.size) return; + + return { + hasGroup: (groupId) => headSlots.has(parseInt(groupId) - 1), + hasEvent: (event) => + headSlots.has(headSlotFor(event, parseInt(event.id) - 1)), + }; } - dirtyTimelineEventGroupKeys.clear(); - const result = [...timelineEventGroupsByKey.values()].sort( - (a, b) => - Number(a.initialEvent.id) - Number(b.initialEvent.id) || - a.key.localeCompare(b.key), - ); + function getInitialEvent(): WorkflowExecutionStartedEvent | undefined { + return initialEvent; + } - cachedTimelineEventGroups = result; - cachedTimelineEventGroupsRevision = revision; - return result; -} + function getEvent(eventId: string): WorkflowEvent | undefined { + const id = Number(eventId); + if (!Number.isSafeInteger(id) || id < 1 || String(id) !== eventId) return; + const event = events[id - 1]; + return event?.id === eventId ? event : undefined; + } -/** - * Matches lifecycle groups, and the events in them, that contain an event - * carrying any of `keys`. Keys not in this run are ignored; returns undefined - * when none remain, so a stale selection never hides the whole history. - */ -export function getEventGroupMatcher( - keys: readonly EventGroupKey[], -): EventGroupMatcher | undefined { - const headSlots = new Set(); - for (const key of keys) { - for (const headSlot of eventGroupIndex.get(key)?.headSlots ?? []) { - headSlots.add(headSlot); - } + function getEventGroup( + eventId: string, + opts?: GroupArrayOptions, + ): EventGroup | undefined { + const event = getEvent(eventId); + if (!event) return; + const headSlot = headSlotFor(event, Number(eventId) - 1); + const recordIndex = headGroup[headSlot]; + if (!recordIndex) return; + const record = records[recordIndex - 1]; + if (!record.headsGroup) return; + if (opts?.excludeWorkflowTasks && isWorkflowTaskGroup(record)) return; + return materializeEventGroup(record) ?? undefined; } - if (!headSlots.size) return; - return { - hasGroup: (groupId) => headSlots.has(parseInt(groupId) - 1), - hasEvent: (event) => - headSlots.has(headSlotFor(event, parseInt(event.id) - 1)), - }; -} + /** Flat WorkflowEvent[] in ascending event-id order. */ + function getEventArray(): WorkflowEvent[] { + if (cachedEvents && cachedEventsRevision === revision) return cachedEvents; -/** Flat WorkflowEvent[] in ascending event-id order. */ -export function getEventArray(): WorkflowEvent[] { - if (cachedEvents && cachedEventsRevision === revision) return cachedEvents; + const result: WorkflowEvent[] = []; + for (let slot = 0; slot <= maxSlot; slot++) { + const event = events[slot]; + if (event) result.push(event); + } - const result: WorkflowEvent[] = []; - for (let slot = 0; slot <= maxSlot; slot++) { - const event = events[slot]; - if (event) result.push(event); + cachedEvents = result; + cachedEventsRevision = revision; + return result; } - cachedEvents = result; - cachedEventsRevision = revision; - return result; -} + /** + * The WorkflowTaskFailed/TimedOut event that is currently active (i.e. has no + * subsequent WorkflowTaskCompleted), or undefined if none. + */ + function getWorkflowTaskFailedEvent(): WorkflowEvent | undefined { + if (cachedWftFailedRevision === revision) return cachedWftFailed; -/** - * The WorkflowTaskFailed/TimedOut event that is currently active (i.e. has no - * subsequent WorkflowTaskCompleted), or undefined if none. - */ -export function getWorkflowTaskFailedEvent(): WorkflowEvent | undefined { - if (cachedWftFailedRevision === revision) return cachedWftFailed; + let lastFailedEvent: WorkflowEvent | undefined; + let maxCompletedId = -1; - let lastFailedEvent: WorkflowEvent | undefined; - let maxCompletedId = -1; + for (let slot = 0; slot <= maxSlot; slot++) { + const event = events[slot]; + if (!event) continue; - for (let slot = 0; slot <= maxSlot; slot++) { - const event = events[slot]; - if (!event) continue; + if (event.eventType === 'WorkflowTaskCompleted') { + const id = Number(event.id); + if (id > maxCompletedId) maxCompletedId = id; + continue; + } - if (event.eventType === 'WorkflowTaskCompleted') { - const id = Number(event.id); - if (id > maxCompletedId) maxCompletedId = id; - continue; + if ( + (isFailedTaskEvent(event) || isTimedOutTaskEvent(event)) && + !isWorkflowTaskFailedEventDueToReset(event) + ) { + lastFailedEvent = event; + } } - if ( - (isFailedTaskEvent(event) || isTimedOutTaskEvent(event)) && - !isWorkflowTaskFailedEventDueToReset(event) - ) { - lastFailedEvent = event; - } + cachedWftFailedRevision = revision; + cachedWftFailed = + lastFailedEvent && Number(lastFailedEvent.id) >= maxCompletedId + ? lastFailedEvent + : undefined; + return cachedWftFailed; } - cachedWftFailedRevision = revision; - cachedWftFailed = - lastFailedEvent && Number(lastFailedEvent.id) >= maxCompletedId - ? lastFailedEvent - : undefined; - return cachedWftFailed; + return { + reset, + setFailedEvent, + ingestHistoryEvent, + setPendingMetadata, + getPendingActivityScheduledEvent, + onChange, + getLazyGroups, + getGroupArray, + getEventGroupOptions, + getTimelineEventGroups, + hasTimelineEventGroups, + hasUserDefinedEventGroups, + getEventGroupMatcher, + getLatestEventTimeMs, + getEventArray, + getEvent, + getEventGroup, + getInitialEvent, + getWorkflowTaskFailedEvent, + }; } + +export type GroupedEventBuffer = ReturnType; diff --git a/src/lib/services/live-poll.test.ts b/src/lib/services/live-poll.test.ts index b31a058150..235d89ca90 100644 --- a/src/lib/services/live-poll.test.ts +++ b/src/lib/services/live-poll.test.ts @@ -8,12 +8,18 @@ import { vi, } from 'vitest'; +import { handleUnauthorizedOrForbiddenError } from '$lib/utilities/handle-error'; + import { runLivePoll } from './live-poll'; // --------------------------------------------------------------------------- // Mocks // --------------------------------------------------------------------------- +vi.mock('$lib/utilities/handle-error', () => ({ + handleUnauthorizedOrForbiddenError: vi.fn(), +})); + vi.mock('$lib/utilities/request-from-api', () => ({ requestFromAPI: vi.fn(), })); @@ -195,6 +201,51 @@ describe('runLivePoll — waitNewEvent long-poll', () => { // Event delivery // --------------------------------------------------------------------------- +describe('runLivePoll — callback failures', () => { + it.each<{ + callback: 'onEvent' | 'onNewEvents' | 'onToken'; + nextPageToken: string; + }>([ + { callback: 'onEvent', nextPageToken: 'next-token' }, + { callback: 'onNewEvents', nextPageToken: 'next-token' }, + { callback: 'onToken', nextPageToken: 'next-token' }, + { callback: 'onToken', nextPageToken: '' }, + ])( + 'rejects without retrying when $callback throws (token: "$nextPageToken")', + async ({ callback, nextPageToken }) => { + const ctrl = new AbortController(); + const failure = new Error('processing failed'); + const callbacks = { + onEvent: vi.fn(() => true), + onNewEvents: vi.fn(), + onToken: vi.fn(), + }; + callbacks[callback].mockImplementation(() => { + throw failure; + }); + requestFromAPI + .mockResolvedValueOnce(pollResponse([1], nextPageToken)) + .mockImplementation(() => { + ctrl.abort(); + return Promise.resolve(pollResponse([])); + }); + + await expect( + runLivePoll({ + route: '/api/events', + runId: 'run-1', + startToken: 'start-tok', + signal: ctrl.signal, + ...callbacks, + ...FAST, + }), + ).rejects.toBe(failure); + expect(requestFromAPI).toHaveBeenCalledTimes(1); + expect(ctrl.signal.aborted).toBe(false); + }, + ); +}); + describe('runLivePoll — event delivery', () => { it('calls onEvent for each event in the response', async () => { const { onEvent, done } = startPoll([pollResponse([1, 2, 3])]); @@ -496,6 +547,76 @@ describe('runLivePoll — back-off', () => { }); }); +describe('runLivePoll — request errors', () => { + const networkError = (statusCode: number) => ({ + statusCode, + statusText: 'Request failed', + response: new Response(null, { status: statusCode }), + }); + + it('delegates request errors to auth handling and rethrows them', async () => { + const ctrl = new AbortController(); + requestFromAPI.mockImplementationOnce(() => { + ctrl.abort(); + return Promise.resolve(pollResponse([])); + }); + + await runLivePoll({ + route: '/api/events', + runId: 'run-1', + startToken: '', + signal: ctrl.signal, + onEvent: vi.fn(), + ...FAST, + }); + + const { handleError } = requestFromAPI.mock.calls[0][1] as { + handleError: (error: unknown) => void; + }; + const error = networkError(403); + expect(() => handleError(error)).toThrow(); + expect(handleUnauthorizedOrForbiddenError).toHaveBeenCalledWith(error); + }); + + it('rejects on a non-retryable error response', async () => { + const error = networkError(404); + requestFromAPI.mockRejectedValueOnce(error); + + await expect( + runLivePoll({ + route: '/api/events', + runId: 'run-1', + startToken: '', + signal: new AbortController().signal, + onEvent: vi.fn(), + ...FAST, + }), + ).rejects.toBe(error); + expect(requestFromAPI).toHaveBeenCalledTimes(1); + }); + + it.each([408, 429, 503])('retries a %s error response', async (status) => { + const ctrl = new AbortController(); + requestFromAPI + .mockRejectedValueOnce(networkError(status)) + .mockImplementationOnce(() => { + ctrl.abort(); + return Promise.resolve(pollResponse([])); + }); + + await runLivePoll({ + route: '/api/events', + runId: 'run-1', + startToken: '', + signal: ctrl.signal, + onEvent: vi.fn(), + ...FAST, + }); + + expect(requestFromAPI).toHaveBeenCalledTimes(2); + }); +}); + // --------------------------------------------------------------------------- // Abort / cleanup // --------------------------------------------------------------------------- @@ -541,102 +662,104 @@ describe('runLivePoll — abort', () => { }); }); -// --------------------------------------------------------------------------- -// Pause / resume — returned cursor -// -// runLivePoll resolves with the last cursor token it held when aborted. -// The caller saves this and passes it as startToken when resuming, so the -// server picks up exactly where polling left off instead of re-fetching from -// the start. -// --------------------------------------------------------------------------- - describe('runLivePoll — pause/resume cursor', () => { - it('returns empty string when aborted before any request', async () => { + it('does not publish a cursor when aborted before any request', async () => { const ctrl = new AbortController(); + const onToken = vi.fn(); ctrl.abort(); - const token = await runLivePoll({ + await runLivePoll({ route: '/api/events', runId: 'run-1', startToken: '', signal: ctrl.signal, onEvent: vi.fn(), onNewEvents: vi.fn(), + onToken, ...FAST, }); - expect(token).toBe(''); + expect(onToken).not.toHaveBeenCalled(); + expect(requestFromAPI).not.toHaveBeenCalled(); }); - it('returns the startToken when aborted mid-request with no new token received', async () => { + it('publishes an empty cursor when a response has no nextPageToken', async () => { const ctrl = new AbortController(); + const onToken = vi.fn(); requestFromAPI.mockImplementationOnce(() => { ctrl.abort(); return Promise.resolve(pollResponse([])); }); - const token = await runLivePoll({ + await runLivePoll({ route: '/api/events', runId: 'run-1', startToken: 'resume-tok', signal: ctrl.signal, onEvent: vi.fn(), onNewEvents: vi.fn(), + onToken, ...FAST, }); - // No nextPageToken in the response so token reset to ''. - expect(token).toBe(''); + expect(requestFromAPI.mock.calls[0]?.[1]?.token).toBe('resume-tok'); + expect(onToken).toHaveBeenCalledExactlyOnceWith(''); }); - it('returns the latest nextPageToken when aborted while mid-page', async () => { + it('publishes successive cursors and resets at the frontier', async () => { const ctrl = new AbortController(); - // First response has a nextPageToken → token advances. + const onToken = vi.fn(); requestFromAPI.mockImplementationOnce(() => Promise.resolve(pollResponse([], 'page-2-tok')), ); - // Second request (following the token) is where abort fires. + requestFromAPI.mockImplementationOnce(() => { ctrl.abort(); return Promise.resolve(pollResponse([])); }); - const token = await runLivePoll({ + await runLivePoll({ route: '/api/events', runId: 'run-1', startToken: '', signal: ctrl.signal, onEvent: vi.fn(), onNewEvents: vi.fn(), + onToken, ...FAST, }); - // After following 'page-2-tok', the second response has no nextPageToken - // so token resets to ''. - expect(token).toBe(''); + expect(onToken).toHaveBeenCalledTimes(2); + expect(onToken).toHaveBeenNthCalledWith(1, 'page-2-tok'); + expect(onToken).toHaveBeenNthCalledWith(2, ''); + expect(requestFromAPI.mock.calls[1]?.[1]?.token).toBe('page-2-tok'); }); - it('can be resumed from the returned cursor without re-fetching old events', async () => { - // Simulate pausing mid-stream: first poll run is aborted after two pages. + it('can be resumed from the onToken cursor without re-fetching old events', async () => { const ctrl1 = new AbortController(); + let resumeToken = ''; requestFromAPI .mockImplementationOnce(() => Promise.resolve(pollResponse([1], 'tok-a'))) .mockImplementationOnce(() => { ctrl1.abort(); - return Promise.resolve(pollResponse([2])); + return Promise.resolve(pollResponse([2], 'tok-b')); }); - const resumeToken = await runLivePoll({ + await runLivePoll({ route: '/api/events', runId: 'run-1', startToken: '', signal: ctrl1.signal, + onToken: (token) => { + resumeToken = token; + }, onEvent: vi.fn().mockReturnValue(true), onNewEvents: vi.fn(), ...FAST, }); - // Resume: second poll run starts from the saved cursor. + expect(resumeToken).toBe('tok-b'); + const ctrl2 = new AbortController(); requestFromAPI.mockImplementationOnce(() => { ctrl2.abort(); @@ -654,10 +777,8 @@ describe('runLivePoll — pause/resume cursor', () => { ...FAST, }); - // The resumed poll sent the saved cursor as its first token. const secondCallToken = requestFromAPI.mock.calls[2]?.[1]?.token; - expect(secondCallToken).toBe(resumeToken || undefined); - // It delivered only the new event (event 3). + expect(secondCallToken).toBe('tok-b'); expect(onEvent2).toHaveBeenCalledTimes(1); expect(onEvent2.mock.calls[0][0].eventId).toBe('3'); }); diff --git a/src/lib/services/live-poll.ts b/src/lib/services/live-poll.ts index 790095ef22..5768d1f7f3 100644 --- a/src/lib/services/live-poll.ts +++ b/src/lib/services/live-poll.ts @@ -2,8 +2,13 @@ import type { GetWorkflowExecutionHistoryResponse, HistoryEvent, } from '$lib/types/events'; +import { handleUnauthorizedOrForbiddenError } from '$lib/utilities/handle-error'; import { isWorkflowCloseEvent } from '$lib/utilities/is-event-type'; -import { requestFromAPI } from '$lib/utilities/request-from-api'; +import { isNetworkError } from '$lib/utilities/is-network-error'; +import { + type ErrorCallback, + requestFromAPI, +} from '$lib/utilities/request-from-api'; export type LivePollOptions = { route: string; @@ -18,12 +23,24 @@ export type LivePollOptions = { onEvent: (ev: HistoryEvent) => boolean; /** Optional hook, called once per poll iteration that added new events. */ onNewEvents?: () => void; + onToken?: (token: string) => void; /** ms to wait when a long-poll times out with no new events. Default 2000. */ backoffMs?: number; - /** ms to wait after a network error before retrying. Default 5000. */ + /** ms to wait after a retryable error before retrying. Default 5000. */ errorBackoffMs?: number; }; +const handlePollError: ErrorCallback = (error) => { + handleUnauthorizedOrForbiddenError(error); + throw error; +}; + +const isRetryableError = (error: unknown): boolean => { + if (!isNetworkError(error)) return true; + const { statusCode } = error; + return statusCode === 408 || statusCode === 429 || statusCode >= 500; +}; + /** * Token-based long-poll loop for streaming new workflow history events. * @@ -34,15 +51,12 @@ export type LivePollOptions = { * continue immediately. * - nextPageToken absent, no new events (timeout) → reset token; back off * 2 s before retrying so we don't spin on an idle workflow. - * - Network error → back off 5 s and retry. + * - Network failure, 408, 429 or 5xx → back off 5 s and retry. + * - Any other error response → reject so the caller can surface it. * * The loop exits cleanly when `signal` is aborted or once it receives the * workflow's close event. */ -/** - * Returns the last cursor token when the loop exits (due to abort or error). - * The caller can save this token and pass it as `startToken` when resuming. - */ export async function runLivePoll({ route, runId, @@ -50,14 +64,30 @@ export async function runLivePoll({ signal, onEvent, onNewEvents, + onToken, backoffMs = 2000, errorBackoffMs = 5000, -}: LivePollOptions): Promise { +}: LivePollOptions): Promise { + const wait = (delay: number): Promise => { + if (signal.aborted) return Promise.resolve(); + return new Promise((resolve) => { + const finish = () => { + clearTimeout(timer); + signal.removeEventListener('abort', finish); + resolve(); + }; + const timer = setTimeout(finish, delay); + signal.addEventListener('abort', finish, { once: true }); + }); + }; + let token: string = startToken; while (!signal.aborted) { + let response: GetWorkflowExecutionHistoryResponse | undefined; try { - const response = - await requestFromAPI(route, { + response = await requestFromAPI( + route, + { token: token || undefined, request: fetch, params: { @@ -65,28 +95,32 @@ export async function runLivePoll({ waitNewEvent: 'true', }, options: { signal }, - }); - const events = (response?.history?.events ?? []) as HistoryEvent[]; - let added = 0; - for (const ev of events) { - if (onEvent(ev)) added++; - } - if (added > 0) onNewEvents?.(); - if (isWorkflowCloseEvent(events.at(-1))) break; + handleError: handlePollError, + }, + ); + } catch (error) { + if (signal.aborted) break; + if (!isRetryableError(error)) throw error; + await wait(errorBackoffMs); + continue; + } + const events = response?.history?.events ?? []; + let added = 0; + for (const ev of events) { + if (onEvent(ev)) added++; + } + if (added > 0) onNewEvents?.(); + if (isWorkflowCloseEvent(events.at(-1))) break; - if (response?.nextPageToken) { - token = response.nextPageToken as unknown as string; - } else { - token = ''; - if (added === 0) { - await new Promise((r) => setTimeout(r, backoffMs)); - } - } - } catch { - if (!signal.aborted) { - await new Promise((r) => setTimeout(r, errorBackoffMs)); + if (response?.nextPageToken) { + token = String(response.nextPageToken); + onToken?.(token); + } else { + token = ''; + onToken?.(token); + if (added === 0) { + await wait(backoffMs); } } } - return token; } diff --git a/src/lib/services/workflow-history-controller.svelte.test.ts b/src/lib/services/workflow-history-controller.svelte.test.ts new file mode 100644 index 0000000000..d30ac0c296 --- /dev/null +++ b/src/lib/services/workflow-history-controller.svelte.test.ts @@ -0,0 +1,536 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; + +import type { WorkflowExecution } from '$lib/types/workflows'; + +import { + fetchBidirectional, + type FetchBidirectionalParams, +} from './fetch-bidirectional'; +import { createGroupedEventBuffer } from './grouped-event-buffer'; +import { type LivePollOptions, runLivePoll } from './live-poll'; +import { + makeWorkflowCompleted, + makeWorkflowStarted, +} from './test-helpers/synthetic-events'; +import { WorkflowHistoryController } from './workflow-history-controller.svelte.js'; + +vi.mock('./fetch-bidirectional', () => ({ fetchBidirectional: vi.fn() })); +vi.mock('./live-poll', () => ({ runLivePoll: vi.fn() })); + +function deferred() { + let resolve: (value: T) => void = () => {}; + let reject: (error: Error) => void = () => {}; + const promise = new Promise((resolvePromise, rejectPromise) => { + resolve = resolvePromise; + reject = rejectPromise; + }); + return { promise, resolve, reject }; +} + +function workflow(runId = 'run-1', isRunning = false): WorkflowExecution { + return { + name: 'TestWorkflow', + id: 'workflow-1', + runId, + startTime: '2024-01-01T00:00:00Z', + endTime: '', + executionTime: '2024-01-01T00:00:00Z', + status: isRunning ? 'Running' : 'Completed', + historyEvents: '10', + historySizeBytes: '0', + externalPayloadCount: undefined, + externalPayloadSizeBytes: undefined, + memo: {}, + pendingChildren: [], + pendingNexusOperations: [], + pendingActivities: [], + stateTransitionCount: '0', + url: '', + isRunning, + isPaused: false, + canBeTerminated: isRunning, + callbacks: [], + workflowExtendedInfo: {}, + }; +} + +const requests: { + options: FetchBidirectionalParams; + result: ReturnType< + typeof deferred>> + >; +}[] = []; +const polls: { + options: LivePollOptions; + result: ReturnType>; +}[] = []; +const controllers: WorkflowHistoryController[] = []; + +function request(index: number) { + const value = requests[index]; + if (!value) throw new Error(`Missing history request ${index}`); + return value; +} + +function poll(index: number) { + const value = polls[index]; + if (!value) throw new Error(`Missing live poll ${index}`); + return value; +} + +function createController(runId = 'run-1') { + const buffer = createGroupedEventBuffer(); + const controller = new WorkflowHistoryController({ + workflowExecutionIdentity: { + namespace: 'default', + workflowId: 'workflow-1', + runId, + }, + buffer, + maximumPageSize: 20, + pauseAfterPages: 2, + }); + controllers.push(controller); + return { controller, buffer }; +} + +function progress(index: number, totalEstimated = 10, descMinId = 8) { + request(index).options.onProgress?.({ + descMinId, + totalEstimated, + }); +} + +beforeEach(() => { + requests.length = 0; + polls.length = 0; + vi.mocked(fetchBidirectional) + .mockReset() + .mockImplementation((options) => { + const result = deferred>>(); + requests.push({ options, result }); + return result.promise; + }); + vi.mocked(runLivePoll) + .mockReset() + .mockImplementation((options) => { + const result = deferred(); + polls.push({ options, result }); + return result.promise; + }); +}); + +afterEach(async () => { + for (const controller of controllers.splice(0)) controller.dispose(); + for (const { result } of requests) result.resolve(); + for (const { result } of polls) result.resolve(); + await Promise.all([ + ...requests.map(({ result }) => result.promise.catch(() => {})), + ...polls.map(({ result }) => result.promise.catch(() => {})), + ]); +}); + +describe('WorkflowHistoryController', () => { + it('isolates buffers, progress, completion, errors, and polling per controller', async () => { + const first = createController(); + const second = createController('run-2'); + const firstLoad = first.controller.load(workflow('run-1', true)); + const secondLoad = second.controller.load(workflow('run-2', true)); + + request(0).options.onRawPage([makeWorkflowStarted(1)]); + progress(0); + request(0).result.reject(new Error('history failed')); + request(1).result.resolve(); + await Promise.all([firstLoad, secondLoad]); + + expect(first.buffer.getEventArray().map((event) => event.id)).toEqual([ + '1', + ]); + expect(second.buffer.getEventArray()).toEqual([]); + expect(first.controller.totalExpectedEvents).toBe(10); + expect(second.controller.totalExpectedEvents).toBe(0); + expect(first.controller.fetchComplete).toBe(false); + expect(second.controller.fetchComplete).toBe(true); + expect(first.controller.error?.message).toBe('history failed'); + expect(second.controller.error).toBeNull(); + expect(poll(0).options.signal.aborted).toBe(false); + expect(poll(1).options.signal.aborted).toBe(false); + expect(request(1).options).toMatchObject({ + namespace: 'default', + workflowId: 'workflow-1', + runId: 'run-2', + maximumPageSize: 20, + pauseAfterPages: 2, + }); + }); + + it('retains partial history on error and recovers without resetting during retry', async () => { + const { controller, buffer } = createController(); + const load = controller.load(workflow()); + request(0).options.onRawPage([makeWorkflowStarted(1)]); + progress(0); + const failure = new Error('history unavailable'); + request(0).result.reject(failure); + await load; + + expect(controller.error).toBe(failure); + expect(controller.fetchComplete).toBe(false); + expect(controller.loading).toBe(false); + expect(buffer.getEventArray().map((event) => event.id)).toEqual(['1']); + + const retry = controller.retry(workflow()); + expect(controller.error).toBeNull(); + expect(controller.fetchComplete).toBe(false); + expect(controller.loading).toBe(true); + expect(controller.latestEventId).toBe(1); + expect(controller.totalExpectedEvents).toBe(10); + expect(controller.descMinId).toBe(8); + expect(buffer.getEventArray().map((event) => event.id)).toEqual(['1']); + + progress(1, 0, 0); + progress(1, 9, 9); + expect(controller.totalExpectedEvents).toBe(10); + expect(controller.descMinId).toBe(8); + request(1).options.onRawPage([makeWorkflowStarted(1)]); + request(1).options.onRawPage([makeWorkflowCompleted(10)]); + request(1).result.resolve(); + await retry; + await Promise.resolve(); + + expect(controller.history.events.map((event) => event.id)).toEqual([ + '1', + '10', + ]); + expect(controller.latestEventId).toBe(10); + expect(controller.fetchComplete).toBe(true); + expect(controller.loading).toBe(false); + expect(controller.error).toBeNull(); + }); + + it('surfaces poll processing errors without cancelling paused history or automatically restarting polling', async () => { + const { controller, buffer } = createController(); + const load = controller.load(workflow('run-1', true)); + const resume = vi.fn(); + request(0).options.onPause?.({ resume }); + expect(controller.loading).toBe(true); + const failure = new Error('poll processing failed'); + poll(0).result.reject(failure); + + await vi.waitFor(() => expect(controller.error).toBe(failure)); + + expect(controller.loading).toBe(true); + expect(controller.fetchComplete).toBe(false); + expect(request(0).options.signal?.aborted).toBe(false); + expect(poll(0).options.signal.aborted).toBe(true); + expect(resume).not.toHaveBeenCalled(); + controller.updateWorkflow(workflow('run-1', true)); + controller.setLiveUpdatesPaused(true); + controller.setLiveUpdatesPaused(false); + expect(polls).toHaveLength(1); + controller.resume(); + expect(resume).toHaveBeenCalledOnce(); + request(0).options.onRawPage([makeWorkflowStarted(1)]); + progress(0); + request(0).result.resolve(); + await load; + expect(buffer.getEventArray().map((event) => event.id)).toEqual(['1']); + expect(controller.totalExpectedEvents).toBe(10); + expect(controller.error).toBe(failure); + expect(controller.fetchComplete).toBe(true); + expect(controller.loading).toBe(false); + expect(polls).toHaveLength(1); + }); + + it('keeps polling, token updates, and close detection alive after history fails', async () => { + const { controller, buffer } = createController(); + const load = controller.load(workflow('run-1', true)); + const resume = vi.fn(); + request(0).options.onPause?.({ resume }); + const failure = new Error('history failed'); + request(0).result.reject(failure); + await load; + + expect(controller.loading).toBe(false); + expect(controller.fetchComplete).toBe(false); + expect(request(0).options.signal?.aborted).toBe(true); + expect(poll(0).options.signal.aborted).toBe(false); + expect(resume).toHaveBeenCalledOnce(); + request(0).options.onRawPage([makeWorkflowStarted(2)]); + progress(0); + expect(buffer.getEventArray()).toEqual([]); + expect(controller.totalExpectedEvents).toBe(0); + expect(poll(0).options.onEvent(makeWorkflowStarted(1))).toBe(true); + poll(0).options.onToken?.('healthy-token'); + expect(controller.latestEventId).toBe(1); + expect(controller.error).toBe(failure); + expect(poll(0).options.onEvent(makeWorkflowCompleted(10))).toBe(true); + expect(poll(0).options.signal.aborted).toBe(true); + poll(0).result.resolve(); + await vi.waitFor(() => expect(polls).toHaveLength(1)); + expect(buffer.getEventArray().map((event) => event.id)).toEqual([ + '1', + '10', + ]); + expect(controller.fetchComplete).toBe(false); + expect(controller.error).toBe(failure); + }); + + it('retries poll processing from the last acknowledged token and preserves buffered events', async () => { + const { controller, buffer } = createController(); + vi.mocked(runLivePoll).mockImplementationOnce((options) => { + const result = deferred(); + polls.push({ options, result }); + return result.promise.then(() => { + options.onEvent(makeWorkflowStarted(2)); + }); + }); + const load = controller.load(workflow('run-1', true)); + poll(0).options.onEvent(makeWorkflowStarted(1)); + poll(0).options.onToken?.('acknowledged-token'); + request(0).result.resolve(); + await load; + const failure = new Error('event processing failed'); + const ingest = vi + .spyOn(buffer, 'ingestHistoryEvent') + .mockImplementationOnce(() => { + throw failure; + }); + poll(0).result.resolve(); + await vi.waitFor(() => expect(controller.error).toBe(failure)); + ingest.mockRestore(); + expect(controller.fetchComplete).toBe(true); + expect(controller.loading).toBe(false); + controller.updateWorkflow(workflow('run-1', true)); + controller.setLiveUpdatesPaused(false); + expect(polls).toHaveLength(1); + + const retry = controller.retry(workflow('run-1', true)); + expect(controller.error).toBeNull(); + expect(controller.loading).toBe(true); + expect(poll(1).options.startToken).toBe('acknowledged-token'); + expect(poll(1).options.onEvent(makeWorkflowStarted(2))).toBe(true); + expect(buffer.getEventArray().map((event) => event.id)).toEqual(['1', '2']); + request(1).result.resolve(); + await retry; + expect(controller.fetchComplete).toBe(true); + expect(controller.error).toBeNull(); + }); + + it.each(['history-first', 'poll-first'])( + 'settles independent failures in %s order without restarting either operation', + async (order) => { + const { controller } = createController(); + const load = controller.load(workflow('run-1', true)); + const historyFailure = new Error('history failed'); + const pollFailure = new Error('poll failed'); + if (order === 'history-first') { + request(0).result.reject(historyFailure); + await load; + expect(controller.error).toBe(historyFailure); + poll(0).result.reject(pollFailure); + await vi.waitFor(() => expect(controller.error).toBe(pollFailure)); + } else { + poll(0).result.reject(pollFailure); + await vi.waitFor(() => expect(controller.error).toBe(pollFailure)); + expect(controller.loading).toBe(true); + request(0).result.reject(historyFailure); + await load; + expect(controller.error).toBe(historyFailure); + } + expect(controller.fetchComplete).toBe(false); + expect(controller.loading).toBe(false); + controller.updateWorkflow(workflow('run-1', true)); + controller.setLiveUpdatesPaused(false); + expect(requests).toHaveLength(1); + expect(polls).toHaveLength(1); + }, + ); + + it('resets buffered history, progress, completion, and the saved poll token on a fresh load', async () => { + const { controller, buffer } = createController(); + const load = controller.load(workflow('run-1', true)); + request(0).options.onRawPage([makeWorkflowStarted(1)]); + progress(0); + poll(0).options.onEvent(makeWorkflowStarted(2)); + poll(0).options.onToken?.('old-token'); + request(0).result.resolve(); + await load; + expect(buffer.getEventArray().map((event) => event.id)).toEqual(['1', '2']); + expect(controller.latestEventId).toBe(2); + expect(controller.totalExpectedEvents).toBe(10); + expect(controller.descMinId).toBe(8); + expect(controller.fetchComplete).toBe(true); + + const nextLoad = controller.load(workflow('run-1', true)); + expect(poll(0).options.signal.aborted).toBe(true); + expect(poll(1).options.startToken).toBe(''); + expect(buffer.getEventArray()).toEqual([]); + expect(controller.latestEventId).toBe(0); + expect(controller.totalExpectedEvents).toBe(0); + expect(controller.descMinId).toBe(0); + expect(controller.fetchComplete).toBe(false); + request(1).result.resolve(); + await nextLoad; + }); + + it('rejects mismatched retry identity without stopping the current session', async () => { + const { controller } = createController(); + const load = controller.load(workflow('run-1', true)); + await expect(controller.retry(workflow('run-2'))).rejects.toThrow( + 'Workflow does not match this history controller.', + ); + await expect( + controller.retry({ ...workflow(), id: 'other' }), + ).rejects.toThrow('Workflow does not match this history controller.'); + expect(requests).toHaveLength(1); + expect(request(0).options.signal?.aborted).toBe(false); + expect(poll(0).options.signal.aborted).toBe(false); + request(0).result.resolve(); + await load; + }); + + it('ignores stale history and poll callbacks and stale completion after retry', async () => { + const { controller, buffer } = createController(); + const load = controller.load(workflow('run-1', true)); + const resume = vi.fn(); + request(0).options.onPause?.({ resume }); + poll(0).options.onToken?.('saved-token'); + const retry = controller.retry(workflow('run-1', true)); + expect(resume).toHaveBeenCalledOnce(); + expect(request(0).options.signal?.aborted).toBe(true); + expect(poll(0).options.signal.aborted).toBe(true); + + request(0).options.onRawPage([makeWorkflowCompleted(10)]); + progress(0); + const staleResume = vi.fn(); + request(0).options.onPause?.({ resume: staleResume }); + expect(staleResume).toHaveBeenCalledOnce(); + expect(poll(0).options.onEvent(makeWorkflowCompleted(10))).toBe(false); + poll(0).options.onToken?.('stale-token'); + request(0).result.resolve(); + poll(0).result.resolve(); + await load; + await Promise.resolve(); + + expect(buffer.getEventArray()).toEqual([]); + expect(controller.totalExpectedEvents).toBe(0); + expect(controller.fetchComplete).toBe(false); + expect(controller.error).toBeNull(); + expect(polls).toHaveLength(2); + expect(poll(1).options.startToken).toBe('saved-token'); + request(1).result.resolve(); + await retry; + }); + + it('ignores stale history and poll errors after retry', async () => { + const { controller } = createController(); + const load = controller.load(workflow('run-1', true)); + const retry = controller.retry(workflow('run-1', true)); + request(0).result.reject(new Error('stale history')); + poll(0).result.reject(new Error('stale poll')); + await load; + await Promise.resolve(); + expect(controller.error).toBeNull(); + expect(request(1).options.signal?.aborted).toBe(false); + request(1).result.resolve(); + await retry; + }); + + it('keeps resume demand sticky across retries but isolated per controller', async () => { + const { controller } = createController(); + const other = createController('run-2').controller; + const load = controller.load(workflow()); + const otherLoad = other.load(workflow('run-2')); + const resume = vi.fn(); + const otherResume = vi.fn(); + request(0).options.onPause?.({ resume }); + request(1).options.onPause?.({ resume: otherResume }); + controller.resume(); + expect(resume).toHaveBeenCalledOnce(); + expect(otherResume).not.toHaveBeenCalled(); + + request(0).result.reject(new Error('retry required')); + await load; + const retry = controller.retry(workflow()); + const retryResume = vi.fn(); + request(2).options.onPause?.({ resume: retryResume }); + expect(retryResume).toHaveBeenCalledOnce(); + other.resume(); + expect(otherResume).toHaveBeenCalledOnce(); + request(1).result.resolve(); + request(2).result.resolve(); + await Promise.all([otherLoad, retry]); + }); + + it('resumes live updates per controller with its own saved poll token', async () => { + const first = createController().controller; + const second = createController('run-2').controller; + const firstLoad = first.load(workflow('run-1', true)); + const secondLoad = second.load(workflow('run-2', true)); + poll(0).options.onToken?.('first-token'); + poll(1).options.onToken?.('second-token'); + first.setLiveUpdatesPaused(true); + expect(poll(0).options.signal.aborted).toBe(true); + expect(poll(1).options.signal.aborted).toBe(false); + poll(0).result.resolve(); + await vi.waitFor(() => expect(polls).toHaveLength(2)); + first.setLiveUpdatesPaused(false); + await vi.waitFor(() => expect(polls).toHaveLength(3)); + expect(poll(2).options.startToken).toBe('first-token'); + expect(poll(2).options.runId).toBe('run-1'); + request(0).result.resolve(); + request(1).result.resolve(); + await Promise.all([firstLoad, secondLoad]); + }); + + it('does not repoll observed closed history after a failed session and retry', async () => { + const { controller } = createController(); + const load = controller.load(workflow('run-1', true)); + request(0).options.onRawPage([makeWorkflowCompleted(10)]); + expect(poll(0).options.signal.aborted).toBe(true); + request(0).result.reject(new Error('missing middle history')); + await load; + + const retry = controller.retry(workflow('run-1', true)); + controller.updateWorkflow(workflow('run-1', true)); + controller.setLiveUpdatesPaused(false); + poll(0).result.resolve(); + await Promise.resolve(); + expect(polls).toHaveLength(1); + request(1).result.resolve(); + await retry; + expect(controller.fetchComplete).toBe(true); + }); + + it('disposes idempotently, releases pauses, ignores callbacks, and rejects loads', async () => { + const { controller, buffer } = createController(); + const disposeHistory = vi.spyOn(controller.history, 'dispose'); + const load = controller.load(workflow('run-1', true)); + const resume = vi.fn(); + request(0).options.onPause?.({ resume }); + controller.dispose(); + controller.dispose(); + expect(disposeHistory).toHaveBeenCalledOnce(); + expect(resume).toHaveBeenCalledOnce(); + expect(request(0).options.signal?.aborted).toBe(true); + expect(poll(0).options.signal.aborted).toBe(true); + request(0).options.onRawPage([makeWorkflowStarted(1)]); + progress(0); + expect(poll(0).options.onEvent(makeWorkflowStarted(1))).toBe(false); + request(0).result.resolve(); + await load; + controller.resume(); + controller.updateWorkflow(workflow('run-1', true)); + controller.setLiveUpdatesPaused(false); + expect(buffer.getEventArray()).toEqual([]); + expect(controller.loading).toBe(false); + expect(controller.fetchComplete).toBe(false); + expect(resume).toHaveBeenCalledOnce(); + const lateResume = vi.fn(); + request(0).options.onPause?.({ resume: lateResume }); + expect(lateResume).toHaveBeenCalledOnce(); + expect(polls).toHaveLength(1); + await expect(controller.load(workflow())).rejects.toThrow('disposed'); + await expect(controller.retry(workflow())).rejects.toThrow('disposed'); + }); +}); diff --git a/src/lib/services/workflow-history-controller.svelte.ts b/src/lib/services/workflow-history-controller.svelte.ts new file mode 100644 index 0000000000..975b1f555b --- /dev/null +++ b/src/lib/services/workflow-history-controller.svelte.ts @@ -0,0 +1,321 @@ +import { createContext } from 'svelte'; + +import type { HistoryEvent } from '$lib/types/events'; +import type { NetworkError } from '$lib/types/global'; +import type { + WorkflowExecution, + WorkflowExecutionIdentity, +} from '$lib/types/workflows'; +import { getErrorMessage } from '$lib/utilities/error-message'; +import { isWorkflowCloseEvent } from '$lib/utilities/is-event-type'; +import { isNetworkError } from '$lib/utilities/is-network-error'; +import { routeForApi } from '$lib/utilities/route-for-api'; + +import { fetchBidirectional, type PauseHandle } from './fetch-bidirectional'; +import { + createGroupedEventBuffer, + type GroupedEventBuffer, +} from './grouped-event-buffer'; +import { runLivePoll } from './live-poll'; + +import { EventBufferView } from './grouped-event-buffer.svelte'; + +export const [getWorkflowHistoryController, setWorkflowHistoryController] = + createContext(); + +type HistoryLoadSession = { + controller: AbortController; + livePollController: AbortController | null; + livePollTask: Promise | null; + livePollFailed: boolean; + lastPollToken: string; + workflowWasRunning: boolean; +}; + +type WorkflowHistoryControllerOptions = { + workflowExecutionIdentity: WorkflowExecutionIdentity; + buffer?: GroupedEventBuffer; + maximumPageSize?: number; + pauseAfterPages?: number; + liveUpdatesPaused?: boolean; +}; + +export class WorkflowHistoryController { + readonly workflowExecutionIdentity: Readonly; + readonly history: EventBufferView; + + fetchComplete = $state(false); + latestEventId = $state(0); + totalExpectedEvents = $state(0); + descMinId = $state(0); + error = $state.raw(null); + + private started = $state(false); + private disposed = false; + private historyRequested = false; + private historyClosed = false; + private liveUpdatesPaused: boolean; + private pauseHandle: PauseHandle | null = null; + private session: HistoryLoadSession | null = null; + private readonly buffer: GroupedEventBuffer; + private readonly maximumPageSize: number; + private readonly pauseAfterPages: number | undefined; + + constructor({ + workflowExecutionIdentity, + buffer = createGroupedEventBuffer(), + maximumPageSize = 1000, + pauseAfterPages, + liveUpdatesPaused = false, + }: WorkflowHistoryControllerOptions) { + const { namespace, workflowId, runId } = workflowExecutionIdentity; + if (!namespace || !workflowId || !runId) { + throw new Error( + 'Workflow history requires a namespace, Workflow ID, and Run ID.', + ); + } + this.workflowExecutionIdentity = Object.freeze({ + ...workflowExecutionIdentity, + }); + this.buffer = buffer; + this.history = new EventBufferView(buffer); + this.maximumPageSize = maximumPageSize; + this.pauseAfterPages = pauseAfterPages; + this.liveUpdatesPaused = liveUpdatesPaused; + } + + get loading(): boolean { + return this.started && !this.fetchComplete; + } + + load(workflow: WorkflowExecution): Promise { + return this.loadHistory(workflow, { preserveHistory: false }); + } + + retry(workflow: WorkflowExecution): Promise { + return this.loadHistory(workflow, { preserveHistory: true }); + } + + private async loadHistory( + workflow: WorkflowExecution, + { preserveHistory }: { preserveHistory: boolean }, + ): Promise { + if (this.disposed) + throw new Error('Cannot load a disposed workflow history.'); + this.verifyWorkflow(workflow); + const lastPollToken = preserveHistory + ? (this.session?.lastPollToken ?? '') + : ''; + this.stopSession(); + + this.fetchComplete = false; + this.error = null; + this.started = true; + if (!preserveHistory) { + this.latestEventId = 0; + this.totalExpectedEvents = 0; + this.descMinId = 0; + this.historyClosed = false; + this.buffer.reset(parseInt(workflow.historyEvents ?? '0') || 0); + } + this.buffer.setPendingMetadata( + workflow.pendingActivities ?? [], + workflow.pendingNexusOperations ?? [], + ); + + const session: HistoryLoadSession = { + controller: new AbortController(), + livePollController: null, + livePollTask: null, + livePollFailed: false, + lastPollToken, + workflowWasRunning: workflow.isRunning, + }; + this.session = session; + this.startLivePoll(session); + + try { + await fetchBidirectional({ + ...this.workflowExecutionIdentity, + signal: session.controller.signal, + maximumPageSize: this.maximumPageSize, + pauseAfterPages: this.pauseAfterPages, + onProgress: (progress) => { + if (!this.isCurrent(session) || session.controller.signal.aborted) + return; + this.totalExpectedEvents = Math.max( + this.totalExpectedEvents, + progress.totalEstimated, + ); + if (progress.descMinId > 0) { + this.descMinId = this.descMinId + ? Math.min(this.descMinId, progress.descMinId) + : progress.descMinId; + } + }, + onPause: (handle) => { + if ( + !this.isCurrent(session) || + session.controller.signal.aborted || + this.historyRequested + ) { + handle.resume(); + return; + } + this.pauseHandle = handle; + }, + onRawPage: (events) => { + if (!this.isCurrent(session) || session.controller.signal.aborted) + return; + for (const event of events) this.ingestEvent(event, session); + }, + }); + if (this.isCurrent(session)) { + this.pauseHandle = null; + this.fetchComplete = true; + } + } catch (error) { + if (!this.isCurrent(session)) return; + this.error = + error instanceof Error || isNetworkError(error) + ? error + : new Error(getErrorMessage(error)); + session.controller.abort(); + const handle = this.pauseHandle; + this.pauseHandle = null; + handle?.resume(); + } finally { + if (this.isCurrent(session)) this.started = false; + } + } + + updateWorkflow(workflow: WorkflowExecution): void { + if (this.disposed) return; + this.verifyWorkflow(workflow); + this.buffer.setPendingMetadata( + workflow.pendingActivities ?? [], + workflow.pendingNexusOperations ?? [], + ); + const session = this.session; + if (!session) return; + session.workflowWasRunning ||= workflow.isRunning; + this.startLivePoll(session); + } + + setLiveUpdatesPaused(paused: boolean): void { + if (this.disposed) return; + this.liveUpdatesPaused = paused; + const session = this.session; + if (!session) return; + if (paused) { + session.livePollController?.abort(); + return; + } + this.startLivePoll(session); + } + + resume(): void { + if (this.disposed) return; + this.historyRequested = true; + const handle = this.pauseHandle; + this.pauseHandle = null; + handle?.resume(); + } + + dispose(): void { + if (this.disposed) return; + this.disposed = true; + this.started = false; + this.stopSession(); + this.history.dispose(); + } + + private verifyWorkflow(workflow: WorkflowExecution): void { + if ( + workflow.id !== this.workflowExecutionIdentity.workflowId || + workflow.runId !== this.workflowExecutionIdentity.runId + ) { + throw new Error('Workflow does not match this history controller.'); + } + } + + private isCurrent(session: HistoryLoadSession): boolean { + return !this.disposed && this.session === session; + } + + private canPoll(session: HistoryLoadSession): boolean { + return ( + this.isCurrent(session) && + !this.liveUpdatesPaused && + !session.livePollFailed && + session.workflowWasRunning && + !this.historyClosed + ); + } + + private ingestEvent( + event: HistoryEvent, + session: HistoryLoadSession, + ): boolean { + if (!this.isCurrent(session)) return false; + const isNew = this.buffer.ingestHistoryEvent(event); + this.latestEventId = Math.max( + this.latestEventId, + parseInt(event.eventId) || 0, + ); + if (isWorkflowCloseEvent(event)) { + this.historyClosed = true; + session.livePollController?.abort(); + } + return isNew; + } + + private startLivePoll(session: HistoryLoadSession): void { + if (!this.canPoll(session) || session.livePollTask) return; + const controller = new AbortController(); + session.livePollController = controller; + session.livePollTask = runLivePoll({ + route: routeForApi('events.ascending', this.workflowExecutionIdentity), + runId: this.workflowExecutionIdentity.runId, + startToken: session.lastPollToken, + signal: controller.signal, + onEvent: (event) => { + if (controller.signal.aborted) return false; + return this.ingestEvent(event, session); + }, + onToken: (token) => { + if (this.isCurrent(session) && !controller.signal.aborted) { + session.lastPollToken = token; + } + }, + }) + .then(() => { + if (!this.isCurrent(session) || controller.signal.aborted) return; + this.historyClosed = true; + }) + .catch((error) => { + if (!this.isCurrent(session) || controller.signal.aborted) return; + this.error = + error instanceof Error || isNetworkError(error) + ? error + : new Error(getErrorMessage(error)); + session.livePollFailed = true; + controller.abort(); + }) + .finally(() => { + session.livePollTask = null; + session.livePollController = null; + if (controller.signal.aborted) this.startLivePoll(session); + }); + } + + private stopSession(): void { + const session = this.session; + this.session = null; + session?.controller.abort(); + session?.livePollController?.abort(); + const handle = this.pauseHandle; + this.pauseHandle = null; + handle?.resume(); + } +} diff --git a/src/lib/stores/active-events.ts b/src/lib/stores/active-events.ts deleted file mode 100644 index 5b4f8bba98..0000000000 --- a/src/lib/stores/active-events.ts +++ /dev/null @@ -1,31 +0,0 @@ -import { get, writable } from 'svelte/store'; - -import type { EventGroup } from '$lib/models/event-groups/event-groups'; - -export const indexPageSize = 200; -export const startIndex = writable(0); -export const endIndex = writable(indexPageSize); - -export const activeGroups = writable([]); -export const activeGroupHeight = writable(0); - -export const clearActives = () => { - activeGroups.set([]); - activeGroupHeight.set(0); - startIndex.set(0); - endIndex.set(indexPageSize); -}; - -export const clearActiveGroups = () => { - activeGroups.set([]); - activeGroupHeight.set(0); -}; - -export const setActiveGroup = (group: EventGroup) => { - if (!get(activeGroups).includes(group.id)) { - activeGroups.set([group.id]); - } else { - activeGroupHeight.set(0); - activeGroups.set([]); - } -}; diff --git a/src/lib/stores/events.ts b/src/lib/stores/events.ts index a12302eea2..5afeaf7026 100644 --- a/src/lib/stores/events.ts +++ b/src/lib/stores/events.ts @@ -3,21 +3,9 @@ import { derived, type Readable, writable } from 'svelte/store'; import { page } from '$app/stores'; import type { FetchEventsParameters } from '$lib/services/events-service'; -import { getEventArray } from '$lib/services/grouped-event-buffer'; -import { bufferVersion } from '$lib/services/grouped-event-buffer.svelte'; -import type { - WorkflowEvents, - WorkflowTaskCompletedEvent, -} from '$lib/types/events'; import { decodeURIForSvelte } from '$lib/utilities/encode-uri'; -import { getSDKandVersion } from '$lib/utilities/get-sdk-version'; -import { - isResetEvent, - isWorkflowTaskCompletedEvent, -} from '$lib/utilities/is-event-type'; import { eventFilterSort } from './event-view'; -import { eventTypeFilter } from './filters'; import { persistStore } from './persist-store'; const namespace = derived([page], ([$page]) => { @@ -53,37 +41,8 @@ export const parameters: Readable = derived( }, ); -export const timelineEvents = writable(null); - export const pauseLiveUpdates = writable(false); -/** - * Flat view of all workflow events sourced from the grouped-event-buffer. - * Updated by workflow-run-layout — elements are the same WorkflowEvent - * instances the buffer stores (shallow pointer array, not a copy). - * Writable so standalone pages (e.g. workflow-history-event) can populate it - * independently via fetchAllEvents. - */ -export const fullEventHistory = writable([]); - -export const resetEvents = derived(bufferVersion, () => - getEventArray().filter(isResetEvent), -); - -export const sdkInfo = derived(bufferVersion, () => - getSDKandVersion( - getEventArray().filter( - isWorkflowTaskCompletedEvent, - ) as WorkflowTaskCompletedEvent[], - ), -); - -export const filteredEventHistory = derived( - [bufferVersion, eventTypeFilter], - ([, $types]) => - getEventArray().filter((event) => $types.includes(event.category)), -); - export const decodeEventHistory = persistStore( 'decodeEventHistory', true, diff --git a/src/lib/types/workflows.ts b/src/lib/types/workflows.ts index 9e8ac90f82..3653656d51 100644 --- a/src/lib/types/workflows.ts +++ b/src/lib/types/workflows.ts @@ -19,6 +19,12 @@ import type { } from './events'; import type { Optional, Replace } from './global'; +export type WorkflowExecutionIdentity = { + namespace: string; + workflowId: string; + runId: string; +}; + /** * Type-level equivalent of `fromScreamingEnum`: converts a SCREAMING_SNAKE_CASE * enum key to PascalCase and strips the given prefix. diff --git a/src/routes/(app)/import/events/[namespace]/[workflow]/[run]/history/compact/+page.svelte b/src/routes/(app)/import/events/[namespace]/[workflow]/[run]/history/compact/+page.svelte index 799e1265be..5f13436051 100644 --- a/src/routes/(app)/import/events/[namespace]/[workflow]/[run]/history/compact/+page.svelte +++ b/src/routes/(app)/import/events/[namespace]/[workflow]/[run]/history/compact/+page.svelte @@ -1,9 +1,19 @@ - + diff --git a/src/routes/(app)/import/events/[namespace]/[workflow]/[run]/history/feed/+page.svelte b/src/routes/(app)/import/events/[namespace]/[workflow]/[run]/history/feed/+page.svelte index c389484338..30e4681e72 100644 --- a/src/routes/(app)/import/events/[namespace]/[workflow]/[run]/history/feed/+page.svelte +++ b/src/routes/(app)/import/events/[namespace]/[workflow]/[run]/history/feed/+page.svelte @@ -1,9 +1,19 @@ - + diff --git a/src/routes/(app)/namespaces/[namespace]/archival/[workflow]/[run]/history/+page.svelte b/src/routes/(app)/namespaces/[namespace]/archival/[workflow]/[run]/history/+page.svelte index 587089cbbe..6486466ac2 100644 --- a/src/routes/(app)/namespaces/[namespace]/archival/[workflow]/[run]/history/+page.svelte +++ b/src/routes/(app)/namespaces/[namespace]/archival/[workflow]/[run]/history/+page.svelte @@ -10,10 +10,17 @@ import { translate } from '$lib/i18n/translate'; import { IconChevronLeft } from '$lib/io/icon'; import { groupEvents } from '$lib/models/event-groups'; + import type { WorkflowExecutionIdentity } from '$lib/types/workflows'; + import { isWorkflowExecutionStartedEvent } from '$lib/utilities/is-event-type'; import { routeForArchivalWorkflows } from '$lib/utilities/route-for'; let { data }: { data: PageData } = $props(); + const workflowExecutionIdentity: WorkflowExecutionIdentity = $derived({ + namespace: page.params.namespace, + workflowId: page.params.workflow, + runId: page.params.run, + }); const workflowId = $derived(page.params.workflow); const workflowsHref = $derived( routeForArchivalWorkflows({ namespace: page.params.namespace }), @@ -43,7 +50,13 @@ {:then history} {@const groups = groupEvents(history, 'ascending', [], [])} - + {:catch error}

diff --git a/src/routes/(app)/namespaces/[namespace]/workflows/[workflow]/[run]/history/events/[eventId]/+page.svelte b/src/routes/(app)/namespaces/[namespace]/workflows/[workflow]/[run]/history/events/[eventId]/+page.svelte index d8116e18c6..40034c5f98 100644 --- a/src/routes/(app)/namespaces/[namespace]/workflows/[workflow]/[run]/history/events/[eventId]/+page.svelte +++ b/src/routes/(app)/namespaces/[namespace]/workflows/[workflow]/[run]/history/events/[eventId]/+page.svelte @@ -16,9 +16,4 @@ )} | ${params.workflow} | Event ${params.eventId}`} url={page.url.href} /> - + diff --git a/src/routes/(app)/namespaces/[namespace]/workflows/[workflow]/[run]/workers/+page.svelte b/src/routes/(app)/namespaces/[namespace]/workflows/[workflow]/[run]/workers/+page.svelte index 71735f84cd..587367d9b4 100644 --- a/src/routes/(app)/namespaces/[namespace]/workflows/[workflow]/[run]/workers/+page.svelte +++ b/src/routes/(app)/namespaces/[namespace]/workflows/[workflow]/[run]/workers/+page.svelte @@ -4,8 +4,10 @@ import PageTitle from '$lib/components/page-title.svelte'; import WorkersTable from '$lib/components/workers/workers-table/task-queue-workers-table.svelte'; import { translate } from '$lib/i18n/translate'; + import { getWorkflowHistoryController } from '$lib/services/workflow-history-controller.svelte.js'; import { workflowRun } from '$lib/stores/workflow-run'; + const historyController = getWorkflowHistoryController(); const { namespace, workflow: workflowId } = $derived(page.params); const taskQueue = $derived($workflowRun?.workflow?.taskQueue ?? ''); const workerHeartbeatsEnabled = $derived( @@ -20,6 +22,7 @@ ($workflowRun.workerCount = count)} /> diff --git a/tests/integration/workflow-event-detail-live.spec.ts b/tests/integration/workflow-event-detail-live.spec.ts new file mode 100644 index 0000000000..e8d860e5cc --- /dev/null +++ b/tests/integration/workflow-event-detail-live.spec.ts @@ -0,0 +1,278 @@ +import { expect, type Page, test } from '@playwright/test'; + +import { + makeActivityCompleted, + makeActivityScheduled, + makeActivityStarted, + makeWorkflowStarted, +} from '$src/lib/services/test-helpers/synthetic-events'; +import type { HistoryEvent } from '$src/lib/types/events'; +import type { WorkflowExecutionAPIResponse } from '$src/lib/types/workflows'; +import { mockWorkflowApis } from '~/test-utilities/mock-apis'; +import { + EVENT_HISTORY_API, + EVENT_HISTORY_API_REVERSE, +} from '~/test-utilities/mocks/event-history'; +import { mockWorkflow } from '~/test-utilities/mocks/workflow'; + +const { workflowId, runId } = mockWorkflow.workflowExecutionInfo.execution; +const eventUrl = (eventId: string) => + `/namespaces/default/workflows/${workflowId}/${runId}/history/events/${eventId}`; + +const runningWorkflow = { + ...mockWorkflow, + workflowExecutionInfo: { + ...mockWorkflow.workflowExecutionInfo, + status: 'Running', + closeTime: '', + }, + pendingActivities: [], + pendingChildren: [], +}; + +const historyPage = (events: HistoryEvent[]) => ({ + history: { events }, + rawHistory: [], + nextPageToken: null, + archived: false, +}); + +function gate() { + let release = () => {}; + const promise = new Promise((resolve) => { + release = resolve; + }); + return { promise, release }; +} + +async function mockEventDetail( + page: Page, + initialEvents: HistoryEvent[], + liveEvents: HistoryEvent[] = [], + workflow: WorkflowExecutionAPIResponse = runningWorkflow, + reverseEvents = [...initialEvents].reverse(), +) { + const initialResponse = gate(); + const liveResponse = gate(); + const liveRequested = gate(); + const requests = { initial: 0, reverse: 0, live: 0, navigation: 0 }; + + page.on('framenavigated', (frame) => { + if (frame === page.mainFrame()) requests.navigation += 1; + }); + await mockWorkflowApis(page, workflow); + await page.route(EVENT_HISTORY_API, async (route) => { + if ( + new URL(route.request().url()).searchParams.get('waitNewEvent') === 'true' + ) { + requests.live += 1; + if (requests.live === 1) { + liveRequested.release(); + await liveResponse.promise; + return route.fulfill({ json: historyPage(liveEvents) }); + } + return route.fulfill({ json: historyPage([]) }); + } + requests.initial += 1; + await initialResponse.promise; + return route.fulfill({ json: historyPage(initialEvents) }); + }); + await page.route(EVENT_HISTORY_API_REVERSE, async (route) => { + requests.reverse += 1; + if (reverseEvents.length < initialEvents.length) { + if (requests.reverse === 1) { + return route.fulfill({ + json: { + ...historyPage(reverseEvents), + nextPageToken: 'older-events', + }, + }); + } + await initialResponse.promise; + return route.fulfill({ + json: historyPage([...initialEvents].reverse()), + }); + } + return route.fulfill({ json: historyPage(reverseEvents) }); + }); + + return { initialResponse, liveResponse, liveRequested, requests }; +} + +function visibleIds(page: Page) { + return page + .getByTestId('event-summary-log') + .getByTestId('event-summary-row') + .evaluateAll((rows) => rows.map((row) => row.getAttribute('data-eventid'))); +} + +test.describe('Workflow event detail live history', () => { + for (const requestId of ['request-for-started-activity', '123-request-id']) { + test(`resolves ${requestId} and paginates from its event`, async ({ + page, + }) => { + const events = [ + makeWorkflowStarted(1), + makeActivityScheduled(2, 'RequestIdActivity'), + makeActivityStarted(3, 2), + makeActivityScheduled(4), + makeActivityScheduled(5), + ]; + const { initialResponse, liveResponse } = await mockEventDetail( + page, + events, + [], + { + ...runningWorkflow, + workflowExtendedInfo: { + requestIdInfos: { [requestId]: { eventId: '3' } }, + }, + }, + ); + try { + initialResponse.release(); + await page.goto(eventUrl(requestId)); + + await expect.poll(() => visibleIds(page)).toEqual(['3']); + const details = page.getByTestId('event-summary-row-expanded'); + await expect(details).toHaveCount(1); + await expect( + details.getByText('Activity Task Scheduled', { exact: true }), + ).toBeVisible(); + await expect( + details.getByText('Activity Task Started', { exact: true }), + ).toBeVisible(); + await expect(details).toContainText('RequestIdActivity'); + await page.getByTestId('load-previous').click(); + await expect.poll(() => visibleIds(page)).toEqual(['1', '2', '3']); + await expect(page.getByTestId('load-previous')).toBeDisabled(); + await page.getByTestId('load-next').click(); + await expect + .poll(() => visibleIds(page)) + .toEqual(['1', '2', '3', '4', '5']); + await expect(page.getByTestId('load-next')).toBeDisabled(); + await expect(page).toHaveURL(eventUrl(requestId)); + } finally { + initialResponse.release(); + liveResponse.release(); + } + }); + } + + test('shows ordered ten-ID ranges with gaps and enables Next when the live tail grows', async ({ + page, + }) => { + const ids = [1, 2, 5, 10, 11, 13, 19, 20, 21, 24, 29, 30, 31]; + const events = ids.map((id) => + id === 1 ? makeWorkflowStarted(id) : makeActivityScheduled(id), + ); + const { initialResponse, liveResponse, liveRequested, requests } = + await mockEventDetail(page, events, [makeActivityScheduled(35)]); + try { + initialResponse.release(); + await page.goto(eventUrl('11')); + await expect.poll(() => visibleIds(page)).toEqual(['11']); + await liveRequested.promise; + await expect.poll(() => requests.initial).toBe(1); + await expect.poll(() => requests.reverse).toBe(1); + const before = { ...requests }; + + await page.getByTestId('load-previous').click(); + await expect + .poll(() => visibleIds(page)) + .toEqual(['1', '2', '5', '10', '11']); + await expect(page.getByTestId('load-previous')).toBeDisabled(); + + await page.getByTestId('load-next').click(); + await expect + .poll(() => visibleIds(page)) + .toEqual(['1', '2', '5', '10', '11', '13', '19', '20', '21']); + await page.getByTestId('load-next').click(); + await expect.poll(() => visibleIds(page)).toEqual(ids.map(String)); + await expect(page.getByTestId('load-next')).toBeDisabled(); + + liveResponse.release(); + await expect(page.getByTestId('load-next')).toBeEnabled(); + await page.getByTestId('load-next').click(); + await expect + .poll(() => visibleIds(page)) + .toEqual([...ids, 35].map(String)); + await expect(page.getByTestId('load-next')).toBeDisabled(); + expect(requests.initial).toBe(before.initial); + expect(requests.reverse).toBe(before.reverse); + expect(requests.navigation).toBe(before.navigation); + await expect(page).toHaveURL(eventUrl('11')); + } finally { + initialResponse.release(); + liveResponse.release(); + } + }); + + test('keeps a follower expanded while its head and live completion join the group', async ({ + page, + }) => { + const started = makeActivityStarted(3, 2); + const events = [ + makeWorkflowStarted(1), + makeActivityScheduled(2, 'LiveDetailActivity'), + started, + ]; + const { initialResponse, liveResponse, liveRequested, requests } = + await mockEventDetail( + page, + events, + [makeActivityCompleted(4, 2, 3)], + runningWorkflow, + [started], + ); + try { + await page.goto(eventUrl('3')); + const details = page.getByTestId('event-summary-row-expanded'); + await expect.poll(() => visibleIds(page)).toEqual(['3']); + await expect( + details.getByText('Activity Task Started', { exact: true }), + ).toBeVisible(); + await expect( + details.getByText('Activity Task Scheduled', { exact: true }), + ).toHaveCount(0); + await liveRequested.promise; + await expect.poll(() => requests.initial).toBe(1); + await expect.poll(() => requests.reverse).toBe(2); + const before = { ...requests }; + + initialResponse.release(); + await expect(details).toContainText('LiveDetailActivity'); + await expect( + details.getByText('Activity Task Scheduled', { exact: true }), + ).toBeVisible(); + await expect( + details.getByText('Activity Task Completed', { exact: true }), + ).toHaveCount(0); + + liveResponse.release(); + await expect( + details.getByText('Activity Task Completed', { exact: true }), + ).toBeVisible(); + await expect( + details.getByText('Activity Task Started', { exact: true }), + ).toBeVisible(); + await expect( + details.getByText('Activity Task Scheduled', { exact: true }), + ).toBeVisible(); + await expect(details).toHaveCount(1); + await expect.poll(() => visibleIds(page)).toEqual(['3']); + await expect( + page.locator('[data-eventid="3"]').getByRole('button', { + name: /collapse/i, + }), + ).toHaveAttribute('aria-expanded', 'true'); + expect(requests.initial).toBe(before.initial); + expect(requests.reverse).toBe(before.reverse); + expect(requests.navigation).toBe(before.navigation); + await expect(page).toHaveURL(eventUrl('3')); + } finally { + initialResponse.release(); + liveResponse.release(); + } + }); +}); diff --git a/tests/integration/workflow-run-detail-history-errors.spec.ts b/tests/integration/workflow-run-detail-history-errors.spec.ts new file mode 100644 index 0000000000..004fdc6102 --- /dev/null +++ b/tests/integration/workflow-run-detail-history-errors.spec.ts @@ -0,0 +1,276 @@ +import { expect, type Route, test } from '@playwright/test'; + +import { + makeActivityGroup, + makeTimerGroup, + makeWorkflowCompleted, + makeWorkflowStarted, + makeWorkflowTaskFailed, + makeWorkflowTaskScheduled, + makeWorkflowTaskStarted, +} from '$src/lib/services/test-helpers/synthetic-events'; +import type { HistoryEvent } from '$src/lib/types/events'; +import type { + WorkflowExecutionAPIResponse, + WorkflowExecutionInfo, +} from '$src/lib/types/workflows'; +import { mockWorkflowApis } from '~/test-utilities/mock-apis'; +import { + EVENT_HISTORY_API, + EVENT_HISTORY_API_REVERSE, +} from '~/test-utilities/mocks/event-history'; +import { mockWorkflow } from '~/test-utilities/mocks/workflow'; + +const { workflowId, runId } = mockWorkflow.workflowExecutionInfo.execution; +const historyUrl = `/namespaces/default/workflows/${workflowId}/${runId}/history?sort=ascending`; +const events: HistoryEvent[] = [ + makeWorkflowStarted(1), + ...makeActivityGroup(2, 'HistoryRecoveryActivity'), + ...makeTimerGroup(5), + ...makeTimerGroup(7), + makeWorkflowCompleted(9), +]; +const pageSize = 2; +const completedExecutionInfo: WorkflowExecutionInfo = { + ...mockWorkflow.workflowExecutionInfo, + status: 'Completed', + startTime: events[0].eventTime, + executionTime: events[0].eventTime, + closeTime: events[8].eventTime, + historyLength: String(events.length), +}; +const completedWorkflow: WorkflowExecutionAPIResponse = { + ...mockWorkflow, + workflowExecutionInfo: completedExecutionInfo, + pendingActivities: [], + pendingChildren: [], +}; + +function fulfillHistoryPage(route: Route, descending: boolean) { + const offset = Number( + new URL(route.request().url()).searchParams.get('next_page_token') ?? 0, + ); + const orderedEvents = descending ? [...events].reverse() : events; + const nextOffset = offset + pageSize; + return route.fulfill({ + json: { + history: { events: orderedEvents.slice(offset, nextOffset) }, + nextPageToken: nextOffset < events.length ? String(nextOffset) : null, + }, + }); +} + +function failHistoryPage(route: Route) { + return route.fulfill({ + status: 503, + json: { code: 14, message: 'History temporarily unavailable' }, + }); +} + +test.describe('Workflow run detail history loading errors', () => { + test.beforeEach(async ({ page }) => { + await page.addInitScript(() => { + localStorage.setItem('autoRefreshWorkflow', JSON.stringify('off')); + localStorage.setItem('eventView', JSON.stringify('feed')); + localStorage.setItem('eventFilterSort', JSON.stringify('ascending')); + }); + await mockWorkflowApis(page, completedWorkflow); + }); + + test('loads every event through the healthy paginated direction when the other direction returns HTTP 503', async ({ + page, + }) => { + let descendingFailures = 0; + await page.route(EVENT_HISTORY_API_REVERSE, (route) => { + descendingFailures += 1; + return failHistoryPage(route); + }); + await page.route(EVENT_HISTORY_API, (route) => + fulfillHistoryPage(route, false), + ); + + await page.goto(historyUrl); + + await expect(page.getByTestId('workflow-id-heading')).toContainText( + workflowId, + ); + await expect(page.getByTestId('execution-status')).toContainText( + 'Completed', + ); + await expect( + page.getByTestId('event-summary-row').getByTestId('link'), + ).toHaveText(events.map((event) => event.eventId)); + await expect(page.getByTestId('history-load-error')).toBeHidden(); + await expect( + page.getByTestId('event-summary-table').getByRole('table'), + ).not.toHaveAttribute('aria-busy', 'true'); + expect(descendingFailures).toBeGreaterThan(0); + }); + + test('shows the status text fallback when both history directions return HTTP 503 with an empty message', async ({ + page, + }) => { + const failedDirections = new Set(); + for (const api of [EVENT_HISTORY_API, EVENT_HISTORY_API_REVERSE]) { + await page.route(api, (route) => { + failedDirections.add(api); + return route.fulfill({ + status: 503, + json: { code: 14, message: '' }, + }); + }); + } + + await page.goto(historyUrl); + + const heading = page.getByTestId('workflow-id-heading'); + const alert = page.getByTestId('history-load-error'); + const detail = alert.locator('.text-secondary'); + await expect(heading).toBeVisible(); + await expect(heading).toContainText(workflowId); + await expect(alert).toBeVisible(); + await expect(alert).toContainText('Unable to load the full event history.'); + await expect(detail).toBeVisible(); + await expect(detail).toHaveText(/\S/); + await expect.poll(() => failedDirections.size).toBe(2); + }); + + for (const view of ['history', 'timeline']) { + test(`hides a loaded workflow-task failure on ${view} after a partial history error`, async ({ + page, + }) => { + await mockWorkflowApis(page, { + ...completedWorkflow, + workflowExecutionInfo: { + ...completedExecutionInfo, + status: 'Running', + closeTime: '', + }, + }); + for (const { api, pageEvents } of [ + { api: EVENT_HISTORY_API, pageEvents: events.slice(0, 2) }, + { + api: EVENT_HISTORY_API_REVERSE, + pageEvents: [ + makeWorkflowTaskFailed(9, 7, 'NonDeterministicError'), + makeWorkflowTaskStarted(8, 7), + makeWorkflowTaskScheduled(7), + ], + }, + ]) { + await page.route(api, (route) => { + if ( + new URL(route.request().url()).searchParams.has('next_page_token') + ) { + return failHistoryPage(route); + } + return route.fulfill({ + json: { history: { events: pageEvents }, nextPageToken: 'more' }, + }); + }); + } + + await page.goto(historyUrl.replace('/history?', `/${view}?`)); + + await expect(page.getByTestId('history-load-error')).toBeVisible(); + await expect( + page.getByText('Non Deterministic Error', { exact: true }), + ).toBeHidden(); + }); + } + + test('retains partial history after both directions return HTTP 503 and while retrying, then loads the remaining events', async ({ + page, + }) => { + let retrying = false; + let releaseRetry = () => {}; + const retryHeld = new Promise((resolve) => { + releaseRetry = resolve; + }); + const failedDirections = new Set(); + const retryDirections = new Set(); + for (const { api, descending, direction } of [ + { api: EVENT_HISTORY_API, descending: false, direction: 'ascending' }, + { + api: EVENT_HISTORY_API_REVERSE, + descending: true, + direction: 'descending', + }, + ]) { + await page.route(api, async (route) => { + if (retrying) { + retryDirections.add(direction); + await retryHeld; + return fulfillHistoryPage(route, descending); + } + if ( + new URL(route.request().url()).searchParams.has('next_page_token') + ) { + failedDirections.add(direction); + return failHistoryPage(route); + } + return fulfillHistoryPage(route, descending); + }); + } + + try { + await page.goto(historyUrl); + + const heading = page.getByTestId('workflow-id-heading'); + const table = page.getByTestId('event-summary-table'); + const rowIds = page.getByTestId('event-summary-row').getByTestId('link'); + const alert = page.getByTestId('history-load-error'); + const retry = page.getByRole('button', { + name: 'Retry history loading', + exact: true, + }); + await expect(alert).toBeVisible(); + await expect(alert).toContainText( + 'Unable to load the full event history.', + ); + await expect(alert).toContainText( + 'Loaded events are still available. Retry to load the remaining history.', + ); + await expect(heading).toContainText(workflowId); + await expect(page.getByTestId('execution-status')).toContainText( + 'Completed', + ); + await expect(page.getByTestId('history-tab')).toBeVisible(); + await expect(table).toBeVisible(); + await expect(rowIds).toHaveText(['1', '2', '8', '9']); + await expect(table.getByRole('table')).not.toHaveAttribute( + 'aria-busy', + 'true', + ); + await expect(retry).toBeVisible(); + await expect(retry).toBeEnabled(); + expect([...failedDirections].sort()).toEqual(['ascending', 'descending']); + + retrying = true; + await retry.click(); + + await expect.poll(() => retryDirections.size).toBe(2); + await expect(table.getByRole('table')).toHaveAttribute( + 'aria-busy', + 'true', + ); + await expect(heading).toContainText(workflowId); + await expect(rowIds).toHaveText(['1', '2', '8', '9']); + + releaseRetry(); + + await expect(rowIds).toHaveText(events.map((event) => event.eventId)); + await expect(alert).toBeHidden(); + await expect(retry).toBeHidden(); + await expect(page.getByTestId('execution-status')).toContainText( + 'Completed', + ); + await expect(table.getByRole('table')).not.toHaveAttribute( + 'aria-busy', + 'true', + ); + } finally { + releaseRetry(); + } + }); +}); diff --git a/tests/integration/workflow-run-detail-refresh.spec.ts b/tests/integration/workflow-run-detail-refresh.spec.ts new file mode 100644 index 0000000000..d83dfabe51 --- /dev/null +++ b/tests/integration/workflow-run-detail-refresh.spec.ts @@ -0,0 +1,190 @@ +import { expect, type Page, test } from '@playwright/test'; + +import { + makeActivityCompleted, + makeActivityScheduled, + makeActivityStarted, + makeWorkflowCompleted, + makeWorkflowStarted, +} from '$src/lib/services/test-helpers/synthetic-events'; +import type { HistoryEvent } from '$src/lib/types/events'; +import { mockWorkflowApis } from '~/test-utilities/mock-apis'; +import { + EVENT_HISTORY_API, + EVENT_HISTORY_API_REVERSE, +} from '~/test-utilities/mocks/event-history'; +import { mockWorkflow, WORKFLOW_API } from '~/test-utilities/mocks/workflow'; + +const { workflowId, runId } = mockWorkflow.workflowExecutionInfo.execution; +const historyUrl = `/namespaces/default/workflows/${workflowId}/${runId}/history`; +const initialEvents: HistoryEvent[] = [ + makeWorkflowStarted(1), + makeActivityScheduled(2, 'RefreshActivity'), + makeActivityStarted(3, 2), +]; +const activityCompletion = makeActivityCompleted(4, 2, 3); +const workflowCompletion = makeWorkflowCompleted(5); + +const historyPage = (events: HistoryEvent[]) => ({ + history: { events }, + rawHistory: [], + nextPageToken: null, + archived: false, +}); + +function gate() { + let release = () => {}; + const promise = new Promise((resolve) => { + release = resolve; + }); + return { promise, release }; +} + +async function mockRunDetail(page: Page, liveEvents: HistoryEvent[]) { + const runningWorkflow = { + ...mockWorkflow, + workflowExecutionInfo: { + ...mockWorkflow.workflowExecutionInfo, + status: 'Running', + closeTime: '', + historyLength: String(initialEvents.length), + }, + pendingActivities: [], + pendingChildren: [], + }; + const requests = { describe: 0, initial: 0, reverse: 0, live: 0 }; + const state = { completed: false }; + const liveRequested = gate(); + const liveResponse = gate(); + + await mockWorkflowApis(page, runningWorkflow); + await page.route(WORKFLOW_API, (route) => { + requests.describe += 1; + return route.fulfill({ + json: state.completed + ? { + ...runningWorkflow, + workflowExecutionInfo: { + ...runningWorkflow.workflowExecutionInfo, + status: 'Completed', + closeTime: '2024-01-01T00:00:01Z', + historyLength: '5', + }, + } + : runningWorkflow, + }); + }); + await page.route(EVENT_HISTORY_API, async (route) => { + if ( + new URL(route.request().url()).searchParams.get('waitNewEvent') === 'true' + ) { + requests.live += 1; + if (requests.live === 1) { + liveRequested.release(); + await liveResponse.promise; + return route.fulfill({ json: historyPage(liveEvents) }); + } + return route.fulfill({ json: historyPage([]) }); + } + requests.initial += 1; + return route.fulfill({ json: historyPage(initialEvents) }); + }); + await page.route(EVENT_HISTORY_API_REVERSE, (route) => { + requests.reverse += 1; + return route.fulfill({ json: historyPage([...initialEvents].reverse()) }); + }); + + return { requests, state, liveRequested, liveResponse }; +} + +async function openHistory(page: Page, refreshOff: boolean) { + await page.clock.install(); + await page.clock.pauseAt((await page.evaluate(() => Date.now())) + 1000); + await page.goto(`${historyUrl}?refresh_off=${refreshOff}&sort=ascending`); + await expect(page.getByTestId('event-summary-table')).toBeVisible(); + await page.getByTestId('feed').click(); + await expect(page.getByTestId('event-summary-row')).toHaveCount(3); + await expect(page.locator('[data-eventid="2"]')).toContainText( + 'RefreshActivity', + ); + await expect(page.getByTestId('execution-status')).toHaveText('Running'); +} + +test.describe('Workflow run detail refresh', () => { + test('loads history with refresh off, receives a live completion when enabled, and stops requests when disabled again', async ({ + page, + }) => { + const { requests, liveRequested, liveResponse } = await mockRunDetail( + page, + [activityCompletion], + ); + try { + await openHistory(page, true); + await expect(page.getByTestId('pause')).toHaveText('Auto Refresh Off'); + expect(requests.initial).toBeGreaterThan(0); + expect(requests.reverse).toBeGreaterThan(0); + expect(requests.describe).toBe(1); + expect(requests.live).toBe(0); + + const initiallyOff = { ...requests }; + await page.clock.runFor(30_000); + expect(requests).toEqual(initiallyOff); + await expect(page.getByTestId('event-summary-row')).toHaveCount(3); + + await page.getByTestId('pause').click(); + await expect(page.getByTestId('pause')).toHaveText('Auto Refresh On'); + await expect(page).not.toHaveURL(/refresh_off=true/); + await liveRequested.promise; + await expect(page.locator('[data-eventid="4"]')).toHaveCount(0); + + liveResponse.release(); + await expect(page.locator('[data-eventid="4"]')).toBeVisible(); + await expect(page.getByTestId('event-summary-row')).toHaveCount(4); + await page.clock.runFor(10_000); + await expect.poll(() => requests.describe).toBeGreaterThan(1); + + await page.getByTestId('pause').click(); + await expect(page.getByTestId('pause')).toHaveText('Auto Refresh Off'); + await expect(page).toHaveURL(/refresh_off=true/); + const before = { ...requests }; + await page.clock.runFor(30_000); + + expect(requests).toEqual(before); + await expect(page.locator('[data-eventid="4"]')).toBeVisible(); + } finally { + liveResponse.release(); + } + }); + + test('keeps the final history tail when Describe completes before the held terminal history response', async ({ + page, + }) => { + const { requests, state, liveRequested, liveResponse } = + await mockRunDetail(page, [activityCompletion, workflowCompletion]); + try { + await openHistory(page, false); + await liveRequested.promise; + await expect(page.locator('[data-eventid="5"]')).toHaveCount(0); + state.completed = true; + + await page.clock.runFor(10_000); + await expect(page.getByTestId('execution-status')).toHaveText( + 'Completed', + ); + await expect(page.locator('[data-eventid="4"]')).toHaveCount(0); + await expect(page.locator('[data-eventid="5"]')).toHaveCount(0); + + liveResponse.release(); + await expect(page.locator('[data-eventid="4"]')).toBeVisible(); + await expect(page.locator('[data-eventid="5"]')).toBeVisible(); + await expect(page.getByTestId('event-summary-row')).toHaveCount(5); + + const before = { ...requests }; + await page.clock.runFor(30_000); + expect(requests).toEqual(before); + await expect(page.locator('[data-eventid="5"]')).toBeVisible(); + } finally { + liveResponse.release(); + } + }); +}); diff --git a/tests/integration/workflow-run-detail-resume.spec.ts b/tests/integration/workflow-run-detail-resume.spec.ts new file mode 100644 index 0000000000..4d91533cb8 --- /dev/null +++ b/tests/integration/workflow-run-detail-resume.spec.ts @@ -0,0 +1,187 @@ +import { setTimeout as delay } from 'node:timers/promises'; + +import { expect, type Page, test } from '@playwright/test'; + +import { + makeActivityCompleted, + makeActivityScheduled, + makeActivityStarted, + makeWorkflowCompleted, + makeWorkflowStarted, +} from '$src/lib/services/test-helpers/synthetic-events'; +import type { HistoryEvent } from '$src/lib/types/events'; +import type { WorkflowExecutionAPIResponse } from '$src/lib/types/workflows'; +import { mockWorkflowApis } from '~/test-utilities/mock-apis'; +import { + EVENT_HISTORY_API, + EVENT_HISTORY_API_REVERSE, +} from '~/test-utilities/mocks/event-history'; +import { mockWorkflow, WORKFLOW_API } from '~/test-utilities/mocks/workflow'; + +const { workflowId, runId } = mockWorkflow.workflowExecutionInfo.execution; +const secondRunId = '61797bf4-0d48-43d6-94aa-1921f7893200'; +const runUrl = (id: string) => + `/namespaces/default/workflows/${workflowId}/${id}`; + +const historyFor = (name: string): HistoryEvent[] => [ + makeWorkflowStarted(1), + ...Array.from({ length: 3 }, (_, index) => { + const scheduledId = index * 3 + 2; + return [ + makeActivityScheduled(scheduledId, `${name}${index + 1}`), + makeActivityStarted(scheduledId + 1, scheduledId), + makeActivityCompleted(scheduledId + 2, scheduledId, scheduledId + 1), + ]; + }).flat(), + makeWorkflowCompleted(11), +]; +const firstEvents = historyFor('ResumeFirstRunActivity'); +const secondEvents = historyFor('ResumeSecondRunActivity'); +const pageSize = 2; +const fullPageCount = Math.ceil(firstEvents.length / pageSize); + +const workflowFor = (id: string): WorkflowExecutionAPIResponse => ({ + ...mockWorkflow, + workflowExecutionInfo: { + ...mockWorkflow.workflowExecutionInfo, + execution: { workflowId, runId: id }, + status: 'Completed', + startTime: firstEvents[0].eventTime, + executionTime: firstEvents[0].eventTime, + closeTime: firstEvents[10].eventTime, + historyLength: String(firstEvents.length), + }, + pendingActivities: [], + pendingChildren: [], +}); + +async function mockPaginatedRuns(page: Page) { + const requests = new Map(); + await page.addInitScript(() => { + localStorage.setItem('autoRefreshWorkflow', JSON.stringify('off')); + localStorage.setItem('eventView', JSON.stringify('feed')); + }); + await mockWorkflowApis(page, workflowFor(runId)); + await page.route(WORKFLOW_API, (route) => { + const requestedRun = new URL(route.request().url()).searchParams.get( + 'execution.runId', + ); + return route.fulfill({ + json: workflowFor(requestedRun === secondRunId ? secondRunId : runId), + }); + }); + await page.route(EVENT_HISTORY_API_REVERSE, (route) => + route.fulfill({ json: { history: { events: [] }, nextPageToken: null } }), + ); + await page.route(EVENT_HISTORY_API, (route) => { + const url = new URL(route.request().url()); + const requestedRun = url.searchParams.get('execution.runId') ?? ''; + requests.set(requestedRun, (requests.get(requestedRun) ?? 0) + 1); + const events = requestedRun === secondRunId ? secondEvents : firstEvents; + const offset = Number(url.searchParams.get('next_page_token') ?? 0); + const nextOffset = offset + pageSize; + return route.fulfill({ + json: { + history: { events: events.slice(offset, nextOffset) }, + nextPageToken: nextOffset < events.length ? String(nextOffset) : null, + }, + }); + }); + return requests; +} + +async function navigateWithinApp(page: Page, href: string) { + const timeOrigin = await page.evaluate(() => performance.timeOrigin); + await page.evaluate((destination) => { + const link = document.createElement('a'); + link.href = destination; + link.textContent = 'Switch resume test run'; + link.dataset.testid = 'resume-test-run-link'; + document.body.append(link); + link.click(); + }, href); + await expect(page).toHaveURL(href); + expect(await page.evaluate(() => performance.timeOrigin)).toBe(timeOrigin); + await page + .getByTestId('resume-test-run-link') + .evaluate((link) => link.remove()); +} + +test.describe('Workflow run detail resume ownership', () => { + test('does not carry full-history demand into another run on a non-history page, then resumes on history', async ({ + page, + }) => { + const requests = await mockPaginatedRuns(page); + await page.goto(`${runUrl(runId)}/history`); + await expect(page.getByTestId('event-summary-row')).toHaveCount(11); + expect(requests.get(runId)).toBe(fullPageCount); + + await navigateWithinApp(page, `${runUrl(secondRunId)}/pending-activities`); + await expect(page.getByTestId('workflow-id-heading')).toBeVisible(); + await expect.poll(() => requests.get(secondRunId)).toBe(2); + await delay(500); + expect(requests.get(secondRunId)).toBe(2); + + await page.getByTestId('history-tab').click(); + await expect(page.getByTestId('event-summary-row')).toHaveCount(11); + expect(requests.get(secondRunId)).toBe(fullPageCount); + await expect(page.getByTestId('event-summary-table')).toContainText( + 'ResumeSecondRunActivity3', + ); + await expect(page.getByTestId('event-summary-table')).not.toContainText( + 'ResumeFirstRunActivity', + ); + }); + + for (const { view, verify } of [ + { + view: 'history', + verify: async (page: Page) => { + await expect(page.getByTestId('event-summary-row')).toHaveCount(11); + await expect(page.getByTestId('event-summary-table')).toContainText( + 'ResumeSecondRunActivity3', + ); + }, + }, + { + view: 'timeline', + verify: async (page: Page) => { + await page + .getByRole('img', { name: `Workflow ${workflowId}: Completed` }) + .scrollIntoViewIfNeeded(); + const activity = page.getByRole('button', { + name: 'Event ResumeSecondRunActivity3: Completed', + }); + await activity.scrollIntoViewIfNeeded(); + await expect(activity).toBeVisible(); + }, + }, + { + view: 'history/events/8', + verify: async (page: Page) => { + await expect(page.getByTestId('event-summary-log')).toContainText( + 'ResumeSecondRunActivity3', + ); + await expect( + page.getByTestId('event-summary-row-expanded'), + ).toBeVisible(); + }, + }, + ]) { + test(`resumes the replacement history after a same-route run switch on ${view}`, async ({ + page, + }) => { + const requests = await mockPaginatedRuns(page); + await page.goto(`${runUrl(runId)}/${view}`); + await expect.poll(() => requests.get(runId)).toBe(fullPageCount); + await expect(page.getByTestId('workflow-id-heading')).toBeVisible(); + + await navigateWithinApp(page, `${runUrl(secondRunId)}/${view}`); + await expect.poll(() => requests.get(secondRunId)).toBe(fullPageCount); + await verify(page); + await expect(page.locator('body')).not.toContainText( + 'ResumeFirstRunActivity3', + ); + }); + } +}); diff --git a/tests/integration/workflow-run-detail-selection.spec.ts b/tests/integration/workflow-run-detail-selection.spec.ts new file mode 100644 index 0000000000..cd9014a7db --- /dev/null +++ b/tests/integration/workflow-run-detail-selection.spec.ts @@ -0,0 +1,198 @@ +import { expect, type Page, test } from '@playwright/test'; + +import { + makeActivityCompleted, + makeActivityScheduled, + makeActivityStarted, + makeChildWorkflowCompleted, + makeChildWorkflowStarted, + makeStartChildWorkflowInitiated, + makeWorkflowCompleted, + makeWorkflowStarted, +} from '$src/lib/services/test-helpers/synthetic-events'; +import type { HistoryEvent } from '$src/lib/types/events'; +import { mockWorkflowApis, WORKFLOW_API } from '~/test-utilities/mock-apis'; +import { + EVENT_HISTORY_API, + EVENT_HISTORY_API_REVERSE, +} from '~/test-utilities/mocks/event-history'; +import { mockWorkflow } from '~/test-utilities/mocks/workflow'; + +const { workflowId, runId } = mockWorkflow.workflowExecutionInfo.execution; +const timelineUrl = `/namespaces/default/workflows/${workflowId}/${runId}/timeline`; +const graphSelector = '[id="event-history-timeline-graph"]'; +const activityName = 'SelectionActivity'; + +const atSecond = (event: HistoryEvent, second: number): HistoryEvent => ({ + ...event, + eventTime: `2024-01-01T00:00:${String(second).padStart(2, '0')}.000000000Z`, +}); + +const activityEvents = [ + makeWorkflowStarted(1), + atSecond(makeActivityScheduled(2, activityName), 10), + atSecond(makeActivityStarted(3, 2), 15), + atSecond(makeActivityCompleted(4, 2, 3), 20), +]; +const events = [ + ...activityEvents, + atSecond(makeStartChildWorkflowInitiated(5), 25), + atSecond(makeChildWorkflowStarted(6, 5), 30), + atSecond(makeChildWorkflowCompleted(7, 5, 6), 40), + atSecond(makeWorkflowCompleted(8), 50), +]; +const childEvents = [...activityEvents, atSecond(makeWorkflowCompleted(5), 50)]; + +const workflowFor = (id: string, executionRunId: string) => ({ + ...mockWorkflow, + workflowExecutionInfo: { + ...mockWorkflow.workflowExecutionInfo, + execution: { workflowId: id, runId: executionRunId }, + status: 'Completed', + startTime: events[0].eventTime, + executionTime: events[0].eventTime, + closeTime: events[7].eventTime, + historyLength: String( + id === workflowId ? events.length : childEvents.length, + ), + }, + pendingActivities: [], + pendingChildren: [], +}); + +async function openActivity(page: Page) { + await page + .getByRole('button', { name: `Event ${activityName}: Completed` }) + .click(); + await expect(page.locator('.panel')).toHaveCount(1); + await expect(page.locator('.panel')).toContainText(activityName); + await expect( + page.locator('.panel').getByRole('button', { name: 'Close', exact: true }), + ).toBeVisible(); +} + +async function toggleFilter(page: Page, name: string) { + await page.locator('button[aria-controls="event-type-filter"]').click(); + await page.locator('#event-type-filter').getByTestId(name).click(); + await page.keyboard.press('Escape'); +} + +test.describe('Workflow timeline local selection', () => { + test.beforeEach(async ({ page }) => { + await mockWorkflowApis(page, workflowFor(workflowId, runId)); + await page.route(WORKFLOW_API, (route) => { + const url = new URL(route.request().url()); + const id = decodeURIComponent(url.pathname.split('/').at(-1) ?? ''); + return route.fulfill({ + json: workflowFor(id, url.searchParams.get('execution.runId') ?? runId), + }); + }); + for (const api of [EVENT_HISTORY_API, EVENT_HISTORY_API_REVERSE]) { + await page.route(api, (route) => { + const url = new URL(route.request().url()); + const historyEvents = url.pathname.includes('/workflows/child-5/') + ? childEvents + : events; + return route.fulfill({ + json: { + history: { + events: url.pathname.endsWith('history-reverse') + ? [...historyEvents].reverse() + : historyEvents, + }, + nextPageToken: null, + }, + }); + }); + } + await page.goto(`${timelineUrl}?sort=ascending&refresh_off=true`); + await page + .getByRole('img', { name: `Workflow ${workflowId}: Completed` }) + .scrollIntoViewIfNeeded(); + }); + + test('closes the selected panel on sort navigation without hiding the selected group', async ({ + page, + }) => { + await openActivity(page); + await page.getByTestId('zoom-in').click(); + await expect(page).toHaveURL( + (url) => url.searchParams.get('sort') === null, + ); + await expect(page.getByTestId('zoom-in')).toHaveText('Descending'); + await expect(page.locator('.panel')).toHaveCount(0); + await expect( + page.getByRole('button', { name: `Event ${activityName}: Completed` }), + ).toBeVisible(); + await openActivity(page); + await page + .locator('.panel') + .getByRole('button', { name: 'Close', exact: true }) + .click(); + await expect(page.locator('.panel')).toHaveCount(0); + }); + + test('closes the selected panel on category navigation and does not resurrect it when restored', async ({ + page, + }) => { + await openActivity(page); + await toggleFilter(page, 'Activity'); + await expect(page).toHaveURL(/category=/); + await expect( + page.getByRole('button', { name: `Event ${activityName}: Completed` }), + ).toHaveCount(0); + await expect(page.locator('.panel')).toHaveCount(0); + + await toggleFilter(page, 'Activity'); + await expect(page).not.toHaveURL(/category=/); + await expect( + page.getByRole('button', { name: `Event ${activityName}: Completed` }), + ).toBeVisible(); + await expect(page.locator('.panel')).toHaveCount(0); + await openActivity(page); + }); + + test('discards a completed selection when the pending and failed filter removes its group', async ({ + page, + }) => { + await openActivity(page); + await toggleFilter(page, 'Pending and Failed'); + await expect( + page.getByRole('button', { name: `Event ${activityName}: Completed` }), + ).toHaveCount(0); + await expect(page.locator('.panel')).toHaveCount(0); + + await toggleFilter(page, 'All'); + await expect( + page.getByRole('button', { name: `Event ${activityName}: Completed` }), + ).toBeVisible(); + await expect(page.locator('.panel')).toHaveCount(0); + await openActivity(page); + }); + + test('keeps parent selection independent of the child mini-timeline graph', async ({ + page, + }) => { + await page.getByRole('button', { name: /Event ChildWorkflow:/ }).click(); + const panel = page.locator('.panel'); + const childGraph = panel.locator(graphSelector); + await expect( + childGraph.getByRole('img', { name: 'Workflow child-5: Completed' }), + ).toBeVisible(); + await expect( + childGraph.getByRole('button', { + name: `Event ${activityName}: Completed`, + }), + ).toBeDisabled(); + await expect(childGraph.locator('.panel')).toHaveCount(0); + await expect(panel).toHaveCount(1); + await expect(panel).toContainText('ChildWorkflow'); + + await panel.getByRole('button', { name: 'Close', exact: true }).click(); + await expect(page.locator('.panel')).toHaveCount(0); + await expect(page.locator(graphSelector)).toHaveCount(1); + await openActivity(page); + await expect(page.locator('.panel').locator(graphSelector)).toHaveCount(0); + await expect(page.locator('.panel')).not.toContainText('ChildWorkflow'); + }); +}); diff --git a/tests/integration/workflow-run-detail-smoke.spec.ts b/tests/integration/workflow-run-detail-smoke.spec.ts new file mode 100644 index 0000000000..1087c5a828 --- /dev/null +++ b/tests/integration/workflow-run-detail-smoke.spec.ts @@ -0,0 +1,325 @@ +import { test as base, expect } from '@playwright/test'; + +import { + makeActivityCompleted, + makeActivityScheduled, + makeActivityStarted, + makeWorkflowCompleted, + makeWorkflowStarted, +} from '$src/lib/services/test-helpers/synthetic-events'; +import type { HistoryEvent } from '$src/lib/types/events'; +import type { WorkflowExecutionAPIResponse } from '$src/lib/types/workflows'; +import { + mockEventHistoryApi, + mockWorkflowApis, + WORKFLOW_API, +} from '~/test-utilities/mock-apis'; +import { + EVENT_HISTORY_API, + EVENT_HISTORY_API_REVERSE, +} from '~/test-utilities/mocks/event-history'; +import { mockWorkflow } from '~/test-utilities/mocks/workflow'; + +const { workflowId, runId } = mockWorkflow.workflowExecutionInfo.execution; +const secondRunId = '61797bf4-0d48-43d6-94aa-1921f7893200'; +const runUrl = `/namespaces/default/workflows/${workflowId}/${runId}`; +const secondRunUrl = `/namespaces/default/workflows/${workflowId}/${secondRunId}`; + +const atSecond = (event: HistoryEvent, second: number): HistoryEvent => ({ + ...event, + eventTime: `2024-01-01T00:00:${String(second).padStart(2, '0')}.000000000Z`, +}); + +const historyFor = (activityName: string): HistoryEvent[] => [ + makeWorkflowStarted(1), + atSecond(makeActivityScheduled(2, activityName), 10), + atSecond(makeActivityStarted(3, 2), 15), + atSecond(makeActivityCompleted(4, 2, 3), 30), + atSecond(makeWorkflowCompleted(5), 40), +]; + +const events = historyFor('SmokeFirstRunActivity'); +const workflowFor = (id: string): WorkflowExecutionAPIResponse => ({ + ...mockWorkflow, + workflowExecutionInfo: { + ...mockWorkflow.workflowExecutionInfo, + execution: { workflowId, runId: id }, + status: 'Completed', + startTime: events[0].eventTime, + executionTime: events[0].eventTime, + closeTime: events[4].eventTime, + historyLength: String(events.length), + }, + pendingActivities: [], + pendingChildren: [], +}); + +const test = base.extend<{ pageErrors: Error[] }>({ + pageErrors: [ + async ({ page }, use) => { + const errors: Error[] = []; + page.on('pageerror', (error) => errors.push(error)); + await use(errors); + expect(errors.map((error) => error.message)).toEqual([]); + }, + { auto: true }, + ], +}); + +test.describe('Workflow run detail smoke', () => { + test.beforeEach(async ({ page }) => { + await page.addInitScript(() => { + localStorage.setItem('autoRefreshWorkflow', JSON.stringify('off')); + localStorage.setItem('eventView', JSON.stringify('feed')); + localStorage.setItem('eventFilterSort', JSON.stringify('descending')); + }); + await mockWorkflowApis(page, workflowFor(runId)); + await mockEventHistoryApi(page, { + history: { events }, + nextPageToken: null, + }); + }); + + test('navigates timeline, feed, compact, JSON, and event detail back to history', async ({ + page, + }) => { + await page.goto(`${runUrl}/timeline`); + await page + .getByRole('img', { name: `Workflow ${workflowId}: Completed` }) + .scrollIntoViewIfNeeded(); + await expect( + page.getByRole('img', { name: `Workflow ${workflowId}: Completed` }), + ).toBeVisible(); + await expect( + page.getByRole('button', { + name: 'Event SmokeFirstRunActivity: Completed', + }), + ).toBeVisible(); + + await page.getByTestId('history-tab').click(); + await expect(page.getByTestId('event-summary-row')).toHaveCount(5); + await page.getByTestId('compact').click(); + await expect(page.getByTestId('event-summary-table')).toContainText( + 'SmokeFirstRunActivity', + ); + await page.getByTestId('json').click(); + await expect(page.getByTestId('event-history-json')).toContainText( + 'WorkflowExecutionStarted', + ); + await page.getByRole('button', { name: 'Next', exact: true }).click(); + await expect(page.getByTestId('event-history-json')).toContainText( + 'SmokeFirstRunActivity', + ); + await expect(page.getByTestId('event-summary-table')).toBeHidden(); + await page.getByTestId('feed').click(); + await expect(page.getByTestId('event-summary-row')).toHaveCount(5); + + await page + .getByTestId('event-summary-row') + .filter({ has: page.getByRole('link', { name: '2', exact: true }) }) + .getByRole('link', { name: '2', exact: true }) + .click(); + await expect(page).toHaveURL(`${runUrl}/history/events/2`); + await expect(page.getByTestId('event-summary-log')).toContainText( + 'SmokeFirstRunActivity', + ); + await expect(page.getByTestId('event-summary-row-expanded')).toBeVisible(); + await page.goBack(); + await expect(page).toHaveURL(`${runUrl}/history`); + await expect(page.getByTestId('event-summary-row')).toHaveCount(5); + }); + + test('preserves category and sort filters across timeline and history views', async ({ + page, + }) => { + await page.goto(`${runUrl}/history?sort=ascending`); + await expect(page.getByTestId('event-summary-row')).toHaveCount(5); + await page.locator('button[aria-controls="event-type-filter"]').click(); + await page.locator('#event-type-filter').getByTestId('Activity').click(); + await page.keyboard.press('Escape'); + await expect(page.getByTestId('event-summary-row')).toHaveCount(2); + await expect(page.getByTestId('event-summary-table')).not.toContainText( + 'SmokeFirstRunActivity', + ); + const filteredQuery = new URL(page.url()).search; + expect(new URL(page.url()).searchParams.get('sort')).toBe('ascending'); + expect(new URL(page.url()).searchParams.has('category')).toBe(true); + + await page.getByTestId('timeline-tab').click(); + await expect(page).toHaveURL(`${runUrl}/timeline${filteredQuery}`); + await page + .getByRole('img', { name: `Workflow ${workflowId}: Completed` }) + .scrollIntoViewIfNeeded(); + await expect( + page.getByRole('img', { name: `Workflow ${workflowId}: Completed` }), + ).toBeVisible(); + await expect( + page.getByRole('button', { name: /Event SmokeFirstRunActivity:/ }), + ).toBeHidden(); + await page.getByTestId('history-tab').click(); + await expect(page).toHaveURL(`${runUrl}/history${filteredQuery}`); + await expect(page.getByTestId('event-summary-row')).toHaveCount(2); + await expect(page.getByTestId('event-summary-row').first()).toContainText( + 'Workflow Execution Started', + ); + await page.getByTestId('compact').click(); + await expect(page.getByTestId('event-summary-table')).toContainText( + 'No Events Match', + ); + await page.getByTestId('json').click(); + await expect(page.getByTestId('event-history-json')).toContainText( + 'WorkflowExecutionStarted', + ); + await expect(page.getByRole('slider')).toHaveAttribute('max', '2'); + await page.getByTestId('feed').click(); + await expect(page.getByTestId('event-summary-row')).toHaveCount(2); + }); + + test('waits for the workflow start before showing an elapsed-time baseline', async ({ + page, + }) => { + let releaseAscending = () => {}; + const ascendingHeld = new Promise((resolve) => { + releaseAscending = resolve; + }); + await page.route(EVENT_HISTORY_API, async (route) => { + await ascendingHeld; + await route.fulfill({ + json: { history: { events }, nextPageToken: null }, + }); + }); + let reversePages = 0; + await page.route(EVENT_HISTORY_API_REVERSE, async (route) => { + reversePages += 1; + if (reversePages === 1) { + await route.fulfill({ + json: { + history: { events: events.slice(1).reverse() }, + nextPageToken: 'workflow-start', + }, + }); + return; + } + await ascendingHeld; + await route.fulfill({ + json: { history: { events: [events[0]] }, nextPageToken: null }, + }); + }); + + try { + await page.goto(`${runUrl}/history`); + const scheduled = page + .getByTestId('event-summary-row') + .filter({ has: page.getByRole('link', { name: '2', exact: true }) }); + await expect(scheduled).toBeVisible(); + await expect(page.getByTestId('event-summary-row')).toHaveCount(4); + await scheduled + .getByRole('cell') + .filter({ visible: true }) + .nth(1) + .hover(); + await expect( + scheduled.getByRole('tooltip', { name: /^\+/ }), + ).toBeHidden(); + + releaseAscending(); + await expect(page.getByTestId('event-summary-row')).toHaveCount(5); + await scheduled + .getByRole('cell') + .filter({ visible: true }) + .nth(1) + .hover(); + await expect( + scheduled.getByRole('tooltip', { name: '+10s', exact: true }), + ).toBeVisible(); + } finally { + releaseAscending(); + } + }); + + test('switches runs through an execution link and browser Back without leaking history', async ({ + page, + }) => { + const firstStarted = makeWorkflowStarted(1); + const linkedEvents = [ + { + ...firstStarted, + workflowExecutionStartedEventAttributes: { + ...firstStarted.workflowExecutionStartedEventAttributes, + continuedExecutionRunId: secondRunId, + }, + }, + ...events.slice(1), + ]; + const secondEvents = historyFor('SmokeSecondRunActivity'); + await page.route(WORKFLOW_API, (route) => { + const requestedRun = new URL(route.request().url()).searchParams.get( + 'execution.runId', + ); + return route.fulfill({ + json: workflowFor(requestedRun === secondRunId ? secondRunId : runId), + }); + }); + for (const api of [EVENT_HISTORY_API, EVENT_HISTORY_API_REVERSE]) { + await page.route(api, (route) => { + const url = new URL(route.request().url()); + const runEvents = + url.searchParams.get('execution.runId') === secondRunId + ? secondEvents + : linkedEvents; + return route.fulfill({ + json: { + history: { + events: url.pathname.endsWith('history-reverse') + ? [...runEvents].reverse() + : runEvents, + }, + nextPageToken: null, + }, + }); + }); + } + + await page.goto(`${runUrl}/history/events/1`); + await expect(page.getByTestId('event-summary-log')).toBeVisible(); + const documentRequests: string[] = []; + page.on('request', (request) => { + if ( + request.isNavigationRequest() && + request.frame() === page.mainFrame() + ) { + documentRequests.push(request.url()); + } + }); + const documentTimeOrigin = await page.evaluate( + () => performance.timeOrigin, + ); + await page.getByRole('link', { name: secondRunId, exact: true }).click(); + await expect(page).toHaveURL(`${secondRunUrl}/timeline`); + await page.getByTestId('history-tab').click(); + await expect(page.getByTestId('event-summary-row')).toHaveCount(5); + await expect(page.getByTestId('event-summary-table')).toContainText( + 'SmokeSecondRunActivity', + ); + await expect(page.getByTestId('event-summary-table')).not.toContainText( + 'SmokeFirstRunActivity', + ); + + await page.goBack(); + await expect(page).toHaveURL(`${secondRunUrl}/timeline`); + await page.goBack(); + await expect(page).toHaveURL(`${runUrl}/history/events/1`); + await page.getByTestId('history-tab').click(); + await expect(page.getByTestId('event-summary-row')).toHaveCount(5); + await expect(page.getByTestId('event-summary-table')).toContainText( + 'SmokeFirstRunActivity', + ); + await expect(page.getByTestId('event-summary-table')).not.toContainText( + 'SmokeSecondRunActivity', + ); + expect(await page.evaluate(() => performance.timeOrigin)).toBe( + documentTimeOrigin, + ); + expect(documentRequests).toEqual([]); + }); +});