All files / server/services/examples examples-cache.ts

83.43% Statements 141/169
70.58% Branches 48/68
94.44% Functions 34/36
87.75% Lines 129/147

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 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332                    115x       89x                                                     7x                                     34x 34x 34x 34x 34x       34x 34x 34x       93x 93x 93x       2x 2x 2x 2x 2x 2x 2x         2x                 34x 34x 34x 34x 34x 34x 34x         34x 34x 34x 34x 34x 34x         34x       43x 43x 2x 2x 2x 2x       55x 55x 55x       3x 3x 3x 3x 3x 3x 3x 3x 3x 3x         3x               87x 87x 87x 86x               28x       2x                   83x 76x 72x 5x 1x                     114x   114x 114x       114x 109x       109x 109x 109x   109x 109x 109x   109x 109x 109x 109x 109x     62x 62x     47x 47x         114x             114x 114x   114x 114x 114x 119x 114x 114x 119x 119x   114x 5x 5x     114x 114x       114x   66x 66x     48x 48x             39x 2x             5x 7x   5x 4x 4x       2x 2x   2x 5x 1x 2x 2x 2x 2x                                 34x 34x 34x 34x 34x    
import type { ExamplesRef, FullCommitSha, RepositorySlug } from "@shared/examples";
import type { ExampleRecord } from "./examples-schema";
import { ExamplesError } from "./examples-error";
import type { TutorCapability } from "../course-content/course-content-loader";
import type { ExampleTutorAnnotation } from "../course-content/embedded-tutor-annotation";
 
export type SourceCacheKey = `examples:source:v1:${RepositorySlug}:${ExamplesRef}`;
export type RevisionCacheKey = `examples:revision:v1:${RepositorySlug}:${FullCommitSha}`;
 
export function toSourceCacheKey(repository: RepositorySlug, ref: ExamplesRef): SourceCacheKey {
  return `examples:source:v1:${repository}:${ref}`;
}
 
export function toRevisionCacheKey(repository: RepositorySlug, revision: FullCommitSha): RevisionCacheKey {
  return `examples:revision:v1:${repository}:${revision}`;
}
 
export interface SourceCacheEntry {
  repository: RepositorySlug;
  ref: ExamplesRef;
  activeRevision: FullCommitSha;
  checkedAt: number;
  expiresAt: number;
  stale: boolean;
  nextRetryAt: number;
  lastAccessedAt: number;
}
 
export interface RevisionCacheEntry {
  repository: RepositorySlug;
  revision: FullCommitSha;
  examples: ExampleRecord[];
  tutor?: TutorCapability;
  exampleTutorAnnotations?: ReadonlyMap<string, ExampleTutorAnnotation>;
  contentBytes: number;
  /** Refs of this repository the server resolved to this revision; an example's revision is checked against them. */
  resolvedRefs?: ReadonlySet<ExamplesRef>;
  lastAccessedAt: number;
}
 
/** Bounds the provenance kept per snapshot; the oldest resolved ref is forgotten first. */
const MAX_RESOLVED_REFS_PER_REVISION = 16;
 
export interface ExamplesCacheOptions {
  maxSources: number;
  maxSnapshots: number;
  maxSnapshotBytes: number;
  now?: () => number;
  /** Sources the LRU never evicts: the operator's default Course, which overrides must not displace. */
  protectedSourceKeys?: readonly SourceCacheKey[];
}
 
interface SharedFlight {
  controller: AbortController;
  promise: Promise<unknown>;
  subscribers: number;
  settled: boolean;
}
 
export class ExamplesCache {
  private readonly sources = new Map<SourceCacheKey, SourceCacheEntry>();
  private readonly revisions = new Map<RevisionCacheKey, RevisionCacheEntry>();
  private readonly sourceFlights = new Map<SourceCacheKey, SharedFlight>();
  private readonly revisionFlights = new Map<RevisionCacheKey, SharedFlight>();
  private totalSnapshotBytes = 0;
  private readonly now: () => number;
  private readonly protectedSources: ReadonlySet<SourceCacheKey>;
 
  constructor(private readonly options: ExamplesCacheOptions) {
    this.now = options.now ?? Date.now;
    this.protectedSources = new Set(options.protectedSourceKeys);
  }
 
  getSource(key: SourceCacheKey): SourceCacheEntry | undefined {
    const entry = this.sources.get(key);
    if (entry) entry.lastAccessedAt = this.now();
    return entry;
  }
 
