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

82.81% Statements 53/64
80.3% Branches 53/66
95% Functions 19/20
85.18% Lines 46/54

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                                                                                    11x 11x 11x           11x 11x               11x                                                       13x 13x 13x           13x 13x                                   3x 3x 3x 2x 2x     2x 2x 2x                   7x 7x     3x 3x                         20x     20x       6x 6x   3x   3x 3x 3x           4x 1x         13x     13x   13x             13x 1x           3x 3x 3x                           13x 13x 13x 13x 13x      
import type {
  BrowserOverrideSelection,
  ExampleDetailResponse,
  ExamplesCatalogResponse,
  ExamplesRef,
  ExamplesRequestSelection,
  ExamplesSourceMetadata,
  FullCommitSha,
  RepositorySlug,
  TutorCapabilityMetadata,
} from "@shared/examples";
import { config, type ParsedExamplesConfig } from "../../config";
import { BuiltInProvider } from "./built-in-provider";
import { ExamplesCache, type RevisionCacheEntry, toSourceCacheKey } from "./examples-cache";
import type { TutorCapability } from "../course-content/course-content-loader";
import { ExamplesError } from "./examples-error";
import { GitHubRevisionResolver } from "./github-revision-resolver";
import { ExamplesLoadController } from "./examples-load-controller";
import { RevisionProvider, SecureExamplesFetcher } from "./http-provider";
import type { ExampleRecord } from "./examples-schema";
import { SourceProvider, type RequestContext } from "./source-provider";
import { resolveExamplesSelection } from "./source-selection";
import type {
  ResolvedTutorCourseContent,
  TutorCourseContentRequest,
  TutorCourseContentResolver,
} from "../course-content/course-content-session";
 
export interface ExamplesRepositoryOptions {
  examplesConfig?: ParsedExamplesConfig;
  builtInProvider?: Pick<BuiltInProvider, "getExamples">;
  sourceProvider?: Pick<SourceProvider, "resolve" | "getRevision">;
  cache?: ExamplesCache;
  loadController?: ExamplesLoadController;
}
 
export class ExamplesRepository implements TutorCourseContentResolver {
  private readonly examplesConfig: ParsedExamplesConfig;
  private readonly builtInProvider: Pick<BuiltInProvider, "getExamples">;
  private readonly sourceProvider: Pick<SourceProvider, "resolve" | "getRevision">;
 
  constructor(options: ExamplesRepositoryOptions = {}) {
    this.examplesConfig = options.examplesConfig ?? config.examples;
    this.builtInProvider = options.builtInProvider ?? new BuiltInProvider();
    const loads = options.loadController ?? new ExamplesLoadController({
      maxConcurrentLoads: this.examplesConfig.maxConcurrentLoads,
      maxLoadQueue: this.examplesConfig.maxLoadQueue,
      maxOutboundFetches: this.examplesConfig.maxOutboundFetches,
      globalLoadStartsPerMinute: this.examplesConfig.globalLoadStartsPerMinute,
    });
    const fetcher = new SecureExamplesFetcher(loads);
    const cache = options.cache ?? new ExamplesCache({
      maxSources: this.examplesConfig.maxSources,
      maxSnapshots: this.examplesConfig.snapshotCacheMaxEntries,
      maxSnapshotBytes: this.examplesConfig.snapshotCacheMaxBytes,
      protectedSourceKeys: this.examplesConfig.mode === "repository-ref" && this.examplesConfig.repository
        ? [toSourceCacheKey(this.examplesConfig.repository, this.examplesConfig.ref)]
        : [],
    });
    this.sourceProvider = options.sourceProvider ?? new SourceProvider(
      new GitHubRevisionResolver(fetcher),
      new RevisionProvider(fetcher, this.examplesConfig.maxFileFetchConcurrency),
      cache,
      loads,
      { refreshMs: this.examplesConfig.refreshMs, refreshRetryMs: this.examplesConfig.refreshRetryMs },
    );
  }
 
  async validate(selection: BrowserOverrideSelection, context: RequestContext): Promise<ExamplesSourceMetadata> {
    const resolved = resolveExamplesSelection({ kind: "browser-override", ...selection }, this.examplesConfig);
    if (resolved.mode !== "repository-ref") {
      throw new ExamplesError("INVALID_SELECTION", "Invalid external examples selection");
    }
    const result = await this.sourceProvider.resolve(resolved.repository, resolved.ref, this.withPriority(context, resolved), true);
    return {
      selection: "browser-override",
      mode: "repository-ref",
      repository: resolved.repository,
      ref: resolved.ref,
      revision: result.revision,
      status: result.status,
      stale: false,
      tutor: tutorMetadata(result.snapshot.tutor),
    };
  }
 
  async getCatalog(selection: ExamplesRequestSelection, context: RequestContext): Promise<ExamplesCatalogResponse> {
    const resolved = resolveExamplesSelection(selection, this.examplesConfig);
    const builtins = await this.builtInProvider.getExamples();
    Iif (resolved.mode === "builtin") {
      return this.catalog({
        selection: "default", mode: "builtin", repository: null, ref: null,
        revision: null, status: "builtin", stale: false, tutor: { status: "absent" },
      }, builtins);
    }
    const remote = await this.sourceProvider.resolve(resolved.repository, resolved.ref, this.withPriority(context, resolved), false);
    return this.catalog({
      selection: resolved.selection,
      mode: "repository-ref",
      repository: resolved.repository,
      ref: resolved.ref,
      revision: remote.revision,
      status: remote.status,
      stale: remote.stale,
      tutor: tutorMetadata(remote.snapshot.tutor),
    }, deduplicateExamples([...builtins, ...remote.snapshot.examples]));
  }
 
