mirror of
https://github.com/baserow/baserow.git
synced 2026-12-04 08:18:42 +00:00
* feat: introduce User-backed workspace identities Replaces workspace core.Agent subjects with identities stored as Django Users, so permissions, execution and attribution use the same record. - User.objects and WorkspaceUser.objects are human-only; permission and identity code opts in through objects_and_identities. is_human and is_identity classify a user at runtime. - Login, tokens, seats, notification recipients, personal views and last-admin checks stay human-only. Roles, teams and field grants work for identities unchanged. - Agent applications run as an identity, never as a person. Every shared tool rechecks the identity's authority on each call, and MCP refuses a tool that skips that boundary. - Migrations add the profile metadata and index, remove the Agent model and delete or clear legacy Agent data: trash entries, role assignments, team memberships, integration authorizations and run-as bindings. - Rename the management API, UI, events and feature flag to identity. Squashed and rebased onto develop; the previous history is kept on backup/6556-before-develop-rebase. * refactor: remove generic subject options endpoint * refactor: simplify identity selection and Agent run-as options * feat: distinguish identity notification senders * fix: restrict identity bindings to identity managers * docs: record users and identities verification * fix: restore snapshots as the person restoring A restore checked the snapshot creator's permission and used the creator to decide whether an Agent keeps its identity binding. It now checks the person restoring, passed to the import as `restored_by`. `copied_by` stays unset on restore, so credential checks keyed on it behave as on develop. Restoring a snapshot whose creator was deleted works again. The copy rule for identity bindings covers Agent run-as only; a copied Local Baserow integration keeps its authorized subject. * fix: leave settings pages the user may not open A settings route without a permitted tab rendered an empty page, as the Identities page did with its feature flag off. It now opens the first page the user may see. * fix: renumber the legacy Agent cleanup migrations Develop added agent 0016 and integrations 0043, so the migrations that clear legacy Agent run-as bindings and integration authorizations move to agent 0017 and integrations 0044. * test(agent): run the trigger self-event test as an identity The test added on develop created a `core.Agent`, which this branch removes. It now uses an identity user as the Agent's run-as subject. * perf: load user types once per batched permission check * refactor: state the stored subjects in each subject type * fix: give every user a profile * fix: keep identity attribution on rows copied in their workspace * refactor: give people and identities their own subject type UserSubjectType stays the type both are registered and stored under. It forwards what differs to HumanSubjectType and IdentitySubjectType, so get_specific_type is the only place in subject code that inspects the user type. The registry returns the specific type on request and get_by_model keeps returning the stored type, which never reads the profile. An identity's membership is checked in one query instead of two. * fix: keep the roles of identities when a database is duplicated The role import read subjects through the model's default manager, which only returns people, so duplicating or restoring a database failed when an identity held a role on it. It now resolves the subject through the subject registry. A subject that no longer exists is skipped instead of failing the whole duplicate or restore. * refactor: look up a subject type from its content type in one place * fix: reload a cached token whose profile is incomplete A token cached by the previous release has a profile without the user type, which reads as not a person, so its requests were refused until the entry expired. The token cache now treats it as a miss, with the check the user cache already used. * refactor: check the user type once where the check was repeated The MCP endpoint loader, the personal view permission manager and the identity trash type each asked the same question several times. The rule that an identity is never selected by email moves from the team handler to the identity subject type. * refactor: leave trashed workspaces out of the identity membership manager WorkspaceUser.objects_and_identities was named after objects but also returned memberships of trashed workspaces, so callers filtered them by hand. It now follows the existing pair: it leaves trashed workspaces out, and objects_and_identities_and_trash includes them, as objects_and_trash does for people. * test: state the behaviour of every user type The table fails when a user type is added and says what has to be decided first. An unknown type is checked to be denied. * refactor: refuse to say whether a stored user subject is interactive The answer differs between a person and an identity, so reading it from the stored type would be wrong for one of them. It now raises and points to the specific type. * refactor: lock the person in membership writes instead of checking the type Leaving a workspace, removing a member and adding a user lock the user through the people manager, which refuses an identity or an unknown type in the same query. Nothing adds an identity through add_user_to_workspace, so its branch for identities goes. The last admin check compares the membership with the people who are admin, which needs no type check. * test: leave no rows behind in the legacy authorization migration test The test left an integration that pointed at a user that didn't exist and a workspace, in the database the migration tests share. Tests that ran after it then failed on the foreign key or on the workspace id. It now uses a real user and empties the two tables. * docs: describe the subject types and compare the Subject table alternative ADR 013 is shorter and states that people and identities each have a specific subject type under the stored auth.User type. It compares shared User storage with a Subject table that users and identities would both point to. * chore: run the legacy run-as cleanup after the agent actions migration Develop added agent migration 0017, so the cleanup becomes 0018 and depends on it. * test: leave no rows behind in the legacy agent migration tests Like the legacy authorization test, these left a workspace in the database the migration tests share, which a later test that creates workspaces with fixed ids collides with. * fix: write and read the workspace role of an identity in one place The role assignment API wrote the role of an identity through the membership update of people, which told every member of the workspace about it and stored Builder as MEMBER, while the identities API stored BUILDER and returned the stored value. Both now write through the identity handler, which stores the role like the role of a person, and the role is read with the resolver the workspace members use. * fix: take no row lock in the membership writes of a person Leaving a workspace locked the user before the membership while removing or updating a member locks the membership first, so the two could deadlock. The user type never changes and these operations refuse an identity, so the lock protected nothing: they now only check that the user is a person. Leaving no longer locks the admin memberships and removing a member no longer checks for the last admin, as before identities. * fix: find an identity by its name only in the subject options The search also matched the email and username, which for an identity hold an internal key, so searching a part of that key returned every identity. * chore: run the identity migrations after the new ones on develop Develop added core 0138, integrations 0044 and enterprise 0073, so the identity migrations become core 0139 and 0140, integrations 0045 and enterprise 0074 and depend on them. * fix: keep the identity of a copied integration only for identity managers A duplicated application or a restored snapshot kept the identity its Local Baserow integration acts as, without checking the person who made the copy. Restoring a snapshot could so bring back a binding an admin had removed. The copy now keeps the identity only when that person may bind identities, as the Agent application already did, and is otherwise authorized as that person. * docs: follow the renumbered migrations and the copy rule in the test plan The test plan named the identity migrations and their tests by their old numbers and still said a copied integration keeps its subject. * test(agent): run the row trigger tests as an identity The row trigger tests added on develop created a `core.Agent`, which this branch removes. They now use an identity user as the Agent's run-as subject, and the e2e fixture creates it through the identities endpoint.
2090 lines
62 KiB
JavaScript
2090 lines
62 KiB
JavaScript
import { vi, describe, beforeEach, test, expect } from 'vitest'
|
|
|
|
import { RealTimeHandler } from '@baserow/modules/core/plugins/realTimeHandler'
|
|
import { logoutAndRedirectToLogin } from '@baserow/modules/core/utils/auth'
|
|
import {
|
|
FIRST_CONNECT_CURSOR,
|
|
NO_REPLAY_AVAILABLE,
|
|
} from '@baserow/modules/core/plugins/realtimeProtocol'
|
|
|
|
vi.mock('#imports', () => ({
|
|
useRuntimeConfig: () => ({
|
|
public: { publicBackendUrl: 'http://localhost' },
|
|
}),
|
|
}))
|
|
|
|
vi.mock('@baserow/modules/core/utils/auth', () => ({
|
|
logoutAndRedirectToLogin: vi.fn(() => Promise.resolve()),
|
|
}))
|
|
|
|
// The handler reads WebSocket.OPEN / CONNECTING constants; the test
|
|
// environment may not provide them on the class object, in which case the
|
|
// readiness gate would short-circuit and silently swallow sends.
|
|
if (typeof globalThis.WebSocket === 'undefined') {
|
|
globalThis.WebSocket = {}
|
|
}
|
|
if (typeof globalThis.WebSocket.OPEN !== 'number') {
|
|
globalThis.WebSocket.OPEN = 1
|
|
globalThis.WebSocket.CONNECTING = 0
|
|
globalThis.WebSocket.CLOSING = 2
|
|
globalThis.WebSocket.CLOSED = 3
|
|
}
|
|
|
|
function makeStore() {
|
|
const dispatched = []
|
|
const webSocketId = 'test-ws-id-' + Math.random().toString(36).slice(2)
|
|
const store = {
|
|
getters: {
|
|
'auth/token': 'token',
|
|
'auth/webSocketId': webSocketId,
|
|
'workspace/isLoaded': true,
|
|
'aiProvider/hasLoaded': true,
|
|
'aiProvider/getWorkspaceId': null,
|
|
'aiProvider/isLoaded': true,
|
|
},
|
|
dispatch(name, value) {
|
|
dispatched.push([name, value])
|
|
return Promise.resolve()
|
|
},
|
|
subscribe() {},
|
|
_dispatched: dispatched,
|
|
}
|
|
return store
|
|
}
|
|
|
|
function makeHandler() {
|
|
const store = makeStore()
|
|
const context = { store, app: { $router: { push: vi.fn() } } }
|
|
const handler = new RealTimeHandler(context)
|
|
// Stand-in for an open websocket so _sendReplayEventsRequest goes
|
|
// through.
|
|
const sentMessages = []
|
|
handler.socket = {
|
|
readyState: 1, // WebSocket.OPEN
|
|
onclose: null,
|
|
send(payload) {
|
|
sentMessages.push(JSON.parse(payload))
|
|
},
|
|
close() {},
|
|
}
|
|
return { handler, store, context, sentMessages }
|
|
}
|
|
|
|
function fire(handler, type, data) {
|
|
return Promise.all(
|
|
(handler.events[type] || []).map((cb) => cb(handler.context, data))
|
|
)
|
|
}
|
|
|
|
describe('RealTimeHandler force_disconnect', () => {
|
|
test('logs the user out through the app router and stops reconnecting', async () => {
|
|
const { handler, store, context } = makeHandler()
|
|
handler.reconnect = true
|
|
|
|
await fire(handler, 'force_disconnect', {})
|
|
|
|
expect(handler.reconnect).toBe(false)
|
|
expect(logoutAndRedirectToLogin).toHaveBeenCalledWith(
|
|
context.app.$router,
|
|
store,
|
|
false,
|
|
true
|
|
)
|
|
})
|
|
})
|
|
|
|
describe('RealTimeHandler application updates', () => {
|
|
test.each([false, true])(
|
|
'invalidates agent choices, with selected identity changed=%s',
|
|
async (changed) => {
|
|
const { handler, store } = makeHandler()
|
|
const application = { id: 3, type: 'agent', _: { realtimeVersion: 7 } }
|
|
store.getters['application/get'] = () => application
|
|
await fire(handler, 'agent_run_as_updated', {
|
|
agent_ids: [3],
|
|
selected_agent_ids: changed ? [3] : [],
|
|
})
|
|
expect(store._dispatched).toEqual([
|
|
[
|
|
'application/forceUpdate',
|
|
{
|
|
application,
|
|
data: {
|
|
_: {
|
|
realtimeVersion: 7,
|
|
runAsOptionsVersion: 1,
|
|
runAsIdentityVersion: Number(changed),
|
|
},
|
|
},
|
|
},
|
|
],
|
|
])
|
|
}
|
|
)
|
|
|
|
test('invalidates each loaded Agent once from a combined identity update', async () => {
|
|
const { handler, store } = makeHandler()
|
|
const applications = [
|
|
{ id: 3, type: 'agent', _: { runAsIdentityVersion: 7 } },
|
|
{ id: 4, type: 'agent', _: { runAsOptionsVersion: 2 } },
|
|
{ id: 5, type: 'database' },
|
|
]
|
|
store.getters['application/get'] = (id) =>
|
|
applications.find((application) => application.id === id)
|
|
|
|
await fire(handler, 'agent_run_as_updated', {
|
|
agent_ids: [3, 4, 5, 6],
|
|
selected_agent_ids: [3],
|
|
})
|
|
|
|
expect(
|
|
store._dispatched.map(([action, { application, data }]) => [
|
|
action,
|
|
application.id,
|
|
data._,
|
|
])
|
|
).toEqual([
|
|
[
|
|
'application/forceUpdate',
|
|
3,
|
|
{ runAsIdentityVersion: 8, runAsOptionsVersion: 1 },
|
|
],
|
|
[
|
|
'application/forceUpdate',
|
|
4,
|
|
{ runAsOptionsVersion: 3, runAsIdentityVersion: 0 },
|
|
],
|
|
])
|
|
})
|
|
|
|
test('marks application updates as external, including unchanged public metadata', async () => {
|
|
const { handler, store } = makeHandler()
|
|
const application = { id: 3, type: 'agent', readiness: 'ready' }
|
|
store.getters['application/get'] = (id) =>
|
|
application.id === id ? application : undefined
|
|
|
|
await fire(handler, 'application_updated', {
|
|
application_id: 3,
|
|
application: { ...application },
|
|
})
|
|
|
|
expect(store._dispatched).toEqual([
|
|
[
|
|
'application/forceUpdate',
|
|
{ application, data: application, viaRealtime: true },
|
|
],
|
|
])
|
|
})
|
|
})
|
|
|
|
describe('RealTimeHandler identity events', () => {
|
|
test('create and update events upsert the serialized identity', () => {
|
|
const { handler, store } = makeHandler()
|
|
const identity = { id: 1, workspace_id: 42, name: 'Writer' }
|
|
|
|
fire(handler, 'identity_created', { workspace_id: 42, identity })
|
|
fire(handler, 'identity_updated', { workspace_id: 42, identity })
|
|
|
|
expect(store._dispatched).toContainEqual(['identity/forceCreate', identity])
|
|
expect(store._dispatched).toContainEqual(['identity/forceUpdate', identity])
|
|
})
|
|
|
|
test('delete events remove the identity from its workspace', () => {
|
|
const { handler, store } = makeHandler()
|
|
|
|
fire(handler, 'identity_deleted', { workspace_id: 42, identity_id: 1 })
|
|
|
|
expect(store._dispatched).toContainEqual([
|
|
'identity/forceDelete',
|
|
{ workspaceId: 42, identityId: 1 },
|
|
])
|
|
})
|
|
})
|
|
|
|
describe('RealTimeHandler replay_events flow', () => {
|
|
let env
|
|
beforeEach(() => {
|
|
env = makeHandler()
|
|
})
|
|
|
|
test('authentication sends a baseline replay request when replay is enabled', () => {
|
|
fire(env.handler, 'authentication', {
|
|
success: true,
|
|
replay_enabled: true,
|
|
})
|
|
const replayRequest = env.sentMessages.find(
|
|
(m) => m.type === 'replay_events'
|
|
)
|
|
expect(replayRequest).toEqual({
|
|
type: 'replay_events',
|
|
supports_retry: true,
|
|
last_seen_id: FIRST_CONNECT_CURSOR,
|
|
})
|
|
})
|
|
|
|
test('authentication does not send replay_events when replay is disabled', () => {
|
|
fire(env.handler, 'authentication', {
|
|
success: true,
|
|
replay_enabled: false,
|
|
})
|
|
const replayRequest = env.sentMessages.find(
|
|
(m) => m.type === 'replay_events'
|
|
)
|
|
expect(replayRequest).toBeUndefined()
|
|
expect(env.handler.replayEnabled).toBe(false)
|
|
})
|
|
|
|
test('authentication requests replay even without active workspace', () => {
|
|
const local = makeHandler()
|
|
fire(local.handler, 'authentication', {
|
|
success: true,
|
|
replay_enabled: true,
|
|
})
|
|
const replayRequest = local.sentMessages.find(
|
|
(m) => m.type === 'replay_events'
|
|
)
|
|
expect(replayRequest).toEqual({
|
|
type: 'replay_events',
|
|
supports_retry: true,
|
|
last_seen_id: FIRST_CONNECT_CURSOR,
|
|
})
|
|
})
|
|
|
|
test('client stores zero latest_event_id from empty table and sends it back on reconnect', () => {
|
|
// Server returns 0 as latest_event_id when replay is enabled but no
|
|
// events have been recorded yet (Coalesce(Max("id"), 0)).
|
|
env.handler.replayEnabled = true
|
|
fire(env.handler, 'replay_events_result', {
|
|
force_refresh: false,
|
|
latest_event_id: 0,
|
|
})
|
|
expect(env.handler.lastSeenEventId).toBe(0)
|
|
|
|
// Reconnect: client sends 0 which is a valid cursor (not a sentinel).
|
|
env.sentMessages.length = 0
|
|
env.handler._sendReplayEventsRequest()
|
|
const replayRequest = env.sentMessages.find(
|
|
(m) => m.type === 'replay_events'
|
|
)
|
|
expect(replayRequest).toEqual({
|
|
type: 'replay_events',
|
|
supports_retry: true,
|
|
last_seen_id: 0,
|
|
})
|
|
})
|
|
|
|
test('replay_events_result needing refresh fires the toast', () => {
|
|
env.handler.lastSeenEventId = 10
|
|
fire(env.handler, 'replay_events_result', {
|
|
force_refresh: true,
|
|
latest_event_id: 42,
|
|
})
|
|
expect(
|
|
env.store._dispatched.some(
|
|
([n, v]) => n === 'toast/setWorkspaceOutdated' && v === true
|
|
)
|
|
).toBe(true)
|
|
expect(env.handler.lastSeenEventId).toBe(10)
|
|
})
|
|
|
|
test('replay_events_result with force_refresh does not advance latest_event_id', () => {
|
|
env.handler.lastSeenEventId = 50
|
|
fire(env.handler, 'replay_events_result', {
|
|
force_refresh: true,
|
|
latest_event_id: 42,
|
|
})
|
|
expect(
|
|
env.store._dispatched.some(
|
|
([n, v]) => n === 'toast/setWorkspaceOutdated' && v === true
|
|
)
|
|
).toBe(true)
|
|
// The high-water mark must not regress below the live-message value.
|
|
expect(env.handler.lastSeenEventId).toBe(50)
|
|
})
|
|
|
|
test('replay_events_result with force_refresh false advances baseline without toast', () => {
|
|
fire(env.handler, 'replay_events_result', {
|
|
force_refresh: false,
|
|
latest_event_id: 99,
|
|
})
|
|
expect(
|
|
env.store._dispatched.some(
|
|
([n, v]) => n === 'toast/setWorkspaceOutdated' && v === true
|
|
)
|
|
).toBe(false)
|
|
expect(env.handler.lastSeenEventId).toBe(99)
|
|
})
|
|
})
|
|
|
|
describe('RealTimeHandler transient replay recovery', () => {
|
|
let env
|
|
|
|
function receive(data, socket = env.handler.socket) {
|
|
socket.onmessage({ data: JSON.stringify(data) })
|
|
}
|
|
|
|
function authenticate(cursor = FIRST_CONNECT_CURSOR) {
|
|
env.handler.lastSeenEventId = cursor
|
|
receive({ type: 'authentication', success: true, replay_enabled: true })
|
|
}
|
|
|
|
async function openSocket() {
|
|
await env.handler.connect(false)
|
|
const socket = env.handler.socket
|
|
socket.readyState = WebSocket.OPEN
|
|
socket.send = (payload) => env.sentMessages.push(JSON.parse(payload))
|
|
socket.onopen()
|
|
return socket
|
|
}
|
|
|
|
beforeEach(async () => {
|
|
vi.useFakeTimers()
|
|
vi.spyOn(Math, 'random').mockReturnValue(0)
|
|
env = makeHandler()
|
|
env.handler.socket = null
|
|
await openSocket()
|
|
})
|
|
|
|
afterEach(() => {
|
|
env.handler.disconnect()
|
|
vi.restoreAllMocks()
|
|
vi.useRealTimers()
|
|
})
|
|
|
|
test('retries once with the original cursor and leaves the existing warning alone', () => {
|
|
authenticate(10)
|
|
env.store.dispatch('toast/setWorkspaceOutdated', true)
|
|
env.store._dispatched.length = 0
|
|
|
|
receive({ type: 'replay_events_retry', retry_after_ms: 1000 })
|
|
// Duplicate responses and manual attempts must not create extra requests.
|
|
receive({ type: 'replay_events_retry', retry_after_ms: 1000 })
|
|
env.handler._sendReplayEventsRequest()
|
|
expect(env.sentMessages).toHaveLength(1)
|
|
expect(env.store._dispatched).toEqual([])
|
|
|
|
vi.advanceTimersByTime(999)
|
|
expect(env.sentMessages).toHaveLength(1)
|
|
vi.advanceTimersByTime(1)
|
|
expect(env.sentMessages).toEqual([
|
|
{ type: 'replay_events', last_seen_id: 10, supports_retry: true },
|
|
{ type: 'replay_events', last_seen_id: 10, supports_retry: true },
|
|
])
|
|
vi.advanceTimersByTime(60000)
|
|
expect(env.sentMessages).toHaveLength(2)
|
|
})
|
|
|
|
test.each([null, undefined, '5000', NaN, Infinity, -Infinity])(
|
|
'uses the base retry delay for invalid retry_after_ms %s',
|
|
(retryAfterMs) => {
|
|
authenticate(10)
|
|
// Call the registered callback directly: JSON would turn NaN/Infinity into
|
|
// null, concealing whether the retry scheduler handles non-finite values.
|
|
fire(env.handler, 'replay_events_retry', {
|
|
retry_after_ms: retryAfterMs,
|
|
})
|
|
|
|
vi.advanceTimersByTime(999)
|
|
expect(env.sentMessages).toHaveLength(1)
|
|
vi.advanceTimersByTime(1)
|
|
expect(env.sentMessages).toEqual([
|
|
{ type: 'replay_events', last_seen_id: 10, supports_retry: true },
|
|
{ type: 'replay_events', last_seen_id: 10, supports_retry: true },
|
|
])
|
|
vi.advanceTimersByTime(60000)
|
|
expect(env.sentMessages).toHaveLength(2)
|
|
}
|
|
)
|
|
|
|
test('an abandoned replay does not schedule a retry for an in-flight request', () => {
|
|
authenticate(10)
|
|
// Keep the request in flight to exercise the abandoned-replay guard itself.
|
|
env.handler.replayAbandoned = true
|
|
env.store.dispatch('toast/setWorkspaceOutdated', true)
|
|
env.store._dispatched.length = 0
|
|
const pendingTimers = vi.getTimerCount()
|
|
|
|
receive({ type: 'replay_events_retry', retry_after_ms: 1000 })
|
|
|
|
expect(vi.getTimerCount()).toBe(pendingTimers)
|
|
vi.advanceTimersByTime(60000)
|
|
expect(env.sentMessages).toEqual([
|
|
{ type: 'replay_events', last_seen_id: 10, supports_retry: true },
|
|
])
|
|
expect(env.store._dispatched).toEqual([])
|
|
})
|
|
|
|
test('merges live and replay events in order without applying duplicates', () => {
|
|
const received = []
|
|
env.handler.registerEvent('row_updated', (_context, data) => {
|
|
received.push(data._event_id)
|
|
})
|
|
authenticate(10)
|
|
receive({ type: 'replay_events_retry', retry_after_ms: 1000 })
|
|
receive({ type: 'row_updated', _event_id: 12 })
|
|
// Ephemeral events continue immediately while persistent updates await replay.
|
|
receive({ type: 'presence.space_discard', space: 'table-1' })
|
|
expect(env.store._dispatched).toContainEqual([
|
|
'presence/clearSpace',
|
|
{ space: 'table-1' },
|
|
])
|
|
expect(received).toEqual([])
|
|
|
|
vi.advanceTimersByTime(1000)
|
|
expect(env.sentMessages.at(-1).last_seen_id).toBe(10)
|
|
receive({ type: 'row_updated', _event_id: 10 })
|
|
receive({ type: 'row_updated', _event_id: 11 })
|
|
receive({ type: 'row_updated', _event_id: 12 })
|
|
receive({
|
|
type: 'replay_events_result',
|
|
force_refresh: false,
|
|
latest_event_id: 12,
|
|
})
|
|
|
|
expect(received).toEqual([11, 12])
|
|
expect(env.handler.lastSeenEventId).toBe(12)
|
|
expect(env.store._dispatched).not.toContainEqual([
|
|
'toast/setWorkspaceOutdated',
|
|
true,
|
|
])
|
|
receive({ type: 'row_updated', _event_id: 13 })
|
|
// Channel-layer copies can remain queued until after replay completes.
|
|
receive({ type: 'row_updated', _event_id: 11 })
|
|
receive({ type: 'row_updated', _event_id: 12 })
|
|
expect(received).toEqual([11, 12, 13])
|
|
})
|
|
|
|
test('retries the first-connect baseline and applies live events below it', () => {
|
|
const callback = vi.fn()
|
|
env.handler.registerEvent('row_updated', callback)
|
|
authenticate()
|
|
receive({ type: 'replay_events_retry', retry_after_ms: 1000 })
|
|
receive({ type: 'row_updated', _event_id: 12 })
|
|
vi.advanceTimersByTime(1000)
|
|
expect(env.sentMessages.at(-1).last_seen_id).toBe(FIRST_CONNECT_CURSOR)
|
|
|
|
receive({
|
|
type: 'replay_events_result',
|
|
force_refresh: false,
|
|
latest_event_id: 15,
|
|
})
|
|
expect(callback).toHaveBeenCalledExactlyOnceWith(env.context, {
|
|
type: 'row_updated',
|
|
_event_id: 12,
|
|
})
|
|
expect(env.handler.lastSeenEventId).toBe(15)
|
|
})
|
|
|
|
test('backs off with jitter, caps the delay, and resets after a result', () => {
|
|
authenticate(10)
|
|
Math.random.mockReturnValue(0.5)
|
|
for (const delay of [1125, 2250, 4500, 8500, 16500, 29500, 29500]) {
|
|
const sentBefore = env.sentMessages.length
|
|
receive({ type: 'replay_events_retry', retry_after_ms: 1000 })
|
|
vi.advanceTimersByTime(delay - 1)
|
|
expect(env.sentMessages).toHaveLength(sentBefore)
|
|
vi.advanceTimersByTime(1)
|
|
expect(env.sentMessages).toHaveLength(sentBefore + 1)
|
|
}
|
|
|
|
receive({
|
|
type: 'replay_events_result',
|
|
force_refresh: false,
|
|
latest_event_id: 15,
|
|
})
|
|
env.handler._sendReplayEventsRequest()
|
|
const sentBefore = env.sentMessages.length
|
|
receive({ type: 'replay_events_retry', retry_after_ms: 1000 })
|
|
vi.advanceTimersByTime(1125)
|
|
expect(env.sentMessages).toHaveLength(sentBefore + 1)
|
|
expect(env.sentMessages.at(-1).last_seen_id).toBe(15)
|
|
})
|
|
|
|
test('a result cancels a scheduled retry', () => {
|
|
authenticate(10)
|
|
receive({ type: 'replay_events_retry', retry_after_ms: 1000 })
|
|
receive({
|
|
type: 'replay_events_result',
|
|
force_refresh: false,
|
|
latest_event_id: 10,
|
|
})
|
|
vi.advanceTimersByTime(60000)
|
|
expect(env.sentMessages).toHaveLength(1)
|
|
})
|
|
|
|
test.each([FIRST_CONNECT_CURSOR, 10])(
|
|
'socket replacement preserves buffered events and safely recovers cursor %s',
|
|
async (cursor) => {
|
|
const callback = vi.fn()
|
|
env.handler.registerEvent('row_updated', callback)
|
|
authenticate(cursor)
|
|
receive({ type: 'replay_events_retry', retry_after_ms: 1000 })
|
|
receive({ type: 'row_updated', _event_id: 12 })
|
|
const oldSocket = env.handler.socket
|
|
oldSocket.readyState = WebSocket.CLOSED
|
|
oldSocket.onclose()
|
|
vi.advanceTimersByTime(2000)
|
|
expect(env.sentMessages).toHaveLength(1)
|
|
|
|
await openSocket()
|
|
receive({ type: 'authentication', success: true, replay_enabled: true })
|
|
expect(env.sentMessages.at(-1).last_seen_id).toBe(
|
|
cursor === FIRST_CONNECT_CURSOR ? NO_REPLAY_AVAILABLE : cursor
|
|
)
|
|
// Delayed callbacks from the old socket must not affect the new attempt.
|
|
receive({ type: 'replay_events_retry', retry_after_ms: 1000 }, oldSocket)
|
|
receive(
|
|
{
|
|
type: 'replay_events_result',
|
|
force_refresh: true,
|
|
latest_event_id: 99,
|
|
},
|
|
oldSocket
|
|
)
|
|
vi.advanceTimersByTime(2000)
|
|
expect(env.sentMessages).toHaveLength(2)
|
|
expect(callback).not.toHaveBeenCalled()
|
|
expect(env.store._dispatched).not.toContainEqual([
|
|
'toast/setWorkspaceOutdated',
|
|
true,
|
|
])
|
|
|
|
receive({
|
|
type: 'replay_events_result',
|
|
force_refresh: cursor === FIRST_CONNECT_CURSOR,
|
|
latest_event_id:
|
|
cursor === FIRST_CONNECT_CURSOR ? NO_REPLAY_AVAILABLE : 15,
|
|
})
|
|
expect(callback).toHaveBeenCalledTimes(1)
|
|
expect(env.store._dispatched).toContainEqual([
|
|
'toast/setWorkspaceOutdated',
|
|
cursor === FIRST_CONNECT_CURSOR,
|
|
])
|
|
}
|
|
)
|
|
|
|
test('disconnect cancels retry and starts the next session with a new baseline', async () => {
|
|
authenticate(10)
|
|
receive({ type: 'replay_events_retry', retry_after_ms: 1000 })
|
|
const oldSocket = env.handler.socket
|
|
env.handler.disconnect()
|
|
receive({ type: 'replay_events_retry', retry_after_ms: 1000 }, oldSocket)
|
|
vi.advanceTimersByTime(60000)
|
|
expect(env.sentMessages).toHaveLength(1)
|
|
|
|
await openSocket()
|
|
receive({ type: 'authentication', success: true, replay_enabled: true })
|
|
expect(env.sentMessages.at(-1).last_seen_id).toBe(FIRST_CONNECT_CURSOR)
|
|
})
|
|
|
|
test('reconnecting to a server without replay preserves the unrecovered-gap warning', async () => {
|
|
const callback = vi.fn()
|
|
env.handler.registerEvent('row_updated', callback)
|
|
authenticate(10)
|
|
receive({ type: 'replay_events_retry', retry_after_ms: 1000 })
|
|
receive({ type: 'row_updated', _event_id: 12 })
|
|
env.handler.socket.readyState = WebSocket.CLOSED
|
|
env.handler.socket.onclose()
|
|
await openSocket()
|
|
receive({ type: 'authentication', success: true, replay_enabled: false })
|
|
|
|
expect(callback).toHaveBeenCalledTimes(1)
|
|
expect(env.store._dispatched).toContainEqual([
|
|
'toast/setWorkspaceOutdated',
|
|
true,
|
|
])
|
|
vi.advanceTimersByTime(60000)
|
|
expect(env.sentMessages).toHaveLength(1)
|
|
})
|
|
|
|
test('an unreplayable gap stays outdated after live messages and another reconnect', async () => {
|
|
authenticate(10)
|
|
receive({ type: 'row_updated', _event_id: 12 })
|
|
receive({
|
|
type: 'replay_events_result',
|
|
force_refresh: true,
|
|
latest_event_id: NO_REPLAY_AVAILABLE,
|
|
})
|
|
expect(env.store._dispatched).toContainEqual([
|
|
'toast/setWorkspaceOutdated',
|
|
true,
|
|
])
|
|
env.store._dispatched.length = 0
|
|
|
|
env.handler.socket.readyState = WebSocket.CLOSED
|
|
env.handler.socket.onclose()
|
|
await openSocket()
|
|
receive({ type: 'authentication', success: true, replay_enabled: true })
|
|
receive({
|
|
type: 'replay_events_result',
|
|
force_refresh: false,
|
|
latest_event_id: 12,
|
|
})
|
|
expect(env.sentMessages).toHaveLength(1)
|
|
expect(env.store._dispatched).not.toContainEqual([
|
|
'toast/setWorkspaceOutdated',
|
|
false,
|
|
])
|
|
})
|
|
|
|
test.each(['count', 'bytes'])(
|
|
'buffer %s overflow requires refresh and a late result cannot clear it',
|
|
async (limit) => {
|
|
authenticate(10)
|
|
receive({ type: 'replay_events_retry', retry_after_ms: 1000 })
|
|
if (limit === 'count') {
|
|
for (let id = 11; id <= 1011; id++) {
|
|
receive({ type: 'row_updated', _event_id: id })
|
|
}
|
|
} else {
|
|
receive({
|
|
type: 'row_updated',
|
|
_event_id: 11,
|
|
text: 'x'.repeat(3 * 1024 * 1024),
|
|
})
|
|
}
|
|
expect(env.store._dispatched).toContainEqual([
|
|
'toast/setWorkspaceOutdated',
|
|
true,
|
|
])
|
|
env.store._dispatched.length = 0
|
|
receive({
|
|
type: 'replay_events_result',
|
|
force_refresh: false,
|
|
latest_event_id: 1011,
|
|
})
|
|
vi.advanceTimersByTime(60000)
|
|
expect(env.sentMessages).toHaveLength(1)
|
|
expect(env.store._dispatched).toEqual([])
|
|
|
|
env.handler.socket.readyState = WebSocket.CLOSED
|
|
env.handler.socket.onclose()
|
|
await openSocket()
|
|
receive({ type: 'authentication', success: true, replay_enabled: true })
|
|
expect(env.sentMessages).toHaveLength(1)
|
|
expect(env.store._dispatched).not.toContainEqual([
|
|
'toast/setWorkspaceOutdated',
|
|
false,
|
|
])
|
|
|
|
env.handler.disconnect()
|
|
await openSocket()
|
|
receive({ type: 'authentication', success: true, replay_enabled: true })
|
|
expect(env.sentMessages.at(-1).last_seen_id).toBe(FIRST_CONNECT_CURSOR)
|
|
}
|
|
)
|
|
})
|
|
|
|
describe('RealTimeHandler high-water mark', () => {
|
|
test('updateLastSeenId takes the max of incoming ids', () => {
|
|
const { handler } = makeHandler()
|
|
handler.updateLastSeenId({ _event_id: 5 })
|
|
expect(handler.lastSeenEventId).toBe(5)
|
|
handler.updateLastSeenId({ _event_id: 3 })
|
|
expect(handler.lastSeenEventId).toBe(5)
|
|
handler.updateLastSeenId({ _event_id: 7 })
|
|
expect(handler.lastSeenEventId).toBe(7)
|
|
handler.updateLastSeenId({ type: 'no_id' })
|
|
expect(handler.lastSeenEventId).toBe(7)
|
|
})
|
|
})
|
|
|
|
describe('RealTimeHandler AI provider updates', () => {
|
|
test('recovers an oversized marker for the loaded workspace scope', async () => {
|
|
const { handler, store } = makeHandler()
|
|
store.getters['aiProvider/getWorkspaceId'] = 42
|
|
|
|
await fire(handler, 'ai_provider_updated', {
|
|
type: 'ai_provider_updated',
|
|
model_availability_updated: true,
|
|
requires_refresh: true,
|
|
workspace_id: 42,
|
|
refresh_workspace_availability: true,
|
|
refresh_provider_settings: true,
|
|
})
|
|
|
|
expect(store._dispatched).toContainEqual([
|
|
'workspace/refreshAllGenerativeAIModels',
|
|
{ realtimeRecovery: true },
|
|
])
|
|
expect(store._dispatched).toContainEqual([
|
|
'aiProvider/fetchInitial',
|
|
{ workspaceId: 42, realtimeRecovery: true },
|
|
])
|
|
})
|
|
|
|
test('recovers only the providers from an oversized instance marker', async () => {
|
|
const { handler, store } = makeHandler()
|
|
|
|
await fire(handler, 'ai_provider_updated', {
|
|
type: 'ai_provider_updated',
|
|
model_availability_updated: true,
|
|
requires_refresh: true,
|
|
workspace_id: null,
|
|
refresh_workspace_availability: false,
|
|
refresh_provider_settings: true,
|
|
})
|
|
|
|
expect(store._dispatched).toEqual([
|
|
[
|
|
'aiProvider/fetchInitial',
|
|
{ workspaceId: null, realtimeRecovery: true },
|
|
],
|
|
])
|
|
})
|
|
|
|
test('does not load provider settings for a different active scope', async () => {
|
|
const { handler, store } = makeHandler()
|
|
store.getters['aiProvider/getWorkspaceId'] = 43
|
|
|
|
await fire(handler, 'ai_provider_updated', {
|
|
type: 'ai_provider_updated',
|
|
model_availability_updated: true,
|
|
requires_refresh: true,
|
|
workspace_id: 42,
|
|
refresh_workspace_availability: true,
|
|
refresh_provider_settings: true,
|
|
})
|
|
|
|
expect(store._dispatched).toContainEqual([
|
|
'workspace/refreshAllGenerativeAIModels',
|
|
{ realtimeRecovery: true },
|
|
])
|
|
expect(
|
|
store._dispatched.some(([name]) => name === 'aiProvider/fetchInitial')
|
|
).toBe(false)
|
|
})
|
|
|
|
test('retries a failed instance provider recovery once and consumes the failure', async () => {
|
|
vi.useFakeTimers()
|
|
try {
|
|
const { handler, store } = makeHandler()
|
|
store.dispatch = vi.fn().mockRejectedValue(new Error('offline'))
|
|
|
|
const recovery = fire(handler, 'ai_provider_updated', {
|
|
type: 'ai_provider_updated',
|
|
model_availability_updated: true,
|
|
requires_refresh: true,
|
|
workspace_id: null,
|
|
refresh_workspace_availability: false,
|
|
refresh_provider_settings: true,
|
|
})
|
|
await vi.runAllTimersAsync()
|
|
await expect(recovery).resolves.toEqual([undefined])
|
|
|
|
expect(store.dispatch).toHaveBeenCalledTimes(2)
|
|
expect(store.dispatch).toHaveBeenNthCalledWith(
|
|
1,
|
|
'aiProvider/fetchInitial',
|
|
{
|
|
workspaceId: null,
|
|
realtimeRecovery: true,
|
|
}
|
|
)
|
|
expect(store.dispatch).toHaveBeenNthCalledWith(
|
|
2,
|
|
'aiProvider/fetchInitial',
|
|
{
|
|
workspaceId: null,
|
|
realtimeRecovery: true,
|
|
}
|
|
)
|
|
} finally {
|
|
vi.useRealTimers()
|
|
}
|
|
})
|
|
|
|
test('does not retry provider recovery after its scope is abandoned', async () => {
|
|
vi.useFakeTimers()
|
|
try {
|
|
const { handler, store } = makeHandler()
|
|
store.getters['aiProvider/getWorkspaceId'] = 42
|
|
store.dispatch = vi.fn((name) => {
|
|
if (name === 'aiProvider/fetchInitial') {
|
|
store.getters['aiProvider/getWorkspaceId'] = 43
|
|
return Promise.reject(new Error('offline'))
|
|
}
|
|
return Promise.resolve()
|
|
})
|
|
|
|
const recovery = fire(handler, 'ai_provider_updated', {
|
|
type: 'ai_provider_updated',
|
|
model_availability_updated: false,
|
|
requires_refresh: true,
|
|
workspace_id: 42,
|
|
refresh_workspace_availability: false,
|
|
refresh_provider_settings: true,
|
|
})
|
|
await vi.runAllTimersAsync()
|
|
await expect(recovery).resolves.toEqual([undefined])
|
|
|
|
expect(store.dispatch).toHaveBeenCalledTimes(1)
|
|
expect(store.dispatch).toHaveBeenCalledWith('aiProvider/fetchInitial', {
|
|
workspaceId: 42,
|
|
realtimeRecovery: true,
|
|
})
|
|
} finally {
|
|
vi.useRealTimers()
|
|
}
|
|
})
|
|
|
|
test('applies complete instance payloads without fetching', () => {
|
|
const { handler, store } = makeHandler()
|
|
const instanceProviders = [{ id: 1, provider_type: 'openai' }]
|
|
const instanceFeatureSettings = [{ feature_type: 'kuma', mode: 'disabled' }]
|
|
|
|
fire(handler, 'ai_provider_updated', {
|
|
type: 'ai_provider_updated',
|
|
model_availability_updated: true,
|
|
generative_ai_models_enabled_by_workspace: {
|
|
42: { openai: ['gpt-5'] },
|
|
43: { anthropic: ['claude-4.5'] },
|
|
},
|
|
ai_features_by_workspace: {
|
|
42: { kuma: { is_enabled: true, state: 'configured' } },
|
|
43: { kuma: { is_enabled: false, state: 'disabled' } },
|
|
},
|
|
instance_ai_providers: instanceProviders,
|
|
instance_ai_provider_feature_settings: instanceFeatureSettings,
|
|
})
|
|
|
|
expect(store._dispatched).toContainEqual([
|
|
'workspace/forceUpdateGenerativeAIModels',
|
|
{
|
|
workspaceId: 42,
|
|
generativeAIModelsEnabled: { openai: ['gpt-5'] },
|
|
aiFeatures: { kuma: { is_enabled: true, state: 'configured' } },
|
|
},
|
|
])
|
|
expect(store._dispatched).toContainEqual([
|
|
'workspace/forceUpdateGenerativeAIModels',
|
|
{
|
|
workspaceId: 43,
|
|
generativeAIModelsEnabled: { anthropic: ['claude-4.5'] },
|
|
aiFeatures: { kuma: { is_enabled: false, state: 'disabled' } },
|
|
},
|
|
])
|
|
expect(store._dispatched).toContainEqual([
|
|
'aiProvider/replaceFromRealtime',
|
|
{
|
|
workspaceId: null,
|
|
providers: instanceProviders,
|
|
featureSettings: instanceFeatureSettings,
|
|
},
|
|
])
|
|
expect(store._dispatched).not.toContainEqual([
|
|
'workspace/refreshAllGenerativeAIModels',
|
|
undefined,
|
|
])
|
|
expect(store._dispatched).not.toContainEqual([
|
|
'aiProvider/refresh',
|
|
undefined,
|
|
])
|
|
})
|
|
|
|
test('applies the loaded workspace provider snapshot without fetching', () => {
|
|
const { handler, store } = makeHandler()
|
|
const workspaceProviders = [{ id: 2, provider_type: 'anthropic' }]
|
|
const workspaceFeatureSettings = [{ feature_type: 'kuma', mode: 'inherit' }]
|
|
store.getters['aiProvider/getWorkspaceId'] = 42
|
|
|
|
fire(handler, 'ai_provider_updated', {
|
|
type: 'ai_provider_updated',
|
|
model_availability_updated: true,
|
|
generative_ai_models_enabled_by_workspace: {
|
|
42: { openai: ['gpt-5'] },
|
|
},
|
|
ai_features_by_workspace: {
|
|
42: { kuma: { is_enabled: true, state: 'inherited' } },
|
|
},
|
|
ai_providers_by_workspace: { 42: workspaceProviders },
|
|
ai_provider_feature_settings_by_workspace: {
|
|
42: workspaceFeatureSettings,
|
|
},
|
|
})
|
|
|
|
expect(store._dispatched).toContainEqual([
|
|
'workspace/forceUpdateGenerativeAIModels',
|
|
{
|
|
workspaceId: 42,
|
|
generativeAIModelsEnabled: { openai: ['gpt-5'] },
|
|
aiFeatures: { kuma: { is_enabled: true, state: 'inherited' } },
|
|
},
|
|
])
|
|
expect(store._dispatched).not.toContainEqual([
|
|
'workspace/refreshAllGenerativeAIModels',
|
|
undefined,
|
|
])
|
|
expect(store._dispatched).toContainEqual([
|
|
'aiProvider/replaceFromRealtime',
|
|
{
|
|
workspaceId: 42,
|
|
providers: workspaceProviders,
|
|
featureSettings: workspaceFeatureSettings,
|
|
},
|
|
])
|
|
expect(store._dispatched).not.toContainEqual([
|
|
'aiProvider/refresh',
|
|
undefined,
|
|
])
|
|
})
|
|
|
|
test('provider metadata changes apply their snapshot without fetching', () => {
|
|
const { handler, store } = makeHandler()
|
|
const instanceProviders = [{ id: 1, provider_type: 'openai' }]
|
|
const instanceFeatureSettings = [{ feature_type: 'kuma', mode: 'disabled' }]
|
|
|
|
fire(handler, 'ai_provider_updated', {
|
|
type: 'ai_provider_updated',
|
|
model_availability_updated: false,
|
|
instance_ai_providers: instanceProviders,
|
|
instance_ai_provider_feature_settings: instanceFeatureSettings,
|
|
})
|
|
|
|
expect(store._dispatched).not.toContainEqual([
|
|
'workspace/refreshAllGenerativeAIModels',
|
|
undefined,
|
|
])
|
|
expect(store._dispatched).toContainEqual([
|
|
'aiProvider/replaceFromRealtime',
|
|
{
|
|
workspaceId: null,
|
|
providers: instanceProviders,
|
|
featureSettings: instanceFeatureSettings,
|
|
},
|
|
])
|
|
expect(store._dispatched).not.toContainEqual([
|
|
'aiProvider/refresh',
|
|
undefined,
|
|
])
|
|
})
|
|
|
|
test('captures a provider snapshot while the initial load is in flight', () => {
|
|
const { handler, store } = makeHandler()
|
|
store.getters['aiProvider/hasLoaded'] = false
|
|
const providers = [{ id: 1, provider_type: 'openai' }]
|
|
|
|
fire(handler, 'ai_provider_updated', {
|
|
type: 'ai_provider_updated',
|
|
model_availability_updated: false,
|
|
instance_ai_providers: providers,
|
|
})
|
|
|
|
expect(store._dispatched).toContainEqual([
|
|
'aiProvider/replaceFromRealtime',
|
|
{
|
|
workspaceId: null,
|
|
providers,
|
|
featureSettings: undefined,
|
|
},
|
|
])
|
|
})
|
|
})
|
|
|
|
describe('RealTimeHandler reconnect logic', () => {
|
|
let env
|
|
|
|
beforeEach(() => {
|
|
vi.useFakeTimers()
|
|
env = makeHandler()
|
|
})
|
|
|
|
afterEach(() => {
|
|
vi.useRealTimers()
|
|
})
|
|
|
|
test('connection failure without auth response keeps retrying', () => {
|
|
const { handler } = env
|
|
handler.reconnect = true
|
|
handler.authenticationSuccess = true
|
|
|
|
// Simulate 5 connection failures (onclose without auth response)
|
|
for (let i = 0; i < 5; i++) {
|
|
handler.delayedReconnect()
|
|
}
|
|
|
|
// attempts incremented but no failedConnecting dispatch
|
|
expect(handler.attempts).toBe(5)
|
|
expect(
|
|
env.store._dispatched.some(
|
|
([n, v]) => n === 'toast/setFailedConnecting' && v === true
|
|
)
|
|
).toBe(false)
|
|
})
|
|
|
|
test('explicit auth rejection sets state that would stop retries', () => {
|
|
const { handler } = env
|
|
// Simulate: server sent {success: false} for current token
|
|
fire(handler, 'authentication', {
|
|
web_socket_id: null,
|
|
success: false,
|
|
})
|
|
|
|
expect(handler.authResponseReceived).toBe(true)
|
|
expect(handler.authenticationSuccess).toBe(false)
|
|
// The connect() guard checks:
|
|
// authResponseReceived && !authenticationSuccess && token === lastToken
|
|
// With this state + same token, connect() would bail
|
|
})
|
|
|
|
test('auth rejection flag resets when new connection starts', () => {
|
|
const { handler } = env
|
|
fire(handler, 'authentication', {
|
|
web_socket_id: null,
|
|
success: false,
|
|
})
|
|
expect(handler.authResponseReceived).toBe(true)
|
|
|
|
// Simulate what connect() does before creating WebSocket
|
|
handler.authResponseReceived = false
|
|
|
|
// Now the guard won't fire even with authenticationSuccess=false
|
|
expect(handler.authResponseReceived).toBe(false)
|
|
})
|
|
|
|
test('successful connect resets attempts to zero', () => {
|
|
const { handler } = env
|
|
handler.attempts = 5
|
|
handler.reconnect = true
|
|
handler.connected = true
|
|
|
|
// Simulate what onopen does
|
|
handler.connected = true
|
|
handler.attempts = 0
|
|
|
|
expect(handler.attempts).toBe(0)
|
|
})
|
|
|
|
test('delayedReconnect skipped when unloading is true', () => {
|
|
const { handler } = env
|
|
handler.reconnect = true
|
|
handler.unloading = true
|
|
|
|
const attemptsBefore = handler.attempts
|
|
handler.delayedReconnect()
|
|
|
|
expect(handler.attempts).toBe(attemptsBefore)
|
|
expect(
|
|
env.store._dispatched.some(([n]) => n === 'toast/setReconnecting')
|
|
).toBe(false)
|
|
})
|
|
|
|
test('retry signal clears the unloading latch and reconnects', () => {
|
|
const { handler } = env
|
|
// ``pagehide``/``beforeunload`` set the latch; a later ``pageshow`` or
|
|
// ``online`` event (both wired to _onShouldRetryNow) must clear it so
|
|
// reconnects are not suppressed forever after a bfcache restore.
|
|
handler.unloading = true
|
|
handler.connected = false
|
|
handler.reconnect = true
|
|
handler.anonymous = false
|
|
|
|
const connectSpy = vi.spyOn(handler, 'connect')
|
|
handler._onShouldRetryNow()
|
|
|
|
expect(handler.unloading).toBe(false)
|
|
expect(connectSpy).toHaveBeenCalledWith(true, false)
|
|
connectSpy.mockRestore()
|
|
})
|
|
|
|
test('wires a window focus listener to the retry handler', () => {
|
|
const addSpy = vi.spyOn(window, 'addEventListener')
|
|
const handler = new RealTimeHandler({
|
|
store: makeStore(),
|
|
app: { $router: { push: vi.fn() } },
|
|
})
|
|
const focusCall = addSpy.mock.calls.find(([type]) => type === 'focus')
|
|
expect(focusCall).toBeDefined()
|
|
expect(focusCall[1]).toBe(handler._onShouldRetryNow)
|
|
addSpy.mockRestore()
|
|
})
|
|
|
|
test('delayedReconnect skipped when reconnect is false', () => {
|
|
const { handler } = env
|
|
handler.reconnect = false
|
|
|
|
handler.delayedReconnect()
|
|
|
|
expect(handler.attempts).toBe(0)
|
|
})
|
|
|
|
test('visibility change to visible triggers immediate reconnect when disconnected', () => {
|
|
const { handler } = env
|
|
handler.connected = false
|
|
handler.reconnect = true
|
|
handler.anonymous = false
|
|
handler.reconnectTimeout = setTimeout(() => {}, 99999)
|
|
|
|
const connectSpy = vi.spyOn(handler, 'connect')
|
|
Object.defineProperty(document, 'visibilityState', {
|
|
value: 'visible',
|
|
writable: true,
|
|
configurable: true,
|
|
})
|
|
handler._onVisibilityChange()
|
|
|
|
expect(connectSpy).toHaveBeenCalledWith(true, false)
|
|
expect(handler.attempts).toBe(0)
|
|
expect(
|
|
env.store._dispatched.some(
|
|
([n, v]) => n === 'toast/setFailedConnecting' && v === false
|
|
)
|
|
).toBe(true)
|
|
// The "Reconnecting" toast stays up across the immediate retry — only
|
|
// ``onopen`` clears it — so it should NOT be dispatched false here.
|
|
expect(
|
|
env.store._dispatched.some(
|
|
([n, v]) => n === 'toast/setReconnecting' && v === false
|
|
)
|
|
).toBe(false)
|
|
connectSpy.mockRestore()
|
|
})
|
|
|
|
test('visibility reconnect retries after max attempts without keeping failure toast', () => {
|
|
const { handler } = env
|
|
handler.connected = false
|
|
handler.reconnect = true
|
|
handler.attempts = 11
|
|
|
|
const connectSpy = vi.spyOn(handler, 'connect')
|
|
Object.defineProperty(document, 'visibilityState', {
|
|
value: 'visible',
|
|
writable: true,
|
|
configurable: true,
|
|
})
|
|
|
|
handler._onVisibilityChange()
|
|
|
|
expect(handler.attempts).toBe(0)
|
|
expect(connectSpy).toHaveBeenCalledWith(true, false)
|
|
expect(
|
|
env.store._dispatched.some(
|
|
([n, v]) => n === 'toast/setFailedConnecting' && v === false
|
|
)
|
|
).toBe(true)
|
|
connectSpy.mockRestore()
|
|
})
|
|
|
|
test('delayedReconnect increments attempts each call', () => {
|
|
const { handler } = env
|
|
handler.reconnect = true
|
|
|
|
handler.delayedReconnect()
|
|
handler.delayedReconnect()
|
|
handler.delayedReconnect()
|
|
|
|
expect(handler.attempts).toBe(3)
|
|
})
|
|
|
|
test('delayedReconnect dispatches reconnecting toast', () => {
|
|
const { handler } = env
|
|
handler.reconnect = true
|
|
|
|
handler.delayedReconnect()
|
|
|
|
expect(
|
|
env.store._dispatched.some(
|
|
([n, v]) => n === 'toast/setReconnecting' && v === true
|
|
)
|
|
).toBe(true)
|
|
})
|
|
})
|
|
|
|
describe('RealTimeHandler replay request params', () => {
|
|
test('reconnect sends last_seen_id', () => {
|
|
const { handler, sentMessages } = makeHandler()
|
|
handler.replayEnabled = true
|
|
handler.lastSeenEventId = 42
|
|
|
|
handler._sendReplayEventsRequest()
|
|
|
|
const msg = sentMessages.find((m) => m.type === 'replay_events')
|
|
expect(msg).toEqual({
|
|
type: 'replay_events',
|
|
supports_retry: true,
|
|
last_seen_id: 42,
|
|
})
|
|
})
|
|
|
|
test('initial replay request sends FIRST_CONNECT_CURSOR for last_seen_id', () => {
|
|
const { handler, sentMessages } = makeHandler()
|
|
handler.replayEnabled = true
|
|
|
|
handler._sendReplayEventsRequest()
|
|
|
|
const msg = sentMessages.find((m) => m.type === 'replay_events')
|
|
expect(msg).toEqual({
|
|
type: 'replay_events',
|
|
supports_retry: true,
|
|
last_seen_id: FIRST_CONNECT_CURSOR,
|
|
})
|
|
})
|
|
|
|
test('_canReplayEvents returns false when replay is disabled', () => {
|
|
const { handler } = makeHandler()
|
|
handler.replayEnabled = false
|
|
|
|
expect(handler._canReplayEvents()).toBe(false)
|
|
})
|
|
|
|
test('_canReplayEvents returns true when replay is enabled and socket is open', () => {
|
|
const { handler } = makeHandler()
|
|
handler.replayEnabled = true
|
|
|
|
expect(handler._canReplayEvents()).toBe(true)
|
|
})
|
|
})
|
|
|
|
describe('RealTimeHandler disconnect', () => {
|
|
test('disconnect resets all realtime state', () => {
|
|
const { handler, store } = makeHandler()
|
|
handler.lastSeenEventId = 42
|
|
handler.attempts = 5
|
|
handler.reconnect = true
|
|
handler.connected = false
|
|
|
|
handler.disconnect()
|
|
|
|
// Reset to FIRST_CONNECT_CURSOR so the next connection is treated as fresh.
|
|
expect(handler.lastSeenEventId).toBe(FIRST_CONNECT_CURSOR)
|
|
expect(handler.attempts).toBe(0)
|
|
expect(handler.reconnect).toBe(false)
|
|
expect(
|
|
store._dispatched.some(
|
|
([n, v]) => n === 'toast/setWorkspaceOutdated' && v === false
|
|
)
|
|
).toBe(true)
|
|
expect(
|
|
store._dispatched.some(
|
|
([n, v]) => n === 'toast/setReconnecting' && v === false
|
|
)
|
|
).toBe(true)
|
|
})
|
|
|
|
test('disconnect closes socket even when not fully connected', () => {
|
|
const { handler } = makeHandler()
|
|
let closeCalled = false
|
|
handler.connected = false
|
|
handler.socket = {
|
|
readyState: WebSocket.CONNECTING,
|
|
onclose: () => {},
|
|
close() {
|
|
closeCalled = true
|
|
},
|
|
send() {},
|
|
}
|
|
|
|
handler.disconnect()
|
|
|
|
expect(closeCalled).toBe(true)
|
|
expect(handler.socket).toBeNull()
|
|
})
|
|
})
|
|
|
|
describe('RealTimeHandler onclose toast suppression', () => {
|
|
let env
|
|
|
|
beforeEach(() => {
|
|
vi.useFakeTimers()
|
|
env = makeHandler()
|
|
})
|
|
|
|
afterEach(() => {
|
|
vi.useRealTimers()
|
|
Object.defineProperty(document, 'visibilityState', {
|
|
value: 'visible',
|
|
writable: true,
|
|
configurable: true,
|
|
})
|
|
Object.defineProperty(navigator, 'onLine', {
|
|
value: true,
|
|
writable: true,
|
|
configurable: true,
|
|
})
|
|
})
|
|
|
|
test('delayedReconnect while hidden does not show reconnecting toast', () => {
|
|
const { handler, store } = env
|
|
handler.reconnect = true
|
|
handler.connected = false
|
|
|
|
Object.defineProperty(document, 'visibilityState', {
|
|
value: 'hidden',
|
|
writable: true,
|
|
configurable: true,
|
|
})
|
|
|
|
handler.delayedReconnect()
|
|
|
|
expect(
|
|
store._dispatched.some(
|
|
([n, v]) => n === 'toast/setReconnecting' && v === true
|
|
)
|
|
).toBe(false)
|
|
})
|
|
|
|
test('delayedReconnect while offline shows reconnecting toast but does not schedule retry', () => {
|
|
const { handler, store } = env
|
|
handler.reconnect = true
|
|
handler.connected = false
|
|
|
|
Object.defineProperty(document, 'visibilityState', {
|
|
value: 'visible',
|
|
writable: true,
|
|
configurable: true,
|
|
})
|
|
Object.defineProperty(navigator, 'onLine', {
|
|
value: false,
|
|
writable: true,
|
|
configurable: true,
|
|
})
|
|
|
|
handler.delayedReconnect()
|
|
|
|
expect(
|
|
store._dispatched.some(
|
|
([n, v]) => n === 'toast/setReconnecting' && v === true
|
|
)
|
|
).toBe(true)
|
|
expect(handler.attempts).toBe(0)
|
|
|
|
Object.defineProperty(navigator, 'onLine', {
|
|
value: true,
|
|
writable: true,
|
|
configurable: true,
|
|
})
|
|
})
|
|
|
|
test('delayedReconnect while unloading does not show reconnecting toast', () => {
|
|
const { handler, store } = env
|
|
handler.reconnect = true
|
|
handler.connected = false
|
|
handler.unloading = true
|
|
|
|
handler.delayedReconnect()
|
|
|
|
expect(
|
|
store._dispatched.some(
|
|
([n, v]) => n === 'toast/setReconnecting' && v === true
|
|
)
|
|
).toBe(false)
|
|
})
|
|
})
|
|
|
|
describe('RealTimeHandler max attempts', () => {
|
|
let env
|
|
|
|
beforeEach(() => {
|
|
vi.useFakeTimers()
|
|
env = makeHandler()
|
|
})
|
|
|
|
afterEach(() => {
|
|
vi.useRealTimers()
|
|
})
|
|
|
|
test('shows the failed toast but keeps retrying slowly after max attempts', () => {
|
|
const { handler, store } = env
|
|
handler.reconnect = true
|
|
handler.attempts = 10
|
|
const connectSpy = vi.spyOn(handler, 'connect').mockImplementation(() => {})
|
|
|
|
handler.delayedReconnect()
|
|
|
|
// Capped so slow retries can't grow the count unbounded.
|
|
expect(handler.attempts).toBe(11)
|
|
handler.delayedReconnect()
|
|
expect(handler.attempts).toBe(11)
|
|
|
|
expect(
|
|
store._dispatched.some(
|
|
([n, v]) => n === 'toast/setFailedConnecting' && v === true
|
|
)
|
|
).toBe(true)
|
|
|
|
// Self-heals when the backend returns, with no user action.
|
|
expect(connectSpy).not.toHaveBeenCalled()
|
|
vi.advanceTimersByTime(30000)
|
|
expect(connectSpy).toHaveBeenCalledWith(true, false)
|
|
connectSpy.mockRestore()
|
|
})
|
|
|
|
test('connect does not show failed toast while tab is hidden', () => {
|
|
const { handler, store } = makeHandler()
|
|
// Genuine auth rejection — the path that still raises the Failed toast.
|
|
handler.authResponseReceived = true
|
|
handler.authenticationSuccess = false
|
|
handler.lastToken = 'token'
|
|
handler.reconnect = true
|
|
handler.socket = null
|
|
Object.defineProperty(document, 'visibilityState', {
|
|
value: 'hidden',
|
|
writable: true,
|
|
configurable: true,
|
|
})
|
|
|
|
handler.connect(true, false)
|
|
|
|
expect(
|
|
store._dispatched.some(
|
|
([n, v]) => n === 'toast/setFailedConnecting' && v === true
|
|
)
|
|
).toBe(false)
|
|
expect(
|
|
store._dispatched.some(
|
|
([n, v]) => n === 'toast/setReconnecting' && v === false
|
|
)
|
|
).toBe(true)
|
|
|
|
Object.defineProperty(document, 'visibilityState', {
|
|
value: 'visible',
|
|
writable: true,
|
|
configurable: true,
|
|
})
|
|
})
|
|
|
|
test('delayedReconnect still schedules retry at exactly max attempts', () => {
|
|
const { handler, store } = env
|
|
handler.reconnect = true
|
|
handler.attempts = 9
|
|
|
|
handler.delayedReconnect()
|
|
|
|
expect(handler.attempts).toBe(10)
|
|
expect(
|
|
store._dispatched.some(
|
|
([n, v]) => n === 'toast/setReconnecting' && v === true
|
|
)
|
|
).toBe(true)
|
|
expect(
|
|
store._dispatched.some(
|
|
([n, v]) => n === 'toast/setFailedConnecting' && v === true
|
|
)
|
|
).toBe(false)
|
|
})
|
|
})
|
|
|
|
describe('RealTimeHandler replay_enabled=false cursor reset', () => {
|
|
test('auth with replay_enabled=false sets lastSeenEventId to NO_REPLAY_AVAILABLE', () => {
|
|
const { handler } = makeHandler()
|
|
handler.lastSeenEventId = 42
|
|
|
|
fire(handler, 'authentication', {
|
|
success: true,
|
|
replay_enabled: false,
|
|
})
|
|
|
|
expect(handler.lastSeenEventId).toBe(NO_REPLAY_AVAILABLE)
|
|
})
|
|
|
|
test('auth with replay_enabled=true does not reset lastSeenEventId', () => {
|
|
const { handler } = makeHandler()
|
|
handler.lastSeenEventId = 42
|
|
|
|
fire(handler, 'authentication', {
|
|
success: true,
|
|
replay_enabled: true,
|
|
})
|
|
|
|
expect(handler.lastSeenEventId).toBe(42)
|
|
})
|
|
})
|
|
|
|
describe('RealTimeHandler connect early-exit', () => {
|
|
test('connect() itself does not gate on attempt count', () => {
|
|
// The max-attempts guard lives in delayedReconnect(), not connect().
|
|
// connect() only checks token validity, so a high attempt count alone
|
|
// does not prevent a connection attempt.
|
|
const { handler, store } = makeHandler()
|
|
handler.attempts = 99
|
|
handler.reconnect = true
|
|
handler.socket = null
|
|
|
|
handler.connect(true, false)
|
|
|
|
expect(
|
|
store._dispatched.some(
|
|
([n, v]) => n === 'toast/setFailedConnecting' && v === true
|
|
)
|
|
).toBe(false)
|
|
})
|
|
|
|
test('connect does not show failed toast while tab is hidden', () => {
|
|
const { handler, store } = makeHandler()
|
|
// Genuine auth rejection — the path that still raises the Failed toast.
|
|
handler.authResponseReceived = true
|
|
handler.authenticationSuccess = false
|
|
handler.lastToken = 'token'
|
|
handler.reconnect = true
|
|
handler.socket = null
|
|
Object.defineProperty(document, 'visibilityState', {
|
|
value: 'hidden',
|
|
writable: true,
|
|
configurable: true,
|
|
})
|
|
|
|
handler.connect(true, false)
|
|
|
|
expect(
|
|
store._dispatched.some(
|
|
([n, v]) => n === 'toast/setFailedConnecting' && v === true
|
|
)
|
|
).toBe(false)
|
|
expect(
|
|
store._dispatched.some(
|
|
([n, v]) => n === 'toast/setReconnecting' && v === false
|
|
)
|
|
).toBe(true)
|
|
})
|
|
})
|
|
|
|
describe('RealTimeHandler connection watchdog', () => {
|
|
beforeEach(() => {
|
|
vi.useFakeTimers()
|
|
})
|
|
|
|
afterEach(() => {
|
|
vi.useRealTimers()
|
|
})
|
|
|
|
test('force-closes a socket stuck in CONNECTING so a reconnect can start', () => {
|
|
const { handler } = makeHandler()
|
|
let closed = false
|
|
handler.socket = {
|
|
readyState: WebSocket.CONNECTING,
|
|
close() {
|
|
closed = true
|
|
},
|
|
send() {},
|
|
}
|
|
handler._armConnectionTimeout()
|
|
|
|
vi.advanceTimersByTime(9999)
|
|
expect(closed).toBe(false)
|
|
vi.advanceTimersByTime(1)
|
|
expect(closed).toBe(true)
|
|
})
|
|
|
|
test('does not close a socket that finished connecting', () => {
|
|
const { handler } = makeHandler()
|
|
let closed = false
|
|
handler.socket = {
|
|
readyState: WebSocket.OPEN,
|
|
close() {
|
|
closed = true
|
|
},
|
|
send() {},
|
|
}
|
|
handler._armConnectionTimeout()
|
|
|
|
vi.advanceTimersByTime(10000)
|
|
expect(closed).toBe(false)
|
|
})
|
|
|
|
test('clearing the watchdog cancels the pending force-close', () => {
|
|
const { handler } = makeHandler()
|
|
let closed = false
|
|
handler.socket = {
|
|
readyState: WebSocket.CONNECTING,
|
|
close() {
|
|
closed = true
|
|
},
|
|
send() {},
|
|
}
|
|
handler._armConnectionTimeout()
|
|
handler._clearConnectionTimeout()
|
|
|
|
vi.advanceTimersByTime(10000)
|
|
expect(closed).toBe(false)
|
|
expect(handler.connectionTimeout).toBeNull()
|
|
})
|
|
})
|
|
|
|
describe('RealTimeHandler sendFocus', () => {
|
|
test('sendFocus sends correctly shaped presence.focus message', () => {
|
|
const { handler, sentMessages } = makeHandler()
|
|
handler.connected = true
|
|
|
|
handler.sendFocus(
|
|
'table',
|
|
{ table_id: 42 },
|
|
{ type: 'cell', row_id: 1, field_id: 2, editing: false }
|
|
)
|
|
|
|
expect(sentMessages).toHaveLength(1)
|
|
expect(sentMessages[0]).toEqual({
|
|
type: 'presence.focus',
|
|
page: 'table',
|
|
table_id: 42,
|
|
focus: { type: 'cell', row_id: 1, field_id: 2, editing: false },
|
|
})
|
|
})
|
|
|
|
test('sendFocus sends null focus for clear', () => {
|
|
const { handler, sentMessages } = makeHandler()
|
|
handler.connected = true
|
|
|
|
handler.sendFocus('table', { table_id: 42 }, null)
|
|
|
|
expect(sentMessages).toHaveLength(1)
|
|
expect(sentMessages[0]).toEqual({
|
|
type: 'presence.focus',
|
|
page: 'table',
|
|
table_id: 42,
|
|
focus: null,
|
|
})
|
|
})
|
|
|
|
test('sendFocus is suppressed when not connected', () => {
|
|
const { handler, sentMessages } = makeHandler()
|
|
handler.connected = false
|
|
|
|
handler.sendFocus(
|
|
'table',
|
|
{ table_id: 42 },
|
|
{ type: 'cell', row_id: 1, field_id: 2, editing: false }
|
|
)
|
|
|
|
expect(sentMessages).toHaveLength(0)
|
|
})
|
|
|
|
test('sendFocus is suppressed when socket is not open', () => {
|
|
const { handler, sentMessages } = makeHandler()
|
|
handler.connected = true
|
|
handler.socket.readyState = WebSocket.CLOSED
|
|
|
|
handler.sendFocus(
|
|
'table',
|
|
{ table_id: 42 },
|
|
{ type: 'cell', row_id: 1, field_id: 2, editing: false }
|
|
)
|
|
|
|
expect(sentMessages).toHaveLength(0)
|
|
})
|
|
|
|
test('sendFocus spreads parameters into top-level message', () => {
|
|
const { handler, sentMessages } = makeHandler()
|
|
handler.connected = true
|
|
|
|
handler.sendFocus(
|
|
'table',
|
|
{ table_id: 10, extra_param: 'val' },
|
|
{ type: 'row', row_id: 5, editing: true }
|
|
)
|
|
|
|
expect(sentMessages[0]).toEqual({
|
|
type: 'presence.focus',
|
|
page: 'table',
|
|
table_id: 10,
|
|
extra_param: 'val',
|
|
focus: { type: 'row', row_id: 5, editing: true },
|
|
})
|
|
})
|
|
})
|
|
|
|
describe('RealTimeHandler presence events', () => {
|
|
test('presence.members dispatches handleMembers', () => {
|
|
const { handler, store } = makeHandler()
|
|
fire(handler, 'presence.members', {
|
|
space: 'table-1',
|
|
entries: [{ presence_id: 'pid-1', user_id: 10 }],
|
|
})
|
|
expect(
|
|
store._dispatched.some(
|
|
([n, v]) =>
|
|
n === 'presence/handleMembers' &&
|
|
v.space === 'table-1' &&
|
|
v.entries.length === 1
|
|
)
|
|
).toBe(true)
|
|
})
|
|
|
|
test('presence.join dispatches handleJoin', () => {
|
|
const { handler, store } = makeHandler()
|
|
fire(handler, 'presence.join', {
|
|
space: 'table-1',
|
|
presence_id: 'pid-2',
|
|
user_id: 20,
|
|
})
|
|
expect(
|
|
store._dispatched.some(
|
|
([n, v]) =>
|
|
n === 'presence/handleJoin' &&
|
|
v.space === 'table-1' &&
|
|
v.presence_id === 'pid-2' &&
|
|
v.user_id === 20
|
|
)
|
|
).toBe(true)
|
|
})
|
|
|
|
test('presence.leave dispatches handleLeave', () => {
|
|
const { handler, store } = makeHandler()
|
|
fire(handler, 'presence.leave', {
|
|
space: 'table-1',
|
|
presence_id: 'pid-3',
|
|
})
|
|
expect(
|
|
store._dispatched.some(
|
|
([n, v]) =>
|
|
n === 'presence/handleLeave' &&
|
|
v.space === 'table-1' &&
|
|
v.presence_id === 'pid-3'
|
|
)
|
|
).toBe(true)
|
|
})
|
|
|
|
test('presence.space_discard dispatches clearSpace', () => {
|
|
const { handler, store } = makeHandler()
|
|
fire(handler, 'presence.space_discard', {
|
|
space: 'table-1',
|
|
})
|
|
expect(
|
|
store._dispatched.some(
|
|
([n, v]) => n === 'presence/clearSpace' && v.space === 'table-1'
|
|
)
|
|
).toBe(true)
|
|
})
|
|
|
|
test('presence.focus dispatches handleFocus with correct shape', () => {
|
|
const { handler, store } = makeHandler()
|
|
fire(handler, 'presence.focus', {
|
|
space: 'table-1',
|
|
presence_id: 'pid-5',
|
|
focus: { type: 'cell', row_id: 10, field_id: 20, editing: true },
|
|
})
|
|
expect(
|
|
store._dispatched.some(
|
|
([n, v]) =>
|
|
n === 'presence/handleFocus' &&
|
|
v.space === 'table-1' &&
|
|
v.presence_id === 'pid-5' &&
|
|
v.focus.type === 'cell' &&
|
|
v.focus.row_id === 10 &&
|
|
v.focus.field_id === 20 &&
|
|
v.focus.editing === true
|
|
)
|
|
).toBe(true)
|
|
})
|
|
|
|
test('presence.focus dispatches null focus for clear', () => {
|
|
const { handler, store } = makeHandler()
|
|
fire(handler, 'presence.focus', {
|
|
space: 'table-1',
|
|
presence_id: 'pid-6',
|
|
focus: null,
|
|
})
|
|
expect(
|
|
store._dispatched.some(
|
|
([n, v]) =>
|
|
n === 'presence/handleFocus' &&
|
|
v.space === 'table-1' &&
|
|
v.presence_id === 'pid-6' &&
|
|
v.focus === null
|
|
)
|
|
).toBe(true)
|
|
})
|
|
|
|
test('presence.editors_active dispatches handleEditorsActive', () => {
|
|
const { handler, store } = makeHandler()
|
|
fire(handler, 'presence.editors_active', {
|
|
space: 'table-1',
|
|
active: true,
|
|
})
|
|
expect(
|
|
store._dispatched.some(
|
|
([n, v]) =>
|
|
n === 'presence/handleEditorsActive' &&
|
|
v.space === 'table-1' &&
|
|
v.active === true
|
|
)
|
|
).toBe(true)
|
|
})
|
|
})
|
|
|
|
describe('RealTimeHandler token refresh on reconnect', () => {
|
|
function makeRefreshStore({ shouldRefresh = false } = {}) {
|
|
const dispatched = []
|
|
const store = {
|
|
getters: {
|
|
'auth/token': 'stale-token',
|
|
'auth/webSocketId': 'ws-id',
|
|
'auth/isAuthenticated': true,
|
|
'auth/shouldRefreshToken': () => shouldRefresh,
|
|
},
|
|
dispatch(name, value) {
|
|
dispatched.push([name, value])
|
|
if (name === 'auth/refresh') {
|
|
const refreshCount = dispatched.filter(
|
|
([n]) => n === 'auth/refresh'
|
|
).length
|
|
store.getters['auth/token'] = `fresh-token-${refreshCount}`
|
|
}
|
|
return Promise.resolve()
|
|
},
|
|
subscribe() {},
|
|
_dispatched: dispatched,
|
|
}
|
|
return store
|
|
}
|
|
|
|
function makeHandlerWith(store) {
|
|
const context = { store, app: { $router: { push: vi.fn() } } }
|
|
return { handler: new RealTimeHandler(context), store }
|
|
}
|
|
|
|
beforeEach(() => {
|
|
Object.defineProperty(document, 'visibilityState', {
|
|
value: 'visible',
|
|
writable: true,
|
|
configurable: true,
|
|
})
|
|
})
|
|
|
|
test('an expiring access token is refreshed before the socket opens', async () => {
|
|
const store = makeRefreshStore({ shouldRefresh: true })
|
|
const { handler } = makeHandlerWith(store)
|
|
|
|
await handler.connect(true, false)
|
|
|
|
expect(store._dispatched.some(([n]) => n === 'auth/refresh')).toBe(true)
|
|
expect(handler.lastToken).toBe('fresh-token-1')
|
|
expect(
|
|
store._dispatched.some(
|
|
([n, v]) => n === 'toast/setFailedConnecting' && v === true
|
|
)
|
|
).toBe(false)
|
|
})
|
|
|
|
test('a fresh-looking token is not refreshed on a normal reconnect', async () => {
|
|
const store = makeRefreshStore({ shouldRefresh: false })
|
|
const { handler } = makeHandlerWith(store)
|
|
|
|
await handler.connect(true, false)
|
|
|
|
expect(store._dispatched.some(([n]) => n === 'auth/refresh')).toBe(false)
|
|
expect(handler.lastToken).toBe('stale-token')
|
|
})
|
|
|
|
test('anonymous reconnects never refresh the token', async () => {
|
|
const store = makeRefreshStore({ shouldRefresh: true })
|
|
// An anonymous session has no refresh token to spend.
|
|
store.getters['auth/isAuthenticated'] = false
|
|
const { handler } = makeHandlerWith(store)
|
|
|
|
await handler.connect(true, true)
|
|
|
|
expect(store._dispatched.some(([n]) => n === 'auth/refresh')).toBe(false)
|
|
})
|
|
|
|
test('auth rejection forces a token refresh on the next reconnect', async () => {
|
|
// The token looks fresh to the client (shouldRefresh=false) but the server
|
|
// rejects it. The reconnect must still refresh instead of giving up.
|
|
const store = makeRefreshStore({ shouldRefresh: false })
|
|
const { handler } = makeHandlerWith(store)
|
|
handler.reconnect = true
|
|
handler.anonymous = false
|
|
|
|
await handler.connect(true, false)
|
|
expect(handler.lastToken).toBe('stale-token')
|
|
|
|
fire(handler, 'authentication', { success: false })
|
|
expect(handler.forceTokenRefresh).toBe(true)
|
|
|
|
await handler.connect(true, false)
|
|
|
|
expect(store._dispatched.some(([n]) => n === 'auth/refresh')).toBe(true)
|
|
expect(handler.lastToken).toBe('fresh-token-1')
|
|
expect(handler.forceTokenRefresh).toBe(false)
|
|
expect(
|
|
store._dispatched.some(
|
|
([n, v]) => n === 'toast/setFailedConnecting' && v === true
|
|
)
|
|
).toBe(false)
|
|
})
|
|
|
|
test('a successful reconnect clears the forced-refresh flag', async () => {
|
|
const store = makeRefreshStore({ shouldRefresh: false })
|
|
const { handler } = makeHandlerWith(store)
|
|
handler.forceTokenRefresh = true
|
|
|
|
fire(handler, 'authentication', { success: true, replay_enabled: false })
|
|
|
|
expect(handler.forceTokenRefresh).toBe(false)
|
|
})
|
|
|
|
test('stops refreshing once a freshly refreshed token is also rejected', async () => {
|
|
const store = makeRefreshStore({ shouldRefresh: false })
|
|
const { handler } = makeHandlerWith(store)
|
|
handler.reconnect = true
|
|
handler.anonymous = false
|
|
|
|
fire(handler, 'authentication', { success: false })
|
|
expect(handler.forceTokenRefresh).toBe(true)
|
|
expect(handler.tokenRefreshRetries).toBe(1)
|
|
await handler.connect(true, false)
|
|
expect(handler.lastToken).toBe('fresh-token-1')
|
|
|
|
fire(handler, 'authentication', { success: false })
|
|
expect(handler.forceTokenRefresh).toBe(false)
|
|
|
|
// The next reconnect reuses the same rejected token and surfaces failure.
|
|
const refreshesBefore = store._dispatched.filter(
|
|
([n]) => n === 'auth/refresh'
|
|
).length
|
|
await handler.connect(true, false)
|
|
const refreshesAfter = store._dispatched.filter(
|
|
([n]) => n === 'auth/refresh'
|
|
).length
|
|
expect(refreshesAfter).toBe(refreshesBefore)
|
|
expect(
|
|
store._dispatched.some(
|
|
([n, v]) => n === 'toast/setFailedConnecting' && v === true
|
|
)
|
|
).toBe(true)
|
|
})
|
|
|
|
test('a 401 refresh clears the session and surfaces the failure toast', async () => {
|
|
const dispatched = []
|
|
const store = {
|
|
getters: {
|
|
'auth/token': 'stale-token',
|
|
'auth/webSocketId': 'ws-id',
|
|
'auth/isAuthenticated': true,
|
|
'auth/shouldRefreshToken': () => true,
|
|
},
|
|
dispatch(name, value) {
|
|
dispatched.push([name, value])
|
|
if (name === 'auth/refresh') {
|
|
store.getters['auth/token'] = null
|
|
const error = new Error('session expired')
|
|
error.response = { status: 401 }
|
|
return Promise.reject(error)
|
|
}
|
|
return Promise.resolve()
|
|
},
|
|
subscribe() {},
|
|
_dispatched: dispatched,
|
|
}
|
|
const { handler } = makeHandlerWith(store)
|
|
|
|
await handler.connect(true, false)
|
|
|
|
expect(dispatched.some(([n]) => n === 'auth/refresh')).toBe(true)
|
|
expect(
|
|
dispatched.some(
|
|
([n, v]) => n === 'toast/setFailedConnecting' && v === true
|
|
)
|
|
).toBe(true)
|
|
})
|
|
|
|
test('a transient refresh failure retries with backoff instead of failing', async () => {
|
|
vi.useFakeTimers()
|
|
const dispatched = []
|
|
const store = {
|
|
getters: {
|
|
'auth/token': 'stale-token',
|
|
'auth/webSocketId': 'ws-id',
|
|
'auth/isAuthenticated': true,
|
|
'auth/shouldRefreshToken': () => true,
|
|
},
|
|
dispatch(name, value) {
|
|
dispatched.push([name, value])
|
|
if (name === 'auth/refresh') {
|
|
// No ``response`` — a network-level error that leaves the token intact.
|
|
return Promise.reject(new Error('Network Error'))
|
|
}
|
|
return Promise.resolve()
|
|
},
|
|
subscribe() {},
|
|
_dispatched: dispatched,
|
|
}
|
|
const { handler } = makeHandlerWith(store)
|
|
handler.reconnect = true
|
|
|
|
await handler.connect(true, false)
|
|
|
|
expect(
|
|
dispatched.some(
|
|
([n, v]) => n === 'toast/setFailedConnecting' && v === true
|
|
)
|
|
).toBe(false)
|
|
expect(
|
|
dispatched.some(([n, v]) => n === 'toast/setReconnecting' && v === true)
|
|
).toBe(true)
|
|
expect(handler.connecting).toBe(false)
|
|
|
|
clearTimeout(handler.reconnectTimeout)
|
|
vi.useRealTimers()
|
|
})
|
|
})
|
|
|
|
describe('RealTimeHandler last_viewed_updated', () => {
|
|
const fireFor = (application, lastViewed) => {
|
|
const { handler, store } = makeHandler()
|
|
store.getters['application/get'] = (id) =>
|
|
application?.id === id ? application : undefined
|
|
fire(handler, 'last_viewed_updated', {
|
|
type: 'last_viewed_updated',
|
|
item_type: 'database_view',
|
|
item_id: 7,
|
|
application_id: 3,
|
|
workspace_id: 1,
|
|
last_viewed: lastViewed,
|
|
})
|
|
return store._dispatched
|
|
}
|
|
|
|
test('applies a newer timestamp to the application', () => {
|
|
const application = { id: 3, last_viewed: '2026-01-01T12:00:00Z' }
|
|
expect(fireFor(application, '2026-01-01T12:05:00Z')).toEqual([
|
|
[
|
|
'application/forceUpdate',
|
|
{ application, data: { last_viewed: '2026-01-01T12:05:00Z' } },
|
|
],
|
|
])
|
|
})
|
|
|
|
test('applies the first timestamp of a never viewed application', () => {
|
|
const application = { id: 3, last_viewed: null }
|
|
expect(fireFor(application, '2026-01-01T12:00:00Z')).toHaveLength(1)
|
|
})
|
|
|
|
test('compares as moments, not as strings', () => {
|
|
// A fractional second sorts before a whole one as a string, yet is later.
|
|
const application = { id: 3, last_viewed: '2026-01-01T12:00:00Z' }
|
|
expect(fireFor(application, '2026-01-01T12:00:00.500000Z')).toHaveLength(1)
|
|
})
|
|
|
|
test('ignores an older or equal timestamp, so late events cannot go back', () => {
|
|
const application = { id: 3, last_viewed: '2026-01-01T12:05:00Z' }
|
|
expect(fireFor(application, '2026-01-01T12:00:00Z')).toEqual([])
|
|
expect(fireFor(application, '2026-01-01T12:05:00Z')).toEqual([])
|
|
})
|
|
|
|
test('ignores an application that is not in the store', () => {
|
|
expect(fireFor(undefined, '2026-01-01T12:05:00Z')).toEqual([])
|
|
})
|
|
})
|
|
|
|
describe('RealTimeHandler application_pending_count_updated', () => {
|
|
test('sets the count of an application in the store only', () => {
|
|
const { handler, store } = makeHandler()
|
|
const application = { id: 3, pending_count: 0 }
|
|
store.getters['application/get'] = (id) =>
|
|
application.id === id ? application : undefined
|
|
|
|
fire(handler, 'application_pending_count_updated', {
|
|
application_id: 3,
|
|
pending_count: 2,
|
|
})
|
|
fire(handler, 'application_pending_count_updated', {
|
|
application_id: 4,
|
|
pending_count: 1,
|
|
})
|
|
|
|
expect(store._dispatched).toEqual([
|
|
['application/forceUpdate', { application, data: { pending_count: 2 } }],
|
|
])
|
|
})
|
|
})
|