mirror of
https://github.com/stablyai/orca.git
synced 2026-11-05 19:47:27 +00:00
* chore(lint): remove disable directives that suppress nothing
Each was reported unused by the oxlint config that owns its rule (root,
casting, react-doctor, anti-slop, native-plugins), including 17 file-level
react-doctor blanket disables whose rule no longer fires. An unused
react-hooks disable was masking a react/purity finding in
useAgentBucketCounts (compiler rules skip functions with hook
suppressions); suppress that one explicitly where the code explains it.
* test(tab-bar): use typed tab/file fixtures instead of @ts-expect-error partials
* chore(lint): fix misc suppressed lint violations instead of disabling
- consistent-type-imports: the "vi.importActual requires inline import()"
rationale was wrong; use typed vi.mock(import(...), importOriginal) or a
type-only namespace import.
- no-control-regex: source-control commit/push failure summaries, shell PATH
hydration, and ipynb ANSI parsing reuse the shared ansi-escape-sequences
stripper and control-character pattern instead of private copies.
- no-explicit-any / no-useless-spread / no-this-alias: typed `this` in
bridge test mocks, drop blanket file-level disables, drop a this-alias.
* refactor(main): replace avoidable type assertions with checked narrowing
17 production cast suppressions in main/wsl-guest removed: untrusted IPC
and RPC payloads (Jira issue update, WSL guest plugin install, handshake
type) now narrow through isRecord/type guards and build typed results;
redundant casts dropped; hand-rolled object checks and errno casts use the
existing isRecord / hasErrorCode helpers.
* refactor(renderer,mobile): replace avoidable type assertions with checked types
13 production cast suppressions removed: RPC failures read through the
`ok` discriminant instead of casting to RpcFailure; react-native-web host
refs narrowed with instanceof HTMLElement; redundant reply/diff casts
become checked annotations; the TUI agent param uses z.custom(isTuiAgent)
like its sibling schemas; the agent-status slice cast that hid missing
actions is gone so the creator's return type checks the whole slice.
* chore(lint): drop dead tiptap wrapper; scope anti-slop mocking rule to test support
- safe-react-node-view-renderer patched handleSelectionUpdate, which
@tiptap/react 3.31.3 no longer has, so it always returned early. Use the
stock ReactNodeViewRenderer.
- The anti-slop test override only matched *.test.{ts,tsx}, forcing
file-level no-module-mocking disables in test harnesses and fixtures.
Match *-test-harness, *-test-fixture(s), .test-fixture and *.test.mjs,
then drop those disables and the now-redundant per-file exemptions.
* test: replace repeated cast suppressions with typed fixtures (main/shared/e2e)
Net -119 cast directives. Typed fixtures replace recurring casts:
unusedSshConnection/unusedOrcadHostTransport placeholders, a typed
readPersistedState harness read (exposed a test treating optional
httpProxyUrl as always set), real Response objects in fetch spies, an
updater main-window fixture, a CDP webContents adapter, one shared
releaseModuleExport for cross-version tests, and requireOverlayDir in
place of `as string` on possibly-undefined overlay paths.
* fix(runtime): validate loaded device rows and host scope instead of casting
Two cast suppressions claimed checks that did not happen:
- device-registry-file-read: "normalizeLoadedDeviceRow re-validates every
field" was false; deviceId, token, name and timestamps were never
checked. Rows without an identity are now dropped and the file is set
aside through the existing corrupt-file path (registry reads as
doubtful, so no revocation verdicts); a non-string token is stripped
so the row stays listed but cannot authenticate.
- client-ui: "only optionality differs" was false; any string reached
persisted workspaceHostScope. Narrow it with isWorkspaceHostScope and
ignore unknown scopes (wire schema unchanged for mixed versions). The
remaining cast now states what it actually covers.
* test(runtime,ipc): drop redundant cast suppressions; typed runtime store fixture
-98 cast directives across runtime/ipc tests: 61 casts that typecheck
without the assertion; a typed vi.fn for scoped invalidation; a
partialRuntimeStore fixture in place of `store as never` for
OrcaRuntimeService; typed worker terminal/authority builders in the
incarnation-fallback suite (the old stub lacked runtimeId, ptyId,
worktreeId and launchTokenHash) plus removal of stacked duplicate
directives there.
* chore(lint): typed vi.mock imports and explicit listener snapshot in shared-bucket tests
Remaining files from the misc-rule pass that overlapped other buckets:
codex-accounts mocks use the typed vi.mock(import(...)) form instead of
a consistent-type-imports disable; the daemon late-exit fixture copies
its listener set with Array.from instead of a no-useless-spread disable.
* refactor(github,mobile): narrow routing settings type; drop remaining avoidable casts
- work-item-routing cast a one-field object to AppState['settings'] under
a claim that readers only consume activeRuntimeEnvironmentId. Return the
existing RuntimeFocusSettings pick instead and narrow the cache-key
chain's parameters, so the compiler enforces that claim.
- mobile file preview reads refusals through the RpcResponse `ok`
discriminant rather than a cast.
- terminal document host-notify accepts `unknown` errors, removing the
message-bridge cast.
- native chat readability drops a redundant repo-list cast.
* test(renderer): replace repeated cast suppressions with typed fixtures
-140 cast directives (and ~150 unsuppressed casts of the same shapes):
- mockPanePtyArgs owns the connectPanePty fixture casts, so a wrong
argument order or fixture is now a type error; drop binding casts for
members PanePtyBinding already declares.
- Seed AppState tab rows with the typed makeTerminalTab; this exposed a
split direction 'row' that is not a TerminalPaneSplitDirection.
- Partial GlobalSettings use getDefaultSettings overrides; Jira-only
stores use createTestStore; runtime environment rows/statuses come from
a typed paired-runtime-environment fixture.
* chore(lint): drop no-module-mocking disable now covered by the test-fixture glob
* test(e2e): fix all 221 grandfathered e2e type errors; baseline to zero
The e2e typecheck baseline grandfathered 221 errors in 119 files. About a
third were tests drifted from the current API, several of which would
fail or mislead at runtime:
- terminal-shortcuts called a nonexistent xterm buffer method;
- the daemon-lifecycle fake lacked terminateOwnedTree, hidden by importing
its type from a module that does not export it;
- arguments in the wrong position (listProcesses(hostId, opts), a dropped
pty.write inputKind, an extra toWebTerminalSurfaceTabId argument);
- removed enum values ('drawer', 'idle', 'editor',
'session-insecure-origin') and a launch_source the telemetry schema
rejects;
- missing required fields (turnScope, childWorkOpen, providerIdentity,
reviewLookupOutcome, runtimeServiceAccount behind an `as RelayConfig`);
- dead reads (tab.customTitle, bucket.targets, changedPixels).
Also lifts variables that narrowed to `never` after poll-callback
assignment, and adds a typed xterm render-dimensions accessor. Includes
the cross-version suites' shared releaseModuleExport adoption.
* chore(typecheck): gate the now-clean e2e typecheck in local lint
The e2e baseline is empty, so the ratchet now rejects any tests/ type
error. CI already runs it via run-ratchets; add it to pnpm lint's
explicit ratchet list and replace the stale 'not yet clean' note.
* test(mobile): typecheck every mobile test; baseline 105 files -> 0
mobile/tests-typecheck-baseline.txt grandfathered 105 test files (531
errors) whose types CI never checked. Contract changes had landed without
these tests following, and type pins in them silently checked nothing.
- Root cause: salvagedOptional (src/shared/zod-salvage.ts) cast away
zod's optional marker, so every reply type built on it claimed
salvaged fields were always present. Return a real ZodOptional;
runtime is unchanged (the outer optional short-circuits undefined).
- Production now takes the port it uses: RpcOperationSender instead of
RpcClient for send-only callers, a narrow fetch signature, and only the
request fields push-receive reads.
- findAllByHostType/findByHostType replace `'Text' as never` lookups;
stubRpcClient gives tests a typed RpcClient.
- Real test bugs: settings-host-client-lifecycle "relay" hosts were
direct hosts (relayHostId no longer exists); two toEqualTypeOf pins
could never hold; a recovery hook ran with an undefined scope key;
a create-PR test cast to a never-imported type; "no URL" assertions
passed on null; plus stale required props, args and enum values.
* test(e2e): parse workerStart result instead of casting it
* test(runtime): typed partial runtime stores with production-shaped fixture data
Route every partial store passed to OrcaRuntimeService through
partialRuntimeStore with typed row builders, removing 60 cast directives
that hid fixture data production never produces:
- paired-client-navigation-test-harness keyed setWorktreeMeta writes by
`[object Object]` (it took an id where the store takes a target), so
reads never saw them;
- invalid worktree lineage origin/capture and incomplete workspace lineage;
- getWorkspaceSession returning null where the store returns the default
session; getGitHubCache returning undefined;
- orcad migration states missing migrationId/manifest/receipt, with a
toEqual pinned to that incomplete shape;
- partial repos, metadata, folders, project groups and notification rows.
* refactor(renderer): resolve suppressed React hook lint instead of disabling it
109 of 187 react-hooks/react-doctor suppressions fixed:
- ~95 exhaustive-deps disables only hid stable refs and setters passed
through controller objects; list them (identity never changes, so
nothing re-runs), plus a few real stale closures (tabId/worktreeId).
- Effects keyed on one value that read the latest props now use
useEffectEvent (WebConnect, skill freshness, Bitbucket dialog seeding,
Landing preflight, automation catalog, structured-session recovery,
file explorer).
- The conditional layout-owner hook is selected once at module load from
the build constant instead of a rules-of-hooks disable that also hid
the whole controller from compiler and react-doctor rules.
- A hook disable was masking a react/purity Date.now() in the palette's
recent-tabs memo; sample it when the snapshot is captured.
- Three identical debounced-search effects share
useTaskSearchDebouncedApply; layout snapshot merge helpers move out to
stay under max-lines.
Remaining suppressions are mount-once resources, invalidation epochs,
deliberately keyed fields, and test harnesses that mock the dispatcher.
* chore(ratchet): exempt test harnesses and fixtures from the focus-read ratchet
The ratchet skipped *.test-fixture.ts but scanned *-test-harness,
*-test-fixture(s) and *.test-support files. Those seed settings with
getDefaultSettings (which the ratchet discovers as a focus reader) and
never route host work, so 17 baseline entries were false positives, and
replacing a test's `settings: {...} as never` with typed defaults tripped
it. Match the repo's test-support names and prune (which also drops one
stale entry), and rename the frame-ordering harness to *-test-harness like
its siblings. A blanket "-harness" match would also exempt
e2e-terminal-pty-harness, which production imports, so the names stay
explicit.
* test: merge duplicate shared/constants imports
* revert(file-explorer): restore original tree load effects pending SSH e2e investigation
* test(runtime): drop RuntimeStore cast now that the fixture is typed
---------
Co-authored-by: OrcaWin <293788423+OrcaWin@users.noreply.github.com>
570 lines
20 KiB
TypeScript
570 lines
20 KiB
TypeScript
import { createHash, randomUUID } from 'node:crypto'
|
|
import { once } from 'node:events'
|
|
import { afterEach, describe, expect, it, vi } from 'vitest'
|
|
import nacl from 'tweetnacl'
|
|
import WebSocket from 'ws'
|
|
import type { IdleRegionalRehomeRequest } from '../../cloud/packages/relay-contract/src/idle-regional-rehome'
|
|
import {
|
|
openInMemoryRelayDatabase,
|
|
readRelayDatabasePoolPressure
|
|
} from '../../cloud/apps/relay/src/database'
|
|
import { createRelayServer } from '../../cloud/apps/relay/src/relay-server'
|
|
import { IDLE_REHOME_MIN_CONTROL_AGE_MS } from '../../cloud/apps/relay/src/host-session-registry'
|
|
import { CONTROL_RENEWAL_BATCH_INTERVAL_MS } from '../../cloud/apps/relay/src/control-renewal-batch'
|
|
import { RELAY_PROTOCOL_LIMITS } from '../../cloud/packages/relay-contract/src/protocol-limits'
|
|
import type * as AdminTokenVerifier from '../../cloud/apps/relay/src/admin-token-verifier'
|
|
import { RelayOriginPool } from '../../src/main/runtime/mobile-cloud-relay/relay-origin-pool'
|
|
import { RELAY_HOST_CAPABILITY_HEADERS } from '../../src/main/runtime/mobile-cloud-relay/relay-control-protocol'
|
|
import type { MobileSocketTransport } from '../../src/main/runtime/rpc/mobile-socket-wiring'
|
|
import { createRelayExecutionProcess } from './helpers/relay-execution-process'
|
|
|
|
vi.mock('../../cloud/apps/relay/src/relay-token-verifier', () => ({
|
|
createRelayTokenVerifier: () => async (hostId: string) => ({
|
|
sub: 'transport-test-user',
|
|
prof: 'profile-1',
|
|
org: 'org-1',
|
|
relayHostId: hostId,
|
|
purpose: 'host-control',
|
|
exp: 4_102_444_800
|
|
}),
|
|
readBearer: (value: string | undefined) => value?.replace(/^Bearer /, '') ?? null
|
|
}))
|
|
|
|
vi.mock('../../cloud/apps/relay/src/admin-token-verifier', async (importOriginal) => ({
|
|
...(await importOriginal<typeof AdminTokenVerifier>()),
|
|
createRegionalRehomeTokenVerifier: () => async (token: string) => token === 'test-director-token'
|
|
}))
|
|
|
|
const cleanups: (() => Promise<void>)[] = []
|
|
afterEach(async () => {
|
|
const failures: unknown[] = []
|
|
for (const cleanup of cleanups.splice(0).toReversed()) {
|
|
try {
|
|
await cleanup()
|
|
} catch (error) {
|
|
failures.push(error)
|
|
}
|
|
}
|
|
vi.restoreAllMocks()
|
|
if (failures.length > 0) {
|
|
throw new AggregateError(failures, 'relay topology cleanup failed')
|
|
}
|
|
})
|
|
|
|
async function topology() {
|
|
const execution = await createRelayExecutionProcess()
|
|
cleanups.push(() => execution.close())
|
|
let clock = Date.now()
|
|
vi.spyOn(Date, 'now').mockImplementation(() => clock)
|
|
const database = await openInMemoryRelayDatabase()
|
|
cleanups.push(() => database.close())
|
|
const keypair = nacl.box.keyPair()
|
|
const hostId = createHash('sha256').update(keypair.publicKey).digest('base64url').slice(0, 16)
|
|
const identity = { userId: 'transport-test-user', relayHostId: hostId }
|
|
const cells = [
|
|
{
|
|
id: 'transport-us',
|
|
url: 'https://transport-us.example.test',
|
|
region: 'us-central1' as const,
|
|
capacityRequests: 100
|
|
},
|
|
{
|
|
id: 'transport-asia',
|
|
url: 'https://transport-asia.example.test',
|
|
region: 'asia-east2' as const,
|
|
capacityRequests: 100
|
|
}
|
|
]
|
|
const incarnations = [
|
|
'11111111-1111-4111-8111-111111111111',
|
|
'22222222-2222-4222-8222-222222222222'
|
|
]
|
|
const endpoints = new Map<string, string>()
|
|
const sockets = new Set<WebSocket>()
|
|
const servers = cells.map((cell, index) =>
|
|
createRelayServer(
|
|
{
|
|
port: 0,
|
|
publicUrl: cell.url,
|
|
cellUrl: cell.url,
|
|
role: 'cell',
|
|
cellId: cell.id,
|
|
region: cell.region,
|
|
cells,
|
|
dataDir: '',
|
|
authIssuer: 'https://auth.example.test',
|
|
authAudience: 'orca-relay',
|
|
adminJwksUrl: 'https://auth.example.test/jwks',
|
|
jwksUrl: 'https://auth.example.test/jwks',
|
|
assignmentSigningKey: new Uint8Array(32),
|
|
adminAudience: 'https://director.example.test/v1/admin/drain',
|
|
deployServiceAccount: 'deploy@example.test',
|
|
runtimeServiceAccount: 'relay-cell@example.test',
|
|
rehomeAudience: 'https://director.example.test/v1/admin/host-drain',
|
|
rehomeDirectorServiceAccount: 'director@example.test',
|
|
databasePoolMax: 1,
|
|
publicAssignmentsEnabled: true,
|
|
publicAssignmentConcurrency: 2,
|
|
publicAssignmentQueueMax: 128,
|
|
publicAssignmentWaitMs: 4_000,
|
|
publicResolveConcurrency: 1,
|
|
publicResolveWaitMs: 5_000,
|
|
publicAssignmentRetryAfterSeconds: 5,
|
|
regionCorrectionCohortPercent: 100
|
|
},
|
|
database,
|
|
{ now: () => clock, random: () => 0.5, cellIncarnation: incarnations[index] }
|
|
)
|
|
)
|
|
cleanups.push(async () => {
|
|
for (const socket of sockets) {
|
|
socket.terminate()
|
|
}
|
|
for (const relay of servers) {
|
|
relay.sessions.drain(0)
|
|
await new Promise<void>((resolve) => relay.server.close(() => resolve()))
|
|
}
|
|
})
|
|
const source = servers[0]!
|
|
const target = servers[1]!
|
|
await source.assignments.inspectRegionalRehomeControl()
|
|
clock += 86_400_000
|
|
await source.assignments.applyRegionalRehomeControl({
|
|
expectedGeneration: 0,
|
|
enabled: true,
|
|
notBefore: clock,
|
|
ratePerMinute: 10,
|
|
preferenceMaxAgeMs: 86_400_000,
|
|
hostCooldownMs: 604_800_000,
|
|
drainGraceMs: 60_000
|
|
})
|
|
await source.assignments.reconcileCells(cells)
|
|
const startedAt = clock - 1_000
|
|
const safety = () => ({
|
|
observedAt: clock,
|
|
sqlFailures: 0,
|
|
reconnects: 0,
|
|
controlActivityRecoveryFailures: 0,
|
|
databasePoolWaiting: 0,
|
|
databasePoolWaitersMax: 0,
|
|
databasePoolWaitMsMax: 0
|
|
})
|
|
const heartbeat = async () => {
|
|
for (const [index, cell] of cells.entries()) {
|
|
const relay = servers[index]!
|
|
relay.observability.flush({
|
|
...relay.runtimeCounts(),
|
|
...readRelayDatabasePoolPressure(database)
|
|
})
|
|
await source.assignments.recordCellHeartbeat({
|
|
cellId: cell.id,
|
|
cellUrl: cell.url,
|
|
region: cell.region,
|
|
cellIncarnation: incarnations[index]!,
|
|
startedAt,
|
|
ready: true,
|
|
observedRequests: 0
|
|
})
|
|
await source.assignments.recordCellRegionalRehomeStatus({
|
|
cellId: cell.id,
|
|
cellIncarnation: incarnations[index]!,
|
|
regionalRehomeProtocol: 3,
|
|
safety: {
|
|
observedAt: clock,
|
|
sqlFailures: 0,
|
|
reconnects: 0,
|
|
controlActivityRecoveryFailures: 0,
|
|
databasePoolWaiting: 0,
|
|
databasePoolWaitersMax: 0,
|
|
databasePoolWaitMsMax: 0
|
|
}
|
|
})
|
|
}
|
|
}
|
|
await heartbeat()
|
|
for (const [index, relay] of servers.entries()) {
|
|
relay.server.listen(0, '127.0.0.1')
|
|
await once(relay.server, 'listening')
|
|
const address = relay.server.address()
|
|
if (!address || typeof address === 'string') {
|
|
throw new Error('missing local address')
|
|
}
|
|
endpoints.set(new URL(cells[index]!.url).host, `ws://127.0.0.1:${address.port}`)
|
|
}
|
|
const connect = (url: string, headers?: Record<string, string>) => {
|
|
const parsed = new URL(url)
|
|
const socket = new WebSocket(`${endpoints.get(parsed.host)}${parsed.pathname}`, { headers })
|
|
sockets.add(socket)
|
|
return socket
|
|
}
|
|
let failCorroboration = 0
|
|
let pauseCorroboration = false
|
|
let corroborationFailures = 0
|
|
let rejectTargetControls = false
|
|
let targetControlFailures = 0
|
|
const executionErrors: unknown[] = []
|
|
let delayedReply: (() => void) | null = null
|
|
const received: string[] = []
|
|
const pool = new RelayOriginPool({
|
|
directorUrl: 'https://director.example.test',
|
|
relayHostId: hostId,
|
|
identity: { userId: identity.userId, profileId: 'profile-1', organizationId: 'org-1' },
|
|
keypair: { ...keypair, publicKeyB64: Buffer.from(keypair.publicKey).toString('base64') },
|
|
appVersion: 'transport-test',
|
|
isCurrent: () => true,
|
|
onStatus: () => {},
|
|
now: () => clock,
|
|
mobileSocketWiring: {
|
|
attachTransport: (transport: MobileSocketTransport) => {
|
|
transport.onMessage((raw, reply) => {
|
|
const value = raw.toString()
|
|
received.push(value)
|
|
void execution
|
|
.execute(value)
|
|
.then((output) => {
|
|
if (output === 'mutation-1') {
|
|
delayedReply = () => reply('mutation-1-ack')
|
|
} else {
|
|
reply(`host:${output}`)
|
|
}
|
|
})
|
|
.catch((error) => executionErrors.push(error))
|
|
})
|
|
return () => {}
|
|
}
|
|
} as never,
|
|
createControlSocket: (url, token) => {
|
|
if (rejectTargetControls && new URL(url).host === new URL(cells[1]!.url).host) {
|
|
targetControlFailures++
|
|
throw new Error('simulated_target_unavailable')
|
|
}
|
|
const socket = connect(url, {
|
|
authorization: `Bearer ${token}`,
|
|
...RELAY_HOST_CAPABILITY_HEADERS
|
|
})
|
|
if (process.env.ORCA_RELAY_TRANSPORT_DIAGNOSTICS === '1') {
|
|
const cell = new URL(url).host
|
|
console.info('transport-control-created', {
|
|
cell,
|
|
stack: new Error('transport control created').stack
|
|
})
|
|
socket.on('message', (raw) => {
|
|
const message = JSON.parse(raw.toString())
|
|
if (['region-restored', 'host-hello-ack', 'drain'].includes(message.type)) {
|
|
console.info('transport-control-message', {
|
|
cell,
|
|
type: message.type,
|
|
assignmentEpoch: message.assignmentEpoch,
|
|
generation: message.generation
|
|
})
|
|
}
|
|
})
|
|
socket.on('close', (code) => console.info('transport-control-close', { cell, code }))
|
|
}
|
|
return socket
|
|
},
|
|
createDataSocket: (url) => connect(url),
|
|
fetch: (async () => {
|
|
if (failCorroboration > 0 || pauseCorroboration) {
|
|
failCorroboration = Math.max(0, failCorroboration - 1)
|
|
corroborationFailures++
|
|
return Response.json({ error: 'temporary_director_failure' }, { status: 503 })
|
|
}
|
|
const assignment = await source.assignments.resolve(identity)
|
|
if (!assignment) {
|
|
return Response.json({ error: 'assignment_not_found' }, { status: 409 })
|
|
}
|
|
return Response.json({
|
|
v: 1,
|
|
cellUrl: assignment.cellUrl,
|
|
assignmentEpoch: assignment.assignmentEpoch,
|
|
lease: 'synthetic-assignment-lease'
|
|
})
|
|
}) as typeof fetch
|
|
})
|
|
cleanups.push(async () => {
|
|
pool.closeNow()
|
|
})
|
|
const assignment = await source.assignments.assign(identity, 'us-central1')
|
|
const controlIntervals = vi.spyOn(globalThis, 'setInterval')
|
|
let controlHeartbeat: (() => void) | undefined
|
|
try {
|
|
await pool.openInitial(
|
|
{
|
|
v: 1,
|
|
cellUrl: assignment.cellUrl,
|
|
assignmentEpoch: assignment.assignmentEpoch,
|
|
lease: 'synthetic-assignment-lease'
|
|
},
|
|
hostId
|
|
)
|
|
const session = source.sessions.get(identity)
|
|
if (session?.heartbeatTimer) {
|
|
const intervals = controlIntervals.mock.calls.filter(
|
|
(call, index) =>
|
|
controlIntervals.mock.results[index]?.type === 'return' &&
|
|
controlIntervals.mock.results[index]?.value === session.heartbeatTimer &&
|
|
call[1] === RELAY_PROTOCOL_LIMITS.controlPingIntervalMs &&
|
|
typeof call[0] === 'function'
|
|
)
|
|
if (intervals.length === 1 && typeof intervals[0]?.[0] === 'function') {
|
|
controlHeartbeat = intervals[0][0]
|
|
}
|
|
}
|
|
} finally {
|
|
controlIntervals.mockRestore()
|
|
}
|
|
const sourceControl = source.sessions.get(identity)
|
|
if (!sourceControl || !controlHeartbeat) {
|
|
throw new Error('missing source control heartbeat')
|
|
}
|
|
for (
|
|
let elapsed = 0;
|
|
elapsed < IDLE_REHOME_MIN_CONTROL_AGE_MS;
|
|
elapsed += RELAY_PROTOCOL_LIMITS.controlPingIntervalMs
|
|
) {
|
|
const renewalDueAt = sourceControl.activityRenewalDueAt
|
|
const completedRenewal = sourceControl.activityRenewalCompletedAttempt
|
|
clock += Math.min(
|
|
RELAY_PROTOCOL_LIMITS.controlPingIntervalMs,
|
|
IDLE_REHOME_MIN_CONTROL_AGE_MS - elapsed
|
|
)
|
|
controlHeartbeat()
|
|
await expect
|
|
.poll(() => [sourceControl.lastPongAt, sourceControl.pendingPingAt])
|
|
.toEqual([clock, null])
|
|
if (clock >= renewalDueAt) {
|
|
await expect
|
|
.poll(() => sourceControl.activityRenewalCompletedAttempt, {
|
|
timeout: CONTROL_RENEWAL_BATCH_INTERVAL_MS * 2
|
|
})
|
|
.toBeGreaterThan(completedRenewal)
|
|
}
|
|
}
|
|
await heartbeat()
|
|
const attachPhone = async (cellIndex: number, device: string) => {
|
|
const invite = await source.store.createInvite(identity, device)
|
|
const socket = connect(`${cells[cellIndex]!.url}/v1/connect/${hostId}`)
|
|
await once(socket, 'open')
|
|
const hello = once(socket, 'message')
|
|
socket.send(
|
|
JSON.stringify({ type: 'relay-auth', v: 1, mode: 'connect', credential: invite.inviteToken })
|
|
)
|
|
const [raw] = await hello
|
|
expect(JSON.parse(raw.toString())).toMatchObject({ type: 'relay-hello', ok: true })
|
|
return socket
|
|
}
|
|
let candidate: (IdleRegionalRehomeRequest & { sourceCellUrl: string }) | undefined
|
|
const prepareMove = async () => {
|
|
const issued = await source.assignments.exchangeRegionCorrection(
|
|
identity,
|
|
{ v: 1, action: 'issue-window' },
|
|
assignment.assignmentEpoch
|
|
)
|
|
await source.assignments.exchangeRegionCorrection(
|
|
identity,
|
|
{
|
|
v: 1,
|
|
action: 'report',
|
|
generation: issued.window!.generation,
|
|
assignmentEpoch: assignment.assignmentEpoch,
|
|
policyVersion: 1,
|
|
outcome: 'conclusive',
|
|
measurements: { 'us-central1': 180, 'asia-east2': 40 }
|
|
},
|
|
assignment.assignmentEpoch
|
|
)
|
|
candidate = (await source.assignments.selectIdleRegionalRehomeCandidates(safety()))[0]
|
|
expect(candidate).toBeDefined()
|
|
return candidate!
|
|
}
|
|
const move = async () => {
|
|
if (!candidate) {
|
|
await prepareMove()
|
|
}
|
|
const { sourceCellUrl, ...request } = candidate!
|
|
const address = endpoints.get(new URL(sourceCellUrl).host)!.replace('ws:', 'http:')
|
|
const response = await fetch(`${address}/v1/admin/host-idle-rehome`, {
|
|
method: 'POST',
|
|
headers: { authorization: 'Bearer test-director-token', 'content-type': 'application/json' },
|
|
body: JSON.stringify({ ...request, cohortPercent: 100, directorSafety: safety() })
|
|
})
|
|
const body = (await response.json()) as { v: number; outcome: string }
|
|
expect(response.status, JSON.stringify(body)).toBe(200)
|
|
return { outcome: body.outcome }
|
|
}
|
|
return {
|
|
source,
|
|
target,
|
|
pool,
|
|
identity,
|
|
database,
|
|
cells,
|
|
attachPhone,
|
|
connectDevice: () => connect(`${cells[0]!.url}/v1/connect/${hostId}`),
|
|
move,
|
|
prepareMove,
|
|
heartbeat,
|
|
now: () => clock,
|
|
advance: (ms: number) => {
|
|
clock += ms
|
|
},
|
|
received,
|
|
failNextCorroboration: () => {
|
|
failCorroboration = 1
|
|
},
|
|
pauseCorroboration: (paused: boolean) => {
|
|
pauseCorroboration = paused
|
|
},
|
|
corroborationFailures: () => corroborationFailures,
|
|
targetControlFailures: () => targetControlFailures,
|
|
failTarget: () => {
|
|
rejectTargetControls = true
|
|
const session = target.sessions.get(identity)
|
|
if (session?.socket) {
|
|
session.socket.terminate()
|
|
}
|
|
},
|
|
execution,
|
|
executionErrors,
|
|
mutations: () => execution.mutations(),
|
|
reply: () => {
|
|
if (!delayedReply) {
|
|
throw new Error('no delayed mutation')
|
|
}
|
|
delayedReply()
|
|
}
|
|
}
|
|
}
|
|
|
|
async function echo(socket: WebSocket, value: string) {
|
|
const marker = `${value}:${randomUUID()}`
|
|
const response = once(socket, 'message')
|
|
socket.send(marker)
|
|
const [raw] = await response
|
|
expect(raw.toString()).toBe(`host:${marker}`)
|
|
}
|
|
|
|
describe('idle region correction across real relay and desktop WebSockets', () => {
|
|
it('releases the empty source and recovers normally when the target never registers', async () => {
|
|
const context = await topology()
|
|
await context.prepareMove()
|
|
context.failTarget()
|
|
expect(await context.move()).toEqual({ outcome: 'committed' })
|
|
await expect.poll(() => context.source.sessions.get(context.identity)).toBeNull()
|
|
await expect
|
|
.poll(async () =>
|
|
context.database.query(
|
|
`SELECT activity_id FROM relay_assignment_activity_leases
|
|
WHERE user_id = ? AND relay_host_id = ? AND cell_id = ?`,
|
|
[context.identity.userId, context.identity.relayHostId, context.cells[0]!.id]
|
|
)
|
|
)
|
|
.toEqual([])
|
|
await expect.poll(context.targetControlFailures).toBeGreaterThan(0)
|
|
context.advance(15 * 60_000 + 1)
|
|
await context.heartbeat()
|
|
expect(await context.source.assignments.abortExpiredEvacuations()).toBe(1)
|
|
expect(await context.source.assignments.resolve(context.identity)).toMatchObject({
|
|
cellId: context.cells[0]!.id,
|
|
assignmentEpoch: 3
|
|
})
|
|
await expect
|
|
.poll(() => context.pool.activeAssignment?.cellUrl, { timeout: 15_000 })
|
|
.toBe(context.cells[0]!.url)
|
|
await expect
|
|
.poll(() => context.source.sessions.get(context.identity)?.state, { timeout: 15_000 })
|
|
.toBe('active')
|
|
const returning = await context.attachPhone(0, 'phone-after-target-failure')
|
|
await echo(returning, 'after-target-failure')
|
|
expect(await context.mutations()).toBe(0)
|
|
expect(context.executionErrors).toEqual([])
|
|
}, 30_000)
|
|
|
|
it('rejects an arrival during cutover and restores admissions after a definite failed commit', async () => {
|
|
const context = await topology()
|
|
await context.prepareMove()
|
|
const original = context.source.sessions.get(context.identity)!
|
|
let entered!: () => void
|
|
let release!: () => void
|
|
const committing = new Promise<void>((resolve) => {
|
|
entered = resolve
|
|
})
|
|
const gate = new Promise<void>((resolve) => {
|
|
release = resolve
|
|
})
|
|
vi.spyOn(context.source.assignments, 'commitIdleRegionalRehome').mockImplementationOnce(
|
|
async () => {
|
|
entered()
|
|
await gate
|
|
throw new Error('simulated_database_unavailable_before_commit')
|
|
}
|
|
)
|
|
const move = context.move()
|
|
await committing
|
|
try {
|
|
const invite = await context.source.store.createInvite(context.identity, 'racing-phone')
|
|
const arriving = context.connectDevice()
|
|
const rejected = once(arriving, 'close')
|
|
await once(arriving, 'open')
|
|
arriving.send(
|
|
JSON.stringify({
|
|
type: 'relay-auth',
|
|
v: 1,
|
|
mode: 'connect',
|
|
credential: invite.inviteToken
|
|
})
|
|
)
|
|
expect((await rejected)[0]).toBe(4409)
|
|
expect(context.source.sessions.get(context.identity)).toBe(original)
|
|
} finally {
|
|
release()
|
|
await move
|
|
}
|
|
expect(await move).toEqual({ outcome: 'deferred' })
|
|
expect(context.source.sessions.get(context.identity)).toBe(original)
|
|
const returning = await context.attachPhone(0, 'retrying-phone')
|
|
await echo(returning, 'after-definite-abort')
|
|
expect(await context.mutations()).toBe(0)
|
|
expect(context.executionErrors).toEqual([])
|
|
}, 30_000)
|
|
|
|
it('defers for either connected device, then moves after both disconnect without replaying work', async () => {
|
|
const context = await topology()
|
|
const phone = await context.attachPhone(0, 'phone')
|
|
const tablet = await context.attachPhone(0, 'tablet')
|
|
const sourceSession = context.source.sessions.get(context.identity)!
|
|
await echo(phone, 'before-cutover')
|
|
phone.send('mutation-1')
|
|
await expect.poll(context.mutations).toBe(1)
|
|
expect(await context.move()).toEqual({ outcome: 'busy' })
|
|
expect(context.source.sessions.get(context.identity)).toBe(sourceSession)
|
|
expect((await context.source.assignments.resolve(context.identity))?.cellId).toBe(
|
|
context.cells[0]!.id
|
|
)
|
|
const acknowledged = once(phone, 'message')
|
|
context.reply()
|
|
expect((await acknowledged)[0].toString()).toBe('mutation-1-ack')
|
|
const phoneClosed = once(phone, 'close')
|
|
phone.close()
|
|
await phoneClosed
|
|
await expect.poll(() => sourceSession.activeSplices.size).toBe(1)
|
|
expect(await context.move()).toEqual({ outcome: 'busy' })
|
|
await echo(tablet, 'quiet-tablet-still-connected')
|
|
const tabletClosed = once(tablet, 'close')
|
|
tablet.close()
|
|
await tabletClosed
|
|
await expect.poll(() => sourceSession.activeSplices.size).toBe(0)
|
|
expect(await context.move()).toEqual({ outcome: 'committed' })
|
|
await expect
|
|
.poll(() => context.pool.activeAssignment?.cellUrl, { timeout: 15_000 })
|
|
.toBe(context.cells[1]!.url)
|
|
await expect.poll(() => context.source.sessions.get(context.identity)).toBeNull()
|
|
const returning = await context.attachPhone(1, 'returning-phone')
|
|
await echo(returning, 'after-idle-cutover')
|
|
expect(await context.mutations()).toBe(1)
|
|
expect(context.executionErrors).toEqual([])
|
|
expect(context.execution.sequence()).toBe(4)
|
|
}, 30_000)
|
|
})
|