Skip to content

A full-featured download manager.

18.7 KB
Raw Blame
import path from 'node:path'
import type {
  InitSegment,
  MediaPart,
  SegmentPlan,
} from '@core/media/segment-plan'
import { segmentFraction } from '@shared/utils/media-progress'

// ---------------------------------------------------------------------------
// Public interface — narrow aria2 client (injected by T15 adapter)
// ---------------------------------------------------------------------------

export interface SegmentAria2 {
  /** Returns the aria2 gid for the queued download. One URL per call; multiple URLs = mirrors. */
  addUri(
    uris: string[],
    opts: {
      dir: string
      out: string
      header?: string[]
      'max-tries'?: number
      'retry-wait'?: number
    }
  ): Promise<string>
  forceRemove(gid: string): Promise<void>
  /** Purge a terminal segment from aria2's stopped result and durable store. */
  removeDownloadResult(gid: string): Promise<void>
  /**
   * Register a single callback to receive completion notifications.
   * Important: onComplete and onError register a SINGLE callback each.
   * A fresh SegmentAria2 instance (or a fan-out adapter) MUST be used per
   * SegmentDownloader instance — sharing one across concurrent runs will
   * overwrite the callbacks. The adapter wiring (bootstrap) is responsible
   * for fan-out and filtering by gid.
   */
  /**
   * In-progress byte counts for a single segment gid, or null when the gid is
   * unknown / the query failed. Used by the poll loop to derive real byte
   * progress from aria2's own view of each segment.
   */
  tellStatus(
    gid: string
  ): Promise<{ completedLength: number; totalLength: number } | null>
  onComplete(cb: (gid: string) => void): void
  /**
   * Register a single callback to receive error notifications.
   * Important: onComplete and onError register a SINGLE callback each.
   * A fresh SegmentAria2 instance (or a fan-out adapter) MUST be used per
   * SegmentDownloader instance — sharing one across concurrent runs will
   * overwrite the callbacks. The adapter wiring (bootstrap) is responsible
   * for fan-out and filtering by gid.
   */
  onError(cb: (gid: string) => void): void
}

/** Byte-accurate progress emitted by {@link SegmentDownloader.run}. */
export interface SegmentProgress {
  /** All planned jobs, including partial contributions from active jobs. */
  fraction: number
  completedParts: number
  totalParts: number
  /**
   * Summed `completedLength` of finished + in-flight segments, in bytes.
   * Finished segments count their full size; in-flight ones count aria2's
   * live `completedLength` from the most recent poll.
   */
  downloadedBytes: number
  /** Full plan size, or zero until every job has a known size. */
  totalBytes: number
}

/** A stable index in the plan's [init?, ...segments] order, across retries. */
export interface SegmentFileProgress {
  index: number
  downloadedBytes: number
  totalBytes: number
  completed: boolean
}

/**
 * Injectable timer seam for the byte-polling loop. Returns a stop function.
 * Production uses `setInterval`; tests inject a manual scheduler to drive
 * polls deterministically without real (or fake) timers.
 */
export type PollScheduler = (cb: () => void | Promise<void>) => () => void

// ---------------------------------------------------------------------------
// Internal types
// ---------------------------------------------------------------------------

interface Job {
  /** Flat sequential index in the job list (0 = init if present, then segments). */
  jobIndex: number
  /** Part type: 'init' | 'segment' */
  kind: 'init' | 'segment'
  /** Original MediaPart or InitSegment. */
  part: InitSegment | MediaPart
  /** Absolute output path inside tmpDir. */
  outPath: string
  /** How many re-add attempts remain after the first failure. */
  retriesLeft: number
  knownSize?: number
}

// ---------------------------------------------------------------------------
// Constants
// ---------------------------------------------------------------------------

const MAX_TRIES = 5
const RETRY_WAIT = 3
/** How many times we re-submit a failed segment ourselves (on top of aria2's MAX_TRIES). */
const MAX_SELF_RETRIES = 3
const PAD = 6 // e.g. "000042.seg"
/** Byte-progress poll cadence — one tellStatus RPC per active gid per tick. */
const DEFAULT_POLL_INTERVAL_MS = 700

/** Default scheduler: a real setInterval, cleared via the returned stop fn. */
const realPollScheduler: PollScheduler = (cb) => {
  const handle = setInterval(() => {
    void cb()
  }, DEFAULT_POLL_INTERVAL_MS)
  return () => clearInterval(handle)
}

