diff --git a/CHANGELOG.md b/CHANGELOG.md index d4b224b..603e9c9 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,6 +1,6 @@ # Changelog -## 1.2.0 (2026-11-05) +## 1.2.0 (2026-11-30) ### Features @@ -29,6 +29,14 @@ - CI: the coverage job runs on Linux arm64 (Debian trixie container) instead of macOS, where kcov hung the unit-test binary until the step timed out on every run. It is no longer advisory, and fails below 90% line coverage +- Usage reporting moves from the `source` query parameter to the + `User-Agent` header, following serpapi-ruby and SerpApi#11027. Every + request (GET and the Image API POST alike) sends + `serpapi-zig/ zig/ (; )`, e.g. + `serpapi-zig/1.2.0 zig/0.16.0 (macos; aarch64)`, in place of std.http's + default `zig/0.16.0 (std.http)`. The Zig version is the compiler that + built the client and the platform is the build target. The value is a + compile-time constant, exported as `serpapi.user_agent` ### Behavior changes @@ -36,6 +44,13 @@ every request clears the previous failure, so they return null after a success or a transport error. Previously the last failure lingered, and a DNS error after a 404 still reported the 404 +- The client no longer adds `source=serpapi-zig:` to request URLs + or to the Image API form, so it no longer shows up in `lastError().url` + either +- Fix: a `source` passed to the constructor is sent once, as given. + Previously the library appended its own, and the request carried two + `source` values. A `source` passed to a call was, and still is, sent as + given ### Breaking changes diff --git a/README.md b/README.md index afcd220..6d87a0b 100644 --- a/README.md +++ b/README.md @@ -84,8 +84,8 @@ Released versions are listed on the [releases page](https://github.com/serpapi/serpapi-zig/releases); changes are recorded in [CHANGELOG.md](CHANGELOG.md). The version number lives in one place, `build.zig.zon`: `build.zig` forwards it to the library as -`serpapi.version`, which is what the client reports to serpapi.com, and -`rake release` reads it to name the tag. +`serpapi.version`, which is what the client reports to serpapi.com in its +`User-Agent` header, and `rake release` reads it to name the tag. ## Simple Usage @@ -170,9 +170,18 @@ The client reports its configuration back: ```zig client.engine() // ?[]const u8: default engine, "google" here client.apiKey() // ?[]const u8: the API key given to the constructor -serpapi.version // the library version, "1.2.0", reported to serpapi.com +serpapi.version // the library version, "1.2.0" +serpapi.user_agent // "serpapi-zig/1.2.0 zig/0.16.0 (macos; aarch64)" ``` +Every request sends `serpapi.user_agent` as its `User-Agent` header, so +SerpApi can see which library versions, Zig versions and platforms are in +use and focus testing on them. It names the library version, the Zig +compiler that built the client, and the build target's OS and CPU +architecture; it carries no search parameters and nothing about your +account. The client adds no `source` query parameter: a `source` you pass +yourself, to the constructor or a call, is sent as given. + Printing the client masks the API key, as serpapi-ruby's `inspect` does — the first and last four characters of a key longer than eight, `****` otherwise: @@ -358,7 +367,7 @@ connection, TLS) — such errors carry no details beyond the Zig error itself. ```zig var archived = client.searchArchive(search_id) catch |err| { if (client.lastError()) |info| { - // SerpApiError: HTTP 404 https://serpapi.com/searches/.json?source=serpapi-zig%3A1.2.0: Search not found. + // SerpApiError: HTTP 404 https://serpapi.com/searches/.json: Search not found. std.debug.print("{t}: HTTP {?d} {?s}: {s}\n", .{ err, if (info.status) |s| @intFromEnum(s) else null, info.url, info.message, }); @@ -507,13 +516,15 @@ binaries and merges the two reports. Full details in [CHANGELOG.md](CHANGELOG.md). -- [2026-11-05] 1.2.0 Image API, error details and a safer client dump +- [2026-11-30] 1.2.0 Image API, error details, User-Agent usage reporting and a safer client dump - Added `uploadImage()` and `uploadImageBytes()` (and typed `uploadImageAs()` / `uploadImageBytesAs()`) for the [Image API](https://serpapi.com/image-api), returning the `image_id` to use with engines such as `google_lens`. The `api_key` goes in the form body, never in the URL, and images over 500 KiB fail fast with `error.ImageTooLarge` - Added `lastError()`, returning a `serpapi.ErrorInfo` with the message, HTTP status, request URL (without the `api_key`) and `search_id` of the last failure - Printing a client with `{f}` masks the API key (`abcd****wxyz`) - `errorMessage()` and `lastError()` describe the most recent request only: a success or a transport error clears the previous failure - **Breaking:** the API key moved out of `Client.params` (use `apiKey()`), `Client.last_error` is now `?serpapi.ErrorInfo`, and `serpapi.Error` gains `ImageTooLarge`. Pin `v1.1.0` to keep the old API - `rake release` runs lint, tests, integration tests and oobt, and only from a clean `master` + - Every request identifies the library, the Zig version and the platform in its `User-Agent` header (`serpapi.user_agent`, e.g. `serpapi-zig/1.2.0 zig/0.16.0 (macos; aarch64)`) instead of the `source` query parameter, as serpapi-ruby does + - A `source` passed to the constructor is sent once, as given; it was previously sent alongside the library's own - [2026-09-23] 1.1.0 Markdown output, timeouts and connection reuse - Added `md()` and `searchArchiveMd()` for `output=md` results optimized for LLMs and AI agents - `serpapi.Error` is exported from the module root, and `serpapi.version` comes from `build.zig.zon` diff --git a/build.zig b/build.zig index 9895d47..47f46cf 100644 --- a/build.zig +++ b/build.zig @@ -13,7 +13,7 @@ pub fn build(b: *std.Build) void { }); // The library version reported to serpapi.com comes straight from the - // package manifest, so `rake release` and the `source` parameter agree. + // package manifest, so `rake release` and the User-Agent agree. const build_options = b.addOptions(); build_options.addOption([]const u8, "version", manifest.version); mod.addOptions("build_options", build_options); diff --git a/src/client.zig b/src/client.zig index 42baae0..bbba174 100644 --- a/src/client.zig +++ b/src/client.zig @@ -9,12 +9,29 @@ //! * persistent HTTP connection (keep-alive, reused between requests) const std = @import("std"); +const builtin = @import("builtin"); const Allocator = std.mem.Allocator; -/// Library version, reported to the backend through the `source` parameter. +/// Library version, reported to the backend in `user_agent`. /// Single-sourced from `build.zig.zon` via `build.zig`. pub const version: []const u8 = @import("build_options").version; +/// `User-Agent` header sent with every request, so serpapi.com can report +/// library usage by version, Zig version and platform, e.g. +/// `serpapi-zig/1.2.0 zig/0.16.0 (macos; aarch64)`. The client is compiled +/// in, so the Zig version is the compiler's and the platform is the build +/// target's. +pub const user_agent = userAgent(version, builtin.zig_version_string, builtin.os.tag, builtin.cpu.arch); + +fn userAgent( + comptime library_version: []const u8, + comptime zig_version: []const u8, + comptime os: std.Target.Os.Tag, + comptime arch: std.Target.Cpu.Arch, +) []const u8 { + return "serpapi-zig/" ++ library_version ++ " zig/" ++ zig_version ++ " (" ++ @tagName(os) ++ "; " ++ @tagName(arch) ++ ")"; +} + /// Backend service host. pub const backend = "serpapi.com"; @@ -186,8 +203,6 @@ pub const Client = struct { } try self.addParamValue(field.name, @field(options, field.name)); } - // track the zig library as a client for statistic purpose - try self.addParam("source", "serpapi-zig:" ++ version); return self; } @@ -674,10 +689,6 @@ pub const Client = struct { }; } - /// Constructor defaults the Image API takes; search defaults such as - /// `engine` or `output` are meaningless there and are not sent. - const image_form_defaults = [_][]const u8{ "api_key", "source" }; - /// Read the image file at `path`, checking its size before loading it. /// Caller owns the result. fn readImage(self: *Client, path: []const u8) ![]u8 { @@ -723,9 +734,11 @@ pub const Client = struct { } /// Write the Image API multipart/form-data body: the call `params`, - /// then the `api_key` and `source` defaults they do not override, then - /// the image itself in the `image` field. A call parameter named - /// `image` would send a second `image` part, so it is a compile error. + /// then the constructor `api_key` unless they override it, then the + /// image itself in the `image` field. Search defaults such as `engine` + /// or `output` are meaningless there and are not sent. A call parameter + /// named `image` would send a second `image` part, so it is a compile + /// error. fn writeImageForm( self: *const Client, w: *std.Io.Writer, @@ -742,13 +755,11 @@ pub const Client = struct { try writeFormValue(w, @field(params, field.name)); try w.writeAll("\r\n"); } - for (image_form_defaults) |key| { - if (hasParam(params, key)) continue; - const value = self.param(key) orelse continue; - try writeFormFieldHead(w, boundary, key); - try w.writeAll(value); + if (!hasParam(params, "api_key")) if (self.apiKey()) |key| { + try writeFormFieldHead(w, boundary, "api_key"); + try w.writeAll(key); try w.writeAll("\r\n"); - } + }; try w.print("--{s}\r\nContent-Disposition: form-data; name=\"image\"; filename=\"", .{boundary}); try writeQuoted(w, file_name); @@ -918,7 +929,10 @@ pub const Client = struct { // non-200 status rather than being replayed as a GET. .redirect_behavior = if (request.body == null) @enumFromInt(3) else .unhandled, .keep_alive = keep_alive, - .headers = .{ .content_type = if (request.body) |body| .{ .override = body.content_type } else .default }, + .headers = .{ + .user_agent = .{ .override = user_agent }, + .content_type = if (request.body) |body| .{ .override = body.content_type } else .default, + }, }); defer req.deinit(); @@ -1085,7 +1099,8 @@ test "constructor defaults" { try testing.expect(client.persistent); try testing.expectEqual(@as(?[]const u8, null), client.engine()); try testing.expectEqual(@as(?[]const u8, null), client.apiKey()); - try testing.expectEqualStrings("serpapi-zig:" ++ version, client.param("source").?); + // the library reports itself in the User-Agent header, not a parameter + try testing.expectEqual(@as(usize, 0), client.params.items.len); } test "constructor options" { @@ -1127,7 +1142,7 @@ test "buildUrl merges defaults with call parameters" { defer testing.allocator.free(url); try testing.expectEqualStrings( - "https://serpapi.com/search?q=coffee&api_key=secret&engine=google&source=serpapi-zig%3A" ++ version, + "https://serpapi.com/search?q=coffee&api_key=secret&engine=google", url, ); } @@ -1140,7 +1155,7 @@ test "buildUrl call parameters override defaults" { defer testing.allocator.free(url); try testing.expectEqualStrings( - "https://serpapi.com/search?engine=bing&source=serpapi-zig%3A" ++ version, + "https://serpapi.com/search?engine=bing", url, ); } @@ -1157,7 +1172,7 @@ test "buildUrl stringifies numbers and booleans" { defer testing.allocator.free(url); try testing.expectEqualStrings( - "https://serpapi.com/locations.json?q=Austin&limit=3&no_cache=true&source=serpapi-zig%3A" ++ version, + "https://serpapi.com/locations.json?q=Austin&limit=3&no_cache=true", url, ); } @@ -1170,7 +1185,7 @@ test "buildUrl percent-encodes reserved characters" { defer testing.allocator.free(url); try testing.expectEqualStrings( - "https://serpapi.com/search?q=fresh%20coffee%20%26%20tea%3D100%25&source=serpapi-zig%3A" ++ version, + "https://serpapi.com/search?q=fresh%20coffee%20%26%20tea%3D100%25", url, ); } @@ -1184,14 +1199,14 @@ test "buildUrl extra parameters yield to call parameters" { const url = try client.buildUrl(testing.allocator, "/search", .{ .q = "coffee" }, extra); defer testing.allocator.free(url); try testing.expectEqualStrings( - "https://serpapi.com/search?q=coffee&output=html&source=serpapi-zig%3A" ++ version, + "https://serpapi.com/search?q=coffee&output=html", url, ); const override = try client.buildUrl(testing.allocator, "/search", .{ .q = "coffee", .output = "json" }, extra); defer testing.allocator.free(override); try testing.expectEqualStrings( - "https://serpapi.com/search?q=coffee&output=json&source=serpapi-zig%3A" ++ version, + "https://serpapi.com/search?q=coffee&output=json", override, ); } @@ -1205,7 +1220,7 @@ test "buildUrl markdown output" { const url = try client.buildUrl(testing.allocator, "/search", .{ .q = "coffee" }, extra); defer testing.allocator.free(url); try testing.expectEqualStrings( - "https://serpapi.com/search?q=coffee&output=md&source=serpapi-zig%3A" ++ version, + "https://serpapi.com/search?q=coffee&output=md", url, ); } @@ -1577,14 +1592,14 @@ test "recordUrl leaves the api key out of the reported URL" { try testing.expectError(Error.SerpApiError, client.checkResponse("{\"error\":\"Invalid API key.\"}", .unauthorized)); try client.recordUrl("/search", .{ .q = "coffee" }, &.{.{ .key = "output", .value = "html" }}); try testing.expectEqualStrings( - "https://serpapi.com/search?q=coffee&output=html&engine=google&source=serpapi-zig%3A" ++ version, + "https://serpapi.com/search?q=coffee&output=html&engine=google", client.lastError().?.url.?, ); // a key passed with the call is left out as well try client.recordUrl("/account", .{ .api_key = "call_key" }, &.{}); try testing.expectEqualStrings( - "https://serpapi.com/account?engine=google&source=serpapi-zig%3A" ++ version, + "https://serpapi.com/account?engine=google", client.lastError().?.url.?, ); try testing.expectEqual(std.http.Status.unauthorized, client.lastError().?.status.?); @@ -1593,7 +1608,7 @@ test "recordUrl leaves the api key out of the reported URL" { const url = try client.buildUrl(testing.allocator, "/account", .{ .api_key = "call_key" }, &.{}); defer testing.allocator.free(url); try testing.expectEqualStrings( - "https://serpapi.com/account?api_key=call_key&engine=google&source=serpapi-zig%3A" ++ version, + "https://serpapi.com/account?api_key=call_key&engine=google", url, ); } @@ -1724,7 +1739,6 @@ test "writeImageForm sends the image and api_key in the body, not search default try testing.expectEqualStrings( "--BOUNDARY\r\nContent-Disposition: form-data; name=\"api_key\"\r\n\r\nsecret\r\n" ++ - "--BOUNDARY\r\nContent-Disposition: form-data; name=\"source\"\r\n\r\nserpapi-zig:" ++ version ++ "\r\n" ++ "--BOUNDARY\r\nContent-Disposition: form-data; name=\"image\"; filename=\"image.png\"\r\n" ++ "Content-Type: image/png\r\n\r\n" ++ png_1x1 ++ "\r\n--BOUNDARY--\r\n", body.written(), @@ -1742,7 +1756,6 @@ test "writeImageForm call parameters override the constructor key" { try testing.expectEqualStrings( "--B\r\nContent-Disposition: form-data; name=\"api_key\"\r\n\r\noverride\r\n" ++ "--B\r\nContent-Disposition: form-data; name=\"retries\"\r\n\r\n2\r\n" ++ - "--B\r\nContent-Disposition: form-data; name=\"source\"\r\n\r\nserpapi-zig:" ++ version ++ "\r\n" ++ // quotes and line breaks cannot break out of the header "--B\r\nContent-Disposition: form-data; name=\"image\"; filename=\"na%22me%0D%0A.jpg\"\r\n" ++ "Content-Type: image/jpeg\r\n\r\ndata\r\n--B--\r\n", @@ -1933,3 +1946,120 @@ test "image upload helpers clean up on allocation failure" { } }.run, .{path}); } + +test "userAgent names the library, the Zig version and the platform" { + try testing.expectEqualStrings( + "serpapi-zig/1.2.0 zig/0.16.0 (macos; aarch64)", + comptime userAgent("1.2.0", "0.16.0", .macos, .aarch64), + ); + try testing.expectEqualStrings( + "serpapi-zig/1.2.0 zig/0.16.0 (linux; x86_64)", + comptime userAgent("1.2.0", "0.16.0", .linux, .x86_64), + ); + try testing.expectEqualStrings( + "serpapi-zig/1.2.0 zig/0.16.0 (windows; x86)", + comptime userAgent("1.2.0", "0.16.0", .windows, .x86), + ); + try testing.expectEqualStrings( + "serpapi-zig/1.2.0 zig/0.17.0-dev.42+0123abcd (wasi; wasm32)", + comptime userAgent("1.2.0", "0.17.0-dev.42+0123abcd", .wasi, .wasm32), + ); + + // this build: the version from build.zig.zon and the native target + try testing.expectEqualStrings( + "serpapi-zig/" ++ version ++ " zig/" ++ builtin.zig_version_string ++ + " (" ++ @tagName(builtin.os.tag) ++ "; " ++ @tagName(builtin.cpu.arch) ++ ")", + user_agent, + ); +} + +test "every request identifies the library in the User-Agent header" { + var client = try Client.init(testing.allocator, .{ .timeout = 30 }); + defer client.deinit(); + const io = client.threaded.io(); + + const loopback: std.Io.net.IpAddress = try .parseIp4("127.0.0.1", 0); + var server = try loopback.listen(io, .{}); + defer server.deinit(io); + + // Records the request line and User-Agent of a GET, then of a POST. + const Capture = struct { + const Request = struct { + line: [128]u8 = undefined, + line_len: usize = 0, + user_agent: [128]u8 = undefined, + user_agent_len: usize = 0, + }; + requests: [2]Request = .{ .{}, .{} }, + + fn serve(capture: *@This(), server_ptr: *std.Io.net.Server, server_io: std.Io) !void { + for (&capture.requests) |*request| { + var stream = try server_ptr.accept(server_io); + defer stream.close(server_io); + var read_buffer: [4096]u8 = undefined; + var reader = stream.reader(server_io, &read_buffer); + + const line = std.mem.trimEnd(u8, try reader.interface.takeDelimiterInclusive('\n'), "\r\n"); + @memcpy(request.line[0..line.len], line); + request.line_len = line.len; + var content_length: usize = 0; + while (true) { + const header = std.mem.trimEnd(u8, try reader.interface.takeDelimiterInclusive('\n'), "\r\n"); + if (header.len == 0) break; + const colon = std.mem.indexOfScalar(u8, header, ':') orelse continue; + const value = std.mem.trim(u8, header[colon + 1 ..], " "); + if (std.ascii.eqlIgnoreCase(header[0..colon], "user-agent")) { + @memcpy(request.user_agent[0..value.len], value); + request.user_agent_len = value.len; + } else if (std.ascii.eqlIgnoreCase(header[0..colon], "content-length")) { + content_length = try std.fmt.parseInt(usize, value, 10); + } + } + try reader.interface.discardAll(content_length); + + var write_buffer: [256]u8 = undefined; + var writer = stream.writer(server_io, &write_buffer); + try writer.interface.writeAll("HTTP/1.1 200 OK\r\nContent-Length: 2\r\nConnection: close\r\n\r\n{}"); + try writer.interface.flush(); + } + } + }; + var capture: Capture = .{}; + var served = try io.concurrent(Capture.serve, .{ &capture, &server, io }); + defer _ = served.cancel(io) catch {}; + + const base = try std.fmt.allocPrint(testing.allocator, "http://127.0.0.1:{d}", .{server.socket.address.getPort()}); + defer testing.allocator.free(base); + const search_url = try std.mem.concat(testing.allocator, u8, &.{ base, "/search?q=coffee" }); + defer testing.allocator.free(search_url); + const image_url_local = try std.mem.concat(testing.allocator, u8, &.{ base, "/image" }); + defer testing.allocator.free(image_url_local); + + var body: std.Io.Writer.Allocating = .init(testing.allocator); + defer body.deinit(); + _ = try client.fetch(.{ .url = search_url }, &body.writer); + _ = try client.fetch(.{ + .url = image_url_local, + .body = .{ .content_type = "multipart/form-data; boundary=B", .bytes = "--B--\r\n" }, + }, &body.writer); + try served.await(io); + + try testing.expectEqualStrings("GET /search?q=coffee HTTP/1.1", capture.requests[0].line[0..capture.requests[0].line_len]); + try testing.expectEqualStrings("POST /image HTTP/1.1", capture.requests[1].line[0..capture.requests[1].line_len]); + for (capture.requests) |request| { + try testing.expectEqualStrings(user_agent, request.user_agent[0..request.user_agent_len]); + } +} + +test "a source parameter from the caller is sent once, as given" { + var client = try Client.init(testing.allocator, .{ .source = "my-app" }); + defer client.deinit(); + + const url = try client.buildUrl(testing.allocator, "/search", .{ .q = "coffee" }, &.{}); + defer testing.allocator.free(url); + try testing.expectEqualStrings("https://serpapi.com/search?q=coffee&source=my-app", url); + + const call = try client.buildUrl(testing.allocator, "/search", .{ .q = "coffee", .source = "my-call" }, &.{}); + defer testing.allocator.free(call); + try testing.expectEqualStrings("https://serpapi.com/search?q=coffee&source=my-call", call); +} diff --git a/src/root.zig b/src/root.zig index 89fc93f..9b25bd9 100644 --- a/src/root.zig +++ b/src/root.zig @@ -9,6 +9,7 @@ const std = @import("std"); pub const client = @import("client.zig"); pub const version = client.version; +pub const user_agent = client.user_agent; pub const image_max_size = client.image_max_size; pub const Client = client.Client; pub const Param = client.Param; diff --git a/test/integration.zig b/test/integration.zig index 723d7d4..b183711 100644 --- a/test/integration.zig +++ b/test/integration.zig @@ -7,6 +7,7 @@ //! * search archive API //! * image API (upload, then a Google Lens search on the uploaded image) //! * error reporting on invalid input (message, HTTP status, key-free URL) +//! * usage reporting (User-Agent header, caller-provided `source`) //! //! Tests that need an API key read the SERPAPI_KEY environment variable //! and are skipped otherwise (e.g. `SERPAPI_KEY=secret zig build itest`). @@ -287,6 +288,24 @@ test "persistent connection performs multiple searches" { } } +test "searches identify the library in the User-Agent, and a caller's source goes through" { + const key = apiKey(testing.allocator) orelse return error.SkipZigTest; + defer testing.allocator.free(key); + + // The header itself is checked offline: serpapi.com echoes neither it + // nor `source` back. This shows the backend accepts both. + try testing.expect(std.mem.startsWith(u8, serpapi.user_agent, "serpapi-zig/" ++ serpapi.version ++ " zig/")); + + var client = try serpapi.Client.init(testing.allocator, .{ .api_key = key, .engine = "google", .source = "serpapi-zig-itest" }); + defer client.deinit(); + + var result = try client.search(.{ .q = "coffee" }); + defer result.deinit(); + const metadata = result.value.object.get("search_metadata").?.object; + try testing.expectEqualStrings("Success", metadata.get("status").?.string); + try testing.expect(result.value.object.get("search_parameters").?.object.get("source") == null); +} + /// Smallest valid PNG: a 1x1 transparent pixel. const png_1x1 = "\x89PNG\r\n\x1a\n\x00\x00\x00\x0dIHDR\x00\x00\x00\x01\x00\x00\x00\x01\x08\x06\x00\x00\x00\x1f\x15\xc4\x89" ++ "\x00\x00\x00\x0aIDATx\x9cc\x00\x01\x00\x00\x05\x00\x01\x0d\x0a\x2d\xb4\x00\x00\x00\x00IEND\xaeB\x60\x82";