iterate.com / git

git clone https://git.iterate.com/repos/git

git / releases.tsmain at 517348b

// releases.ts — WHAT A RELEASE IS: a tag of git on a commit of `main`, named `v<major>.<minor>.<patch>`
// (`v1.2.7`). A tag tells whoever uses the repo that a new version is there, so they take a
// version and not every commit:
//
//   git ls-remote --tags https://git.<domain>/repos/<name>
//   git clone --branch v1.2.7 https://git.<domain>/repos/<name>
//
// THE TAG IS THE RELEASE. It is an annotated tag in the repo's own remote: its message holds the
// notes, and git shows them (`git show v1.2.7`). A tag is made once and never moved: the push
// names no old commit, and the remote refuses a name that it has.
//
// WHO CUT IT, AND WHEN, is one event on the repo's own context (/repos/<name>), beside its pulls:
//
//   release/cut  { tag, version, commitOid, previous, notes }
//
// `previous` is the tag before it, or null for the first. Who and when are the event's own
// (`source.principal`, `createdAt`), which the platform stamps. A tag that git pushed by hand has
// no such event: the page shows it with its commit alone.
//
// WHAT A PAGE READS IS SMALL, whoever asks and however often: the tags, with a read token that
// the app keeps while it lasts (app.ts), and for the newest tags one kv entry each,
// `git-app:release:<repo>:<tag>`, which the cut writes beside its event. The repo's log is never
// read for a page: it grows with every push and pull, and anyone may ask for a public repo's page.
//
// TO CUT A RELEASE IS THE ONE CALL (`cutRelease`, which the mind's API offers as
// `itx.config.releaseCut`). With no version named, the next one raises the patch: v1.2.7 becomes
// v1.2.8, and a repo's first release is v0.1.0. When main is at the newest release already,
// nothing is cut. The notes, when none are given, are the first line of each commit of main since
// the release before: main is a straight line, each commit one pull (pulls.ts).
//
// WHY THIS FILE SPEAKS GIT'S WIRE. The mind's repo API reads branches and writes main, and knows
// no tag. So the tags are read, and a tag is pushed, as git does it: smart HTTP to the repo's
// Cloudflare Artifacts remote, with a token that is minted for the one request (app.ts, "THE
// REMOTE"). A tag's push carries one object, the tag itself.
import type { IterateConfigEntrypoint } from "iterate/sdk";
import { z } from "zod";

type Itx = ReturnType<IterateConfigEntrypoint["getItx"]>;

/** Where a repo's remote is, and the credential for it (`Basic …`), or null where none is asked. */
export type Remote = { address: string; authorization: string | null };

/** A tag of the remote. `oid` is what the ref names: the tag's own object for an annotated tag,
 *  the commit for a plain one. `commitOid` is the commit either way. */
export type Tag = { name: string; oid: string; commitOid: string };

export type Version = [major: number, minor: number, patch: number];

export type Release = {
  tag: string;
  /** `1.2.7` for the tag `v1.2.7`; null for a tag that is no version. */
  version: string | null;
  commitOid: string;
  /** From the `release/cut` event; each null for a tag that has none. */
  by: string | null;
  at: string | null;
  previous: string | null;
  notes: string | null;
};

const TAGS = "refs/tags/";
const ZERO_OID = "0".repeat(40);
/** How many releases a list holds, newest first, and how many of them with who, when and notes:
 *  one kv read each. */
const RELEASES_LISTED = 200;
const RELEASES_WITH_NOTES = 30;
/** How far back main is read for the notes. */
const HISTORY_READ = 300;
/** The most that is read of one answer of the remote: a list of refs, or a push's report. */
const ANSWER_BYTES = 4 * 1024 * 1024;
const WRITE_TOKEN_SECONDS = 300;
const READ_TOKEN_SECONDS = 300;

// ── VERSIONS ──

