Skip to content

A full-featured download manager.

23.7 KB
Raw Blame
import { type ChildProcessWithoutNullStreams, spawn } from 'node:child_process'
import path from 'node:path'
import { getLogger } from '@core/logger'

export type FinalizeFsErrorCode =
  | 'unsupported'
  | 'rename_unsupported'
  | 'target_exists'
  | 'not_found'
  | 'invalid_path'
  | 'invalid_handle'
  | 'invalid_request'
  | 'permission_denied'
  | 'cross_device'
  | 'symlink_rejected'
  | 'io_error'

export interface FinalizeRenameResult {
  directorySyncMode: 'directory_flushed' | 'remote_acknowledged'
}

export class FinalizeFsError extends Error {
  constructor(
    readonly code: FinalizeFsErrorCode,
    message: string,
    readonly details?: {
      operation?: string
      osError?: number
      ntStatus?: string
      stage?: string
      mutation?: 'not_attempted' | 'applied' | 'unknown'
      attempts?: number
    }
  ) {
    super(message)
    this.name = 'FinalizeFsError'
  }
}

export interface FinalizeFsCapabilities {
  platform: string
  renameNoReplace: boolean
  heldRoots: boolean
  directorySync: boolean
  heldArtifacts: boolean
  /** Held regular-file handles exclude writers, including writable mappings. */
  heldFileWriteExclusion?: boolean
  syncedRenameGuard?: boolean
  reservedExfatRename?: boolean
  tokenExfatReservation?: boolean
}

interface WireResponse {
  request_id?: number | null
  status: 'ok' | 'error'
  handle?: number
  code?: FinalizeFsErrorCode
  message?: string
  operation?: string
  os_error?: number
  nt_status?: string
  stage?: string
  mutation?: 'not_attempted' | 'applied' | 'unknown'
  attempts?: number
  directory_sync_mode?: 'directory_flushed' | 'remote_acknowledged'
  sanitized_name?: string
  platform?: string
  rename_no_replace?: boolean
  held_roots?: boolean
  directory_sync?: boolean
  held_artifacts?: boolean
  held_file_write_exclusion?: boolean
  synced_rename_guard?: boolean
  reserved_exfat_rename?: boolean
  token_exfat_reservation?: boolean
  volume_id?: string
  platform_file_id?: string
}

interface PendingRequest {
  resolve: (value: WireResponse) => void
  reject: (error: Error) => void
  timeout?: NodeJS.Timeout
}

export interface NativeFinalizeFilesystemAdapterOptions {
  requestTimeoutMs?: number
}

export interface FinalizeRootHandle {
  readonly identity?: string
  readonly id: number
}

export interface FinalizeArtifactHandle {
  readonly id: number
}

export interface FinalizeReservation {
  handle: FinalizeArtifactHandle
  platformFileId: string
}

export interface FinalizeReservationOwnership {
  token: string
  volumeId: string
}

