~ knotless Search/
↑↓ move↵ open⇧↵ all results

zat.dev/stream

jetstream v2 in zig · mirror of https://tangled.org/zat.dev/stream

0
0
221 lines · 7.3 KB Raw History
import {
  array,
  integer,
  object,
  string,
  literal,
  nullable,
  safeParse,
  constrain,
  arrayLength,
  type InferOutput,
} from "@atcute/lexicons/validations";

const keySchema = object({
  key: string(),
  count: integer(),
  members: integer(),
});
export const heatSchema = object({
  keys: array(keySchema),
  cells: array(constrain(array(integer()), [arrayLength(3, 3)])),
});
export const segmentsSchema = array(
  constrain(array(integer()), [arrayLength(6, 6)]),
);
export const manifestSchema = object({
  version: literal(1),
  updatedAt: nullable(integer()),
  objects: array(object({ name: string(), digest: string() })),
});

export function heatQuery(url: URL) {
  const step = Number(url.searchParams.get("step") ?? "10");
  const top = Number(url.searchParams.get("top") ?? "12");
  const ns = url.searchParams.get("ns");
  const group = url.searchParams.get("group") ?? "namespaces";
  if (!Number.isSafeInteger(step) || step < 1)
    throw new RangeError("step must be a positive integer");
  if (!Number.isSafeInteger(top) || top < 1 || top > 60)
    throw new RangeError("top must be 1..60");
  if (ns !== null && !/^[a-z0-9-]+\.[a-z0-9-]+$/i.test(ns))
    throw new RangeError("ns must be an authority like fm.teal");
  if (ns === null && group !== "collections" && group !== "namespaces")
    throw new RangeError("group must be namespaces or collections");
  return { step, top, ns, group };
}

export function renderHeat(
  segments: InferOutput<typeof segmentsSchema>,
  heat: InferOutput<typeof heatSchema>,
  url: URL,
) {
  const q = heatQuery(url);
  const maxIdx = segments.at(-1)?.[0] ?? -1;
  if (Math.floor(maxIdx / q.step) + 1 > 2000)
    throw new RangeError(`step ${q.step} yields more than 2000 buckets`);
  type Bucket = {
    bucket: number;
    first_idx: number;
    last_idx: number;
    min_seq: number;
    max_seq: number;
    min_witnessed_at: number;
    max_witnessed_at: number;
    event_count: number;
  };
  const buckets = new Map<number, Bucket>();
  for (const [idx, minSeq, maxSeq, minAt, maxAt, events] of segments) {
    if (idx === undefined) throw new Error("invalid segment index");
    const bucket = Math.floor(idx / q.step);
    if (
      minSeq === undefined ||
      maxSeq === undefined ||
      minAt === undefined ||
      maxAt === undefined ||
      events === undefined
    )
      throw new Error("invalid segment");
    const b = buckets.get(bucket);
    if (b) {
      b.last_idx = idx;
      b.min_seq = Math.min(b.min_seq, minSeq);
      b.max_seq = Math.max(b.max_seq, maxSeq);
      b.min_witnessed_at = Math.min(b.min_witnessed_at, minAt);
      b.max_witnessed_at = Math.max(b.max_witnessed_at, maxAt);
      b.event_count += events;
    } else
      buckets.set(bucket, {
        bucket,
        first_idx: idx,
        last_idx: idx,
        min_seq: minSeq,
        max_seq: maxSeq,
        min_witnessed_at: minAt,
        max_witnessed_at: maxAt,
        event_count: events,
      });
  }
  const cells = new Map<number, Map<string, number>>();
  for (const [idx, rank, count] of heat.cells) {
    if (idx === undefined) throw new Error("invalid segment index");
    const bucket = Math.floor(idx / q.step);
    if (rank === undefined || count === undefined)
      throw new Error("invalid cell");
    const key =
      q.ns !== null || rank < q.top
        ? (heat.keys[rank]?.key ?? "other")
        : "other";
    let row = cells.get(bucket);
    if (!row) {
      row = new Map();
      cells.set(bucket, row);
    }
    row.set(key, (row.get(key) ?? 0) + count);
  }
  return {
    step: q.step,
    top: q.top,
    scope: q.ns !== null ? { kind: "namespace", ns: q.ns } : { kind: q.group },
    buckets: [...buckets.values()],
    cells: [...cells]
      .sort(([a], [b]) => a - b)
      .flatMap(([bucket, row]) =>
        [...row]
          .sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))
          .map(([key, count]) => ({ bucket, key, count })),
      ),
    keys: q.ns !== null ? heat.keys : heat.keys.slice(0, q.top),
  };
}