/** `v1.2.7` or `1.2.7` as numbers; null for any other text. */
export function versionOf(text: string): Version | null {
  const match = /^v?(0|[1-9]\d{0,8})\.(0|[1-9]\d{0,8})\.(0|[1-9]\d{0,8})$/.exec(text);
  return match ? [Number(match[1]), Number(match[2]), Number(match[3])] : null;
}

export const compareVersions = (a: Version, b: Version) => a[0] - b[0] || a[1] - b[1] || a[2] - b[2];

export const tagOf = (version: Version) => `v${version.join(".")}`;

/** The version after `latest`: the patch raised, or the minor or the major with what is under it
 *  at zero. A repo's first is 0.1.0. */
export function nextVersion(latest: Version | null, bump: "patch" | "minor" | "major" = "patch"): Version {
  if (!latest) return [0, 1, 0];
  if (bump === "major") return [latest[0] + 1, 0, 0];
  if (bump === "minor") return [latest[0], latest[1] + 1, 0];
  return [latest[0], latest[1], latest[2] + 1];
}

/** The tags that are versions, newest version first. */
function versionsIn(tags: Tag[]) {
  return tags
    .flatMap((tag) => {
      const version = versionOf(tag.name);
      return version && tag.name.startsWith("v") ? [{ ...tag, version }] : [];
    })
    .sort((a, b) => compareVersions(b.version, a.version));
}

// ── THE RELEASES OF A REPO ──

/** What the cut keeps of a release in the mind's kv, for a page: what its event says. */
const Kept = z.object({
  commitOid: z.string(),
  by: z.string().nullable(),
  at: z.string(),
  previous: z.string().nullable(),
  notes: z.string(),
});
type Kept = z.infer<typeof Kept>;
const keptKey = (repo: string, tag: string) => `git-app:release:${repo}:${tag}`;

/** The repo's releases, newest first: its version tags by version, then any other tag by name,
 *  at most 200. The newest 30 have what their cut kept: who, when, the notes. `remote` is where
 *  the tags are read, with its credential; with none, a token is minted for this one read. */
export async function releasesIn(itx: Itx, repo: string, remote?: Remote): Promise<Release[]> {
  const tags = orderOf(await readTags(remote || (await remoteOf(itx, repo, "read")))).slice(0, RELEASES_LISTED);
  const kept = new Map<string, Kept>();
  await Promise.all(
    tags.slice(0, RELEASES_WITH_NOTES).map(async ({ name }) => {
      const text = await itx.kv.get(keptKey(repo, name));
      if (!text) return;
      try {
        const parsed = Kept.safeParse(JSON.parse(text));
        if (parsed.success) kept.set(name, parsed.data);
      } catch {
        // an entry that is no JSON is no entry
      }
    }),
  );
  return releasesOf(tags, kept);
}

/** Version tags by version, newest first, then any other tag by name. */
function orderOf(tags: Tag[]): Tag[] {
  const versions = versionsIn(tags);
  const others = tags
    .filter((tag) => !versions.some(({ name }) => name === tag.name))
    .sort((a, b) => (a.name < b.name ? 1 : -1));
  return [...versions, ...others];
}

/** Each tag, in the order given, with what was kept of its cut. */
export function releasesOf(tags: Tag[], kept: Map<string, Kept>): Release[] {
  return tags.map((tag) => {
    const cut = kept.get(tag.name);
    // an entry that names another commit than the tag has is not this tag's
    const said = cut && cut.commitOid === tag.commitOid ? cut : null;
    const version = versionOf(tag.name);
    return {
      tag: tag.name,
      version: version && tag.name.startsWith("v") ? version.join(".") : null,
      commitOid: tag.commitOid,
      by: said?.by ?? null,
      at: said?.at ?? null,
      previous: said?.previous ?? null,
      notes: said?.notes ?? null,
    };
  });
}

// ── CUT A RELEASE ──

export type CutInput = {
  /** The version to cut, `1.3.0` or `v1.3.0`: newer than every release of the repo. */
  version?: string;
  /** With no `version`: which part the next one raises. `patch` when not said. */
  bump?: "patch" | "minor" | "major";
  /** What the release brings, as text. With none, the commits of main since the release before. */
  notes?: string;
  /** Who git names as the one who tagged. With none, `releases@<the mind's own domain>`. */
  tagger?: { name: string; email: string };
};

