zat.dev/zds
atproto pds · mirror of https://tangled.org/zat.dev/zds
zds 0.25.1 Latest 2 packages, all images
0
0
const std = @import("std");
const clock = @import("../core/clock.zig");
const config = @import("../core/config.zig");
const log = @import("../core/log.zig");
const http_api = @import("../http/api.zig");
const eventlog = @import("../storage/eventlog.zig");
const store = @import("../storage/store.zig");
const blobstore = @import("../storage/blobstore.zig");
const repo_export_cache = @import("repo_export_cache.zig");
const zat = @import("zat");
const httpz = @import("httpz");
const http = std.http;
const max_subscribe_repos_connections = 32;
/// A subscriber that takes no part of a frame for this long is dropped; a
/// stalled relay otherwise held a stream thread and its write lock forever.
const frame_write_timeout_ms: u64 = 10_000;
/// Backfill reconnect limiter: a consumer that reconnects with a historical
/// cursor more than `max_backfill_connects_per_window` times inside the window
/// is re-streaming history in a loop (a consumer that never persists its
/// cursor drains the whole CPU burst budget on a small machine). Live-tail
/// connects are never limited.
const backfill_window_seconds: u32 = 300;
const max_backfill_connects_per_window: u32 = 4;
const BackfillSlot = struct { ip_hash: u64 = 0, window_start_s: u32 = 0, count: u32 = 0 };
var backfill_slots: [64]BackfillSlot = @splat(.{});
var backfill_slots_lock: std.atomic.Value(bool) = .init(false);
fn backfillReconnectAllowed(ip: []const u8, now_s: u32) bool {
if (ip.len == 0) return true;
const hash = std.hash.Wyhash.hash(0, ip);
while (backfill_slots_lock.cmpxchgWeak(false, true, .acquire, .monotonic) != null) {
std.atomic.spinLoopHint();
}
defer backfill_slots_lock.store(false, .release);
var free_index: ?usize = null;
var oldest_index: usize = 0;
for (&backfill_slots, 0..) |*slot, i| {
if (slot.ip_hash == hash) {
if (now_s -| slot.window_start_s >= backfill_window_seconds) {
slot.window_start_s = now_s;
slot.count = 1;
return true;
}
slot.count += 1;
return slot.count <= max_backfill_connects_per_window;
}
if (slot.ip_hash == 0 and free_index == null) free_index = i;
if (slot.window_start_s < backfill_slots[oldest_index].window_start_s) oldest_index = i;
}
const index = free_index orelse oldest_index;
backfill_slots[index] = .{ .ip_hash = hash, .window_start_s = now_s, .count = 1 };
return true;
}
const max_subscribe_repos_backfills = 4;
const notify_threshold_s = 20 * 60;
var subscribe_repos_connections: usize = 0;
var subscribe_repos_backfills: usize = 0;
var get_repo_connections: usize = 0;
var crawler_last_notified_s: std.atomic.Value(u32) = .init(0);
var crawler_notify_in_flight: std.atomic.Value(bool) = .init(false);
pub const SubscribeReposClient = struct {
state: *StreamState,
thread: ?std.Thread = null,
pub const Context = struct {
cursor: u64,
backfill: bool,
future: bool = false,
peer: []const u8,
/// Set once `init` has created the stream state, which from then on
/// releases the connection and backfill counts itself: on close, or
/// when the library discards a handshake that failed after `init`.
counted_by_state: *bool,
};
pub fn init(conn: *httpz.websocket.Conn, ctx: *const Context) !SubscribeReposClient {
const state = try std.heap.smp_allocator.create(StreamState);
state.* = .{
.conn = conn,
.cursor = ctx.cursor,
.backfill = ctx.backfill,
.future = ctx.future,
.start_cursor = ctx.cursor,
.started_s = nowSeconds(),
};
state.peer_len = @min(ctx.peer.len, state.peer.len);
@memcpy(state.peer[0..state.peer_len], ctx.peer[0..state.peer_len]);
ctx.counted_by_state.* = true;
return .{ .state = state };
}
pub fn afterInit(self: *SubscribeReposClient) !void {
self.state.retain();
const thread = std.Thread.spawn(.{}, streamEvents, .{self.state}) catch |err| {
self.state.release();
log.err("sync subscribeRepos spawn failed cursor={d} err={s}\n", .{ self.state.cursor, @errorName(err) });
return err;
};
self.thread = thread;
_ = subscribers.fetchAdd(1, .monotonic);
}
pub fn clientMessage(_: *SubscribeReposClient, _: []const u8) !void {}
/// The websocket frees the Conn once this returns, so the stream thread
/// has to be gone by then.
pub fn close(self: *SubscribeReposClient) void {
@atomicStore(bool, &self.state.closed, true, .release);
eventlog.wakeWaiters();
if (self.thread) |thread| {
thread.join();
_ = subscribers.fetchSub(1, .monotonic);
}
self.state.finish();
self.state.release();
}
const StreamState = struct {
conn: *httpz.websocket.Conn,
cursor: u64,
backfill: bool,
future: bool = false,
closed: bool = false,
counted: bool = true,
refs: usize = 1,
start_cursor: u64 = 0,
started_s: u32 = 0,
frames: u64 = 0,
bytes: u64 = 0,
peer: [64]u8 = @splat(0),
peer_len: usize = 0,
fn peerText(self: *const StreamState) []const u8 {
return self.peer[0..self.peer_len];
}
fn retain(self: *StreamState) void {
_ = @atomicRmw(usize, &self.refs, .Add, 1, .monotonic);
}
fn release(self: *StreamState) void {
if (@atomicRmw(usize, &self.refs, .Sub, 1, .acq_rel) == 1) {
std.heap.smp_allocator.destroy(self);
}
}
fn finish(self: *StreamState) void {
if (@atomicRmw(bool, &self.counted, .Xchg, false, .acq_rel)) {
_ = @atomicRmw(usize, &subscribe_repos_connections, .Sub, 1, .monotonic);
self.releaseBackfillSlot();
log.info("sync subscribeRepos end peer={s} start_cursor={d} end_cursor={d} frames={d} bytes={d} duration_s={d}\n", .{
self.peerText(),
self.start_cursor,
self.cursor,
self.frames,
self.bytes,
nowSeconds() -| self.started_s,
});
}
}
/// A backfill slot bounds concurrent event-history reads, not
/// connection lifetime; it is released the moment the subscriber
/// catches up to live, or on teardown if it never does.
fn releaseBackfillSlot(self: *StreamState) void {
if (@atomicRmw(bool, &self.backfill, .Xchg, false, .acq_rel)) {
_ = @atomicRmw(usize, &subscribe_repos_backfills, .Sub, 1, .monotonic);
}
}
fn isClosed(self: *const StreamState) bool {
return @atomicLoad(bool, &self.closed, .acquire);
}
};
fn streamEvents(state: *StreamState) void {
defer state.release();
defer state.finish();
// A cursor past the head gets FutureCursor and a close, as the spec and
// the reference PDS do, so a relay sees the problem instead of waiting.
// The close frame asks the client to hang up; the connection's reader
// closes the socket when it answers. Closing it from this thread races
// that reader on the same descriptor.
if (state.future) {
const frame = zat.firehose.encodeErrorFrame(std.heap.page_allocator, "FutureCursor", "Cursor in the future.") catch return;
defer std.heap.page_allocator.free(frame);
writeFirehoseFrame(state.conn, frame) catch return;
writeCloseFrame(state.conn, &future_cursor_close) catch {};
return;
}
var observed = eventlog.currentGeneration();
while (!state.isClosed()) {
var sent = false;
{
var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);
defer arena.deinit();
const events = store.listSeqEvents(arena.allocator(), state.cursor, 100) catch |err| {
log.err("sync subscribeRepos list failed cursor={d} err={s}\n", .{ state.cursor, @errorName(err) });
return;
};
for (events) |event| {
if (state.isClosed()) return;
writeFirehoseFrame(state.conn, event.frame) catch |err| {
switch (err) {
error.BrokenPipe, error.ConnectionResetByPeer, error.Closed => return,
error.WriteTimeout => {
log.info("sync subscribeRepos dropped slow consumer peer={s} cursor={d} timeout_ms={d}\n", .{ state.peerText(), state.cursor, frame_write_timeout_ms });
return;
},
else => log.err("sync subscribeRepos write failed cursor={d} seq={d} bytes={d} err={s}\n", .{ state.cursor, event.seq, event.frame.len, @errorName(err) }),
}
return;
};
state.cursor = event.seq;
state.frames += 1;
state.bytes += event.frame.len;
sent = true;
}
}
if (sent) {
observed = eventlog.currentGeneration();
continue;
}
state.releaseBackfillSlot();
const next = (eventlog.waitForChange(observed, &state.closed) catch return) orelse return;
if (next.generation != observed or next.latest_seq > state.cursor) {
observed = next.generation;
}
}
}
/// A close frame with status 1008 (policy violation) and reason FutureCursor.
const future_cursor_close = [_]u8{ 0x88, 2 + "FutureCursor".len, 0x03, 0xf0 } ++ "FutureCursor".*;
fn writeCloseFrame(conn: *httpz.websocket.Conn, frame: []const u8) !void {
conn.lock.lockUncancelable(conn.io);
defer conn.lock.unlock(conn.io);
if (conn.isClosed()) return error.Closed;
try writeSocketAll(conn.stream.socket.handle, frame, clock.monotonicNs() + frame_write_timeout_ms * std.time.ns_per_ms);
}
fn writeFirehoseFrame(conn: *httpz.websocket.Conn, payload: []const u8) !void {
var header: [10]u8 = undefined;
const header_len = websocketBinaryHeader(&header, payload.len);
conn.lock.lockUncancelable(conn.io);
defer conn.lock.unlock(conn.io);
// closeSocket marks the Conn closed before it takes this lock to close
// the descriptor, which may then be reused by another connection.
if (conn.isClosed()) return error.Closed;
const socket = conn.stream.socket.handle;
const deadline_ns = clock.monotonicNs() + frame_write_timeout_ms * std.time.ns_per_ms;
writeSocketAll(socket, header[0..header_len], deadline_ns) catch |err| return slowConsumer(socket, err);
writeSocketAll(socket, payload, deadline_ns) catch |err| return slowConsumer(socket, err);
}
/// A subscriber that has not taken a frame within the timeout is cut off:
/// shutting the socket down, while the write lock is held and the
/// descriptor still ours, makes the reactor see the connection end and
/// tear it down through its own close path.
fn slowConsumer(socket: std.posix.socket_t, err: anyerror) anyerror {
if (err == error.WriteTimeout) _ = std.c.shutdown(socket, std.posix.SHUT.RDWR);
return err;
}
fn websocketBinaryHeader(header: *[10]u8, payload_len: usize) usize {
header[0] = 0x82;
if (payload_len < 126) {
header[1] = @intCast(payload_len);
return 2;
}
if (payload_len <= std.math.maxInt(u16)) {
header[1] = 126;
std.mem.writeInt(u16, header[2..4], @intCast(payload_len), .big);
return 4;
}
header[1] = 127;
std.mem.writeInt(u64, header[2..10], @intCast(payload_len), .big);
return 10;
}
/// Writes all of `data`, waiting for the socket to drain when its buffer is
/// full rather than spinning, until `deadline_ns` (monotonic).
fn writeSocketAll(socket: std.posix.socket_t, data: []const u8, deadline_ns: u64) !void {
var remaining = data;
while (remaining.len > 0) {
const written = std.c.write(socket, remaining.ptr, remaining.len);
if (written > 0) {
remaining = remaining[@intCast(written)..];
continue;
}
if (written == 0) return error.WriteZero;
switch (std.posix.errno(written)) {
.AGAIN => {
const now = clock.monotonicNs();
if (now >= deadline_ns) return error.WriteTimeout;
var fds = [_]std.posix.pollfd{.{ .fd = socket, .events = std.posix.POLL.OUT, .revents = 0 }};
const wait_ms: i32 = @intCast(@min((deadline_ns - now) / std.time.ns_per_ms + 1, std.math.maxInt(i32)));
_ = std.posix.poll(&fds, wait_ms) catch return error.WriteFailed;
continue;
},
.INTR => continue,
.PIPE => return error.BrokenPipe,
.CONNRESET => return error.ConnectionResetByPeer,
else => return error.WriteFailed,
}
}
}
};
pub fn getBlob(request: *http_api.Request) !void {
var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);
defer arena.deinit();
const allocator = arena.allocator();
var did_buf: [256]u8 = undefined;
const did = http_api.queryParam(request.url.raw, "did", &did_buf) orelse {
return http_api.xrpcError(request, .bad_request, "InvalidRequest", "Missing did");
};
var cid_buf: [256]u8 = undefined;
const cid = http_api.queryParam(request.url.raw, "cid", &cid_buf) orelse {
return http_api.xrpcError(request, .bad_request, "InvalidRequest", "Missing cid");
};
try requireRepoAvailable(request, allocator, did, true);
// Streamed from disk: a 30 MB video read whole was held in memory once
// per download.
const blob = store.publicBlobMetadata(allocator, did, cid) orelse {
return http_api.xrpcError(request, .not_found, "BlobNotFound", "Blob not found");
};
// A blob is named by its content, so its CID is a strong validator.
const etag = try std.fmt.allocPrint(allocator, "\"{s}\"", .{cid});
const cache_control = if (http_api.headerValue(request, "authorization") != null) "private, no-store" else "public, max-age=31536000, immutable";
if (ifNoneMatchHits(http_api.headerValue(request, "if-none-match"), cid)) {
return notModified(request, etag, cache_control);
}
const file = blobstore.open(allocator, did, cid) catch {
return http_api.xrpcError(request, .not_found, "BlobNotFound", "Blob not found");
};
defer file.close(blobstore.fileIo());
const size = (file.stat(blobstore.fileIo()) catch {
return http_api.xrpcError(request, .not_found, "BlobNotFound", "Blob not found");
}).size;
const disposition = try std.fmt.allocPrint(allocator, "attachment; filename=\"{s}\"", .{cid});
const headers = [_]http.Header{
.{ .name = "content-type", .value = blob.mime_type },
.{ .name = "cache-control", .value = cache_control },
.{ .name = "etag", .value = etag },
.{ .name = "x-content-type-options", .value = "nosniff" },
.{ .name = "content-disposition", .value = disposition },
.{ .name = "content-security-policy", .value = "default-src 'none'; sandbox" },
.{ .name = "access-control-allow-origin", .value = "*" },
.{ .name = "access-control-allow-private-network", .value = "true" },
.{ .name = "connection", .value = "close" },
};
try http_api.respondSizedStreamNowClose(request, .ok, &headers, size, BlobBody{ .file = file, .size = size }, BlobBody.write);
}
const BlobBody = struct {
file: std.Io.File,
size: u64,
fn write(self: BlobBody, w: *std.Io.Writer) anyerror!void {
var buf: [16 * 1024]u8 = undefined;
var reader = self.file.reader(blobstore.fileIo(), &buf);
try reader.interface.streamExact64(w, self.size);
}
};
pub fn getRepo(request: *http_api.Request) !void {
var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);
defer arena.deinit();
const allocator = arena.allocator();
var did_buf: [256]u8 = undefined;
const did = http_api.queryParam(request.url.raw, "did", &did_buf) orelse {
return http_api.xrpcError(request, .bad_request, "InvalidRequest", "Missing did");
};
var since_buf: [256]u8 = undefined;
const since = http_api.queryParam(request.url.raw, "since", &since_buf);
try requireRepoAvailable(request, allocator, did, true);
if (try repoNotModified(request, allocator, did)) return;
const full_export = since == null;
if (full_export) {
const active = @atomicRmw(usize, &get_repo_connections, .Add, 1, .monotonic);
const max_connections = config.maxConcurrentRepoExports();
if (active >= max_connections) {
_ = @atomicRmw(usize, &get_repo_connections, .Sub, 1, .monotonic);
log.debug("sync getRepo rejected too_many_connections active={d} max={d} did={s}\n", .{ active + 1, max_connections, did });
return http_api.xrpcError(request, .too_many_requests, "RateLimitExceeded", "too many full getRepo exports");
}
}
defer {
if (full_export) _ = @atomicRmw(usize, &get_repo_connections, .Sub, 1, .monotonic);
}
if (full_export) return sendFullExport(request, allocator, did);
// The blocks are held once; the CAR is written to the socket from them
// rather than encoded and then copied into the response, which held
// about four copies of a repo per export.
const car = store.collectRepoCar(allocator, did, since) catch {
return http_api.xrpcError(request, .not_found, "RepoNotFound", "Repo not found");
};
try http_api.respondStreamNowClose(request, .ok, &carHeaders(request, try commitEtag(allocator, car.root_cid_raw)), CarBody{ .allocator = allocator, .data = car }, CarBody.write);
}
/// A full export, sent from the export cache while the repo is still at the
/// commit it was built from. A miss builds the CAR in its own arena and
/// encodes it once into the cache, freeing the blocks before the send, so a
/// cached repo costs one copy of its CAR; a CAR larger than the cache's
/// budget is streamed from its blocks as before and not kept.
fn sendFullExport(request: *http_api.Request, allocator: std.mem.Allocator, did: []const u8) !void {
const head = store.latestCommitCid(allocator, did) catch |err| switch (err) {
error.RepoNotFound => return http_api.xrpcError(request, .not_found, "RepoNotFound", "Repo not found"),
else => return err,
};
if (repo_export_cache.acquire(did, head)) |entry| {
defer entry.release();
log.debug("sync getRepo export_cache hit did={s} commit={s} bytes={d}\n", .{ did, head, entry.bytes.len });
return sendCachedCar(request, allocator, entry);
}
var build = std.heap.ArenaAllocator.init(std.heap.page_allocator);
var build_held = true;
defer if (build_held) build.deinit();
const car = store.collectRepoCar(build.allocator(), did, null) catch {
return http_api.xrpcError(request, .not_found, "RepoNotFound", "Repo not found");
};
const body = CarBody{ .allocator = build.allocator(), .data = car };
var count_buf: [4096]u8 = undefined;
var counter = std.Io.Writer.Discarding.init(&count_buf);
try body.write(&counter.writer);
const size = counter.fullCount();
const budget = config.repoExportCacheBytes();
if (size > budget) {
return http_api.respondSizedStreamNowClose(request, .ok, &carHeaders(request, try commitEtag(allocator, car.root_cid_raw)), size, body, CarBody.write);
}
const bytes = try repo_export_cache.bytesAllocator().alloc(u8, @intCast(size));
var bytes_owned = true;
defer if (bytes_owned) repo_export_cache.bytesAllocator().free(bytes);
var fixed = std.Io.Writer.fixed(bytes);
try body.write(&fixed);
if (fixed.end != bytes.len) return error.CarSizeChanged;
// Keyed by the commit the export was read at, which a write may have
// moved past `head` in between.
const commit = try zat.cbor.Cid.toString(.{ .raw = car.root_cid_raw }, allocator);
const entry = try repo_export_cache.put(did, commit, bytes, budget);
bytes_owned = false;
defer entry.release();
build.deinit();
build_held = false;
return sendCachedCar(request, allocator, entry);
}
fn sendCachedCar(request: *http_api.Request, allocator: std.mem.Allocator, entry: *repo_export_cache.Entry) !void {
const etag = try std.fmt.allocPrint(allocator, "W/\"{s}\"", .{entry.commit_cid});
try http_api.respondSizedStreamNowClose(request, .ok, &carHeaders(request, etag), entry.bytes.len, CachedCarBody{ .bytes = entry.bytes }, CachedCarBody.write);
}
/// Drops a deleted account's cached export.
pub fn forgetRepoExport(did: []const u8) void {
repo_export_cache.forget(did);
}
fn carHeaders(request: *const http_api.Request, etag: []const u8) [6]http.Header {
return .{
.{ .name = "content-type", .value = "application/vnd.ipld.car" },
.{ .name = "etag", .value = etag },
.{ .name = "cache-control", .value = revalidateCacheControl(request) },
.{ .name = "access-control-allow-origin", .value = "*" },
.{ .name = "access-control-allow-private-network", .value = "true" },
.{ .name = "connection", .value = "close" },
};
}
const CachedCarBody = struct {
bytes: []const u8,
fn write(self: CachedCarBody, w: *std.Io.Writer) anyerror!void {
try w.writeAll(self.bytes);
}
};
const CarBody = struct {
allocator: std.mem.Allocator,
data: store.RepoCarData,
fn write(self: CarBody, w: *std.Io.Writer) anyerror!void {
try zat.car.write(self.allocator, w, .{
.roots = &.{.{ .raw = self.data.root_cid_raw }},
.blocks = self.data.blocks,
});
}
};
pub fn getRecord(request: *http_api.Request) !void {
var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);
defer arena.deinit();
const allocator = arena.allocator();
var did_buf: [256]u8 = undefined;
const did = http_api.queryParam(request.url.raw, "did", &did_buf) orelse {
return http_api.xrpcError(request, .bad_request, "InvalidRequest", "Missing did");
};
var collection_buf: [256]u8 = undefined;
const collection = http_api.queryParam(request.url.raw, "collection", &collection_buf) orelse {
return http_api.xrpcError(request, .bad_request, "InvalidRequest", "Missing collection");
};
var rkey_buf: [512]u8 = undefined;
const rkey = http_api.queryParam(request.url.raw, "rkey", &rkey_buf) orelse {
return http_api.xrpcError(request, .bad_request, "InvalidRequest", "Missing rkey");
};
try requireRepoAvailable(request, allocator, did, false);
if (try repoNotModified(request, allocator, did)) return;
const proof = store.collectRecordProof(allocator, did, collection, rkey) catch |err| switch (err) {
error.RepoNotFound => return http_api.xrpcError(request, .not_found, "RepoNotFound", "Repo not found"),
else => {
log.err("sync getRecord failed did={s} collection={s} rkey={s} err={s}\n", .{ did, collection, rkey, @errorName(err) });
return http_api.xrpcError(request, .internal_server_error, "InternalServerError", "Could not build record proof");
},
};
const body = try store.writeRepoCarData(allocator, proof);
const headers = [_]http.Header{
.{ .name = "content-type", .value = "application/vnd.ipld.car" },
.{ .name = "etag", .value = try commitEtag(allocator, proof.root_cid_raw) },
.{ .name = "cache-control", .value = revalidateCacheControl(request) },
.{ .name = "access-control-allow-origin", .value = "*" },
.{ .name = "access-control-allow-private-network", .value = "true" },
.{ .name = "connection", .value = "close" },
};
if (request.method == .HEAD) {
return http_api.respondNowClose(request, .ok, "", &headers);
}
try http_api.respond(request, .ok, body, &headers);
}
pub fn getBlocks(request: *http_api.Request) !void {
var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);
defer arena.deinit();
const allocator = arena.allocator();
var did_buf: [256]u8 = undefined;
const did = http_api.queryParam(request.url.raw, "did", &did_buf) orelse {
return http_api.xrpcError(request, .bad_request, "InvalidRequest", "Missing did");
};
const cids = http_api.queryParamValues(allocator, request.url.raw, "cids") catch {
return http_api.xrpcError(request, .bad_request, "InvalidRequest", "Invalid cids");
};
if (cids.len == 0) return http_api.xrpcError(request, .bad_request, "InvalidRequest", "Missing cids");
try requireRepoAvailable(request, allocator, did, false);
const found = store.getRepoBlocks(allocator, did, cids) catch |err| switch (err) {
error.InvalidCid => return http_api.xrpcError(request, .bad_request, "InvalidRequest", "Invalid cid"),
else => return err,
};
if (found.missing.len > 0) {
const missing = try std.mem.join(allocator, ",", found.missing);
const message = try std.fmt.allocPrint(allocator, "Could not find cids: {s}", .{missing});
return http_api.xrpcError(request, .bad_request, "InvalidRequest", message);
}
const body = try zat.car.writeAlloc(allocator, .{ .roots = &.{}, .blocks = found.blocks });
const headers = [_]http.Header{
.{ .name = "content-type", .value = "application/vnd.ipld.car" },
.{ .name = "access-control-allow-origin", .value = "*" },
.{ .name = "access-control-allow-private-network", .value = "true" },
.{ .name = "connection", .value = "close" },
};
try http_api.respond(request, .ok, body, &headers);
}
pub fn listBlobs(request: *http_api.Request) !void {
var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);
defer arena.deinit();
const allocator = arena.allocator();
var did_buf: [256]u8 = undefined;
const did = http_api.queryParam(request.url.raw, "did", &did_buf) orelse {
return http_api.xrpcError(request, .bad_request, "InvalidRequest", "Missing did");
};
var since_buf: [256]u8 = undefined;
var cursor_buf: [256]u8 = undefined;
try requireRepoAvailable(request, allocator, did, true);
const body = try store.writeBlobListJson(
allocator,
did,
http_api.queryParam(request.url.raw, "since", &since_buf),
http_api.queryParam(request.url.raw, "cursor", &cursor_buf),
@min(http_api.queryLimit(request.url.raw, 500), 1000),
);
return http_api.json(request, .ok, body);
}
pub fn getLatestCommit(request: *http_api.Request) !void {
var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);
defer arena.deinit();
const allocator = arena.allocator();
var did_buf: [256]u8 = undefined;
const did = http_api.queryParam(request.url.raw, "did", &did_buf) orelse {
return http_api.xrpcError(request, .bad_request, "InvalidRequest", "Missing did");
};
try requireRepoAvailable(request, allocator, did, false);
if (try repoNotModified(request, allocator, did)) return;
const body = store.writeLatestCommitJson(allocator, did) catch |err| switch (err) {
error.RepoNotFound => return http_api.xrpcError(request, .not_found, "RepoNotFound", "Repo not found"),
else => return err,
};
// The body names the commit, so its CID is the validator here too.
const parsed = try std.json.parseFromSliceLeaky(struct { cid: []const u8, rev: []const u8 }, allocator, body, .{});
const headers = [_]http.Header{
.{ .name = "content-type", .value = "application/json; charset=utf-8" },
.{ .name = "etag", .value = try std.fmt.allocPrint(allocator, "W/\"{s}\"", .{parsed.cid}) },
.{ .name = "cache-control", .value = revalidateCacheControl(request) },
.{ .name = "access-control-allow-origin", .value = "*" },
.{ .name = "access-control-allow-private-network", .value = "true" },
.{ .name = "connection", .value = "close" },
};
try http_api.respond(request, .ok, body, &headers);
}
/// Answers 304 when If-None-Match names the repo's current commit. getRepo,
/// getRecord and getLatestCommit all answer from that commit, so a client
/// that already holds it skips the export (the Nov 15 instance spent its CPU
/// on repeated full exports). The tag is weak: tranquil and the reference
/// tag a repo by its head the same way, and a `since` export or record proof
/// is a different representation of the same commit.
fn repoNotModified(request: *http_api.Request, allocator: std.mem.Allocator, did: []const u8) !bool {
const header = http_api.headerValue(request, "if-none-match") orelse return false;
const head = store.latestCommitCid(allocator, did) catch |err| switch (err) {
error.RepoNotFound => return false,
else => return err,
};
if (!ifNoneMatchHits(header, head)) return false;
try notModified(request, try std.fmt.allocPrint(allocator, "W/\"{s}\"", .{head}), revalidateCacheControl(request));
return true;
}
fn commitEtag(allocator: std.mem.Allocator, commit_cid_raw: []const u8) ![]const u8 {
return std.fmt.allocPrint(allocator, "W/\"{s}\"", .{try zat.cbor.Cid.toString(.{ .raw = commit_cid_raw }, allocator)});
}
/// Repo answers change with every commit: a cache may keep one but must ask
/// again before reusing it. A read made with credentials (an owner reading
/// a deactivated repo) is kept out of shared caches.
fn revalidateCacheControl(request: *const http_api.Request) []const u8 {
return if (http_api.headerValue(request, "authorization") != null) "private, no-cache" else "public, no-cache";
}
fn notModified(request: *http_api.Request, etag: []const u8, cache_control: []const u8) !void {
const headers = [_]http.Header{
.{ .name = "etag", .value = etag },
.{ .name = "cache-control", .value = cache_control },
.{ .name = "access-control-allow-origin", .value = "*" },
.{ .name = "access-control-allow-private-network", .value = "true" },
.{ .name = "connection", .value = "close" },
};
try http_api.respond(request, .not_modified, "", &headers);
}
/// Whether an If-None-Match value matches the entity named `opaque`: `*`, or
/// any listed tag, weak or strong, with that value. GET conditionals use the
/// weak comparison (RFC 9110 13.1.2), so the W/ prefix does not matter.
fn ifNoneMatchHits(header: ?[]const u8, opaque_tag: []const u8) bool {
var rest = header orelse return false;
while (true) {
rest = std.mem.trimStart(u8, rest, " \t,");
if (rest.len == 0) return false;
if (rest[0] == '*') return true;
if (std.mem.startsWith(u8, rest, "W/")) rest = rest[2..];
if (rest.len == 0 or rest[0] != '"') return false;
const close = std.mem.indexOfScalarPos(u8, rest, 1, '"') orelse return false;
if (std.mem.eql(u8, rest[1..close], opaque_tag)) return true;
rest = rest[close + 1 ..];
}
}
test "If-None-Match matches by weak comparison" {
const cid = "bafyreigvs";
try std.testing.expect(ifNoneMatchHits("\"bafyreigvs\"", cid));
try std.testing.expect(ifNoneMatchHits("W/\"bafyreigvs\"", cid));
try std.testing.expect(ifNoneMatchHits("\"other\", W/\"bafyreigvs\"", cid));
try std.testing.expect(ifNoneMatchHits("*", cid));
try std.testing.expect(ifNoneMatchHits(" \"x\" ,\t*", cid));
try std.testing.expect(!ifNoneMatchHits(null, cid));
try std.testing.expect(!ifNoneMatchHits("", cid));
try std.testing.expect(!ifNoneMatchHits("\"bafyreigv\"", cid));
try std.testing.expect(!ifNoneMatchHits("\"bafyreigvsx\"", cid));
try std.testing.expect(!ifNoneMatchHits("bafyreigvs", cid));
try std.testing.expect(!ifNoneMatchHits("\"unterminated", cid));
}
pub fn listRepos(request: *http_api.Request) !void {
var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);
defer arena.deinit();
const allocator = arena.allocator();
var cursor_buf: [512]u8 = undefined;
const body = store.writeRepoListJson(allocator, http_api.queryParam(request.url.raw, "cursor", &cursor_buf), http_api.queryLimit(request.url.raw, 500)) catch |err| switch (err) {
error.InvalidCursor => return http_api.xrpcError(request, .bad_request, "InvalidRequest", "Malformed cursor"),
else => return err,
};
return http_api.json(request, .ok, body);
}
pub fn subscribeRepos(request: *http_api.Request) !void {
var cursor_buf: [32]u8 = undefined;
const cursor_param = http_api.queryParam(request.url.raw, "cursor", &cursor_buf);
const current_seq = store.latestSequence();
const start = subscriptionStart(cursor_param, current_seq) catch
return http_api.xrpcError(request, .bad_request, "InvalidRequest", "Malformed cursor");
const cursor = start.cursor;
const backfill = start.backfill;
const peer = http_api.headerValue(request, "fly-client-ip") orelse
http_api.headerValue(request, "x-forwarded-for") orelse "";
const user_agent = http_api.headerValue(request, "user-agent") orelse "";
log.info("sync subscribeRepos connect peer={s} ua={s} cursor={?s} start={d} current={d} backfill={}\n", .{
peer, user_agent, cursor_param, cursor, current_seq, backfill,
});
if (backfill and !backfillReconnectAllowed(peer, nowSeconds())) {
log.info("sync subscribeRepos rejected backfill_reconnect_loop peer={s} ua={s} cursor={d}\n", .{ peer, user_agent, cursor });
return http_api.xrpcError(request, .too_many_requests, "RateLimitExceeded", "too many backfill reconnects from this address; persist your cursor");
}
const active = @atomicRmw(usize, &subscribe_repos_connections, .Add, 1, .monotonic);
if (active >= max_subscribe_repos_connections) {
_ = @atomicRmw(usize, &subscribe_repos_connections, .Sub, 1, .monotonic);
log.debug("sync subscribeRepos rejected too_many_connections active={d} max={d}\n", .{ active +| 1, max_subscribe_repos_connections });
return http_api.xrpcError(request, .too_many_requests, "RateLimitExceeded", "too many subscribeRepos connections");
}
if (backfill) {
const active_backfills = @atomicRmw(usize, &subscribe_repos_backfills, .Add, 1, .monotonic);
if (active_backfills >= max_subscribe_repos_backfills) {
_ = @atomicRmw(usize, &subscribe_repos_backfills, .Sub, 1, .monotonic);
_ = @atomicRmw(usize, &subscribe_repos_connections, .Sub, 1, .monotonic);
log.debug("sync subscribeRepos rejected too_many_backfills active={d} max={d}\n", .{ active_backfills +| 1, max_subscribe_repos_backfills });
return http_api.xrpcError(request, .too_many_requests, "RateLimitExceeded", "too many subscribeRepos backfills");
}
}
// Until `init` creates the stream state these counts are ours to give
// back. After it they are the state's: a handshake that fails later is
// discarded through the handler's close, which releases them, and doing
// it here too counted the connection out twice, underflowing the count.
var counted_by_state = false;
defer if (!counted_by_state) {
_ = @atomicRmw(usize, &subscribe_repos_connections, .Sub, 1, .monotonic);
if (backfill) _ = @atomicRmw(usize, &subscribe_repos_backfills, .Sub, 1, .monotonic);
};
const ctx = SubscribeReposClient.Context{ .cursor = cursor, .backfill = backfill, .future = start.future, .peer = peer, .counted_by_state = &counted_by_state };
const upgraded = try http_api.upgradeWebsocket(SubscribeReposClient, request, &ctx);
if (!upgraded) {
return http_api.xrpcError(request, .upgrade_required, "InvalidRequest", "Expected WebSocket upgrade");
}
}
const SubscriptionStart = struct {
cursor: u64,
backfill: bool,
future: bool = false,
};
fn subscriptionStart(cursor_param: ?[]const u8, current_seq: u64) !SubscriptionStart {
const cursor = if (cursor_param) |raw| try std.fmt.parseInt(u64, raw, 10) else current_seq;
return .{ .cursor = cursor, .backfill = cursor < current_seq, .future = cursor > current_seq };
}
test "backfill reconnect limiter allows a burst then rejects within the window" {
backfill_slots = @splat(.{});
const ip = "203.0.113.7";
var i: u32 = 0;
while (i < max_backfill_connects_per_window) : (i += 1) {
try std.testing.expect(backfillReconnectAllowed(ip, 1000));
}
try std.testing.expect(!backfillReconnectAllowed(ip, 1000));
try std.testing.expect(!backfillReconnectAllowed(ip, 1000 + backfill_window_seconds - 1));
try std.testing.expect(backfillReconnectAllowed(ip, 1000 + backfill_window_seconds));
try std.testing.expect(backfillReconnectAllowed("203.0.113.8", 1000));
try std.testing.expect(backfillReconnectAllowed("", 1000));
backfill_slots = @splat(.{});
}
test "subscribeRepos starts live unless a historical cursor is explicit" {
try std.testing.expectEqual(SubscriptionStart{ .cursor = 42, .backfill = false }, try subscriptionStart(null, 42));
try std.testing.expectEqual(SubscriptionStart{ .cursor = 0, .backfill = true }, try subscriptionStart("0", 42));
try std.testing.expectEqual(SubscriptionStart{ .cursor = 42, .backfill = false }, try subscriptionStart("42", 42));
try std.testing.expectError(error.InvalidCharacter, subscriptionStart("nope", 42));
try std.testing.expectEqual(SubscriptionStart{ .cursor = 73716, .backfill = false, .future = true }, try subscriptionStart("73716", 42));
}
pub fn getRepoStatus(request: *http_api.Request) !void {
var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);
defer arena.deinit();
const allocator = arena.allocator();
var did_buf: [256]u8 = undefined;
const did = http_api.queryParam(request.url.raw, "did", &did_buf) orelse {
return http_api.xrpcError(request, .bad_request, "InvalidRequest", "Missing did");
};
const body = store.writeRepoStatusJson(allocator, did) catch |err| switch (err) {
error.RepoNotFound => return http_api.xrpcError(request, .not_found, "RepoNotFound", "Repo not found"),
else => return err,
};
return http_api.json(request, .ok, body);
}
pub fn notifyOfUpdate(request: *http_api.Request) !void {
return http_api.json(request, .ok, "{}");
}
pub fn requestCrawl(request: *http_api.Request) !void {
return http_api.json(request, .ok, "{}");
}
/// Which sessions may read an account's own repo while it is taken down or
/// deactivated. `export_session` admits the limited session a taken-down
/// account gets, on the reads it needs to migrate away (getRepo, getBlob,
/// listBlobs); other reads take a full session.
fn requireRepoAvailable(request: *http_api.Request, allocator: std.mem.Allocator, did: []const u8, export_session: bool) !void {
const status = store.accountStatus(did) catch |err| switch (err) {
error.RepoNotFound => return http_api.xrpcError(request, .not_found, "RepoNotFound", "Repo not found"),
else => return err,
};
if (status == .active) return;
// The admin token reads any account's repo, as on the reference PDS.
if (status != .deleted and http_api.hasAdminToken(request)) return;
switch (status) {
.active => return,
.suspended => return http_api.xrpcError(request, .bad_request, "RepoSuspended", "Repo is suspended"),
.takendown, .deactivated => {
if (http_api.headerValue(request, "authorization") != null) {
const auth_ctx = (if (export_session)
http_api.requireBearerAccessOrTakendown(request, allocator)
else
http_api.requireBearerAccess(request, allocator)) catch |err| {
return http_api.bearerErrorResponse(request, err);
};
if (std.mem.eql(u8, auth_ctx.account.did, did)) return;
}
return if (status == .takendown)
http_api.xrpcError(request, .bad_request, "RepoTakendown", "Repo has been taken down")
else
http_api.xrpcError(request, .bad_request, "RepoDeactivated", "Repo is deactivated");
},
.deleted => return http_api.xrpcError(request, .not_found, "RepoNotFound", "Repo not found"),
}
}
var subscribers = std.atomic.Value(usize).init(0);
/// Firehose (subscribeRepos) connections open now.
pub fn subscriberCount() usize {
return subscribers.load(.monotonic);
}
pub fn notifyCrawlers(force: bool) void {
const now = nowSeconds();
if (!force) {
const last = crawler_last_notified_s.load(.acquire);
if (last != 0 and now -% last < notify_threshold_s) return;
}
if (crawler_notify_in_flight.cmpxchgStrong(false, true, .acq_rel, .acquire) != null) return;
crawler_last_notified_s.store(now, .release);
const thread = std.Thread.spawn(.{}, notifyCrawlersThread, .{}) catch |err| {
crawler_notify_in_flight.store(false, .release);
log.err("sync request_crawl spawn failed err={s}\n", .{@errorName(err)});
return;
};
thread.detach();
}
fn nowSeconds() u32 {
return @truncate(@as(u64, @intCast(clock.nowSeconds())));
}
fn notifyCrawlersThread() void {
defer crawler_notify_in_flight.store(false, .release);
var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);
defer arena.deinit();
requestConfiguredCrawls(arena.allocator());
}
fn requestConfiguredCrawls(allocator: std.mem.Allocator) void {
const host = publicHostname(config.publicUrl()) orelse {
log.err("sync request_crawl skipped invalid_public_url url={s}\n", .{config.publicUrl()});
return;
};
var crawlers = std.mem.splitScalar(u8, config.crawlers(), ',');
while (crawlers.next()) |crawler_raw| {
const crawler = std.mem.trim(u8, crawler_raw, " \t\r\n/");
if (crawler.len == 0) continue;
requestCrawler(allocator, crawler, host) catch |err| {
log.err("sync request_crawl failed crawler={s} host={s} err={s}\n", .{ crawler, host, @errorName(err) });
continue;
};
}
}
fn requestCrawler(allocator: std.mem.Allocator, crawler: []const u8, host: []const u8) !void {
const url = try std.fmt.allocPrint(allocator, "{s}/xrpc/com.atproto.sync.requestCrawl", .{crawler});
const payload = try std.fmt.allocPrint(allocator, "{{\"hostname\":{f}}}", .{std.json.fmt(host, .{})});
var transport = zat.HttpTransport.init(store.currentIo(), allocator);
defer transport.deinit();
const result = try transport.fetch(.{
.url = url,
.method = .POST,
.payload = payload,
.content_type = "application/json",
.max_response_size = 64 * 1024,
});
if (@backingInt(result.status) < 200 or @backingInt(result.status) >= 300) return error.CrawlerRejected;
log.info("sync request_crawl ok crawler={s} host={s}\n", .{ crawler, host });
}
fn publicHostname(url: []const u8) ?[]const u8 {
const scheme = std.mem.indexOf(u8, url, "://") orelse return null;
var rest = url[scheme + 3 ..];
if (std.mem.indexOfScalar(u8, rest, '/')) |slash| rest = rest[0..slash];
if (std.mem.indexOfScalar(u8, rest, '@')) |at| rest = rest[at + 1 ..];
if (rest.len == 0) return null;
if (std.mem.startsWith(u8, rest, "[")) {
const close = std.mem.indexOfScalar(u8, rest, ']') orelse return null;
return rest[0 .. close + 1];
}
if (std.mem.indexOfScalar(u8, rest, ':')) |colon| return rest[0..colon];
return rest;
}
test "a firehose frame is not written once its connection is closed" {
var threaded: std.Io.Threaded = .init(std.testing.allocator, .{});
defer threaded.deinit();
var pair: [2]std.posix.socket_t = undefined;
try std.testing.expectEqual(@as(c_int, 0), std.c.socketpair(std.posix.AF.UNIX, std.posix.SOCK.STREAM, 0, &pair));
defer _ = std.c.close(pair[0]);
defer _ = std.c.close(pair[1]);
var conn: httpz.websocket.Conn = .{
._closed = true,
.started = 0,
.address = undefined,
.io = threaded.io(),
.stream = .{ .socket = .{ .handle = pair[0], .address = .{ .ip4 = std.Io.net.Ip4Address.loopback(0) } } },
};
try std.testing.expectError(error.Closed, SubscribeReposClient.writeFirehoseFrame(&conn, "frame"));
try std.testing.expectError(error.Closed, SubscribeReposClient.writeCloseFrame(&conn, "close"));
@atomicStore(bool, &conn._closed, false, .monotonic);
try SubscribeReposClient.writeFirehoseFrame(&conn, "frame");
var buf: [16]u8 = undefined;
try std.testing.expectEqual(@as(isize, 2 + "frame".len), std.c.read(pair[1], &buf, buf.len));
}