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

zat.dev/zttp

mirror of https://tangled.org/zat.dev/zttp

0
0
main
189 lines · 7.7 KB Raw History
//! Live smoke test against real origins. Not a unit test: it needs the
//! network and exercises what the loopback fixtures cannot, namely TLS,
//! gzip negotiated by a real server, a real redirect, and a peer that
//! accepts a SYN and never answers.
//!
//!   zig build smoke
//!   zig build smoke -- https://example.com/

const std = @import("std");
const zttp = @import("zttp");

const Check = struct {
    name: []const u8,
    ok: bool,
    detail: []const u8,
};

pub fn main(init: std.process.Init) !void {
    const allocator = init.gpa;
    const io = init.io;

    var client = zttp.Client.initWithUserAgent(io, allocator, "zttp-smoke/0 (+https://tangled.org/zat.dev/zttp)");
    defer client.deinit();

    const args = try init.minimal.args.toSlice(init.arena.allocator());
    if (args.len > 1) {
        const url = args[1];
        var res = try client.fetch(.{ .url = url, .capture_headers = &.{ "content-type", "server" } });
        defer res.deinit(allocator);
        std.debug.print("{d} {s} {d} bytes content-type={s} server={s}\n", .{
            @backingInt(res.status),
            url,
            res.body.len,
            res.headers.get("content-type") orelse "-",
            res.headers.get("server") orelse "-",
        });
        return;
    }

    var checks: std.ArrayList(Check) = .empty;
    defer checks.deinit(allocator);

    try checks.append(allocator, tlsAndGzip(&client, allocator));
    try checks.append(allocator, redirectFollowed(&client, allocator));
    try checks.append(allocator, redirectRewritesPost(&client, allocator));
    try checks.append(allocator, redirectSurfaced(&client, allocator));
    try checks.append(allocator, headDeadline(&client, allocator));
    try checks.append(allocator, capturedHeaders(&client, allocator));
    try checks.append(allocator, streamedToDisk(&client, io));

    var failed: usize = 0;
    for (checks.items) |c| {
        std.debug.print("{s} {s}: {s}\n", .{ if (c.ok) "ok  " else "FAIL", c.name, c.detail });
        if (!c.ok) failed += 1;
    }
    if (failed > 0) {
        std.debug.print("{d} of {d} checks failed\n", .{ failed, checks.items.len });
        std.process.exit(1);
    }
}

fn tlsAndGzip(client: *zttp.Client, allocator: std.mem.Allocator) Check {
    const name = "tls + gzip negotiated and decoded";
    var res = client.fetch(.{
        .url = "https://ziglang.org/",
        .capture_headers = &.{"content-encoding"},
    }) catch |err| return .{ .name = name, .ok = false, .detail = @errorName(err) };
    defer res.deinit(allocator);
    const encoding = res.headers.get("content-encoding") orelse "identity";
    const gzipped = std.ascii.eqlIgnoreCase(encoding, "gzip");
    const looks_html = std.mem.indexOf(u8, res.body, "<html") != null or std.mem.indexOf(u8, res.body, "<!DOCTYPE") != null;
    const ok = res.status == .ok and gzipped and looks_html;
    return .{
        .name = name,
        .ok = ok,
        .detail = if (ok) "200, content-encoding: gzip, body is decoded html" else if (!gzipped) "origin did not send gzip" else "unexpected status or undecoded body",
    };
}

fn redirectFollowed(client: *zttp.Client, allocator: std.mem.Allocator) Check {
    const name = "redirect followed for GET";
    var res = client.fetch(.{ .url = "http://ziglang.org/" }) catch |err|
        return .{ .name = name, .ok = false, .detail = @errorName(err) };
    defer res.deinit(allocator);
    return .{
        .name = name,
        .ok = res.status == .ok,
        .detail = if (res.status == .ok) "http -> https landed on 200" else "did not land on 200",
    };
}

fn redirectRewritesPost(client: *zttp.Client, allocator: std.mem.Allocator) Check {
    const name = "301 on POST is followed as a bodiless GET";
    var res = client.fetch(.{
        .url = "http://ziglang.org/",
        .method = .POST,
        .payload = "{}",
        .content_type = "application/json",
    }) catch |err| return .{ .name = name, .ok = false, .detail = @errorName(err) };
    defer res.deinit(allocator);
    return .{
        .name = name,
        .ok = res.status == .ok,
        .detail = if (res.status == .ok) "landed on 200 over https" else "did not land on 200",
    };
}