export type CutOutcome =
  | { cut: true; tag: string; version: string; commitOid: string; previous: string | null; notes: string }
  | { cut: false; why: string; tag: string | null; commitOid: string | null };

/** CUT A RELEASE OF A REPO: an annotated tag on main's newest commit, then the `release/cut`
 *  event that says so. It answers `{ cut: false, why }` and changes nothing when main is at the
 *  newest release already, or has no commit. It throws, in words for the one who asked, when the
 *  version is no version or is not newer than the newest release, or the remote refuses the tag. */
export async function cutRelease(itx: Itx, repo: string, input: CutInput = {}): Promise<CutOutcome> {
  const handle = itx.repos.get(repo);
  const [history, tags] = await Promise.all([
    handle.log({ limit: HISTORY_READ }),
    readTags(await remoteOf(itx, repo, "read")),
  ]);
  const tip = history[0];
  if (!tip) return { cut: false, why: `${repo} has no commit on main`, tag: null, commitOid: null };
  const latest = versionsIn(tags)[0] || null;
  if (latest && latest.commitOid === tip.oid)
    return {
      cut: false,
      why: `main is at ${latest.name} already: nothing is new`,
      tag: latest.name,
      commitOid: tip.oid,
    };

  let version: Version;
  if (input.version === undefined) version = nextVersion(latest?.version || null, input.bump);
  else {
    const named = versionOf(input.version);
    if (!named) throw new Error(`"${input.version}" is no version: write it as 1.2.7`);
    if (latest && compareVersions(named, latest.version) <= 0)
      throw new Error(`${tagOf(named)} is not newer than ${latest.name}, the newest release`);
    version = named;
  }
  const tag = tagOf(version);
  if (tags.some(({ name }) => name === tag)) throw new Error(`the tag ${tag} is there already`);

  const notes = (input.notes?.trim() || notesOf(history, latest)).slice(0, 20_000);
  const tagger = input.tagger || { name: "releases", email: `releases@${new URL(await itx.url()).hostname}` };
  const name = repo.slice("/repos/".length);
  const object = tagObject({
    tag,
    commitOid: tip.oid,
    tagger,
    seconds: Math.floor(Date.now() / 1000),
    message: `${name} ${tag}\n\n${notes}`,
  });
  await pushTag(await remoteOf(itx, repo, "write"), tag, object);

  const payload = { tag, version: version.join("."), commitOid: tip.oid, previous: latest?.name || null, notes };
  // one tag is cut once: a second try of this call lands no second event
  const [event] = await itx.cd(repo).append({ type: "release/cut", idempotencyKey: `release/cut:${tag}`, payload });
  // what a page reads of this release, so that no page reads the log
  const person = event?.source?.principal || event?.source?.onBehalfOf?.principal;
  const kept: Kept = {
    commitOid: tip.oid,
    by: person?.email?.split("@")[0] || person?.name || null,
    at: event?.createdAt || new Date().toISOString(),
    previous: payload.previous,
    notes,
  };
  await itx.kv.put(keptKey(repo, tag), JSON.stringify(kept));
  return { cut: true, ...payload };
}

/** The notes of a release with none given: the first line of each commit of main since the
 *  release before, newest first. */
function notesOf(history: { oid: string; message: string }[], latest: { name: string; commitOid: string } | null) {
  if (!latest) return `The first release: main at ${history[0]!.oid.slice(0, 7)}.`;
  const reached = history.findIndex(({ oid }) => oid === latest.commitOid);
  const since = reached < 0 ? history : history.slice(0, reached);
  const lines = since.map(({ oid, message }) => `- ${message.trim().split("\n")[0] || "(no message)"} (${oid.slice(0, 7)})`);
  if (reached < 0) lines.push(`- and the commits before these, back to ${latest.name}`);
  return `Since ${latest.name}:\n\n${lines.join("\n")}`;
}

