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
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;
}
}