  setSource(key: SourceCacheKey, entry: Omit<SourceCacheEntry, "lastAccessedAt">): SourceCacheEntry {
    const beforeSources = new Map(this.sources);
    const beforeRevisions = new Map(this.revisions);
    const beforeBytes = this.totalSnapshotBytes;
    const stored = { ...entry, lastAccessedAt: this.now() };
    this.sources.set(key, stored);
    try {
      this.enforceRevisionLimits();
    } catch (error) {
      this.restore(beforeSources, beforeRevisions, beforeBytes);
      throw error;
    }
    return stored;
  }
 
  activateSource(
    sourceKey: SourceCacheKey,
    source: Omit<SourceCacheEntry, "lastAccessedAt">,
    revisionKey: RevisionCacheKey,
    revision: Omit<RevisionCacheEntry, "lastAccessedAt">,
  ): { source: SourceCacheEntry; revision: RevisionCacheEntry } {
    const beforeSources = new Map(this.sources);
    const beforeRevisions = new Map(this.revisions);
    const beforeBytes = this.totalSnapshotBytes;
    const previous = this.revisions.get(revisionKey);
    if (previous) this.totalSnapshotBytes -= previous.contentBytes;
    const accessedAt = this.now();
    const storedRevision = {
      ...revision,
      resolvedRefs: withResolvedRef(previous?.resolvedRefs ?? revision.resolvedRefs, source.ref),
      lastAccessedAt: accessedAt,
    };
    const storedSource = { ...source, lastAccessedAt: accessedAt };
    this.revisions.set(revisionKey, storedRevision);
    this.totalSnapshotBytes += storedRevision.contentBytes;
    this.sources.set(sourceKey, storedSource);
    try {
      this.enforceRevisionLimits();
    } catch (error) {
      this.restore(beforeSources, beforeRevisions, beforeBytes);
      throw error;
    }
    return { source: storedSource, revision: storedRevision };
  }
 
  markSourceFailure(key: SourceCacheKey, nextRetryAt: number): SourceCacheEntry | undefined {
    const entry = this.sources.get(key);
    if (!entry) return undefined;
    entry.stale = true;
    entry.nextRetryAt = nextRetryAt;
    entry.lastAccessedAt = this.now();
    return entry;
  }
 
  getRevision(key: RevisionCacheKey): RevisionCacheEntry | undefined {
    const entry = this.revisions.get(key);
    if (entry) entry.lastAccessedAt = this.now();
    return entry;
  }
 
  setRevision(key: RevisionCacheKey, entry: Omit<RevisionCacheEntry, "lastAccessedAt">): RevisionCacheEntry {
    const beforeSources = new Map(this.sources);
    const beforeRevisions = new Map(this.revisions);
    const beforeBytes = this.totalSnapshotBytes;
    const previous = this.revisions.get(key);
    Iif (previous) this.totalSnapshotBytes -= previous.contentBytes;
    const stored = { ...entry, lastAccessedAt: this.now() };
    this.revisions.set(key, stored);
    this.totalSnapshotBytes += stored.contentBytes;
    try {
      this.enforceRevisionLimits();
    } catch (error) {
      this.restore(beforeSources, beforeRevisions, beforeBytes);
      throw error;
    }
    return stored;
  }
 
  async withSourceSingleflight<T>(
    key: SourceCacheKey,
    load: (signal: AbortSignal) => Promise<T>,
    requestSignal?: AbortSignal,
  ): Promise<T> {
    Iif (requestSignal?.aborted) throw requestSignal.reason ?? new DOMException("Request aborted", "AbortError");
    const current = this.sourceFlights.get(key);
    if (!current || current.controller.signal.aborted) this.admitSource(key);
    return this.withSingleflight(this.sourceFlights, key, load, requestSignal);
  }
 
  async withRevisionSingleflight<T>(
    key: RevisionCacheKey,
    load: (signal: AbortSignal) => Promise<T>,
    requestSignal?: AbortSignal,
  ): Promise<T> {
    return this.withSingleflight(this.revisionFlights, key, load, requestSignal);
  }
 
  getStats() {
    return {
      sources: this.sources.size,
      revisions: this.revisions.size,
      snapshotBytes: this.totalSnapshotBytes,
      sourceFlights: this.sourceFlights.size,
      revisionFlights: this.revisionFlights.size,
    };
  }
 
  private admitSource(key: SourceCacheKey): void {
    if (this.sources.has(key) || this.sourceFlights.has(key)) return;
    const sourceCount = () => new Set([...this.sources.keys(), ...this.sourceFlights.keys()]).size;
    while (sourceCount() >= this.options.maxSources) {
      if (!this.evictOldestSource()) {
        throw new ExamplesError("LOAD_CAPACITY_EXCEEDED", "External examples source capacity is exhausted");
      }
    }
  }
 