export interface FinalizeFilesystemAdapter {
  exfatVolumeIdentity?(root: FinalizeRootHandle): Promise<string | null>
  capabilities(): Promise<FinalizeFsCapabilities>
  reserveExfatTarget?(
    artifact: FinalizeArtifactHandle,
    targetRoot: FinalizeRootHandle,
    targetRelative: string,
    expectedIdentity?: string,
    ownership?: FinalizeReservationOwnership
  ): Promise<FinalizeReservation>
  renameOpenedReserved?(
    artifact: FinalizeArtifactHandle,
    reservation: FinalizeArtifactHandle
  ): Promise<FinalizeRenameResult & { platformFileId: string }>
  /** Map a final-name candidate onto the shared cross-platform domain. */
  sanitizeName?(name: string): Promise<string>
  openRoot(
    rootPath: string,
    expectedIdentity?: string
  ): Promise<FinalizeRootHandle>
  openArtifact(
    root: FinalizeRootHandle,
    relativePath: string,
    intent?: 'rename'
  ): Promise<FinalizeArtifactHandle>
  openRenameGuard?(
    root: FinalizeRootHandle,
    name: string
  ): Promise<{ handle: FinalizeArtifactHandle; platformFileId: string } | null>
  openRemoval?(
    root: FinalizeRootHandle,
    relativePath: string,
    expectedIdentity: string
  ): Promise<FinalizeArtifactHandle>
  renameOpenedNoReplace(
    artifact: FinalizeArtifactHandle,
    targetRoot: FinalizeRootHandle,
    targetRelative: string
  ): Promise<FinalizeRenameResult | undefined>
  linkOpenedNoReplace(
    artifact: FinalizeArtifactHandle,
    targetRoot: FinalizeRootHandle,
    targetRelative: string
  ): Promise<void>
  isolateOpened(
    artifact: FinalizeArtifactHandle,
    targetRoot: FinalizeRootHandle,
    targetRelative: string,
    expectedRootIdentity: string
  ): Promise<void>
  copyOpened(
    artifact: FinalizeArtifactHandle,
    targetRoot: FinalizeRootHandle,
    targetRelative: string
  ): Promise<void>
  renameNoReplace(
    sourceRoot: FinalizeRootHandle,
    sourceRelative: string,
    targetRoot: FinalizeRootHandle,
    targetRelative: string
  ): Promise<FinalizeRenameResult | undefined>
  removeOpened(
    artifact: FinalizeArtifactHandle,
    quarantineRelative: string,
    resumeIsolated: boolean,
    survivor?: FinalizeArtifactHandle
  ): Promise<void>
  syncRoot(root: FinalizeRootHandle): Promise<void>
  close(root: FinalizeRootHandle | FinalizeArtifactHandle): Promise<void>
  dispose(): Promise<void>
}