export async function snapshotResponse(
  url: URL,
  bucket: R2Bucket,
  ctx: ExecutionContext,
): Promise<Response> {
  const cache = caches.default;
  async function read(key: string, ttl: number) {
    const cacheKey = new Request(
      `https://strata.zat.dev/_snapshot-cache/${key}`,
    );
    const cached = await cache.match(cacheKey);
    if (cached) return cached;
    const object = await bucket.get(key);
    if (!object) return null;
    const response = new Response(object.body, {
      headers: { etag: object.etag, "cache-control": `public, max-age=${ttl}` },
    });
    ctx.waitUntil(cache.put(cacheKey, response.clone()));
    return response;
  }
  const pointer = await read("snapshots/manifest", 30);
  if (!pointer)
    return Response.json({ error: "snapshot unavailable" }, { status: 503 });
  const parsed = safeParse(manifestSchema, await pointer.json());
  if (!parsed.ok) throw new Error("invalid snapshot manifest");
  const manifest = parsed.value;
  async function get(name: string) {
    const digest = manifest.objects.find((o) => o.name === name)?.digest;
    if (!digest || !/^[a-f0-9]{64}$/.test(digest)) return null;
    return read(`snapshots/objects/${digest}`, 31536000);
  }
  const headers = {
    "content-type": "application/json",
    "access-control-allow-origin": "*",
    "cache-control": "public, max-age=300",
    "x-strata-generation": pointer.headers.get("etag") ?? "",
  };
  try {
    if (url.pathname === "/api/heat") {
      const q = heatQuery(url);
      const [segments, heat] = await Promise.all([
        get("segments"),
        get(q.ns !== null ? `ns/${q.ns}` : `heat/${q.group}`),
      ]);
      if (!segments) throw new Error("snapshot segments missing");
      if (!heat && q.ns === null) throw new Error("snapshot heat missing");
      const segmentData = safeParse(segmentsSchema, await segments.json());
      const heatData = safeParse(
        heatSchema,
        heat ? await heat.json() : { keys: [], cells: [] },
      );
      if (!segmentData.ok || !heatData.ok) throw new Error("invalid snapshot");
      return Response.json(renderHeat(segmentData.value, heatData.value, url), {
        headers,
      });
    }
    const name = url.pathname.slice("/api/".length);
    const payload = await get(name);
    if (!payload) return Response.json({ error: "not found" }, { status: 404 });
    if (name === "collections" && url.searchParams.has("ns")) {
      const ns = url.searchParams.get("ns");
      if (ns === null || !/^[a-z0-9-]+\.[a-z0-9-]+$/i.test(ns))
        throw new RangeError("ns must be an authority like fm.teal");
      const schema = object({
        collections: array(
          object({
            nsid: string(),
            ns: string(),
            count: integer(),
            segments: integer(),
          }),
        ),
      });
      const data = safeParse(schema, await payload.json());
      if (!data.ok) throw new Error("invalid collections snapshot");
      return Response.json(
        { collections: data.value.collections.filter((c) => c.ns === ns) },
        { headers },
      );
    }
    return new Response(payload.body, { headers });
  } catch (error) {
    if (error instanceof RangeError)
      return Response.json(
        { error: error.message },
        { status: 400, headers: { "access-control-allow-origin": "*" } },
      );
    throw error;
  }
}