-
Notifications
You must be signed in to change notification settings - Fork 3.8k
fix(files,realtime): issue a revision on revert and stop resurrecting cleared cursors #8098
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
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
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
163 changes: 163 additions & 0 deletions
163
apps/sim/app/api/v2/files/[fileId]/versions/[version]/revert/route.test.ts
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,163 @@ | ||
| /** | ||
| * @vitest-environment node | ||
| */ | ||
| import { | ||
| V2_OPERATION_RATE_LIMIT_ALLOWED, | ||
| V2_PREAUTH_RATE_LIMIT_ALLOWED, | ||
| v2ApiKeyAuthModuleMock, | ||
| v2RateLimiterModuleMock, | ||
| v2RouteMocks, | ||
| } from '@sim/testing' | ||
| import { NextRequest } from 'next/server' | ||
| import { beforeEach, describe, expect, it, vi } from 'vitest' | ||
|
|
||
| const mocks = vi.hoisted(() => ({ | ||
| revertVersion: vi.fn(), | ||
| getUserEmailsByIds: vi.fn(), | ||
| findUserEmailsByIds: vi.fn(), | ||
| })) | ||
|
|
||
| vi.mock('@/lib/workspace-files/application/file-versions', () => ({ | ||
| revertWorkspaceFileVersion: { | ||
| operation: { id: 'files.versions.revert', minimumRole: 'write', workspaceApiKey: 'allow' }, | ||
| execute: mocks.revertVersion, | ||
| }, | ||
| })) | ||
|
|
||
| vi.mock('@/lib/api/server/routes/v2-api-key-auth', () => v2ApiKeyAuthModuleMock) | ||
| vi.mock('@/lib/core/rate-limiter', () => v2RateLimiterModuleMock) | ||
|
|
||
| vi.mock('@/lib/users/queries', () => ({ | ||
| getUserEmailsByIds: mocks.getUserEmailsByIds, | ||
| findUserEmailsByIds: mocks.findUserEmailsByIds, | ||
| requireResolvedUserEmail: (emails: Map<string, string>, userId: string) => emails.get(userId)!, | ||
| })) | ||
|
|
||
| import { workspaceFileRevision } from '@/lib/workspace-files/application/file-revision' | ||
| import { POST } from '@/app/api/v2/files/[fileId]/versions/[version]/revert/route' | ||
|
|
||
| const WORKSPACE_ID = 'workspace-1' | ||
| const FILE_ID = 'wf_1' | ||
| const auth = { | ||
| principal: { | ||
| kind: 'workspace_api_key' as const, | ||
| workspaceId: WORKSPACE_ID, | ||
| keyId: 'key-1', | ||
| }, | ||
| rateLimitSubjectIds: ['api-key:key-1', `workspace:${WORKSPACE_ID}`] as const, | ||
| rateLimitSubscription: null, | ||
| keyType: 'workspace' as const, | ||
| } | ||
|
|
||
| const record = { | ||
| id: FILE_ID, | ||
| workspaceId: WORKSPACE_ID, | ||
| name: 'data.csv', | ||
| key: 'workspace/ws/1-x-data.csv', | ||
| path: '/api/files/serve/x', | ||
| size: 8, | ||
| type: 'text/csv', | ||
| uploadedBy: 'user-1', | ||
| folderId: null, | ||
| uploadedAt: new Date('2024-01-01T00:00:00Z'), | ||
| updatedAt: new Date('2024-01-03T00:00:00Z'), | ||
| contentUpdatedAt: new Date('2024-01-04T00:00:00Z'), | ||
| } | ||
|
|
||
| const versionRecord = { | ||
| fileId: FILE_ID, | ||
| version: 4, | ||
| isCurrent: true, | ||
| size: 8, | ||
| contentType: 'text/csv', | ||
| source: 'revert' as const, | ||
| authorUserIds: ['user-1'], | ||
| restoredFromVersion: 2, | ||
| createdAt: new Date('2024-01-04T00:00:00Z'), | ||
| updatedAt: new Date('2024-01-04T00:00:00Z'), | ||
| supersededAt: null, | ||
| } | ||
|
|
||
| const callRevert = (body: unknown) => | ||
| POST( | ||
| new NextRequest(`http://localhost:3000/api/v2/files/${FILE_ID}/versions/2/revert`, { | ||
| method: 'POST', | ||
| headers: { 'Content-Type': 'application/json' }, | ||
| body: JSON.stringify(body), | ||
| }), | ||
| { params: Promise.resolve({ fileId: FILE_ID, version: '2' }) } | ||
| ) | ||
|
|
||
| describe('POST /api/v2/files/[fileId]/versions/[version]/revert', () => { | ||
| beforeEach(() => { | ||
| vi.clearAllMocks() | ||
| v2RouteMocks.authenticate.mockResolvedValue(auth) | ||
| v2RouteMocks.preauthRate.mockResolvedValue(V2_PREAUTH_RATE_LIMIT_ALLOWED) | ||
| v2RouteMocks.operationRate.mockResolvedValue(V2_OPERATION_RATE_LIMIT_ALLOWED) | ||
| mocks.revertVersion.mockResolvedValue({ | ||
| file: record, | ||
| version: versionRecord, | ||
| reverted: true, | ||
| revertedFrom: 3, | ||
| }) | ||
| mocks.getUserEmailsByIds.mockResolvedValue(new Map([['user-1', 'ada@example.com']])) | ||
| mocks.findUserEmailsByIds.mockResolvedValue(new Map([['user-1', 'ada@example.com']])) | ||
| }) | ||
|
|
||
| /** | ||
| * A revert consumes the caller's revision, so the response has to issue its replacement — | ||
| * otherwise chaining a second conditional write needs a metadata re-read, and the window | ||
| * between the two is exactly what the revision is meant to close. | ||
| */ | ||
| it('returns the revision naming the content the revert produced', async () => { | ||
| const expectedRevision = workspaceFileRevision(record)! | ||
|
|
||
| const response = await callRevert({ workspaceId: WORKSPACE_ID, expectedRevision }) | ||
|
|
||
| expect(response.status).toBe(200) | ||
| const body = await response.json() | ||
| expect(body.data.reverted).toBe(true) | ||
| expect(body.data.revision).toBe(expectedRevision) | ||
| expect(mocks.revertVersion).toHaveBeenCalledWith( | ||
| expect.objectContaining({ | ||
| input: expect.objectContaining({ | ||
| fileId: FILE_ID, | ||
| assertedWorkspaceId: WORKSPACE_ID, | ||
| version: 2, | ||
| expectedRevision, | ||
| }), | ||
| }) | ||
| ) | ||
| }) | ||
|
|
||
| it('returns the current content revision when the version was already current', async () => { | ||
| mocks.revertVersion.mockResolvedValue({ | ||
| file: record, | ||
| version: { ...versionRecord, version: 3, source: 'api', restoredFromVersion: null }, | ||
| reverted: false, | ||
| revertedFrom: 3, | ||
| }) | ||
|
|
||
| const body = await (await callRevert({ workspaceId: WORKSPACE_ID })).json() | ||
|
|
||
| expect(body.data.reverted).toBe(false) | ||
| expect(body.data.revision).toBe(workspaceFileRevision(record)) | ||
| }) | ||
|
|
||
| it('forwards the caller revision precondition to the use case', async () => { | ||
| const expectedRevision = workspaceFileRevision(record)! | ||
|
|
||
| await callRevert({ workspaceId: WORKSPACE_ID, expectedRevision }) | ||
|
|
||
| expect(mocks.revertVersion).toHaveBeenCalledWith( | ||
| expect.objectContaining({ | ||
| input: expect.objectContaining({ | ||
| fileId: FILE_ID, | ||
| assertedWorkspaceId: WORKSPACE_ID, | ||
| version: 2, | ||
| expectedRevision, | ||
| }), | ||
| }) | ||
| ) | ||
| }) | ||
| }) | ||
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
60 changes: 60 additions & 0 deletions
60
apps/sim/app/workspace/providers/socket-presence-merge.test.ts
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,60 @@ | ||
| import { describe, expect, it } from 'vitest' | ||
| import { mergePresenceRoster } from '@/app/workspace/providers/socket-presence-merge' | ||
| import type { PresenceUser } from '@/stores/presence/types' | ||
|
|
||
| function peer(overrides: Partial<PresenceUser> = {}): PresenceUser { | ||
| return { | ||
| socketId: 'socket-1', | ||
| userId: 'user-1', | ||
| userName: 'Ada', | ||
| ...overrides, | ||
| } | ||
| } | ||
|
|
||
| describe('mergePresenceRoster', () => { | ||
| it('clears the pointer when the roster carries an explicit null cursor', () => { | ||
| const previous = [peer({ cursor: { x: 10, y: 20 } })] | ||
|
|
||
| const merged = mergePresenceRoster(previous, [peer({ cursor: null })]) | ||
|
|
||
| expect(merged[0].cursor).toBeNull() | ||
| }) | ||
|
|
||
| it('keeps the known pointer when the roster omits the cursor', () => { | ||
| const previous = [peer({ cursor: { x: 10, y: 20 } })] | ||
|
|
||
| const merged = mergePresenceRoster(previous, [peer()]) | ||
|
|
||
| expect(merged[0].cursor).toEqual({ x: 10, y: 20 }) | ||
| }) | ||
|
|
||
| it('keeps the known selection when the roster omits it', () => { | ||
| const previous = [peer({ selection: { type: 'block', id: 'block-1' } })] | ||
|
|
||
| const merged = mergePresenceRoster(previous, [peer()]) | ||
|
|
||
| expect(merged[0].selection).toEqual({ type: 'block', id: 'block-1' }) | ||
| }) | ||
|
|
||
| it('applies a cleared selection, which the wire spells as type none', () => { | ||
| const previous = [peer({ selection: { type: 'block', id: 'block-1' } })] | ||
|
|
||
| const merged = mergePresenceRoster(previous, [peer({ selection: { type: 'none' } })]) | ||
|
|
||
| expect(merged[0].selection).toEqual({ type: 'none' }) | ||
| }) | ||
|
|
||
| it('passes through a peer it has no previous presence for', () => { | ||
| const joining = peer({ socketId: 'socket-2', userId: 'user-2', cursor: { x: 1, y: 2 } }) | ||
|
|
||
| expect(mergePresenceRoster([], [joining])).toEqual([joining]) | ||
| }) | ||
|
|
||
| it('drops peers the roster no longer lists', () => { | ||
| const previous = [peer(), peer({ socketId: 'socket-2', userId: 'user-2' })] | ||
|
|
||
| const merged = mergePresenceRoster(previous, [peer()]) | ||
|
|
||
| expect(merged.map((user) => user.socketId)).toEqual(['socket-1']) | ||
| }) | ||
| }) |
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,32 @@ | ||
| import type { PresenceUser } from '@/stores/presence/types' | ||
|
|
||
| /** | ||
| * Folds a `presence-update` roster over the presence already held for each socket. | ||
| * | ||
| * The server rebuilds a socket's presence record from scratch when it joins a room, so a re-join | ||
| * of the same workflow broadcasts a roster whose `cursor` and `selection` are simply absent. The | ||
| * fields are carried over rather than blanked, which is what keeps a peer's pointer from | ||
| * flickering on every re-join. | ||
| * | ||
| * A `null` `cursor` is therefore not the same as an absent one: it is a pointer the peer | ||
| * explicitly cleared on leaving the canvas. Coalescing the two with `??` would resurrect a stale | ||
| * pointer whenever the clearing `cursor-update` was missed — dropped by the visibility gate | ||
| * during a join, or by a rejoin that never refreshed the roster. `selection` needs no such | ||
| * split: a cleared selection is `{ type: 'none' }`, and the wire type admits no `null`. | ||
| */ | ||
| export function mergePresenceRoster( | ||
| previous: PresenceUser[], | ||
| incoming: PresenceUser[] | ||
| ): PresenceUser[] { | ||
| const previousBySocketId = new Map(previous.map((user) => [user.socketId, user])) | ||
|
|
||
| return incoming.map((user) => { | ||
| const existing = previousBySocketId.get(user.socketId) | ||
| if (!existing) return user | ||
| return { | ||
| ...user, | ||
| cursor: user.cursor === undefined ? existing.cursor : user.cursor, | ||
| selection: user.selection ?? existing.selection, | ||
| } | ||
| }) | ||
| } |
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.
Uh oh!
There was an error while loading. Please reload this page.