export class NativeFinalizeFilesystemAdapter
  implements FinalizeFilesystemAdapter
{
  private child!: ChildProcessWithoutNullStreams
  private generation = 0
  private disposed = false
  private requestTail: Promise<unknown> = Promise.resolve()
  private readonly handleGenerations = new WeakMap<object, number>()
  private nextRequestId = 1
  private incoming = Buffer.alloc(0)
  private readonly pending = new Map<number, PendingRequest>()
  private readonly requestTimeoutMs: number
  private deadError: Error | null = null
  private remoteDurabilityReported = false

  constructor(
    private readonly binaryPath: string,
    options: NativeFinalizeFilesystemAdapterOptions = {}
  ) {
    this.requestTimeoutMs = options.requestTimeoutMs ?? 30_000
    if (
      !Number.isSafeInteger(this.requestTimeoutMs) ||
      this.requestTimeoutMs <= 0
    )
      throw new Error('finalize sidecar request timeout must be positive')
    this.startChild()
  }

  private startChild(): void {
    this.generation += 1
    this.deadError = null
    this.incoming = Buffer.alloc(0)
    const child = spawn(this.binaryPath, [], {
      stdio: ['pipe', 'pipe', 'pipe'],
    })
    this.child = child
    const fail = (error: Error) => {
      if (this.child === child) this.markDead(error)
    }
    child.stdout.on('data', (chunk: Buffer) => {
      if (this.child === child) this.receive(chunk)
    })
    child.stderr.resume()
    child.stdin.once('error', fail)
    child.once('error', fail)
    child.once('exit', (code) =>
      fail(new Error(`finalize filesystem sidecar exited: ${code}`))
    )
  }

  private heldHandle(
    id: number,
    generation: number,
    identity?: string
  ): FinalizeRootHandle {
    const handle = Object.freeze({ id, ...(identity ? { identity } : {}) })
    this.handleGenerations.set(handle, generation)
    return handle
  }

  private nativeId(
    handle: FinalizeRootHandle | FinalizeArtifactHandle
  ): number {
    if (this.deadError) throw this.deadError
    if (this.handleGenerations.get(handle) !== this.generation) {
      throw new FinalizeFsError(
        'invalid_handle',
        'finalize handle belongs to an earlier sidecar process'
      )
    }
    return handle.id
  }

  async capabilities(): Promise<FinalizeFsCapabilities> {
    // A new operation may recover the transport. Old operations retain their
    // failed promises/handle generations and cannot mutate through the child.
    if (this.deadError && !this.disposed) this.startChild()
    const response = await this.request({ op: 'capabilities' }, false)
    return {
      platform: response.platform ?? 'unknown',
      renameNoReplace: response.rename_no_replace === true,
      heldRoots: response.held_roots === true,
      directorySync: response.directory_sync === true,
      heldArtifacts: response.held_artifacts === true,
      heldFileWriteExclusion: response.held_file_write_exclusion === true,
      syncedRenameGuard: response.synced_rename_guard === true,
      reservedExfatRename: response.reserved_exfat_rename === true,
      tokenExfatReservation: response.token_exfat_reservation === true,
    }
  }

  async createPrivateRoot(
    parent: FinalizeRootHandle,
    name: string
  ): Promise<FinalizeRootHandle> {
    const generation = this.generation
    const result = await this.request({
      op: 'create_private_root',
      root: this.nativeId(parent),
      name,
    })
    if (result.handle === undefined || !result.platform_file_id)
      throw new Error('sidecar omitted private root identity')
    return this.heldHandle(result.handle, generation, result.platform_file_id)
  }

  async removePrivateRoot(
    parent: FinalizeRootHandle,
    name: string,
    root: FinalizeRootHandle
  ): Promise<void> {
    await this.request({
      op: 'remove_private_root',
      parent: this.nativeId(parent),
      name,
      root: this.nativeId(root),
    })
  }

  async openSelectedFile(
    root: FinalizeRootHandle,
    relative: string
  ): Promise<FinalizeArtifactHandle> {
    const generation = this.generation
    const result = await this.request({
      op: 'open_selected_file',
      root: this.nativeId(root),
      relative,
    })
    if (result.handle === undefined)
      throw new Error('sidecar omitted selected file handle')
    return this.heldHandle(result.handle, generation)
  }

  async copySelectedFile(
    file: FinalizeArtifactHandle,
    target: FinalizeRootHandle,
    relative: string
  ): Promise<void> {
    await this.request({
      op: 'copy_selected_file',
      artifact: this.nativeId(file),
      target_root: this.nativeId(target),
      target_relative: relative,
    })
  }

  /** Dedicated operation sidecars can be killed without interrupting downloads. */
  async abort(): Promise<void> {
    this.disposed = true
    const child = this.child
    if (child.exitCode !== null || child.signalCode !== null) return
    await new Promise<void>((resolve, reject) => {
      const kill = setTimeout(() => child.kill('SIGKILL'), 5000)
      const stuck = setTimeout(() => {
        detach()
        reject(new Error('operation filesystem process did not exit'))
      }, 10000)
      const detach = () => {
        clearTimeout(kill)
        clearTimeout(stuck)
      }
      child.once('close', () => {
        detach()
        resolve()
      })
      this.markDead(new Error('operation filesystem work cancelled'))
      child.kill('SIGTERM')
    })
  }

  async exfatVolumeIdentity(root: FinalizeRootHandle): Promise<string | null> {
    const response = await this.request({
      op: 'exfat_volume_identity',
      root: this.nativeId(root),
    })
    if (response.volume_id === undefined) return null
    if (!/^[a-f0-9]{32}$/.test(response.volume_id))
      throw new Error('invalid volume identity')
    return response.volume_id
  }

  async reserveExfatTarget(
    artifact: FinalizeArtifactHandle,
    targetRoot: FinalizeRootHandle,
    targetRelative: string,
    expectedIdentity?: string,
    ownership?: FinalizeReservationOwnership
  ): Promise<FinalizeReservation> {
    const generation = this.generation
    const response = await this.request({
      op: 'reserve_exfat_target',
      artifact: this.nativeId(artifact),
      target_root: this.nativeId(targetRoot),
      target_relative: targetRelative,
      expected_identity: expectedIdentity,
      token: ownership?.token,
      volume_id: ownership?.volumeId,
    })
    if (response.handle === undefined || !response.platform_file_id)
      throw new Error('sidecar omitted reservation identity')
    return {
      handle: this.heldHandle(response.handle, generation),
      platformFileId: response.platform_file_id,
    }
  }

  async renameOpenedReserved(
    artifact: FinalizeArtifactHandle,
    reservation: FinalizeArtifactHandle
  ): Promise<FinalizeRenameResult & { platformFileId: string }> {
    const response = await this.request({
      op: 'rename_opened_reserved',
      artifact: this.nativeId(artifact),
      reservation: this.nativeId(reservation),
    })
    if (
      !response.platform_file_id ||
      response.directory_sync_mode !== 'directory_flushed'
    )
      throw new Error('sidecar omitted reserved publication result')
    return {
      platformFileId: response.platform_file_id,
      directorySyncMode: response.directory_sync_mode,
    }
  }

  async openRenameGuard(root: FinalizeRootHandle, name: string) {
    const generation = this.generation
    const result = await this.request({
      op: 'open_rename_guard',
      root: this.nativeId(root),
      relative: name,
    })
    if (result.handle === undefined) return null
    const handle = this.heldHandle(result.handle, generation)
    if (!result.platform_file_id) {
      await this.close(handle)
      throw new Error('rename guard omitted its file ID')
    }
    return { handle, platformFileId: result.platform_file_id }
  }

  async openArtifact(
    root: FinalizeRootHandle,
    relativePath: string,
    intent?: 'rename'
  ): Promise<FinalizeArtifactHandle> {
    const generation = this.generation
    const response = await this.request({
      op: 'open_artifact',
      rename_only: intent === 'rename',
      root: this.nativeId(root),
      relative: relativePath,
    })
    if (response.handle === undefined) {
      throw new Error('sidecar omitted artifact handle')
    }
    return this.heldHandle(response.handle, generation)
  }

  async openRemoval(
    root: FinalizeRootHandle,
    relativePath: string,
    expectedIdentity: string
  ): Promise<FinalizeArtifactHandle> {
    const generation = this.generation
    const response = await this.request({
      op: 'open_removal',
      root: this.nativeId(root),
      relative: relativePath,
      expected_identity: expectedIdentity,
    })
    if (response.handle === undefined)
      throw new Error('sidecar omitted removal handle')
    return this.heldHandle(response.handle, generation)
  }

  async renameOpenedNoReplace(
    artifact: FinalizeArtifactHandle,
    targetRoot: FinalizeRootHandle,
    targetRelative: string
  ): Promise<FinalizeRenameResult | undefined> {
    const response = await this.request({
      op: 'rename_opened_no_replace',
      artifact: this.nativeId(artifact),
      target_root: this.nativeId(targetRoot),
      target_relative: targetRelative,
    })
    if (
      response.directory_sync_mode === 'directory_flushed' ||
      response.directory_sync_mode === 'remote_acknowledged'
    ) {
      return { directorySyncMode: response.directory_sync_mode }
    }
  }

  async linkOpenedNoReplace(
    artifact: FinalizeArtifactHandle,
    targetRoot: FinalizeRootHandle,
    targetRelative: string
  ): Promise<void> {
    await this.request({
      op: 'link_opened_no_replace',
      artifact: this.nativeId(artifact),
      target_root: this.nativeId(targetRoot),
      target_relative: targetRelative,
    })
  }

  async isolateOpened(
    artifact: FinalizeArtifactHandle,
    targetRoot: FinalizeRootHandle,
    targetRelative: string,
    expectedRootIdentity: string
  ): Promise<void> {
    await this.request({
      op: 'isolate_opened',
      expected_root_identity: expectedRootIdentity,
      artifact: this.nativeId(artifact),
      target_root: this.nativeId(targetRoot),
      target_relative: targetRelative,
    })
  }

  async copyOpened(
    artifact: FinalizeArtifactHandle,
    targetRoot: FinalizeRootHandle,
    targetRelative: string
  ): Promise<void> {
    await this.request({
      op: 'copy_opened',
      artifact: this.nativeId(artifact),
      target_root: this.nativeId(targetRoot),
      target_relative: targetRelative,
    })
  }

  async sanitizeName(name: string): Promise<string> {
    const response = await this.request({ op: 'sanitize_name', name })
    if (response.sanitized_name === undefined) {
      throw new Error('sidecar omitted sanitized name')
    }
    return response.sanitized_name
  }

  async openRoot(
    rootPath: string,
    expectedIdentity?: string,
    readOnly = false
  ): Promise<FinalizeRootHandle> {
    if (!path.isAbsolute(rootPath)) {
      throw new FinalizeFsError('invalid_path', 'root path must be absolute')
    }
    const generation = this.generation
    const response = await this.request({
      op: 'open_root',
      read_only: readOnly,
      path: normalizeSidecarRootPath(rootPath),
      expected_identity: expectedIdentity,
    })
    if (response.handle === undefined)
      throw new Error('sidecar omitted root handle')
    return this.heldHandle(
      response.handle,
      generation,
      response.platform_file_id
    )
  }

  async renameNoReplace(
    sourceRoot: FinalizeRootHandle,
    sourceRelative: string,
    targetRoot: FinalizeRootHandle,
    targetRelative: string
  ): Promise<FinalizeRenameResult | undefined> {
    const response = await this.request({
      op: 'rename_no_replace',
      source_root: this.nativeId(sourceRoot),
      source_relative: sourceRelative,
      target_root: this.nativeId(targetRoot),
      target_relative: targetRelative,
    })
    if (
      response.directory_sync_mode === 'directory_flushed' ||
      response.directory_sync_mode === 'remote_acknowledged'
    ) {
      return { directorySyncMode: response.directory_sync_mode }
    }
  }

  async removeOpened(
    artifact: FinalizeArtifactHandle,
    quarantineRelative: string,
    resumeIsolated: boolean,
    survivor?: FinalizeArtifactHandle
  ): Promise<void> {
    await this.request({
      op: survivor ? 'remove_opened_preserving' : 'remove_opened',
      ...(survivor ? { survivor: this.nativeId(survivor) } : {}),
      artifact: this.nativeId(artifact),
      quarantine_relative: quarantineRelative,
      resume_isolated: resumeIsolated,
    })
  }

  async syncRoot(root: FinalizeRootHandle): Promise<void> {
    await this.request({
      op: 'sync_root',
      root: this.nativeId(root),
    })
  }

  async close(
    root: FinalizeRootHandle | FinalizeArtifactHandle
  ): Promise<void> {
    await this.request({ op: 'close', handle: this.nativeId(root) })
    this.handleGenerations.delete(root)
  }

  async dispose(): Promise<void> {
    this.disposed = true
    if (this.deadError) {
      if (this.child.exitCode === null && this.child.signalCode === null)
        this.child.kill()
      return
    }
    if (this.child.exitCode !== null || this.child.signalCode !== null) return
    this.child.stdin.end()
    await new Promise<void>((resolve) => {
      const timeout = setTimeout(() => {
        this.child.kill()
        resolve()
      }, 5_000)
      timeout.unref()
      this.child.once('exit', () => {
        clearTimeout(timeout)
        resolve()
      })
    })
  }

  private request(
    body: Record<string, unknown>,
    includeRequestId = true
  ): Promise<WireResponse> {
    const generation = this.generation
    const result = this.requestTail.then(() => {
      if (generation !== this.generation)
        throw new FinalizeFsError(
          'invalid_handle',
          'finalize operation lost its sidecar process'
        )
      return this.sendRequest(body, includeRequestId)
    })
    this.requestTail = result.catch(() => undefined)
    return result
  }

  private async sendRequest(
    body: Record<string, unknown>,
    includeRequestId = true
  ): Promise<WireResponse> {
    if (this.disposed)
      throw new Error('finalize filesystem adapter is disposed')
    if (this.deadError) throw this.deadError
    const requestId = this.nextRequestId++
    const payload = Buffer.from(
      JSON.stringify(
        includeRequestId ? { ...body, request_id: requestId } : body
      )
    )
    if (payload.length > 64 * 1024)
      throw new Error('finalize sidecar request too large')
    const frame = Buffer.allocUnsafe(payload.length + 4)
    frame.writeUInt32LE(payload.length)
    payload.copy(frame, 4)
    const response = new Promise<WireResponse>((resolve, reject) => {
      const key = includeRequestId ? requestId : 0
      // Content hashing, copies and filesystem syncs have no fixed deadline.
      // Only the startup handshake is bounded, after earlier I/O has finished.
      const timeout =
        body.op === 'capabilities'
          ? setTimeout(() => {
              this.markDead(
                new Error(
                  `finalize filesystem sidecar request timed out after ${this.requestTimeoutMs}ms`
                )
              )
            }, this.requestTimeoutMs)
          : undefined
      timeout?.unref()
      this.pending.set(key, { resolve, reject, timeout })
    })
    const child = this.child
    child.stdin.write(frame, (error) => {
      if (error && this.child === child) this.markDead(error)
    })
    const result = await response.catch((cause: unknown) => {
      if (
        body.op === 'rename_opened_no_replace' ||
        body.op === 'rename_no_replace' ||
        body.op === 'rename_opened_reserved' ||
        body.op === 'reserve_exfat_target'
      ) {
        const error = new FinalizeFsError(
          'io_error',
          'rename response lost; filesystem recovery is required',
          {
            operation: String(body.op),
            stage: 'transport',
            mutation: 'unknown',
          }
        )
        error.cause = cause
        throw error
      }
      throw cause
    })
    if (
      result.directory_sync_mode === 'remote_acknowledged' &&
      !this.remoteDurabilityReported
    ) {
      this.remoteDurabilityReported = true
      getLogger('finalize').warn(
        { durability: result.directory_sync_mode },
        'SMB directory flush is unsupported; namespace durability depends on the remote server'
      )
    }
    if (result.status === 'error') {
      throw new FinalizeFsError(
        result.code ?? 'io_error',
        `${result.operation ?? body.op}: ${result.message ?? 'finalize filesystem operation failed'}`,
        {
          operation: result.operation ?? String(body.op),
          osError: result.os_error,
          ntStatus: result.nt_status,
          stage: result.stage,
          mutation: result.mutation,
          attempts: result.attempts,
        }
      )
    }
    return result
  }

  private receive(chunk: Buffer): void {
    this.incoming = Buffer.concat([this.incoming, chunk])
    while (this.incoming.length >= 4) {
      const length = this.incoming.readUInt32LE(0)
      if (length > 64 * 1024) {
        this.markDead(new Error('finalize sidecar response too large'))
        this.child.kill()
        return
      }
      if (this.incoming.length < length + 4) return
      const payload = this.incoming.subarray(4, length + 4)
      this.incoming = this.incoming.subarray(length + 4)
      let response: WireResponse
      try {
        response = JSON.parse(payload.toString('utf8')) as WireResponse
      } catch (error) {
        this.markDead(error as Error)
        this.child.kill()
        return
      }
      const key = response.request_id ?? 0
      const pending = this.pending.get(key)
      if (!pending) {
        if (
          (response.request_id === undefined || response.request_id === null) &&
          this.pending.size > 0
        ) {
          this.markDead(
            new FinalizeFsError(
              response.code ?? 'io_error',
              response.message ?? 'unattributed finalize sidecar response'
            )
          )
          this.child.kill()
          return
        }
        continue
      }
      this.pending.delete(key)
      clearTimeout(pending.timeout)
      pending.resolve(response)
    }
  }

  private markDead(error: Error): void {
    if (!this.deadError) this.deadError = error
    for (const pending of this.pending.values()) {
      clearTimeout(pending.timeout)
      pending.reject(this.deadError)
    }
    this.pending.clear()
    if (this.child.exitCode === null && this.child.signalCode === null)
      this.child.kill()
  }
}

/**
 * The sidecar's Windows root walker rejects verbatim `\\?\` namespace paths,
 * while user-selected and API-derived roots can carry either spelling.
 * Normalize to the Win32 form before the path crosses the sidecar boundary.
 */
export function normalizeSidecarRootPath(rootPath: string): string {
  if (process.platform !== 'win32') return rootPath
  return rootPath
    .replace(/^\\\\\?\\UNC\\/i, '\\\\')
    .replace(/^\\\\\?\\([a-z]:\\)/i, '$1')
}