// ---------------------------------------------------------------------------
// Helpers
// ---------------------------------------------------------------------------

function padIndex(n: number): string {
  return `${String(n).padStart(PAD, '0')}.seg`
}

function buildHeaders(
  part: InitSegment | MediaPart,
  requestHeaders: Record<string, string>
): string[] {
  const headers: string[] = []
  // Replay caller-provided headers (Referer, Cookie, etc.)
  for (const [name, value] of Object.entries(requestHeaders)) {
    headers.push(`${name}: ${value}`)
  }
  // Range header for byte-range parts
  if (part.byteRange) {
    const { offset, length } = part.byteRange
    headers.push(`Range: bytes=${offset}-${offset + length - 1}`)
  }
  return headers
}

// ---------------------------------------------------------------------------
// SegmentDownloader
// ---------------------------------------------------------------------------

export class SegmentDownloader {
  private readonly aria2: SegmentAria2
  private readonly tmpDir: string
  private readonly concurrency: number

  /** Maps a live gid → its Job record. */
  private readonly activeJobs = new Map<string, Job>()
  /** Set of all gids currently in-flight (submitted but not yet complete/error). */
  private readonly activeGids = new Set<string>()
  /** Terminal gids whose durable result deletion has not settled yet. */
  private readonly settlingGids = new Set<string>()
  /** Async add/terminal-cleanup operations that cancel() must drain. */
  private readonly pendingOperations = new Set<Promise<void>>()

  private rejectRun: ((err: Error) => void) | null = null
  /** Flag to guard against cancel-during-retry race: set when cancel() is called. */
  private cancelled = false

  private readonly pollScheduler: PollScheduler
  /** Stops the active byte-poll loop; null when no run is in flight. */
  private stopPoll: (() => void) | null = null

  constructor(deps: {
    aria2: SegmentAria2
    tmpDir: string
    concurrency?: number
    pollScheduler?: PollScheduler
  }) {
    this.aria2 = deps.aria2
    this.tmpDir = deps.tmpDir
    this.concurrency = deps.concurrency ?? 16
    this.pollScheduler = deps.pollScheduler ?? realPollScheduler
  }

  /** The live aria2 gids of segments currently in flight for this stream. */
  getActiveGids(): string[] {
    return [...this.activeGids]
  }

  /** Count of in-flight segment gids (allocation-free — for progress polling). */
  getActiveGidCount(): number {
    return this.activeGids.size
  }

  /** Stop the byte-poll loop; idempotent, safe on every exit path. */
  private stopPolling(): void {
    if (this.stopPoll) {
      this.stopPoll()
      this.stopPoll = null
    }
  }

  private trackOperation(operation: Promise<void>): void {
    this.pendingOperations.add(operation)
    void operation.finally(() => {
      this.pendingOperations.delete(operation)
    })
  }

  private async purgeResult(gid: string): Promise<void> {
    try {
      await this.aria2.removeDownloadResult(gid)
    } catch (firstError) {
      try {
        // A live/stale classification race can make the first terminal purge
        // fail. forceRemove performs stop + a second durable purge attempt.
        await this.aria2.forceRemove(gid)
      } catch (retryError) {
        throw new AggregateError(
          [firstError, retryError],
          `Failed to purge segment ${gid}`
        )
      }
    }
  }

  // -------------------------------------------------------------------------
  // Public API
  // -------------------------------------------------------------------------

