-
Notifications
You must be signed in to change notification settings - Fork 490
feat: add polling fallback for stale asset downloads #7926
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
12 commits
Select commit
Hold shift + click to select a range
020f880
feat: add polling fallback for stale asset downloads
DrJKL 39d664a
docs: add granular Pinia store testing guidance
DrJKL 459d733
feat: poll task endpoint for stale download recovery
DrJKL fe962e9
docs: add caveat about task-specific payload/result schemas
DrJKL e95d04c
refactor(test): use vi.hoisted for event handler mock state
DrJKL 8807e14
refactor(test): use block body to avoid type assertion
DrJKL 6c180e0
refactor: improve task polling with fromZodError and parallel execution
DrJKL 464e66c
Merge branch 'main' into feat/stale-download-polling
DrJKL 72c9196
Faster threshold between messages to start the polling.
DrJKL 06b3ebb
Mark asset_id as optional. It is only populated when the download is …
DrJKL 1061f78
Update src/stores/assetDownloadStore.ts
DrJKL e3bb74b
fix: ensure polling starts immediately for active downloads on init
DrJKL File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,138 @@ | ||
| --- | ||
| globs: | ||
| - '**/*.test.ts' | ||
| - '**/*.spec.ts' | ||
| --- | ||
|
|
||
| # Vitest Patterns | ||
|
|
||
| ## Setup | ||
|
|
||
| Use `createTestingPinia` from `@pinia/testing`, not `createPinia`: | ||
|
|
||
| ```typescript | ||
| import { createTestingPinia } from '@pinia/testing' | ||
| import { setActivePinia } from 'pinia' | ||
| import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' | ||
|
|
||
| describe('MyStore', () => { | ||
| beforeEach(() => { | ||
| setActivePinia(createTestingPinia({ stubActions: false })) | ||
| vi.useFakeTimers() | ||
| vi.resetAllMocks() | ||
| }) | ||
|
|
||
| afterEach(() => { | ||
| vi.useRealTimers() | ||
| }) | ||
| }) | ||
| ``` | ||
|
|
||
| **Why `stubActions: false`?** By default, testing pinia stubs all actions. Set to `false` when testing actual store behavior. | ||
|
|
||
| ## Mock Patterns | ||
|
|
||
| ### Reset all mocks at once | ||
|
|
||
| ```typescript | ||
| beforeEach(() => { | ||
| vi.resetAllMocks() // Not individual mock.mockReset() calls | ||
| }) | ||
| ``` | ||
|
|
||
| ### Module mocks with vi.mock() | ||
|
|
||
| ```typescript | ||
| vi.mock('@/scripts/api', () => ({ | ||
| api: { | ||
| addEventListener: vi.fn(), | ||
| fetchData: vi.fn() | ||
| } | ||
| })) | ||
|
|
||
| vi.mock('@/services/myService', () => ({ | ||
| myService: { | ||
| doThing: vi.fn() | ||
| } | ||
| })) | ||
| ``` | ||
|
|
||
| ### Configure mocks in tests | ||
|
|
||
| ```typescript | ||
| import { api } from '@/scripts/api' | ||
| import { myService } from '@/services/myService' | ||
|
|
||
| it('handles success', () => { | ||
| vi.mocked(myService.doThing).mockResolvedValue({ data: 'test' }) | ||
| // ... test code | ||
| }) | ||
| ``` | ||
|
|
||
| ## Testing Event Listeners | ||
|
|
||
| When a store registers event listeners at module load time: | ||
|
|
||
| ```typescript | ||
| function getEventHandler() { | ||
| const call = vi.mocked(api.addEventListener).mock.calls.find( | ||
| ([event]) => event === 'my_event' | ||
| ) | ||
| return call?.[1] as (e: CustomEvent<MyEventType>) => void | ||
| } | ||
|
|
||
| function dispatch(data: MyEventType) { | ||
| const handler = getEventHandler() | ||
| handler(new CustomEvent('my_event', { detail: data })) | ||
| } | ||
|
|
||
| it('handles events', () => { | ||
| const store = useMyStore() | ||
| dispatch({ field: 'value' }) | ||
| expect(store.items).toHaveLength(1) | ||
| }) | ||
| ``` | ||
|
|
||
| ## Testing with Fake Timers | ||
|
|
||
| For stores with intervals, timeouts, or polling: | ||
|
|
||
| ```typescript | ||
| beforeEach(() => { | ||
| vi.useFakeTimers() | ||
| }) | ||
|
|
||
| afterEach(() => { | ||
| vi.useRealTimers() | ||
| }) | ||
|
|
||
| it('polls after delay', async () => { | ||
| const store = useMyStore() | ||
| store.startPolling() | ||
|
|
||
| await vi.advanceTimersByTimeAsync(30000) | ||
|
|
||
| expect(mockService.fetch).toHaveBeenCalled() | ||
| }) | ||
| ``` | ||
|
|
||
| ## Assertion Style | ||
|
|
||
| Prefer `.toHaveLength()` over `.length.toBe()`: | ||
|
|
||
| ```typescript | ||
| // Good | ||
| expect(store.items).toHaveLength(1) | ||
|
|
||
| // Avoid | ||
| expect(store.items.length).toBe(1) | ||
| ``` | ||
|
|
||
| Use `.toMatchObject()` for partial matching: | ||
|
|
||
| ```typescript | ||
| expect(store.completedItems[0]).toMatchObject({ | ||
| id: 'task-123', | ||
| status: 'done' | ||
| }) | ||
| ``` |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,70 @@ | ||
| /** | ||
| * Task Service for polling background task status. | ||
| * | ||
| * CAVEAT: The `payload` and `result` schemas below are specific to | ||
| * `task:download_file` tasks. Other task types may have different | ||
| * payload/result structures. We are not generalizing this until | ||
| * additional use cases arise. | ||
| */ | ||
| import { z } from 'zod' | ||
| import { fromZodError } from 'zod-validation-error' | ||
|
|
||
| import { api } from '@/scripts/api' | ||
|
|
||
| const TASKS_ENDPOINT = '/tasks' | ||
|
|
||
| const zTaskStatus = z.enum(['created', 'running', 'completed', 'failed']) | ||
|
|
||
| const zDownloadFileResult = z.object({ | ||
| success: z.boolean(), | ||
| file_path: z.string().optional(), | ||
| bytes_downloaded: z.number().optional(), | ||
| content_type: z.string().optional(), | ||
| hash: z.string().optional(), | ||
| filename: z.string().optional(), | ||
| asset_id: z.string().optional(), | ||
| metadata: z.record(z.unknown()).optional(), | ||
| error: z.string().optional() | ||
| }) | ||
|
|
||
| const zTaskResponse = z.object({ | ||
| id: z.string().uuid(), | ||
| idempotency_key: z.string(), | ||
| task_name: z.string(), | ||
| payload: z.record(z.unknown()), | ||
| status: zTaskStatus, | ||
| result: zDownloadFileResult.optional(), | ||
| error_message: z.string().optional(), | ||
| create_time: z.string().datetime(), | ||
| update_time: z.string().datetime(), | ||
| started_at: z.string().datetime().optional(), | ||
| completed_at: z.string().datetime().optional() | ||
| }) | ||
|
|
||
| export type TaskResponse = z.infer<typeof zTaskResponse> | ||
|
|
||
| function createTaskService() { | ||
| async function getTask(taskId: string): Promise<TaskResponse> { | ||
| const res = await api.fetchApi(`${TASKS_ENDPOINT}/${taskId}`) | ||
|
|
||
| if (!res.ok) { | ||
| if (res.status === 404) { | ||
| throw new Error(`Task not found: ${taskId}`) | ||
| } | ||
| throw new Error(`Failed to get task ${taskId}: ${res.status}`) | ||
| } | ||
|
|
||
| const data = await res.json() | ||
| const result = zTaskResponse.safeParse(data) | ||
|
|
||
| if (!result.success) { | ||
| throw new Error(fromZodError(result.error).message) | ||
| } | ||
coderabbitai[bot] marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
|
||
| return result.data | ||
| } | ||
|
|
||
| return { getTask } | ||
| } | ||
|
|
||
| export const taskService = createTaskService() | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
nit: you could make the a generic and inject the zDownloadFileResult in the
getTaskfunction to future proof this a bitThere was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
That's what the caveat at the top is for.
I don't like to make single use things generic. Reusable things, those should be generic.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
YAGNI