  async getExample(
    repository: RepositorySlug | undefined,
    revision: FullCommitSha | undefined,
    id: string,
    context: RequestContext,
  ): Promise<ExampleDetailResponse | null> {
    const builtins = await this.builtInProvider.getExamples();
    const builtin = builtins.find((candidate) => candidate.id === id);
    if (builtin) return toDetail(builtin, null);
    Iif (!repository && !revision) return null;
    Iif (!repository || !revision) {
      throw new ExamplesError("INVALID_REVISION", "External example details require repository and revision");
    }
    const snapshot = await this.sourceProvider.getRevision(repository, revision, context);
    const example = snapshot.examples.find((candidate) => candidate.id === id);
    return example ? toDetail(example, revision) : null;
  }
 
  /**
   * The browser revision is untrusted metadata (Course Content SSOT 5). Without an
   * example, the server pins the selection's current revision. An example stays on
   * the revision it was loaded from while that snapshot is a validated one of the
   * same repository/ref; otherwise only the current revision is accepted.
   */
  async resolveTutorContent(request: TutorCourseContentRequest, context: RequestContext): Promise<ResolvedTutorCourseContent> {
    const prioritized = this.withPriority(context, request);
    const snapshot = request.exampleId === undefined
      ? (await this.sourceProvider.resolve(request.repository, request.ref, prioritized, true)).snapshot
      : await this.exampleSnapshot(request, prioritized);
    this.assertExampleInSnapshot(snapshot.examples, request.exampleId);
    return {
      ...request,
      revision: snapshot.revision,
      tutor: snapshot.tutor ?? { status: "absent" },
      contentBytes: snapshot.contentBytes,
      ...(request.exampleId !== undefined && snapshot.exampleTutorAnnotations?.has(request.exampleId)
        ? { exampleTutorAnnotation: snapshot.exampleTutorAnnotations.get(request.exampleId) }
        : {}),
    };
  }
 
  /** The operator default keeps a GitHub quota reserve that browser overrides cannot spend. */
  private withPriority(context: RequestContext, source: { repository: RepositorySlug; ref: ExamplesRef }): RequestContext {
    const isDefault = this.examplesConfig.mode === "repository-ref"
      && source.repository === this.examplesConfig.repository
      && source.ref === this.examplesConfig.ref;
    return { ...context, sourcePriority: isDefault ? "default" : "override" };
  }
 
  private async exampleSnapshot(request: TutorCourseContentRequest, context: RequestContext): Promise<RevisionCacheEntry> {
    try {
      return await this.sourceProvider.getRevision(request.repository, request.revision, context, request.ref);
    } catch (error) {
      Iif (!(error instanceof ExamplesError) || error.code !== "INVALID_REVISION") throw error;
    }
    const resolved = await this.sourceProvider.resolve(request.repository, request.ref, context, true);
    Eif (resolved.revision !== request.revision) {
      throw new ExamplesError("INVALID_REVISION", "Course Content example revision is no longer available");
    }
    return resolved.snapshot;
  }
 
  private assertExampleInSnapshot(examples: readonly ExampleRecord[], exampleId: string | undefined): void {
    if (exampleId !== undefined && !examples.some(({ id }) => id === exampleId)) {
      throw new ExamplesError("EXAMPLE_NOT_FOUND", "Course Content example is not in the selected revision");
    }
  }
 
  private catalog(source: ExamplesSourceMetadata, examples: ExampleRecord[]): ExamplesCatalogResponse {
    return {
      schemaVersion: 1,
      source,
      examples: examples.map(({ files, tutorAnnotation: _tutorAnnotation, ...example }) => ({
        ...example,
        files: files.map(({ content: _content, ...file }) => file),
      })),
    };
  }
}
 
function tutorMetadata(value: TutorCapability | undefined): TutorCapabilityMetadata {
  if (!value || value.status === "absent") return { status: "absent" };
  return value.status === "valid"
    ? { status: "valid" }
    : { status: "invalid", reason: "invalid-tutor-bundle" };
}
 
function toDetail(example: ExampleRecord, revision: FullCommitSha | null): ExampleDetailResponse {
  const main = example.files.find((file) => file.name === example.main);
  const remaining = example.files.filter((file) => file !== main);
  return {
    schemaVersion: 1,
    id: example.id,
    title: example.title,
    category: example.category,
    ...(example.description === undefined ? {} : { description: example.description }),
    main: example.main,
    source: example.source,
    revision,
    files: main ? [main, ...remaining] : example.files,
  };
}
 
function deduplicateExamples(examples: ExampleRecord[]): ExampleRecord[] {
  const ids = new Set<string>();
  return examples.filter((example) => {
    Iif (ids.has(example.id)) return false;
    ids.add(example.id);
    return true;
  });
}