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

zat.dev/stream

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

0
0
81 lines · 2.3 KB Raw History
import assert from "node:assert/strict";
import { test } from "node:test";
import { DatabaseSync } from "node:sqlite";
import { renderHeat, heatQuery } from "../src/snapshot";

test("snapshot aggregation matches SQLite for sparse segments, zero counts and arbitrary bucket sizes", () => {
  const db = new DatabaseSync(":memory:");
  db.exec("CREATE TABLE cells(idx INTEGER,key TEXT,count INTEGER)");
  const cells = [
    [0, 0, 10],
    [0, 1, 0],
    [7, 0, 20],
    [7, 1, 4],
    [25, 1, 6],
    [25, 2, 8],
  ];
  const keys = [
    { key: "app.a", count: 30, members: 1 },
    { key: "app.b", count: 10, members: 1 },
  ];
  const names = ["app.a", "app.b", "app.c"];
  for (const [idx, rank, count] of cells) {
    assert.notEqual(rank, undefined);
    if (rank === undefined) throw Error("missing rank");
    db.prepare("INSERT INTO cells VALUES(?,?,?)").run(
      idx ?? 0,
      names[rank] ?? "",
      count ?? 0,
    );
  }
  for (const step of [1, 3, 10, 100])
    for (const top of [1, 2, 60]) {
      const result = renderHeat(
        [
          [0, 1, 9, 100, 200, 10],
          [7, 10, 33, 200, 300, 24],
          [25, 34, 47, 400, 500, 14],
        ],
        { keys, cells },
        new URL(`https://test/api/heat?step=${step}&top=${top}`),
      );
      const expected = db
        .prepare(
          "SELECT idx / CAST(? AS INTEGER) AS bucket,CASE WHEN key IN (SELECT key FROM cells GROUP BY key ORDER BY SUM(count) DESC LIMIT ?) THEN key ELSE 'other' END AS key,SUM(count) AS count FROM cells GROUP BY bucket,2 ORDER BY bucket,2",
        )
        .all(step, Math.min(top, 2));
      assert.deepEqual(
        result.cells,
        expected.map((row) => ({ ...row })),
      );
      assert.equal(
        result.buckets.reduce((sum, b) => sum + b.event_count, 0),
        48,
      );
    }
  db.close();
});

test("query validation preserves bounds", () => {
  for (const query of [
    "step=0",
    "step=1.5",
    "top=61",
    "group=nope",
    "ns=../x",
  ]) {
    assert.throws(
      () => heatQuery(new URL("https://test/api/heat?" + query)),
      RangeError,
    );
  }
  assert.throws(
    () =>
      renderHeat(
        [[7000, 1, 2, 1, 2, 1]],
        { keys: [], cells: [] },
        new URL("https://test/api/heat?step=1"),
      ),
    RangeError,
  );
});