mirror of
https://github.com/stablyai/orca.git
synced 2026-11-19 04:23:57 +00:00
fix(wsl-hosts): settle mapped-drive starts and drive answers from review
- A start compares only the drives it will journal, plus those of rows the request names, after planning: whole-distro and Retry starts no longer refuse over refused, retained, unrelated or unanswered drive-letter rows. - Remember a failed lookup as "maps nowhere" (only timeouts stay unknown), expire answers after 60 s for user actions, and persist answers in userData so the prune and the unreadable-journal fence know drives after a restart without ever reading one in the background. Off Windows a drive letter is never WSL. - An unanswered drive appears under a distro's "Not moving" only if it last mapped there or one of its projects was picked. - Git gate ignores stray worktree entries, reads 8 at a time, and its timeout aborts the reads it can; the main path rewriter restores folded keys' case from the moved roots. Co-authored-by: Neil <neil@stably.ai>
This commit is contained in:
@@ -55,3 +55,10 @@ describe('the prune check’s mapped drives', () => {
|
||||
expect(realpathNative).not.toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
|
||||
describe('the prune check off Windows', () => {
|
||||
it('treats drive letters as outside WSL off Windows', () => {
|
||||
vi.spyOn(process, 'platform', 'get').mockReturnValue('linux')
|
||||
expect(wslMoveDistroMappedDrivesLastKnown(store, 'Ubuntu')).toEqual([])
|
||||
})
|
||||
})
|
||||
|
||||
@@ -41,7 +41,11 @@ export function wslMoveDesktopRewriteContext(
|
||||
): WslMoveDesktopRewriteContext {
|
||||
return {
|
||||
cutover,
|
||||
rewritePath: createUncToLinuxPathRewriter(cutover.manifest.source.distro, cutover.mappedDrives),
|
||||
rewritePath: createUncToLinuxPathRewriter(
|
||||
cutover.manifest.source.distro,
|
||||
cutover.mappedDrives,
|
||||
{ linuxRoots: wslMoveScopeRootPaths(cutover.manifest) }
|
||||
),
|
||||
destinationHostId: toRuntimeExecutionHostId(cutover.destinationEnvironmentId),
|
||||
recordSeededHostWorkspaceIds: (workspaceIds) =>
|
||||
recordSeededHostWorkspaces(userDataPath, cutover.migrationId, workspaceIds)
|
||||
|
||||
+20
-8
@@ -107,17 +107,29 @@ describe('moving a project saved under a mapped drive', () => {
|
||||
expect(listWslMoveCutovers(rig.userDataPath)).toEqual([])
|
||||
})
|
||||
|
||||
it('lists the projects of a drive that does not answer as not moving, and moves the rest', async () => {
|
||||
// An offline share elsewhere must not block moving the distro's other projects.
|
||||
it('lists an unanswered drive’s projects only where it last mapped here, or when picked', async () => {
|
||||
rig.world.repos = [
|
||||
rig.world.repos[0],
|
||||
{ ...rig.world.repos[0], id: 'repo-s', path: 'S:\\shared\\tool' }
|
||||
{ ...rig.world.repos[0], id: 'repo-s', path: 'S:\\shared\\tool' },
|
||||
{ ...rig.world.repos[0], id: 'repo-v', path: 'V:\\home\\dev\\v' }
|
||||
]
|
||||
expect(await previewWslMove(rig.world.deps, { distro: 'Ubuntu' })).toMatchObject({
|
||||
outcome: 'ready',
|
||||
repoIds: ['repo-1'],
|
||||
mappedDrives: [W],
|
||||
refused: [{ kind: 'repo', id: 'repo-s', reason: 'mapped-drive-unverifiable' }]
|
||||
// S: never answered (an offline share anywhere); V: last mapped into this distro.
|
||||
known.V = '\\\\wsl.localhost\\Ubuntu'
|
||||
shares.V = 'unverifiable'
|
||||
const whole = await previewWslMove(rig.world.deps, { distro: 'Ubuntu' })
|
||||
expect(whole).toMatchObject({ outcome: 'ready', repoIds: ['repo-1'], mappedDrives: [W] })
|
||||
expect(whole.outcome === 'ready' ? whole.refused : null).toEqual([
|
||||
{ kind: 'repo', id: 'repo-v', reason: 'mapped-drive-unverifiable' }
|
||||
])
|
||||
const picked = await previewWslMove(rig.world.deps, {
|
||||
distro: 'Ubuntu',
|
||||
repoIds: ['repo-1', 'repo-s'],
|
||||
folderWorkspaceIds: []
|
||||
})
|
||||
expect(picked.outcome === 'ready' ? picked.refused : null).toContainEqual({
|
||||
kind: 'repo',
|
||||
id: 'repo-s',
|
||||
reason: 'mapped-drive-unverifiable'
|
||||
})
|
||||
})
|
||||
|
||||
|
||||
@@ -14,7 +14,11 @@ import {
|
||||
} from '../../../../shared/wsl-move/wsl-move-cutover'
|
||||
import { wslHostsAcceptNewWork } from '../../../wsl/host-lifecycle/wsl-host-gate'
|
||||
import type { WslMappedDrive } from '../../../../shared/wsl-move/wsl-mapped-drive-paths'
|
||||
import { journaledWslMoveDrives, readWslMoveSourceDrives } from './wsl-move-driver-source-drives'
|
||||
import {
|
||||
journaledWslMoveDrives,
|
||||
readWslMoveSourceDrives,
|
||||
wslMoveStartDriveRefusal
|
||||
} from './wsl-move-driver-source-drives'
|
||||
import { listWslMoveCutoverChain } from '../cutover-recovery/wsl-move-cutover-journal'
|
||||
|
||||
import { type WslMovePlan, planWslMove } from '../manifest-scope/wsl-move-delta-plan'
|
||||
@@ -238,10 +242,7 @@ export async function prepareWslMove(
|
||||
? { repoIds: request.repoIds ?? [], folderWorkspaceIds: request.folderWorkspaceIds ?? [] }
|
||||
: undefined
|
||||
const catalog = deps.readCatalog()
|
||||
const drives = await readWslMoveSourceDrives(deps, catalog, request, expectedMappedDrives)
|
||||
if ('outcome' in drives) {
|
||||
return drives
|
||||
}
|
||||
const drives = await readWslMoveSourceDrives(deps, catalog, request)
|
||||
const planned = planWslMove(
|
||||
deps.userDataPath,
|
||||
catalog,
|
||||
@@ -251,7 +252,13 @@ export async function prepareWslMove(
|
||||
drives
|
||||
)
|
||||
if (planned.outcome === 'refused') {
|
||||
return refusal(planned.code, planned.refused?.length ? { refused: planned.refused } : {})
|
||||
// A picked project whose drive moved since the preview is a changed scope, not "nothing new".
|
||||
const changed =
|
||||
expectedMappedDrives &&
|
||||
wslMoveStartDriveRefusal(catalog, request, drives, [], expectedMappedDrives)
|
||||
return (
|
||||
changed || refusal(planned.code, planned.refused?.length ? { refused: planned.refused } : {})
|
||||
)
|
||||
}
|
||||
let { plan } = planned
|
||||
// A delta goes to the host its chain already moved into; another host would split the projects.
|
||||
@@ -279,6 +286,18 @@ export async function prepareWslMove(
|
||||
}
|
||||
throw error
|
||||
}
|
||||
const changedDrives =
|
||||
expectedMappedDrives &&
|
||||
wslMoveStartDriveRefusal(
|
||||
catalog,
|
||||
request,
|
||||
drives,
|
||||
plan.mappedDrives ?? [],
|
||||
expectedMappedDrives
|
||||
)
|
||||
if (changedDrives) {
|
||||
return changedDrives
|
||||
}
|
||||
const scope: WslMoveTerminalScope = {
|
||||
workspaceIds: exported.workspaceIds,
|
||||
workspaceKeys: new Set(exported.workspaceKeys)
|
||||
|
||||
@@ -80,7 +80,11 @@ export type WslMoveDriverDeps = {
|
||||
/** What drive letters map to; absent off Windows, where no drive is mapped. */
|
||||
driveShares?: WslMoveDriveShares
|
||||
/** Whether the host's Git can take a mapped-drive repo, read through its share path. */
|
||||
windowsGitVerdict?: (readablePath: string, distro: string) => Promise<WslMoveWindowsGitVerdict>
|
||||
windowsGitVerdict?: (
|
||||
readablePath: string,
|
||||
distro: string,
|
||||
signal?: AbortSignal
|
||||
) => Promise<WslMoveWindowsGitVerdict>
|
||||
/** Busy, working, automation and dispatch facts for the scope, from their owning stores. */
|
||||
gateInputs: (scope: WslMoveTerminalScope) => Promise<WslMoveGateInputs>
|
||||
/** The panes the scope's live terminals belong to; read before Sleep ends their sessions. */
|
||||
|
||||
+54
-34
@@ -1,7 +1,7 @@
|
||||
/**
|
||||
* The mapped drives a move plans with: read fresh at preview, and at start again, refusing when
|
||||
* the drives the selection names differ from what the preview showed (the start request carries
|
||||
* them back). With them, the mapped-drive repos the host's Git can't take, which the plan refuses.
|
||||
* The mapped drives a move plans with: read fresh at preview, and at start again. The start then
|
||||
* refuses when the drives its own planned rows name differ from what the preview showed (the start
|
||||
* request carries them back). With them, the mapped-drive repos the host's Git can't take.
|
||||
*/
|
||||
import {
|
||||
WSL_MOVE_MAPPED_DRIVE_UNVERIFIABLE_DETAIL,
|
||||
@@ -25,16 +25,18 @@ export type WslMoveSourceDrives = Required<WslMoveScopeDrives> & {
|
||||
windowsGitRefusals: ReadonlyMap<string, WslMoveScopeRefusal>
|
||||
}
|
||||
|
||||
/** The letters the request's rows name; every local row's when it names none. */
|
||||
function requestedLetters(
|
||||
/** The letters of the rows a request names; null when it names none (the whole distro). */
|
||||
function namedLetters(
|
||||
catalog: WslMoveCatalogRows,
|
||||
request: Pick<WslMoveRequest, 'repoIds' | 'folderWorkspaceIds'>
|
||||
): string[] {
|
||||
const whole = !request.repoIds && !request.folderWorkspaceIds
|
||||
): string[] | null {
|
||||
if (!request.repoIds && !request.folderWorkspaceIds) {
|
||||
return null
|
||||
}
|
||||
return wslMoveDriveLettersInUse({
|
||||
repos: catalog.repos.filter((repo) => whole || request.repoIds?.includes(repo.id)),
|
||||
folderWorkspaces: catalog.folderWorkspaces.filter(
|
||||
(folder) => whole || request.folderWorkspaceIds?.includes(folder.id)
|
||||
repos: catalog.repos.filter((repo) => request.repoIds?.includes(repo.id)),
|
||||
folderWorkspaces: catalog.folderWorkspaces.filter((folder) =>
|
||||
request.folderWorkspaceIds?.includes(folder.id)
|
||||
)
|
||||
})
|
||||
}
|
||||
@@ -42,31 +44,17 @@ function requestedLetters(
|
||||
export async function readWslMoveSourceDrives(
|
||||
deps: Pick<WslMoveDriverDeps, 'driveShares' | 'windowsGitVerdict'>,
|
||||
catalog: WslMoveCatalogRows,
|
||||
request: WslMoveRequest,
|
||||
/** At start: the drives the preview showed. Null for a preview. */
|
||||
expected: readonly WslMappedDrive[] | null
|
||||
): Promise<WslMoveSourceDrives | WslMoveRefusal> {
|
||||
request: WslMoveRequest
|
||||
): Promise<WslMoveSourceDrives> {
|
||||
const read = deps.driveShares
|
||||
? await readWslMoveMappedDrives(catalog, request.distro, deps.driveShares)
|
||||
: { mappedDrives: [], unverifiableLetters: [] }
|
||||
if (expected) {
|
||||
// Only drives this selection names count: an unrelated W: never stops a UNC-only start.
|
||||
const relevant = new Set([
|
||||
...expected.map((drive) => drive.letter.toUpperCase()),
|
||||
...requestedLetters(catalog, request)
|
||||
])
|
||||
if (read.unverifiableLetters.some((letter) => relevant.has(letter))) {
|
||||
return {
|
||||
outcome: 'refused',
|
||||
code: 'wsl_move_unavailable',
|
||||
detail: WSL_MOVE_MAPPED_DRIVE_UNVERIFIABLE_DETAIL
|
||||
}
|
||||
}
|
||||
const fresh = read.mappedDrives.filter((drive) => relevant.has(drive.letter.toUpperCase()))
|
||||
if (!sameWslMappedDrives(expected, fresh)) {
|
||||
return { outcome: 'refused', code: 'wsl_move_scope_changed', detail: 'mapped-drives-changed' }
|
||||
}
|
||||
}
|
||||
: { mappedDrives: [], unverifiableLetters: [], unknownLetters: [] }
|
||||
const named = namedLetters(catalog, request) ?? []
|
||||
// An unclassified drive (an offline share, say) is this distro's to list only when picked.
|
||||
const unverifiableLetters = [
|
||||
...read.unverifiableLetters,
|
||||
...read.unknownLetters.filter((letter) => named.includes(letter))
|
||||
]
|
||||
const windowsGitRefusals =
|
||||
deps.windowsGitVerdict && read.mappedDrives.length > 0
|
||||
? await findWindowsGitRefusals(
|
||||
@@ -76,7 +64,7 @@ export async function readWslMoveSourceDrives(
|
||||
deps.windowsGitVerdict
|
||||
)
|
||||
: new Map<string, WslMoveScopeRefusal>()
|
||||
return { ...read, windowsGitRefusals }
|
||||
return { mappedDrives: read.mappedDrives, unverifiableLetters, windowsGitRefusals }
|
||||
}
|
||||
|
||||
/** The drives a move journals: only those its exported paths named, so a UNC move stays v1. */
|
||||
@@ -90,3 +78,35 @@ export function journaledWslMoveDrives(
|
||||
const named = new Set(exportedLetters)
|
||||
return mappedDrives.filter((drive) => named.has(drive.letter.toUpperCase()))
|
||||
}
|
||||
|
||||
/**
|
||||
* At start: the drives this start will journal, and those of the rows it names, must map where
|
||||
* the preview showed. Hidden, retained, refused or unrelated rows never count.
|
||||
*/
|
||||
export function wslMoveStartDriveRefusal(
|
||||
catalog: WslMoveCatalogRows,
|
||||
request: WslMoveRequest,
|
||||
drives: Pick<WslMoveSourceDrives, 'mappedDrives' | 'unverifiableLetters'>,
|
||||
journaled: readonly WslMappedDrive[],
|
||||
expected: readonly WslMappedDrive[]
|
||||
): WslMoveRefusal | null {
|
||||
const named = namedLetters(catalog, request)
|
||||
// A drive the preview showed, or one a picked row uses, that no longer answers.
|
||||
const needed = new Set([...expected.map((drive) => drive.letter.toUpperCase()), ...(named ?? [])])
|
||||
if (drives.unverifiableLetters.some((letter) => needed.has(letter))) {
|
||||
return {
|
||||
outcome: 'refused',
|
||||
code: 'wsl_move_unavailable',
|
||||
detail: WSL_MOVE_MAPPED_DRIVE_UNVERIFIABLE_DETAIL
|
||||
}
|
||||
}
|
||||
const relevant = new Set([
|
||||
...journaled.map((drive) => drive.letter.toUpperCase()),
|
||||
...(named ?? [])
|
||||
])
|
||||
const only = (list: readonly WslMappedDrive[]): WslMappedDrive[] =>
|
||||
list.filter((drive) => relevant.has(drive.letter.toUpperCase()))
|
||||
return sameWslMappedDrives(only(expected), only(drives.mappedDrives))
|
||||
? null
|
||||
: { outcome: 'refused', code: 'wsl_move_scope_changed', detail: 'mapped-drives-changed' }
|
||||
}
|
||||
|
||||
+106
@@ -0,0 +1,106 @@
|
||||
/**
|
||||
* A start compares only the drives its own planned rows name with what the preview showed: a
|
||||
* refused, unanswered, retained or unrelated drive-letter row never refuses a whole-distro start
|
||||
* (the orchestrator's Retry sends no ids).
|
||||
*/
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { WSL_HOSTS_INTERNAL_GATE_ENV } from '../../../../shared/remote-runtime/wsl-hosts/wsl-host-internal-gate'
|
||||
import type { WslMoveRequest } from '../../../../shared/wsl-move/wsl-move-driver-types'
|
||||
import type { WslMappedDriveRead } from '../../../wsl/filesystem/wsl-mapped-drive-share'
|
||||
import { testState } from '../../persistence-test-harness'
|
||||
import {
|
||||
createWslMoveKillRig,
|
||||
removeWslMoveRigDirs,
|
||||
wslMoveRigRetentionStore,
|
||||
type WslMoveRig
|
||||
} from '../../__fixtures__/wsl-mover/wsl-move-kill-rig'
|
||||
import { listWslMoveCutovers } from '../cutover-recovery/wsl-move-cutover-journal'
|
||||
import { runWslMoveRetentionPass } from '../cutover-recovery/wsl-move-retention'
|
||||
import { resetWslMoveDesktopRewriteStoresForTests } from '../desktop-state/wsl-move-desktop-rewrite-stores'
|
||||
import { moveProjectsToWslHost } from '../wsl-move-driver'
|
||||
import { previewWslMove } from './wsl-move-driver-preview'
|
||||
|
||||
vi.mock('electron', () => ({
|
||||
app: { getPath: () => testState.dir },
|
||||
safeStorage: {
|
||||
isEncryptionAvailable: () => true,
|
||||
encryptString: (plaintext: string) => Buffer.from(`encrypted:${plaintext}`, 'utf-8'),
|
||||
decryptString: (ciphertext: Buffer) => ciphertext.toString('utf-8').slice('encrypted:'.length)
|
||||
}
|
||||
}))
|
||||
vi.mock('../../../telemetry/client', () => ({ track: vi.fn() }))
|
||||
vi.mock('../../../telemetry/cohort-classifier', () => ({
|
||||
getCohortAtEmit: vi.fn(() => ({ nth_repo_added: 1 }))
|
||||
}))
|
||||
|
||||
const W = { letter: 'W', share: '\\\\wsl.localhost\\Ubuntu' }
|
||||
const UNC = '\\\\wsl.localhost\\Ubuntu\\home\\dev\\app'
|
||||
|
||||
let rig: WslMoveRig
|
||||
let shares: Record<string, WslMappedDriveRead>
|
||||
let known: Record<string, string | null>
|
||||
|
||||
beforeEach(() => {
|
||||
vi.stubEnv(WSL_HOSTS_INTERNAL_GATE_ENV, '1')
|
||||
vi.spyOn(console, 'warn').mockImplementation(() => {})
|
||||
rig = createWslMoveKillRig()
|
||||
shares = { W: { share: W.share } }
|
||||
known = { W: W.share }
|
||||
rig.world.deps.driveShares = {
|
||||
classify: async (letter) => (letter in known ? { share: known[letter] } : null),
|
||||
readNow: async (letter) => shares[letter] ?? { share: null }
|
||||
}
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks()
|
||||
vi.unstubAllEnvs()
|
||||
resetWslMoveDesktopRewriteStoresForTests()
|
||||
removeWslMoveRigDirs()
|
||||
})
|
||||
|
||||
const project = (id: string, path: string) => ({ ...rig.world.repos[0], id, path })
|
||||
|
||||
/** Preview, then start as the orchestrator does (no ids) or as the dialog does (the ids shown). */
|
||||
async function previewThenStart(ids: 'none' | 'shown'): Promise<unknown> {
|
||||
const preview = await previewWslMove(rig.world.deps, { distro: 'Ubuntu' })
|
||||
if (preview.outcome !== 'ready') {
|
||||
return preview
|
||||
}
|
||||
const request: WslMoveRequest = {
|
||||
distro: 'Ubuntu',
|
||||
mappedDrives: preview.mappedDrives ?? [],
|
||||
...(ids === 'shown'
|
||||
? { repoIds: preview.repoIds, folderWorkspaceIds: preview.folderWorkspaceIds }
|
||||
: {})
|
||||
}
|
||||
return moveProjectsToWslHost(rig.world.deps, request)
|
||||
}
|
||||
|
||||
describe.each(['none', 'shown'] as const)('a whole-distro start with ids %s', (ids) => {
|
||||
it('moves a UNC project beside a W: repo the host Git refuses', async () => {
|
||||
rig.world.repos = [project('repo-1', UNC), project('repo-w', 'W:\\home\\dev\\other')]
|
||||
rig.world.deps.windowsGitVerdict = async () => 'windows-git-worktrees'
|
||||
expect(await previewThenStart(ids)).toMatchObject({ outcome: 'moved' })
|
||||
expect(listWslMoveCutovers(rig.userDataPath)[0].version).toBe(1)
|
||||
})
|
||||
|
||||
it('moves a UNC project beside an unrelated drive that does not answer', async () => {
|
||||
rig.world.repos = [project('repo-1', UNC), project('repo-s', 'S:\\shared\\tool')]
|
||||
expect(await previewThenStart(ids)).toMatchObject({ outcome: 'moved' })
|
||||
})
|
||||
|
||||
it('moves a new UNC project beside a W: project an earlier move took', async () => {
|
||||
rig.world.repos = [project('repo-1', 'W:\\home\\dev\\app')]
|
||||
expect(await previewThenStart('shown')).toMatchObject({ outcome: 'moved' })
|
||||
await runWslMoveRetentionPass({
|
||||
userDataPath: rig.userDataPath,
|
||||
store: wslMoveRigRetentionStore(rig)
|
||||
})
|
||||
rig.world.repos = [...rig.world.repos, project('repo-2', `${UNC}2`)]
|
||||
// The retained W: row's drive now answers differently; it isn't this start's to compare.
|
||||
shares = { W: { share: '\\\\wsl.localhost\\Ubuntu\\home' } }
|
||||
expect(await previewThenStart(ids)).toMatchObject({ outcome: 'moved' })
|
||||
expect(listWslMoveCutovers(rig.userDataPath).map((record) => record.version)).toContain(1)
|
||||
})
|
||||
})
|
||||
@@ -173,9 +173,9 @@ export function exportWslMoveManifest(
|
||||
? { ...inspection.payload, workspaceSession }
|
||||
: inspection.payload
|
||||
const usedLetters = new Set<string>()
|
||||
const rewriter = createUncToLinuxPathRewriter(request.distro, request.mappedDrives, (letter) =>
|
||||
usedLetters.add(letter)
|
||||
)
|
||||
const rewriter = createUncToLinuxPathRewriter(request.distro, request.mappedDrives, {
|
||||
onMappedDrive: (letter) => usedLetters.add(letter)
|
||||
})
|
||||
const payload = rewriteOrcadMigrationPayloadPaths(
|
||||
{ ...catalog, ...(hasDormantState(dormantState) ? { dormantState } : {}) },
|
||||
rewriter
|
||||
|
||||
+6
@@ -93,6 +93,12 @@ describe('the move path rewriter with mapped drives', () => {
|
||||
expect(rewriter.path('file:///W:/home/me/App/x.ts', 'url')).toBe('file:///home/me/App/x.ts')
|
||||
})
|
||||
|
||||
it('gives a folded w:/ key back the case of the moved root holding it', () => {
|
||||
const roots = createUncToLinuxPathRewriter('Ubuntu', [W], { linuxRoots: ['/home/me/App'] })
|
||||
expect(roots.path('w:/home/me/app/src', 'absolute')).toBe('/home/me/App/src')
|
||||
expect(roots.path('W:\\home\\me\\App\\Src', 'absolute')).toBe('/home/me/App/Src')
|
||||
})
|
||||
|
||||
it('leaves a path on an unmapped letter untouched', () => {
|
||||
expect(rewriter.path('X:\\home\\me\\App', 'absolute')).toBe('X:\\home\\me\\App')
|
||||
expect(rewriter.path('file:///X:/home/me', 'url')).toBe('file:///X:/home/me')
|
||||
|
||||
@@ -23,8 +23,10 @@ export type WslMoveDriveShares = {
|
||||
|
||||
export type WslMoveMappedDrivesRead = {
|
||||
mappedDrives: WslMappedDrive[]
|
||||
/** Letters local projects use that may map into this distro, but Windows did not answer for. */
|
||||
/** Letters last known to map into this distro that Windows did not answer for now. */
|
||||
unverifiableLetters: string[]
|
||||
/** Letters never classified (the lookup timed out): they may map anywhere, or nowhere. */
|
||||
unknownLetters: string[]
|
||||
}
|
||||
|
||||
const DRIVE_PATH = /^([A-Za-z]):[\\/]/
|
||||
@@ -46,7 +48,7 @@ export function wslMoveDriveLettersInUse(rows: {
|
||||
return [...letters].sort()
|
||||
}
|
||||
|
||||
type LetterRead = { mapped: WslMappedDrive } | 'unverifiable' | 'elsewhere'
|
||||
type LetterRead = { mapped: WslMappedDrive } | 'unverifiable' | 'unknown' | 'elsewhere'
|
||||
|
||||
async function readLetter(
|
||||
letter: string,
|
||||
@@ -55,7 +57,7 @@ async function readLetter(
|
||||
): Promise<LetterRead> {
|
||||
const known = await shares.classify(letter).catch(() => null)
|
||||
if (known === null) {
|
||||
return 'unverifiable'
|
||||
return 'unknown'
|
||||
}
|
||||
if (known.share === null || !parseWslUncPath(known.share)) {
|
||||
return 'elsewhere'
|
||||
@@ -85,6 +87,7 @@ export async function readWslMoveMappedDrives(
|
||||
),
|
||||
unverifiableLetters: reads
|
||||
.filter(({ read }) => read === 'unverifiable')
|
||||
.map(({ letter }) => letter)
|
||||
.map(({ letter }) => letter),
|
||||
unknownLetters: reads.filter(({ read }) => read === 'unknown').map(({ letter }) => letter)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,27 +1,39 @@
|
||||
// Convert only the moved distro's UNC and mapped-drive paths; unrelated paths remain unchanged.
|
||||
import {
|
||||
wslMappedDriveComparisonKeyToLinux,
|
||||
wslMappedDriveFileUrlToLinux,
|
||||
wslMoveSourcePathToLinux,
|
||||
type WslMappedDrive
|
||||
} from '../../../../shared/wsl-move/wsl-mapped-drive-paths'
|
||||
import type { OrcadMigrationPathRewriter } from '../../migrating-orcad-catalog/path-rewrite/orcad-migration-path-rewrite'
|
||||
|
||||
export type UncToLinuxRewriteOptions = {
|
||||
/** Told each drive letter a rewrite mapped, so a move journals only the drives it names. */
|
||||
onMappedDrive?: (letter: string) => void
|
||||
/** The moved roots in Linux form: a folded `w:/…` key takes back their case. */
|
||||
linuxRoots?: readonly string[]
|
||||
}
|
||||
|
||||
export function createUncToLinuxPathRewriter(
|
||||
distro: string,
|
||||
mappedDrives: readonly WslMappedDrive[] = [],
|
||||
/** Told each drive letter a rewrite mapped, so a move journals only the drives it names. */
|
||||
onMappedDrive?: (letter: string) => void
|
||||
options: UncToLinuxRewriteOptions = {}
|
||||
): OrcadMigrationPathRewriter {
|
||||
const fileUrl = new RegExp(`^file://(?:wsl\\.localhost|wsl\\$)/([^/]+)(/.*)?$`, 'i')
|
||||
const noted = (value: string, mapped: string | null): string | null => {
|
||||
const letter = mapped === null ? null : DRIVE_LETTER.exec(value)?.[1]
|
||||
if (letter) {
|
||||
onMappedDrive?.(letter.toUpperCase())
|
||||
options.onMappedDrive?.(letter.toUpperCase())
|
||||
}
|
||||
return mapped
|
||||
}
|
||||
const toLinux = (value: string): string | null =>
|
||||
noted(value, wslMoveSourcePathToLinux(value, distro, mappedDrives))
|
||||
noted(
|
||||
value,
|
||||
(options.linuxRoots &&
|
||||
wslMappedDriveComparisonKeyToLinux(value, distro, mappedDrives, options.linuxRoots)) ??
|
||||
wslMoveSourcePathToLinux(value, distro, mappedDrives)
|
||||
)
|
||||
return {
|
||||
path: (value, form) => {
|
||||
switch (form) {
|
||||
|
||||
+26
@@ -65,6 +65,32 @@ describe('windowsGitWorktreeVerdict', () => {
|
||||
})
|
||||
})
|
||||
|
||||
describe('worktree records Git ignores', () => {
|
||||
it('passes over a stray file and an entry with no `gitdir`, as Git does', async () => {
|
||||
const repo = join(root, 'stray')
|
||||
write(join(repo, '.git', 'worktrees', 'notes.txt'), 'x')
|
||||
write(join(repo, '.git', 'worktrees', 'half', 'HEAD'), 'ref: refs/heads/x\n')
|
||||
write(join(repo, '.git', 'worktrees', 'ok', 'gitdir'), '/home/me/ok/.git\n')
|
||||
expect(await verdict(repo)).toBe('ok')
|
||||
})
|
||||
|
||||
it('aborts the reads it started once the check times out', async () => {
|
||||
let seen: AbortSignal | undefined
|
||||
const refusals = await findWindowsGitRefusals(
|
||||
[{ id: 'slow', path: 'W:\\slow', displayName: 'slow', badgeColor: '#000', addedAt: 0 }],
|
||||
'Ubuntu',
|
||||
[{ letter: 'W', share: '\\\\wsl.localhost\\Ubuntu' }],
|
||||
(_path, _distro, signal) => {
|
||||
seen = signal
|
||||
return new Promise(() => {})
|
||||
},
|
||||
10
|
||||
)
|
||||
expect(Object.fromEntries(refusals)).toEqual({ slow: 'git-unreadable' })
|
||||
expect(seen?.aborted).toBe(true)
|
||||
})
|
||||
})
|
||||
|
||||
describe('findWindowsGitRefusals', () => {
|
||||
const repo = (id: string, path: string): Repo => ({
|
||||
id,
|
||||
|
||||
+57
-14
@@ -29,10 +29,30 @@ export type WslMoveWindowsGitVerdict =
|
||||
// Long enough for a cold distro share; a repo whose records don't answer by then stays here.
|
||||
const GIT_RECORDS_TIMEOUT_MS = 5_000
|
||||
|
||||
// Records read at once: enough for many worktrees, few enough not to flood a slow share.
|
||||
const RECORD_READS_AT_ONCE = 8
|
||||
|
||||
const isWindowsLink = (link: string): boolean => isForeignLink(link, true)
|
||||
|
||||
function errorCode(error: unknown): unknown {
|
||||
return error instanceof Error && 'code' in error ? error.code : undefined
|
||||
}
|
||||
|
||||
function isMissing(error: unknown): boolean {
|
||||
return error instanceof Error && 'code' in error && error.code === 'ENOENT'
|
||||
return errorCode(error) === 'ENOENT'
|
||||
}
|
||||
|
||||
/** A worktree record's link; null for an entry Git itself ignores or prunes (no `gitdir`). */
|
||||
async function recordLink(entry: string, signal: AbortSignal | undefined): Promise<string | null> {
|
||||
try {
|
||||
return (await readFile(join(entry, 'gitdir'), { encoding: 'utf8', signal })).trim()
|
||||
} catch (error) {
|
||||
// A stray file in `worktrees/` (ENOTDIR) or an entry with no `gitdir` (ENOENT).
|
||||
if (isMissing(error) || errorCode(error) === 'ENOTDIR') {
|
||||
return null
|
||||
}
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
async function statOrNull(path: string): Promise<Stats | null> {
|
||||
@@ -52,7 +72,8 @@ function readable(base: string, link: string, distro: string): string {
|
||||
/** The repo's common Git directory, null outside Git, or the Windows-link verdict. */
|
||||
async function commonDirOf(
|
||||
repoPath: string,
|
||||
distro: string
|
||||
distro: string,
|
||||
signal: AbortSignal | undefined
|
||||
): Promise<{ commonDir: string } | null | 'windows-git-dir'> {
|
||||
const dotGit = join(repoPath, '.git')
|
||||
const info = await statOrNull(dotGit)
|
||||
@@ -64,7 +85,9 @@ async function commonDirOf(
|
||||
if (info.isDirectory()) {
|
||||
return { commonDir: dotGit }
|
||||
}
|
||||
const link = /^gitdir:\s*(.+)$/m.exec(await readFile(dotGit, 'utf8'))?.[1]?.trim()
|
||||
const link = /^gitdir:\s*(.+)$/m
|
||||
.exec(await readFile(dotGit, { encoding: 'utf8', signal }))?.[1]
|
||||
?.trim()
|
||||
if (!link) {
|
||||
throw new Error('git_link_unreadable')
|
||||
}
|
||||
@@ -72,7 +95,7 @@ async function commonDirOf(
|
||||
return 'windows-git-dir'
|
||||
}
|
||||
const gitDir = readable(repoPath, link, distro)
|
||||
const common = await readFile(join(gitDir, 'commondir'), 'utf8').then(
|
||||
const common = await readFile(join(gitDir, 'commondir'), { encoding: 'utf8', signal }).then(
|
||||
(text) => text.trim(),
|
||||
(error: unknown) => {
|
||||
// No `commondir`: a separate Git folder, which is its own common directory.
|
||||
@@ -91,9 +114,12 @@ async function commonDirOf(
|
||||
/** `repoPath` in a spelling this process reads (the share's, for a mapped drive). */
|
||||
export async function windowsGitWorktreeVerdict(
|
||||
repoPath: string,
|
||||
distro: string
|
||||
distro: string,
|
||||
/** Aborted at the check's timeout: pending reads stop, and no further one starts. */
|
||||
signal?: AbortSignal
|
||||
): Promise<WslMoveWindowsGitVerdict> {
|
||||
const found = await commonDirOf(repoPath, distro)
|
||||
const found = await commonDirOf(repoPath, distro, signal)
|
||||
signal?.throwIfAborted()
|
||||
if (found === null || found === 'windows-git-dir') {
|
||||
return found ?? 'ok'
|
||||
}
|
||||
@@ -104,25 +130,35 @@ export async function windowsGitWorktreeVerdict(
|
||||
}
|
||||
throw error
|
||||
})
|
||||
for (const entry of entries) {
|
||||
for (let start = 0; start < entries.length; start += RECORD_READS_AT_ONCE) {
|
||||
signal?.throwIfAborted()
|
||||
// An unreadable record fails the check: it may be one the host's prune would delete.
|
||||
const link = (await readFile(join(admin, entry, 'gitdir'), 'utf8')).trim()
|
||||
if (isWindowsLink(link)) {
|
||||
const links = await Promise.all(
|
||||
entries
|
||||
.slice(start, start + RECORD_READS_AT_ONCE)
|
||||
.map((entry) => recordLink(join(admin, entry), signal))
|
||||
)
|
||||
if (links.some((link) => link !== null && isWindowsLink(link))) {
|
||||
return 'windows-git-worktrees'
|
||||
}
|
||||
}
|
||||
return 'ok'
|
||||
}
|
||||
|
||||
/** Stops waiting at the timeout, and aborts the reads that support it; a hung stat is left. */
|
||||
async function verdictWithin(
|
||||
check: () => Promise<WslMoveWindowsGitVerdict>,
|
||||
check: (signal: AbortSignal) => Promise<WslMoveWindowsGitVerdict>,
|
||||
timeoutMs: number
|
||||
): Promise<WslMoveWindowsGitVerdict | 'git-unreadable'> {
|
||||
const controller = new AbortController()
|
||||
let timer: ReturnType<typeof setTimeout> | undefined
|
||||
const timeout = new Promise<'git-unreadable'>((done) => {
|
||||
timer = setTimeout(() => done('git-unreadable'), timeoutMs)
|
||||
timer = setTimeout(() => {
|
||||
controller.abort()
|
||||
done('git-unreadable')
|
||||
}, timeoutMs)
|
||||
})
|
||||
const verdict = check().catch((): 'git-unreadable' => 'git-unreadable')
|
||||
const verdict = check(controller.signal).catch((): 'git-unreadable' => 'git-unreadable')
|
||||
return Promise.race([verdict, timeout]).finally(() => clearTimeout(timer))
|
||||
}
|
||||
|
||||
@@ -131,7 +167,11 @@ export async function findWindowsGitRefusals(
|
||||
repos: readonly Repo[],
|
||||
distro: string,
|
||||
mappedDrives: readonly WslMappedDrive[],
|
||||
check: (readablePath: string, distro: string) => Promise<WslMoveWindowsGitVerdict>,
|
||||
check: (
|
||||
readablePath: string,
|
||||
distro: string,
|
||||
signal: AbortSignal
|
||||
) => Promise<WslMoveWindowsGitVerdict>,
|
||||
timeoutMs = GIT_RECORDS_TIMEOUT_MS
|
||||
): Promise<Map<string, WslMoveScopeRefusal>> {
|
||||
const onMappedDrive = repos.filter(
|
||||
@@ -140,7 +180,10 @@ export async function findWindowsGitRefusals(
|
||||
const verdicts = await Promise.all(
|
||||
onMappedDrive.map(async (repo) => {
|
||||
const sharePath = toWslDistroUncPath(repo.path, mappedDrives)
|
||||
return [repo.id, await verdictWithin(() => check(sharePath, distro), timeoutMs)] as const
|
||||
return [
|
||||
repo.id,
|
||||
await verdictWithin((signal) => check(sharePath, distro, signal), timeoutMs)
|
||||
] as const
|
||||
})
|
||||
)
|
||||
const refusals = new Map<string, WslMoveScopeRefusal>()
|
||||
|
||||
+11
-1
@@ -2,7 +2,7 @@
|
||||
import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'
|
||||
import { tmpdir } from 'node:os'
|
||||
import { join } from 'node:path'
|
||||
import { afterEach, beforeEach, describe, expect, it } from 'vitest'
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { wslMoveCutoverFixture as cutover } from '../../__fixtures__/wsl-mover/wsl-move-cutover-fixture'
|
||||
import {
|
||||
clearWslMappedDriveShareCacheForTests,
|
||||
@@ -18,6 +18,7 @@ import {
|
||||
|
||||
let userDataPath: string
|
||||
beforeEach(() => {
|
||||
vi.spyOn(process, 'platform', 'get').mockReturnValue('win32')
|
||||
userDataPath = mkdtempSync(join(tmpdir(), 'wsl-move-unread-'))
|
||||
const record = cutover('move-1', 'destination-committed', {
|
||||
mappedDrives: [{ letter: 'W', share: '\\\\wsl.localhost\\Ubuntu' }]
|
||||
@@ -30,6 +31,7 @@ beforeEach(() => {
|
||||
)
|
||||
})
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks()
|
||||
resetWslMoveFenceForTests()
|
||||
clearWslMappedDriveShareCacheForTests()
|
||||
rmSync(userDataPath, { recursive: true, force: true })
|
||||
@@ -70,4 +72,12 @@ describe('an unreadable WSL move journal', () => {
|
||||
loadWslMoveFence(userDataPath)
|
||||
expect(isWslMoveProjectBlocked(store, { repoId: 'moved-w' })).toBe(true)
|
||||
})
|
||||
|
||||
it('never treats a drive letter as WSL off Windows', () => {
|
||||
vi.spyOn(process, 'platform', 'get').mockReturnValue('darwin')
|
||||
loadWslMoveFence(userDataPath)
|
||||
expect(isWslMoveProjectBlocked(store, { repoId: 'moved-w' })).toBe(false)
|
||||
expect(isWslMoveCwdFenced('W:\\home\\dev\\repo-1')).toBe(false)
|
||||
expect(isWslMoveProjectBlocked(store, { repoId: 'unc' })).toBe(true)
|
||||
})
|
||||
})
|
||||
|
||||
+6
-10
@@ -1,26 +1,22 @@
|
||||
/** What an unreadable WSL move journal still fences: folders its moves could have taken. */
|
||||
import { isWslUncPath } from '../../../../shared/file-access/wsl-paths'
|
||||
import {
|
||||
classifyWslMappedDrive,
|
||||
wslMappedDriveLastKnownShare
|
||||
} from '../../../wsl/filesystem/wsl-mapped-drive-share'
|
||||
import { wslMappedDriveLastKnownShare } from '../../../wsl/filesystem/wsl-mapped-drive-share'
|
||||
|
||||
/**
|
||||
* Without the journal, any folder a move could have taken: a UNC path, or a drive letter not
|
||||
* known to point outside WSL (a moved `W:\` row has nothing else marking it as moved).
|
||||
* known (from this launch or a saved answer) to point outside WSL. A moved `W:\` row has nothing
|
||||
* else marking it as moved.
|
||||
*/
|
||||
export function mayBeInWsl(path: string): boolean {
|
||||
if (isWslUncPath(path)) {
|
||||
return true
|
||||
}
|
||||
const letter = /^([A-Za-z]):[\\/]/.exec(path)?.[1]
|
||||
if (!letter) {
|
||||
// Off Windows a drive letter names no share, so it's never in WSL.
|
||||
if (!letter || process.platform !== 'win32') {
|
||||
return false
|
||||
}
|
||||
// Never read here: it runs on background paths too. A user's preview or add learns the drive.
|
||||
const known = wslMappedDriveLastKnownShare(letter)
|
||||
if (!known) {
|
||||
// One bounded, cached lookup, so a local drive's projects unblock once it answers.
|
||||
void classifyWslMappedDrive(letter).catch(() => {})
|
||||
}
|
||||
return !known || (known.share !== null && isWslUncPath(known.share))
|
||||
}
|
||||
|
||||
@@ -16,6 +16,7 @@ import { browserSiteDisplayController } from '../browser/site-settings/display/b
|
||||
import { ensureActiveOrcaProfile } from '../orca-profiles/profile-index-store'
|
||||
import { getCanonicalUserDataPath } from '../persistence/loading-store/user-data-path'
|
||||
import { getAppEnvironment } from '../../shared/app-lifecycle/app-environment'
|
||||
import { loadWslMappedDriveAnswers } from '../wsl/filesystem/wsl-mapped-drive-answers-file'
|
||||
import { loadWslMoveFence } from '../persistence/moving-wsl-projects/quiescence/wsl-move-scope-guard'
|
||||
import { startWslMoveStartup } from '../persistence/moving-wsl-projects/startup/wsl-move-startup'
|
||||
import { startWslHostsPolicyLiveUpdates } from '../wsl/host-lifecycle/wsl-hosts-policy-live-update'
|
||||
@@ -154,6 +155,8 @@ export async function initializeReadyFoundation(): Promise<void> {
|
||||
})
|
||||
// Why before the store loads: its pane normalization tells a moved project's retained rows from
|
||||
// a rival host's, and no handler or runtime may give a moving project a new terminal.
|
||||
// Saved drive answers first: the fence and the move prune read them and never a drive.
|
||||
loadWslMappedDriveAnswers(getAppEnvironment().getPath('userData'))
|
||||
loadWslMoveFence(getAppEnvironment().getPath('userData'))
|
||||
const profileState = await createProfileStateStoreForStartup({
|
||||
userDataPath: getProfileUserDataPath(),
|
||||
|
||||
@@ -0,0 +1,103 @@
|
||||
import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
|
||||
import type * as NodeFs from 'node:fs'
|
||||
import { tmpdir } from 'node:os'
|
||||
import { join } from 'node:path'
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
|
||||
const realpathNative = vi.hoisted(() => vi.fn())
|
||||
vi.mock('node:fs', async (importOriginal) => {
|
||||
const actual = await importOriginal<typeof NodeFs>()
|
||||
return { ...actual, realpath: Object.assign(actual.realpath, { native: realpathNative }) }
|
||||
})
|
||||
|
||||
import { wslMoveCutoverFixture as cutover } from '../../persistence/__fixtures__/wsl-mover/wsl-move-cutover-fixture'
|
||||
import { wslMoveJournalDirectory } from '../../persistence/moving-wsl-projects/cutover-recovery/wsl-move-cutover-journal'
|
||||
import {
|
||||
isWslMoveProjectBlocked,
|
||||
loadWslMoveFence,
|
||||
resetWslMoveFenceForTests
|
||||
} from '../../persistence/moving-wsl-projects/quiescence/wsl-move-scope-guard'
|
||||
import {
|
||||
loadWslMappedDriveAnswers,
|
||||
wslMappedDriveAnswersPath
|
||||
} from './wsl-mapped-drive-answers-file'
|
||||
import {
|
||||
clearWslMappedDriveShareCacheForTests,
|
||||
readWslMappedDriveShareNow,
|
||||
wslMappedDriveLastKnownShare
|
||||
} from './wsl-mapped-drive-share'
|
||||
|
||||
let userDataPath: string
|
||||
beforeEach(() => {
|
||||
vi.spyOn(process, 'platform', 'get').mockReturnValue('win32')
|
||||
userDataPath = mkdtempSync(join(tmpdir(), 'wsl-drive-answers-'))
|
||||
})
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks()
|
||||
resetWslMoveFenceForTests()
|
||||
clearWslMappedDriveShareCacheForTests()
|
||||
realpathNative.mockReset()
|
||||
rmSync(userDataPath, { recursive: true, force: true })
|
||||
})
|
||||
|
||||
/** A fresh launch: memory gone, only the saved file left. */
|
||||
function restart(): ReturnType<typeof loadWslMappedDriveAnswers> {
|
||||
clearWslMappedDriveShareCacheForTests()
|
||||
return loadWslMappedDriveAnswers(userDataPath)
|
||||
}
|
||||
|
||||
const fake = (real: string) => ({
|
||||
platform: 'win32' as const,
|
||||
realpathRoot: async () => real,
|
||||
now: () => 1_000,
|
||||
timeoutMs: 50
|
||||
})
|
||||
|
||||
describe('saved mapped-drive answers', () => {
|
||||
it('keep each settled answer across a restart, without reading any drive', async () => {
|
||||
const answers = restart()
|
||||
await readWslMappedDriveShareNow('C', fake('C:\\'))
|
||||
await readWslMappedDriveShareNow('W', fake('\\\\wsl.localhost\\Ubuntu\\'))
|
||||
await answers.saved()
|
||||
expect(JSON.parse(readFileSync(wslMappedDriveAnswersPath(userDataPath), 'utf8'))).toEqual({
|
||||
version: 1,
|
||||
answers: [
|
||||
{ letter: 'C', share: null, at: 1_000 },
|
||||
{ letter: 'W', share: '\\\\wsl.localhost\\Ubuntu', at: 1_000 }
|
||||
]
|
||||
})
|
||||
restart()
|
||||
expect(wslMappedDriveLastKnownShare('C')).toEqual({ share: null })
|
||||
expect(wslMappedDriveLastKnownShare('W')).toEqual({ share: '\\\\wsl.localhost\\Ubuntu' })
|
||||
expect(realpathNative).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('ignore a malformed file', () => {
|
||||
writeFileSync(
|
||||
wslMappedDriveAnswersPath(userDataPath),
|
||||
'{"version":1,"answers":[{"letter":"cc"}]}'
|
||||
)
|
||||
restart()
|
||||
expect(wslMappedDriveLastKnownShare('C')).toBeNull()
|
||||
})
|
||||
|
||||
it('let an unreadable journal’s fence pass a C: project after a restart', async () => {
|
||||
const answers = restart()
|
||||
await readWslMappedDriveShareNow('C', fake('C:\\'))
|
||||
await answers.saved()
|
||||
restart()
|
||||
mkdirSync(wslMoveJournalDirectory(userDataPath), { recursive: true })
|
||||
writeFileSync(
|
||||
join(wslMoveJournalDirectory(userDataPath), 'move-1.json'),
|
||||
JSON.stringify({ ...cutover('move-1', 'destination-committed'), version: 3 })
|
||||
)
|
||||
loadWslMoveFence(userDataPath)
|
||||
const store = {
|
||||
getRepo: (id: string) =>
|
||||
({ c: { path: 'C:\\src\\site' }, w: { path: 'W:\\home\\me\\app' } })[id]
|
||||
}
|
||||
expect(isWslMoveProjectBlocked(store, { repoId: 'c' })).toBe(false)
|
||||
expect(isWslMoveProjectBlocked(store, { repoId: 'w' })).toBe(true)
|
||||
expect(realpathNative).not.toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,77 @@
|
||||
/**
|
||||
* Each drive letter's last settled answer (the WSL share it maps to, or nowhere), kept across
|
||||
* launches. Background paths (the move prune, an unreadable journal's fence) only ever read these:
|
||||
* reading a mapped share can boot its stopped distro, so they never ask Windows themselves.
|
||||
*/
|
||||
import { join } from 'node:path'
|
||||
import { z } from 'zod'
|
||||
import { readNodeFileSyncWithinLimit } from '../../../shared/file-content/node-bounded-file-reader'
|
||||
import { parseWslUncPath } from '../../../shared/file-access/wsl-paths'
|
||||
import { durableWriteTempPath, writeFileDurable } from '../../filesystem/durable-file-write'
|
||||
import {
|
||||
seedWslMappedDriveAnswers,
|
||||
setWslMappedDriveAnswerSink,
|
||||
type WslMappedDriveAnswer
|
||||
} from './wsl-mapped-drive-share'
|
||||
|
||||
const FILE_NAME = 'wsl-mapped-drive-answers.json'
|
||||
const MAX_FILE_BYTES = 64 * 1024
|
||||
|
||||
const AnswersSchema = z.object({
|
||||
version: z.literal(1),
|
||||
answers: z
|
||||
.array(
|
||||
z.object({
|
||||
letter: z.string().regex(/^[A-Z]$/),
|
||||
share: z
|
||||
.string()
|
||||
.max(4_096)
|
||||
.refine((share) => parseWslUncPath(share) !== null)
|
||||
.nullable(),
|
||||
at: z.number().finite()
|
||||
})
|
||||
)
|
||||
.max(26)
|
||||
})
|
||||
|
||||
export function wslMappedDriveAnswersPath(userDataPath: string): string {
|
||||
return join(userDataPath, FILE_NAME)
|
||||
}
|
||||
|
||||
/**
|
||||
* Seeds the answers saved by earlier launches, then saves every new one. Reads only this file;
|
||||
* a missing or malformed file leaves every letter unknown.
|
||||
*/
|
||||
export function loadWslMappedDriveAnswers(userDataPath: string): { saved: () => Promise<void> } {
|
||||
const path = wslMappedDriveAnswersPath(userDataPath)
|
||||
try {
|
||||
const raw = readNodeFileSyncWithinLimit(path, MAX_FILE_BYTES).buffer.toString('utf8')
|
||||
const parsed = AnswersSchema.safeParse(JSON.parse(raw))
|
||||
if (parsed.success) {
|
||||
seedWslMappedDriveAnswers(parsed.data.answers)
|
||||
}
|
||||
} catch {
|
||||
// No answers saved yet, or unreadable: unknown letters stay unknown.
|
||||
}
|
||||
let writing: Promise<void> = Promise.resolve()
|
||||
let pending: WslMappedDriveAnswer[] | null = null
|
||||
setWslMappedDriveAnswerSink((answers) => {
|
||||
// Writes run one at a time; a burst of answers saves only the newest set.
|
||||
const queued = pending !== null
|
||||
pending = answers
|
||||
if (queued) {
|
||||
return
|
||||
}
|
||||
writing = writing
|
||||
.then(async () => {
|
||||
const latest = pending ?? []
|
||||
pending = null
|
||||
const body = JSON.stringify({ version: 1, answers: latest })
|
||||
await writeFileDurable(durableWriteTempPath(path), path, body, 0o600)
|
||||
})
|
||||
.catch((error: unknown) => {
|
||||
console.warn('[wsl] Could not save mapped-drive answers:', error)
|
||||
})
|
||||
})
|
||||
return { saved: () => writing }
|
||||
}
|
||||
@@ -225,4 +225,31 @@ describe('fresh reads and last-known answers', () => {
|
||||
)
|
||||
expect(wslMappedDriveLastKnownShare('w')).toEqual({ share: '\\\\wsl.localhost\\Ubuntu' })
|
||||
})
|
||||
|
||||
it('remembers a drive that fails to resolve as mapping nowhere', async () => {
|
||||
const missing = async (): Promise<string> => {
|
||||
throw new Error('ENOENT')
|
||||
}
|
||||
await classifyWslMappedDrive('E', deps(missing))
|
||||
expect(wslMappedDriveLastKnownShare('E')).toEqual({ share: null })
|
||||
await readWslMappedDriveShareNow('U', deps(missing))
|
||||
expect(wslMappedDriveLastKnownShare('U')).toEqual({ share: null })
|
||||
})
|
||||
|
||||
it('classifies a letter again once its answer is a minute old, so a remap is seen', async () => {
|
||||
let now = 0
|
||||
const realpathRoot = vi
|
||||
.fn<WslMappedDriveShareDeps['realpathRoot']>()
|
||||
.mockResolvedValueOnce('Z:\\')
|
||||
.mockResolvedValueOnce('\\\\wsl.localhost\\Ubuntu\\')
|
||||
const clock = deps(realpathRoot, { now: () => now })
|
||||
await expect(classifyWslMappedDrive('Z', clock)).resolves.toEqual({ share: null })
|
||||
now = 30_000
|
||||
await expect(classifyWslMappedDrive('Z', clock)).resolves.toEqual({ share: null })
|
||||
now = 61_000
|
||||
await expect(classifyWslMappedDrive('Z', clock)).resolves.toEqual({
|
||||
share: '\\\\wsl.localhost\\Ubuntu'
|
||||
})
|
||||
expect(realpathRoot).toHaveBeenCalledTimes(2)
|
||||
})
|
||||
})
|
||||
|
||||
@@ -24,10 +24,12 @@ type CacheEntry = { settledAt: number | null; lookup: Promise<string | null> }
|
||||
|
||||
const cache = new Map<string, CacheEntry>()
|
||||
// Each letter's last settled answer from either lookup; background paths read only this.
|
||||
const lastKnown = new Map<string, string | null>()
|
||||
const lastKnown = new Map<string, { share: string | null; at: number }>()
|
||||
|
||||
const defaultDeps: WslMappedDriveShareDeps = {
|
||||
platform: process.platform,
|
||||
get platform() {
|
||||
return process.platform
|
||||
},
|
||||
// The native call asks Windows for the final path; the JS one keeps the drive letter.
|
||||
realpathRoot: (root) =>
|
||||
new Promise((resolve, reject) =>
|
||||
@@ -59,10 +61,11 @@ function startDriveLookup(key: string, deps: WslMappedDriveShareDeps): CacheEntr
|
||||
entry.lookup = deps.realpathRoot(`${key}:\\`).then(
|
||||
(real) => {
|
||||
entry.settledAt = deps.now()
|
||||
return remember(key, real)
|
||||
return remember(key, real, deps.now())
|
||||
},
|
||||
() => {
|
||||
// A failed lookup is asked again by the next add.
|
||||
// Maps nowhere for now (no such drive, a disconnected share); the next add asks again.
|
||||
remember(key, null, deps.now())
|
||||
if (cache.get(key) === entry) {
|
||||
cache.delete(key)
|
||||
}
|
||||
@@ -103,12 +106,39 @@ export async function resolveWslMappedDrivePath(
|
||||
/** What a drive letter maps to right now; `unverifiable` when Windows didn't answer in time. */
|
||||
export type WslMappedDriveRead = { share: string | null } | 'unverifiable'
|
||||
|
||||
function remember(key: string, real: string): string | null {
|
||||
const share = parseWslUncPath(real) ? real.replace(/[\\/]+$/, '') : null
|
||||
lastKnown.set(key, share)
|
||||
function remember(key: string, real: string | null, at: number): string | null {
|
||||
const share = real && parseWslUncPath(real) ? real.replace(/[\\/]+$/, '') : null
|
||||
lastKnown.set(key, { share, at })
|
||||
answerSink?.(wslMappedDriveAnswers())
|
||||
return share
|
||||
}
|
||||
|
||||
/** A letter's settled answer: the share it maps to (null: nowhere), and when it was read. */
|
||||
export type WslMappedDriveAnswer = { letter: string; share: string | null; at: number }
|
||||
|
||||
// Told every settled answer, so a restart knows a drive without reading it.
|
||||
let answerSink: ((answers: WslMappedDriveAnswer[]) => void) | null = null
|
||||
|
||||
export function setWslMappedDriveAnswerSink(
|
||||
sink: ((answers: WslMappedDriveAnswer[]) => void) | null
|
||||
): void {
|
||||
answerSink = sink
|
||||
}
|
||||
|
||||
export function wslMappedDriveAnswers(): WslMappedDriveAnswer[] {
|
||||
return [...lastKnown].map(([letter, known]) => ({ letter, ...known }))
|
||||
}
|
||||
|
||||
/** Seeds answers read from disk; one already settled in this run is newer and wins. */
|
||||
export function seedWslMappedDriveAnswers(answers: readonly WslMappedDriveAnswer[]): void {
|
||||
for (const { letter, share, at } of answers) {
|
||||
const key = letter.toUpperCase()
|
||||
if (!lastKnown.has(key)) {
|
||||
lastKnown.set(key, { share, at })
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
type FreshLookup = { serial: number; settled: Promise<{ share: string | null }> }
|
||||
// Serials order fresh lookups, so a request can tell one started after it from an older one.
|
||||
let freshSerial = 0
|
||||
@@ -118,9 +148,9 @@ function startFreshLookup(key: string, deps: WslMappedDriveShareDeps): FreshLook
|
||||
const entry: FreshLookup = {
|
||||
serial: ++freshSerial,
|
||||
settled: deps.realpathRoot(`${key}:\\`).then(
|
||||
(real) => ({ share: remember(key, real) }),
|
||||
(real) => ({ share: remember(key, real, deps.now()) }),
|
||||
// No such drive, or not one Windows can resolve: nothing is mapped there.
|
||||
() => ({ share: null })
|
||||
() => ({ share: remember(key, null, deps.now()) })
|
||||
)
|
||||
}
|
||||
freshLookups.set(key, entry)
|
||||
@@ -171,10 +201,17 @@ export async function readWslMappedDriveShareNow(
|
||||
return Promise.race([answer, timeout]).finally(() => clearTimeout(timer))
|
||||
}
|
||||
|
||||
/** The letter's last answer, never read here; null before any lookup of it settled. */
|
||||
export function wslMappedDriveLastKnownShare(letter: string): { share: string | null } | null {
|
||||
const key = letter.toUpperCase()
|
||||
return lastKnown.has(key) ? { share: lastKnown.get(key) ?? null } : null
|
||||
/**
|
||||
* The letter's last answer, never read here; null before any lookup of it settled, or when the
|
||||
* answer is older than `maxAgeMs`. Background readers take any age: they never read a drive.
|
||||
*/
|
||||
export function wslMappedDriveLastKnownShare(
|
||||
letter: string,
|
||||
maxAgeMs = Number.POSITIVE_INFINITY,
|
||||
now: number = Date.now()
|
||||
): { share: string | null } | null {
|
||||
const known = lastKnown.get(letter.toUpperCase())
|
||||
return known && now - known.at < maxAgeMs ? { share: known.share } : null
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -188,12 +225,13 @@ export async function classifyWslMappedDrive(
|
||||
if (deps.platform !== 'win32' || !/^[A-Za-z]$/.test(letter)) {
|
||||
return { share: null }
|
||||
}
|
||||
const known = wslMappedDriveLastKnownShare(letter)
|
||||
// A minute, as the cache: a remap after that is classified again.
|
||||
const known = wslMappedDriveLastKnownShare(letter, CACHE_TTL_MS, deps.now())
|
||||
if (known) {
|
||||
return known
|
||||
}
|
||||
await resolveDriveShare(letter, deps)
|
||||
return wslMappedDriveLastKnownShare(letter)
|
||||
return wslMappedDriveLastKnownShare(letter, CACHE_TTL_MS, deps.now())
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -216,5 +254,6 @@ export function wslMappedDriveMatches(
|
||||
export function clearWslMappedDriveShareCacheForTests(): void {
|
||||
cache.clear()
|
||||
lastKnown.clear()
|
||||
answerSink = null
|
||||
freshLookups.clear()
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user