  private withSingleflight<K extends string, T>(
    flights: Map<K, SharedFlight>,
    key: K,
    load: (signal: AbortSignal) => Promise<T>,
    requestSignal?: AbortSignal,
  ): Promise<T> {
    Iif (requestSignal?.aborted) return Promise.reject(requestSignal.reason ?? new DOMException("Request aborted", "AbortError"));
 
    let flight = flights.get(key) as SharedFlight & { promise: Promise<T> } | undefined;
    Iif (flight?.controller.signal.aborted) {
      if (flights.get(key) === flight) flights.delete(key);
      flight = undefined;
    }
    if (!flight) {
      const controller = new AbortController();
      let created!: SharedFlight & { promise: Promise<T> };
      let resolveFlight!: (value: T) => void;
      let rejectFlight!: (error: unknown) => void;
      const promise = new Promise<T>((resolve, reject) => {
        resolveFlight = resolve;
        rejectFlight = reject;
      });
      const settle = () => {
        created.settled = true;
        Eif (flights.get(key) === created) flights.delete(key);
      };
      created = { controller, promise, subscribers: 0, settled: false };
      flight = created;
      flights.set(key, created);
      void Promise.resolve()
        .then(() => load(controller.signal))
        .then(
          (value) => {
            settle();
            resolveFlight(value);
          },
          (error: unknown) => {
            settle();
            rejectFlight(error);
          },
        );
    }
 
    return this.subscribeToFlight(flight, requestSignal);
  }
 
  private subscribeToFlight<T>(
    flight: SharedFlight & { promise: Promise<T> },
    requestSignal?: AbortSignal,
  ): Promise<T> {
    Iif (requestSignal?.aborted) return Promise.reject(requestSignal.reason ?? new DOMException("Request aborted", "AbortError"));
    flight.subscribers += 1;
 
    return new Promise<T>((resolve, reject) => {
      let left = false;
      const leave = () => {
        if (left) return;
        left = true;
        requestSignal?.removeEventListener("abort", onAbort);
        flight.subscribers -= 1;
        if (flight.subscribers === 0 && !flight.settled) flight.controller.abort();
      };
      const onAbort = () => {
        leave();
        reject(requestSignal?.reason ?? new DOMException("Request aborted", "AbortError"));
      };
 
      requestSignal?.addEventListener("abort", onAbort, { once: true });
      Iif (requestSignal?.aborted) {
        onAbort();
        return;
      }
      flight.promise.then(
        (value) => {
          leave();
          resolve(value as T);
        },
        (error: unknown) => {
          leave();
          reject(error);
        },
      );
    });
  }
 
  private enforceRevisionLimits(): void {
    while (this.revisions.size > this.options.maxSnapshots || this.totalSnapshotBytes > this.options.maxSnapshotBytes) {
      Eif (this.evictOldestUnpinnedRevision()) continue;
      if (this.evictOldestSource()) continue;
      throw new ExamplesError("LOAD_CAPACITY_EXCEEDED", "External examples snapshot cache is exhausted");
    }
  }
 
  private evictOldestSource(): boolean {
    const oldest = [...this.sources.entries()]
      .filter(([key]) => !this.sourceFlights.has(key) && !this.protectedSources.has(key))
      .sort(([, left], [, right]) => left.lastAccessedAt - right.lastAccessedAt)[0];
    if (!oldest) return false;
    this.sources.delete(oldest[0]);
    return true;
  }
 
  private evictOldestUnpinnedRevision(): boolean {
    const pinned = new Set(
      [...this.sources.values()].map((entry) => toRevisionCacheKey(entry.repository, entry.activeRevision)),
    );
    const oldest = [...this.revisions.entries()]
      .filter(([key]) => !pinned.has(key) && !this.revisionFlights.has(key))
      .sort(([, left], [, right]) => left.lastAccessedAt - right.lastAccessedAt)[0];
    Iif (!oldest) return false;
    this.revisions.delete(oldest[0]);
    this.totalSnapshotBytes -= oldest[1].contentBytes;
    return true;
  }
 
  private restore(
    sources: Map<SourceCacheKey, SourceCacheEntry>,
    revisions: Map<RevisionCacheKey, RevisionCacheEntry>,
    totalSnapshotBytes: number,
  ): void {
    this.sources.clear();
    for (const [key, entry] of sources) this.sources.set(key, entry);
    this.revisions.clear();
    for (const [key, entry] of revisions) this.revisions.set(key, entry);
    this.totalSnapshotBytes = totalSnapshotBytes;
  }
}
 
function withResolvedRef(refs: ReadonlySet<ExamplesRef> | undefined, ref: ExamplesRef): ReadonlySet<ExamplesRef> {
  const next = new Set(refs);
  next.delete(ref);
  next.add(ref);
  while (next.size > MAX_RESOLVED_REFS_PER_REVISION) next.delete(next.values().next().value as ExamplesRef);
  return next;
}