// ── GIT'S WIRE: the tags of a remote, and the push of one tag ──

/** The repo's remote with a token for one request, as git sends it. */
async function remoteOf(itx: Itx, repo: string, scope: "read" | "write"): Promise<Remote> {
  const artifacts = await itx.cfArtifacts.get(repo);
  const [address, token] = await Promise.all([
    artifacts.remote(),
    artifacts.createToken(scope, scope === "write" ? WRITE_TOKEN_SECONDS : READ_TOKEN_SECONDS),
  ]);
  return { address, authorization: `Basic ${btoa(`x:${token.plaintext}`)}` };
}

const encoder = new TextEncoder();
const decoder = new TextDecoder();

function concat(parts: Uint8Array[]): Uint8Array<ArrayBuffer> {
  const whole = new Uint8Array(parts.reduce((length, part) => length + part.length, 0));
  let at = 0;
  for (const part of parts) {
    whole.set(part, at);
    at += part.length;
  }
  return whole;
}

/** One line of git's wire: four hex digits of its whole length, then the bytes. */
function pktLine(line: string | Uint8Array): Uint8Array {
  const bytes = typeof line === "string" ? encoder.encode(line) : line;
  return concat([encoder.encode((bytes.length + 4).toString(16).padStart(4, "0")), bytes]);
}
const FLUSH = encoder.encode("0000");
const DELIM = encoder.encode("0001");

/** The lines of an answer, each without its length and its last newline. A flush or a
 *  delimiter is no line. An answer that is cut short ends the lines. */
function pktLines(body: Uint8Array): string[] {
  const lines: string[] = [];
  let at = 0;
  while (at + 4 <= body.length) {
    const length = Number.parseInt(decoder.decode(body.subarray(at, at + 4)), 16);
    if (Number.isNaN(length)) break;
    if (length < 4) {
      at += 4;
      continue;
    }
    if (at + length > body.length) break;
    lines.push(decoder.decode(body.subarray(at + 4, at + length)).replace(/\n$/, ""));
    at += length;
  }
  return lines;
}

async function post(remote: Remote, service: "git-upload-pack" | "git-receive-pack", body: Uint8Array<ArrayBuffer>) {
  const headers = new Headers({
    "content-type": `application/x-${service}-request`,
    accept: `application/x-${service}-result`,
    "git-protocol": "version=2",
    "user-agent": "git/2.45.0 (iterate-git-app)",
  });
  if (remote.authorization) headers.set("authorization", remote.authorization);
  const answer = await fetch(`${remote.address}/${service}`, { method: "POST", headers, body, redirect: "manual" });
  const bytes = new Uint8Array(await answer.arrayBuffer());
  // never the remote's own words past a few: an answer of the remote is no text of this app
  if (!answer.ok) throw new Error(`the repo's remote answered ${answer.status} to ${service}`);
  if (bytes.length > ANSWER_BYTES) throw new Error(`the repo's remote answered too much to ${service}`);
  return bytes;
}

/** Every tag of the remote, with the commit it stands on. */
export async function readTags(remote: Remote): Promise<Tag[]> {
  const request = concat([
    pktLine("command=ls-refs\n"),
    DELIM,
    pktLine("peel\n"),
    pktLine(`ref-prefix ${TAGS}\n`),
    FLUSH,
  ]);
  const tags: Tag[] = [];
  for (const line of pktLines(await post(remote, "git-upload-pack", request))) {
    const [oid, ref, ...attributes] = line.split(" ");
    if (!oid || !/^[0-9a-f]{40}$/.test(oid) || !ref?.startsWith(TAGS)) continue;
    const peeled = attributes.find((attribute) => attribute.startsWith("peeled:"))?.slice("peeled:".length);
    // the remote's words are checked before a page puts them in an address
    if (peeled !== undefined && !/^[0-9a-f]{40}$/.test(peeled)) continue;
    if (!isTagName(ref.slice(TAGS.length))) continue;
    tags.push({ name: ref.slice(TAGS.length), oid, commitOid: peeled || oid });
  }
  return tags;
}