  run(
    plan: SegmentPlan,
    headers: Record<string, string>,
    onProgress: (p: SegmentProgress) => void,
    onFileProgress?: (p: SegmentFileProgress) => void
  ): Promise<{ initPath?: string; partPaths: string[] }> {
    this.cancelled = false
    this.rejectRun = null
    this.activeJobs.clear()
    this.activeGids.clear()
    this.settlingGids.clear()

    // Build a flat ordered job list: [init?, seg0, seg1, ...]
    const jobs: Job[] = []
    let jobIndex = 0

    if (plan.init) {
      jobs.push({
        jobIndex,
        kind: 'init',
        part: plan.init,
        outPath: path.join(this.tmpDir, padIndex(jobIndex)),
        retriesLeft: MAX_SELF_RETRIES,
      })
      jobIndex++
    }

    for (const seg of plan.segments) {
      jobs.push({
        jobIndex,
        kind: 'segment',
        part: seg,
        outPath: path.join(this.tmpDir, padIndex(jobIndex)),
        retriesLeft: MAX_SELF_RETRIES,
      })
      jobIndex++
    }

    const total = jobs.length
    let completed = 0

    const lastSeen = new Map<string, { completed: number; total: number }>()
    let finishedBytes = 0
    let knownBytes = 0
    let knownParts = 0
    const recordSize = (job: Job, size: number) => {
      if (!Number.isFinite(size) || size <= 0) return
      if (job.knownSize === undefined) knownParts++
      knownBytes += size - (job.knownSize ?? 0)
      job.knownSize = size
    }
    for (const job of jobs) recordSize(job, job.part.byteRange?.length ?? 0)
    const safeBytes = (value: number) =>
      Number.isFinite(value) ? Math.max(0, value) : 0
    return new Promise<{ initPath?: string; partPaths: string[] }>(
      (resolve, reject) => {
        if (total === 0) {
          resolve({ initPath: undefined, partPaths: [] })
          return
        }

        this.rejectRun = reject

        const fail = (err: Error) => {
          this.stopPolling()
          this.rejectRun = null
          reject(err)
        }

        const report = () => {
          if (this.cancelled) return
          let activeCompleted = 0
          let partialParts = 0
          // Keep settling jobs here until their contribution is atomically
          // transferred to completed. Work per report is bounded by concurrency.
          for (const ls of lastSeen.values()) {
            activeCompleted += ls.completed
            partialParts += segmentFraction(ls.completed, ls.total, false)
          }
          onProgress({
            fraction:
              completed === total ? 1 : (completed + partialParts) / total,
            completedParts: completed,
            totalParts: total,
            downloadedBytes: finishedBytes + activeCompleted,
            totalBytes: knownParts === total ? knownBytes : 0,
          })
        }

        const buildResult = () => {
          const sorted = jobs.slice().sort((a, b) => a.jobIndex - b.jobIndex)
          let initPath: string | undefined
          const partPaths: string[] = []
          for (const j of sorted) {
            if (j.kind === 'init') initPath = j.outPath
            else partPaths.push(j.outPath)
          }
          return { initPath, partPaths }
        }

        const resolveWhenDone = () => {
          if (completed !== total) return
          this.stopPolling()
          this.rejectRun = null
          report()
          resolve(buildResult())
        }

        // Register callbacks once
        this.aria2.onComplete((gid) => {
          const job = this.activeJobs.get(gid)
          if (!job) return
          this.activeJobs.delete(gid)
          this.activeGids.delete(gid)
          this.settlingGids.add(gid)
          const operation = (async () => {
            const ls = lastSeen.get(gid)
            // A prior poll may have seen an unknown length. Read the final
            // size before removing the engine result, retaining the last poll
            // (or declared byte range) if the terminal query fails.
            const status = ls?.total
              ? null
              : await this.aria2.tellStatus(gid).catch(() => null)
            const size = safeBytes(
              status?.totalLength ||
                ls?.total ||
                job.knownSize ||
                status?.completedLength ||
                ls?.completed ||
                0
            )
            recordSize(job, size)
            await this.purgeResult(gid)
            this.settlingGids.delete(gid)
            if (this.cancelled) return
            lastSeen.delete(gid)
            finishedBytes += size
            completed++
            onFileProgress?.({
              index: job.jobIndex,
              downloadedBytes: size,
              totalBytes: size,
              completed: true,
            })
            report()
            releaseSlot()
            resolveWhenDone()
          })().catch((err: Error) => fail(err))
          this.trackOperation(operation)
        })

        this.aria2.onError((gid) => {
          const job = this.activeJobs.get(gid)
          if (!job) return
          this.activeJobs.delete(gid)
          this.activeGids.delete(gid)
          this.settlingGids.add(gid)
          // A retry restarts this segment from zero; drop its cached bytes so
          // the active sum reflects only live in-flight segments.
          lastSeen.delete(gid)
          onFileProgress?.({
            index: job.jobIndex,
            downloadedBytes: 0,
            totalBytes: job.knownSize ?? 0,
            completed: false,
          })
          report()
          const operation = (async () => {
            await this.purgeResult(gid)
            this.settlingGids.delete(gid)
            running--

            if (this.cancelled) return
            if (job.retriesLeft > 0) {
              // Re-submit only after the failed durable row is gone. This also
              // keeps the semaphore count stable across retries.
              job.retriesLeft--
              submitJob(job)
            } else {
              fail(
                new Error(`Segment download failed permanently: ${job.outPath}`)
              )
            }
          })().catch((err: Error) => fail(err))
          this.trackOperation(operation)
        })

        // ── Byte poll ────────────────────────────────────────────────────
        // Refresh the live-byte cache for every in-flight gid, then report.
        // Never throws: tellStatus null-guards and the tick is fire-and-forget.
        let polling = false
        const pollOnce = async () => {
          if (polling || this.cancelled) return
          polling = true
          try {
            const gids = [...this.activeGids]
            if (gids.length > 0) {
              const results = await Promise.all(
                gids.map((g) =>
                  this.aria2.tellStatus(g).then(
                    (s) => ({ gid: g, s }),
                    () => ({ gid: g, s: null })
                  )
                )
              )
              for (const { gid, s } of results) {
                // A gid that completed/errored during the await is no longer
                // active — skip it so we don't resurrect a stale cache entry.
                if (!this.activeGids.has(gid)) continue
                if (s) {
                  const job = this.activeJobs.get(gid)
                  if (!job || this.cancelled) continue
                  recordSize(job, s.totalLength)
                  const totalBytes = job.knownSize ?? 0
                  const downloadedBytes =
                    totalBytes > 0
                      ? Math.min(totalBytes, safeBytes(s.completedLength))
                      : safeBytes(s.completedLength)
                  lastSeen.set(gid, {
                    completed: downloadedBytes,
                    total: totalBytes,
                  })
                  onFileProgress?.({
                    index: job.jobIndex,
                    downloadedBytes,
                    totalBytes,
                    completed: false,
                  })
                }
              }
            }
            report()
          } finally {
            polling = false
          }
        }

        // Semaphore implementation
        let running = 0
        let nextJob = 0

        const submitJob = (job: Job) => {
          if (this.cancelled) {
            return
          }
          running++
          const partHeaders = buildHeaders(job.part, headers)
          const operation = (async () => {
            let gid: string
            try {
              gid = await this.aria2.addUri([job.part.url], {
                dir: this.tmpDir,
                out: path.basename(job.outPath),
                header: partHeaders.length > 0 ? partHeaders : undefined,
                'max-tries': MAX_TRIES,
                'retry-wait': RETRY_WAIT,
              })
            } catch (err) {
              running--
              if (!this.cancelled) fail(err as Error)
              return
            }

            if (this.cancelled) {
              running--
              await this.aria2.forceRemove(gid)
              return
            }
            this.activeJobs.set(gid, job)
            this.activeGids.add(gid)
          })().catch((err: Error) => {
            // At this point addUri succeeded and cancellation owns the gid.
            // Keep run() cancelled; cancel() drains this rejected operation and
            // startup reconciliation retries any rare durable-delete failure.
            if (!this.cancelled) fail(err)
          })
          this.trackOperation(operation)
        }

        const releaseSlot = () => {
          running--
          drain()
        }

        const drain = () => {
          while (running < this.concurrency && nextJob < jobs.length) {
            const next = jobs[nextJob++]
            if (next !== undefined) submitJob(next)
          }
        }

        // Start the byte poll and kick off the initial batch.
        this.stopPoll = this.pollScheduler(pollOnce)
        drain()
      }
    )
  }

  async cancel(): Promise<void> {
    this.cancelled = true
    this.stopPolling()
    const gids = [...new Set([...this.activeGids, ...this.settlingGids])]
    if (this.rejectRun) {
      this.rejectRun(new Error('SegmentDownloader: cancelled'))
      this.rejectRun = null
    }
    await Promise.allSettled(gids.map((g) => this.aria2.forceRemove(g)))
    // addUri can resolve after cancellation and return a gid that was not in
    // the snapshot above. Its tracked continuation force-removes that gid;
    // drain it before cancellation is considered complete.
    while (this.pendingOperations.size > 0) {
      await Promise.allSettled([...this.pendingOperations])
    }
    this.activeGids.clear()
    this.settlingGids.clear()
    this.activeJobs.clear()
  }
}