All files / server/services/examples source-provider.ts

95.83% Statements 46/48
85.1% Branches 40/47
100% Functions 8/8
100% Lines 43/43

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157                                                                                                  20x 20x 20x 20x 20x   20x                 89x 89x 89x 89x 85x 4x 4x     81x 81x 78x 67x 67x 34x 34x 34x 34x 27x 27x 27x                 67x                   48x   43x     48x             48x 41x                           8x 8x 8x 4x   4x               28x 28x 27x 26x         10x 10x 10x      
import type { ExamplesRef, FullCommitSha, RepositorySlug } from "@shared/examples";
import { config } from "../../config";
import { ExamplesError, asExamplesError } from "./examples-error";
import {
  ExamplesCache,
  type RevisionCacheEntry,
  type SourceCacheEntry,
  toRevisionCacheKey,
  toSourceCacheKey,
} from "./examples-cache";
import { ExamplesLoadController } from "./examples-load-controller";
import type { LoadedRevisionSnapshot } from "./http-provider";
import type { SourcePriority } from "./github-api-budget";
 
export interface RequestContext {
  identity: string;
  requestId: string;
  signal?: AbortSignal;
  /** Operator default or browser override; overrides leave a GitHub quota reserve to the default. */
  sourcePriority?: SourcePriority;
}
 
export interface RevisionResolver {
  resolve(
    repository: RepositorySlug,
    ref: ExamplesRef,
    context: RequestContext,
  ): Promise<FullCommitSha>;
}
 
export interface RevisionLoader {
  load(
    repository: RepositorySlug,
    revision: FullCommitSha,
    signal?: AbortSignal,
  ): Promise<LoadedRevisionSnapshot>;
}
 
export interface ResolvedSourceSnapshot {
  revision: FullCommitSha;
  snapshot: RevisionCacheEntry;
  status: "remote" | "cache";
  stale: boolean;
}
 
export class SourceProvider {
  private readonly now: () => number;
 
  constructor(
    private readonly resolver: RevisionResolver,
    private readonly revisionLoader: RevisionLoader,
    private readonly cache: ExamplesCache,
    private readonly loads: ExamplesLoadController,
    private readonly options: { refreshMs?: number; refreshRetryMs?: number; now?: () => number } = {},
  ) {
    this.now = options.now ?? Date.now;
  }
 
  async resolve(
    repository: RepositorySlug,
    ref: ExamplesRef,
    context: RequestContext,
    requireFresh: boolean,
  ): Promise<ResolvedSourceSnapshot> {
    const sourceKey = toSourceCacheKey(repository, ref);
    const existing = this.cache.getSource(sourceKey);
    const now = this.now();
    if (existing && !existing.stale && existing.expiresAt > now) return this.fromEntry(existing);
    if (existing?.stale && existing.nextRetryAt > now) {
      Iif (requireFresh) throw new ExamplesError("SOURCE_UNAVAILABLE", "External examples ref could not be refreshed");
      return this.fromEntry(existing);
    }
 
    try {
      return await this.cache.withSourceSingleflight(sourceKey, (signal) =>
        this.loads.runLoad(async () => {
          const loadContext = { ...context, signal };
          const revision = await this.resolver.resolve(repository, ref, loadContext);
          signal.throwIfAborted();
          const revisionKey = toRevisionCacheKey(repository, revision);
          const cachedSnapshot = this.cache.getRevision(revisionKey);
          const loadedSnapshot = cachedSnapshot ?? await this.loadRevision(repository, revision, loadContext);
          signal.throwIfAborted();
          const checkedAt = this.now();
          const activated = this.cache.activateSource(sourceKey, {
            repository,
            ref,
            activeRevision: revision,
            checkedAt,
            expiresAt: checkedAt + (this.options.refreshMs ?? config.examples.refreshMs),
            stale: false,
            nextRetryAt: 0,
          }, revisionKey, loadedSnapshot);
          return {
            revision,
            snapshot: activated.revision,
            status: cachedSnapshot ? "cache" as const : "remote" as const,
            stale: false,
          };
        }, signal, context.sourcePriority ?? "default"),
        context.signal,
      );
    } catch (error) {
      if (context.signal?.aborted) throw context.signal.reason ?? error;
      // A rate limit announces when GitHub answers again; retrying earlier only wastes quota.
      const retryAfterMs = error instanceof ExamplesError && error.code === "RATE_LIMITED"
        ? (error.retryAfterSeconds ?? 0) * 1000
        : 0;
      const lastGood = this.cache.markSourceFailure(
        sourceKey,
        this.now() + Math.max(retryAfterMs, Math.min(
          this.options.refreshRetryMs ?? config.examples.refreshRetryMs,
          this.options.refreshMs ?? config.examples.refreshMs,
        )),
      );
      if (lastGood && !requireFresh) return this.fromEntry(lastGood);
      throw asExamplesError(error);
    }
  }
 
  /**
   * Returns a cached, server-loaded snapshot. With `ref`, the snapshot must also have
   * been resolved from that ref, so it belongs to that Course selection.
   */
  async getRevision(
    repository: RepositorySlug,
    revision: FullCommitSha,
    _context: RequestContext,
    ref?: ExamplesRef,
  ): Promise<RevisionCacheEntry> {
    const key = toRevisionCacheKey(repository, revision);
    const existing = this.cache.getRevision(key);
    if (!existing || (ref !== undefined && !existing.resolvedRefs?.has(ref))) {
      throw new ExamplesError("INVALID_REVISION", "External examples revision is not a server-authorized snapshot");
    }
    return existing;
  }
 
  private async loadRevision(
    repository: RepositorySlug,
    revision: FullCommitSha,
    context: RequestContext,
  ): Promise<Omit<RevisionCacheEntry, "lastAccessedAt">> {
    const key = toRevisionCacheKey(repository, revision);
    return this.cache.withRevisionSingleflight(key, async (signal) => {
      const loaded = await this.revisionLoader.load(repository, revision, signal);
      return { repository, revision, ...loaded };
    }, context.signal);
  }
 
  private fromEntry(entry: SourceCacheEntry): ResolvedSourceSnapshot {
    const snapshot = this.cache.getRevision(toRevisionCacheKey(entry.repository, entry.activeRevision));
    Iif (!snapshot) throw new ExamplesError("SOURCE_UNAVAILABLE", "External examples snapshot is unavailable");
    return { revision: entry.activeRevision, snapshot, status: "cache", stale: entry.stale };
  }
}