/** An annotated tag as git holds one: its text, and the oid that the text has. */
export type TagObject = { payload: Uint8Array; oid: Promise<string> };

/** `tag` on `commitOid`, tagged by `tagger` at `seconds` (of the epoch, written as UTC), with
 *  `message`. */
export function tagObject(input: {
  tag: string;
  commitOid: string;
  tagger: { name: string; email: string };
  seconds: number;
  message: string;
}): TagObject {
  // git takes no `<`, `>` or newline in a name or an address
  const clean = (text: string) => text.replace(/[<>\n\r\0]/g, "").trim();
  const payload = encoder.encode(
    [
      `object ${input.commitOid}`,
      "type commit",
      `tag ${input.tag}`,
      `tagger ${clean(input.tagger.name) || "releases"} <${clean(input.tagger.email)}> ${input.seconds} +0000`,
      "",
      `${input.message.replace(/\0/g, "").trimEnd()}\n`,
    ].join("\n"),
  );
  const oid = crypto.subtle
    .digest("SHA-1", concat([encoder.encode(`tag ${payload.length}\0`), payload]))
    .then(hex);
  return { payload, oid };
}

const hex = (bytes: ArrayBuffer) =>
  [...new Uint8Array(bytes)].map((byte) => byte.toString(16).padStart(2, "0")).join("");

async function deflate(bytes: Uint8Array<ArrayBuffer>): Promise<Uint8Array> {
  const stream = new Blob([bytes]).stream().pipeThrough(new CompressionStream("deflate"));
  return new Uint8Array(await new Response(stream).arrayBuffer());
}

/** A pack of the one tag object: git's header, the object's type (4, a tag) and length, its text
 *  deflated, and the SHA-1 of all of it. */
async function packOf(object: TagObject): Promise<Uint8Array> {
  const header = new Uint8Array(12);
  header.set(encoder.encode("PACK"), 0);
  new DataView(header.buffer).setUint32(4, 2);
  new DataView(header.buffer).setUint32(8, 1);
  const lengthBytes: number[] = [];
  let size = object.payload.length;
  let byte = (4 << 4) | (size & 0x0f);
  size >>= 4;
  while (size > 0) {
    lengthBytes.push(byte | 0x80);
    byte = size & 0x7f;
    size >>= 7;
  }
  lengthBytes.push(byte);
  const body = concat([header, Uint8Array.from(lengthBytes), await deflate(concat([object.payload]))]);
  return concat([body, new Uint8Array(await crypto.subtle.digest("SHA-1", body))]);
}

/** Push one new tag. The push names no old commit, so the remote refuses a tag that is there. It
 *  throws unless the remote says that it took the pack and made the ref. */
export async function pushTag(remote: Remote, tag: string, object: TagObject): Promise<void> {
  if (!isTagName(tag)) throw new Error(`"${tag}" is no name for a tag`);
  const ref = `${TAGS}${tag}`;
  const request = concat([
    pktLine(`${ZERO_OID} ${await object.oid} ${ref}\0report-status agent=iterate-git-app/1\n`),
    FLUSH,
    await packOf(object),
  ]);
  const report = pktLines(await post(remote, "git-receive-pack", request));
  const refused = report.find((line) => line.startsWith(`ng ${ref} `));
  if (refused) throw new Error(`the remote refused the tag ${tag}: ${refused.slice(`ng ${ref} `.length, 300)}`);
  if (!report.includes("unpack ok") || !report.includes(`ok ${ref}`))
    throw new Error(`the remote did not say that it made the tag ${tag}`);
}

/** A tag's name as this app's pages hold one: letters, digits, `.`, `_` and `-`. */
export const isTagName = (name: string) =>
  /^[A-Za-z0-9_][A-Za-z0-9._-]{0,99}$/.test(name) && !name.endsWith(".") && !name.endsWith(".lock") && !name.includes("..");