fn redirectSurfaced(client: *zttp.Client, allocator: std.mem.Allocator) Check {
    const name = "surface hands the 3xx to the caller";
    var res = client.fetch(.{ .url = "http://ziglang.org/", .on_redirect = .surface }) catch |err|
        return .{ .name = name, .ok = false, .detail = @errorName(err) };
    defer res.deinit(allocator);
    const class = @backingInt(res.status) / 100;
    return .{
        .name = name,
        .ok = class == 3,
        .detail = if (class == 3) "got the 3xx itself" else "expected a 3xx",
    };
}

fn headDeadline(client: *zttp.Client, _: std.mem.Allocator) Check {
    const name = "peer that never answers is abandoned at the head deadline";
    const saved = client.head_deadline_ns;
    defer client.head_deadline_ns = saved;
    client.head_deadline_ns = 2 * std.time.ns_per_s;
    // TEST-NET-1 (RFC 5737) is unrouted: the SYN goes nowhere and nothing
    // ever comes back, which is the shape of a blackholed peer.
    const started = std.Io.Timestamp.now(client.io, .awake).nanoseconds;
    const result = client.fetch(.{ .url = "http://192.0.2.1/" });
    const elapsed_ms = @divFloor(std.Io.Timestamp.now(client.io, .awake).nanoseconds - started, std.time.ns_per_ms);
    if (result) |*res| {
        var r = res.*;
        r.deinit(client.allocator);
        return .{ .name = name, .ok = false, .detail = "unexpectedly got a response" };
    } else |err| {
        const ok = err == error.ResponseHeadTimeout and elapsed_ms < 5000;
        return .{
            .name = name,
            .ok = ok,
            .detail = if (ok) "ResponseHeadTimeout within the deadline" else @errorName(err),
        };
    }
}

fn streamedToDisk(client: *zttp.Client, io: std.Io) Check {
    const name = "open + stream: body goes to a file, not the heap";
    const response = client.open(.{ .url = "https://ziglang.org/download/index.json" }) catch |err|
        return .{ .name = name, .ok = false, .detail = @errorName(err) };
    defer response.deinit();
    if (response.status != .ok) return .{ .name = name, .ok = false, .detail = "not 200" };

    const path = ".zig-cache/smoke-index.json";
    const cwd = std.Io.Dir.cwd();
    var file = cwd.createFile(io, path, .{ .read = true }) catch |err|
        return .{ .name = name, .ok = false, .detail = @errorName(err) };
    defer {
        file.close(io);
        cwd.deleteFile(io, path) catch {};
    }
    var wbuf: [8 * 1024]u8 = undefined;
    var fw = std.Io.File.Writer.initStreaming(file, io, &wbuf);
    var progress: zttp.Progress = .{};
    const n = response.stream(&fw.interface, .{ .progress = &progress }) catch |err|
        return .{ .name = name, .ok = false, .detail = @errorName(err) };
    fw.interface.flush() catch {};
    const on_disk = file.length(io) catch 0;
    const ok = n > 0 and on_disk == n and progress.done.load(.acquire);
    return .{
        .name = name,
        .ok = ok,
        .detail = if (ok) "decoded bytes on disk match the counter" else "size mismatch",
    };
}

fn capturedHeaders(client: *zttp.Client, allocator: std.mem.Allocator) Check {
    const name = "asked-for response headers are captured";
    var res = client.fetch(.{
        .url = "https://ziglang.org/",
        .capture_headers = &.{ "Content-Type", "x-not-sent" },
    }) catch |err| return .{ .name = name, .ok = false, .detail = @errorName(err) };
    defer res.deinit(allocator);
    const ct = res.headers.get("content-type");
    const ok = ct != null and res.headers.get("x-not-sent") == null;
    return .{
        .name = name,
        .ok = ok,
        .detail = if (ok) "content-type captured, absent header stays null" else "capture mismatch",
    };
}