From c9f21bdff2bea88861565a1b68ee26437a77fb91 Mon Sep 17 00:00:00 2001 From: Victor Benarbia Date: Mon, 2 Nov 2026 20:21:45 -0600 Subject: [PATCH 1/3] Parity fixes: lastError, masked key, archive tests, safer release - F13: Client.lastError() returns a serpapi.ErrorInfo with the message, HTTP status, request URL without the api_key, and the search id of the failed search, mirroring serpapi-ruby's SerpApiError fields - F13b: Client.format masks the API key the way serpapi-ruby's inspect does. The key now lives in its own field behind a many-item pointer, so `{any}` on the client or its params prints an address, not the key - D3: live tests for searchArchiveAs, searchArchiveHtml, searchArchiveMd, locationAs, and lastError (401 on a bad key, 404 on an unknown archive) - D5: rake release runs lint, test, itest and oobt first, behind a preflight that needs SERPAPI_KEY and an empty `git status --porcelain` (`git diff --quiet` missed staged and untracked files) - D6: README documents engine(), apiKey(), serpapi.version, printing the client, and lastError() Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 24 +++ README.md | 42 ++++- Rakefile | 18 ++- src/client.zig | 357 +++++++++++++++++++++++++++++++++++++++---- src/root.zig | 1 + test/integration.zig | 79 +++++++++- 6 files changed, 482 insertions(+), 39 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 207bc23..af06837 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,29 @@ # Changelog +## Unreleased + +- `Client.lastError()` returns a `serpapi.ErrorInfo` with the details of the + last failure, mirroring serpapi-ruby's `SerpApiError`: `message` (as + `errorMessage()`), the HTTP `status`, the request `url` without the + `api_key`, and the `search_id` from the error payload +- `Client.format`: printing a client with `{f}` shows its configuration + with the API key masked, as serpapi-ruby's `inspect` does + (`abcd****wxyz`, `****` for a key of eight characters or fewer) +- README documents `engine()`, `apiKey()` and `serpapi.version` +- `rake release` runs `lint`, `test`, `itest` and `oobt` before tagging, + and refuses to start unless `SERPAPI_KEY` is set and `git status + --porcelain` is empty (the previous `git diff --quiet` missed staged and + untracked files) + +### Behavior changes + +- The API key is no longer kept in `Client.params`: it moved to its own + `api_key` field, which `{any}` prints as an address, so dumping the + client state no longer leaks it. `apiKey()` is unchanged; code that read + the key from `client.params.items` must call `apiKey()` instead +- `Client.last_error` is now a `?serpapi.ErrorInfo` instead of `?[]u8`; + `errorMessage()` is unchanged + ## 1.1.0 (2026-09-23) - Markdown output: `md` (Search API) and `searchArchiveMd` (Search Archive diff --git a/README.md b/README.md index 26dde54..305f5cf 100644 --- a/README.md +++ b/README.md @@ -168,6 +168,26 @@ All fields are optional. Parameters passed to a method call override the defaults provided to the constructor. Call `client.deinit()` when the client is no longer needed; it closes the connection and frees all resources. +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.1.0", reported to serpapi.com +``` + +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: + +```zig +std.debug.print("{f}\n", .{client}); +// serpapi.Client{ .engine = "google", .timeout = 30, .persistent = true, .api_key = "abcd****wxyz" } +``` + +The key is stored apart from the other defaults, so dumping the client's +fields with `{any}` does not reveal it either. + `timeout` bounds the whole request — connecting, TLS handshake, and reading the response — and a request that overruns it fails with `error.Timeout` (details in `client.errorMessage()`), dropping the stalled connection so the @@ -298,8 +318,26 @@ requested type), `error.Timeout` (the request overran the client's `timeout`), plus any network / TLS / allocation errors propagated from the standard library. The four client errors are grouped in `serpapi.Error`. -A `Client` is not thread-safe — `errorMessage()` reports the last failure seen -by that instance — so use one client per thread. +`client.lastError()` returns the details of the last failure, mirroring +serpapi-ruby's `SerpApiError`: the `message` (same as `errorMessage()`), the +HTTP `status`, the request `url` with the `api_key` left out — safe to log — +and the `search_id` when serpapi.com assigned one to the failed search. +`status` is null when no response arrived (`error.Timeout`). + +```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.1.0: 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, + }); + } + return err; +}; +``` + +A `Client` is not thread-safe — `errorMessage()` and `lastError()` report the +last failure seen by that instance — so use one client per thread. ## Search asynchronous diff --git a/Rakefile b/Rakefile index 7d5fba5..bf4c698 100644 --- a/Rakefile +++ b/Rakefile @@ -127,15 +127,23 @@ namespace :install do end end -desc 'release: tag the current version and push it to GitHub' -task :release do +namespace :release do + desc 'fail fast unless the working tree is clean and SERPAPI_KEY is set' + task :preflight do + # `git diff --quiet` misses staged and untracked files; porcelain lists all + dirty = `git status --porcelain` + raise 'git status failed' unless $?.success? + raise "working tree is dirty, commit first:\n#{dirty}" unless dirty.strip.empty? + raise 'SERPAPI_KEY is required: without it the integration tests skip' if ENV['SERPAPI_KEY'].to_s.empty? + end +end + +desc 'release: run every check, then tag the current version and push it to GitHub' +task release: %i[release:preflight lint test itest oobt] do version = File.read('build.zig.zon')[/\.version\s*=\s*"([^"]+)"/, 1] raise 'cannot read version from build.zig.zon' if version.nil? puts "releasing v#{version}" - sh 'git diff --quiet' do |ok, _| - raise 'working tree is dirty, commit first' unless ok - end sh "git tag -a v#{version} -m 'Release v#{version}'" sh 'git push origin master --tags' puts "released: https://github.com/serpapi/serpapi-zig/releases/tag/v#{version}" diff --git a/src/client.zig b/src/client.zig index ba60f04..927c370 100644 --- a/src/client.zig +++ b/src/client.zig @@ -44,6 +44,45 @@ pub const Error = error{ Timeout, }; +/// Details of the last failed request, from `Client.lastError()`. The +/// strings are owned by the client and valid until its next failure or +/// `deinit`. +pub const ErrorInfo = struct { + /// What went wrong; the same text as `Client.errorMessage()`. + message: []const u8, + /// HTTP status of the failed response, or null when no response was + /// received (`error.Timeout`). + status: ?std.http.Status = null, + /// The request URL without the `api_key`, safe to log. + url: ?[]const u8 = null, + /// `search_metadata.id` from the error payload, when serpapi.com + /// assigned one to the failed search. + search_id: ?[]const u8 = null, +}; + +/// The API key as held by the client. Formatting with `{f}` masks it, and +/// it is kept behind a many-item pointer so that `{any}` on the client +/// prints an address, never the key bytes. +const Secret = struct { + ptr: [*]const u8, + len: usize, + + fn reveal(self: Secret) []const u8 { + return self.ptr[0..self.len]; + } + + /// Mask the key as serpapi-ruby's `Client#inspect` does: the first and + /// last four characters of a key longer than eight, `****` otherwise. + pub fn format(self: Secret, w: *std.Io.Writer) std.Io.Writer.Error!void { + const key = self.reveal(); + if (key.len > 8) { + try w.print("{s}****{s}", .{ key[0..4], key[key.len - 4 ..] }); + } else { + try w.writeAll("****"); + } + } +}; + /// Client for SerpApi.com. /// /// Query parameters are plain anonymous structs, the same shape @@ -70,14 +109,18 @@ pub const Client = struct { /// Event loop / thread pool backing std.http. Heap-stable inside Client. threaded: std.Io.Threaded, http: std.http.Client, - /// Default query parameters applied to every request (owned copies). + /// Default query parameters applied to every request (owned copies), + /// except the API key, which lives in `api_key`. params: std.array_list.Managed(Param), + /// API key provided to the constructor (owned), see `apiKey`. Sent + /// along with `params`, but never printed. + api_key: ?Secret = null, /// HTTP request timeout in seconds, 0 to wait forever [default: 120]. timeout: u32, /// Keep the connection open between requests (3-4x faster). [default: true] persistent: bool, - /// Last error payload returned by serpapi.com (owned), see `errorMessage`. - last_error: ?[]u8 = null, + /// Last failure (owned strings), see `lastError` and `errorMessage`. + last_error: ?ErrorInfo = null, /// Configuration-only option names; every other `init` field becomes a /// default query parameter, mirroring serpapi-ruby's constructor hash. @@ -117,9 +160,15 @@ pub const Client = struct { }; self.http = .{ .allocator = allocator, .io = self.threaded.io() }; errdefer self.freeParams(); + errdefer self.freeApiKey(); inline for (@typeInfo(@TypeOf(options)).@"struct".fields) |field| { if (comptime isConfigOption(field.name)) continue; + if (comptime std.mem.eql(u8, field.name, "api_key")) { + const key = try allocator.dupe(u8, options.api_key); + self.api_key = .{ .ptr = key.ptr, .len = key.len }; + continue; + } try self.addParamValue(field.name, @field(options, field.name)); } // track the zig library as a client for statistic purpose @@ -131,7 +180,8 @@ pub const Client = struct { /// Release all resources held by the client and close open connections. pub fn deinit(self: *Client) void { const allocator = self.allocator; - if (self.last_error) |msg| allocator.free(msg); + self.clearLastError(); + self.freeApiKey(); self.freeParams(); self.http.deinit(); self.threaded.deinit(); @@ -275,15 +325,50 @@ pub const Client = struct { /// User secret API key as provided to the constructor, if any. pub fn apiKey(self: *const Client) ?[]const u8 { - return self.param("api_key"); + const key = self.api_key orelse return null; + return key.reveal(); } - /// Error payload from serpapi.com for the last failed request, if any. + /// Description of the last failed request, if any: the error payload + /// from serpapi.com, the raw body of a non-200 response, or the client's + /// own message. See `lastError` for the HTTP status, URL and search id. pub fn errorMessage(self: *const Client) ?[]const u8 { + const info = self.last_error orelse return null; + return info.message; + } + + /// Details of the last failed request, if any: message, HTTP status, + /// URL without the api_key, and search id. Mirrors the fields of + /// serpapi-ruby's `SerpApiError`. + /// + /// ```zig + /// var results = client.search(.{ .q = "coffee" }) catch |err| { + /// if (client.lastError()) |info| { + /// std.debug.print("{t}: HTTP {?d} {?s}: {s}\n", .{ + /// err, if (info.status) |s| @intFromEnum(s) else null, info.url, info.message, + /// }); + /// } + /// return err; + /// }; + /// ``` + pub fn lastError(self: *const Client) ?ErrorInfo { return self.last_error; } + /// Print the client configuration with the API key masked, as + /// serpapi-ruby's `Client#inspect` does, e.g. + /// `serpapi.Client{ .engine = "google", .timeout = 120, .persistent = true, .api_key = "abcd****wxyz" }`. + /// Use it with `{f}`: `std.debug.print("{f}\n", .{client})`. + pub fn format(self: *const Client, w: *std.Io.Writer) std.Io.Writer.Error!void { + try w.writeAll("serpapi.Client{ .engine = "); + if (self.engine()) |name| try w.print("\"{s}\"", .{name}) else try w.writeAll("null"); + try w.print(", .timeout = {d}, .persistent = {}, .api_key = ", .{ self.timeout, self.persistent }); + if (self.api_key) |key| try w.print("\"{f}\"", .{key}) else try w.writeAll("null"); + try w.writeAll(" }"); + } + fn param(self: *const Client, key: []const u8) ?[]const u8 { + if (std.mem.eql(u8, key, "api_key")) return self.apiKey(); for (self.params.items) |item| { if (std.mem.eql(u8, item.key, key)) return item.value; } @@ -342,10 +427,42 @@ pub const Client = struct { self.params.deinit(); } - fn setLastError(self: *Client, message: []const u8) !void { - const copy = try self.allocator.dupe(u8, message); - if (self.last_error) |old| self.allocator.free(old); - self.last_error = copy; + fn freeApiKey(self: *Client) void { + if (self.api_key) |key| self.allocator.free(key.reveal()); + self.api_key = null; + } + + fn clearLastError(self: *Client) void { + const info = self.last_error orelse return; + self.allocator.free(info.message); + if (info.url) |url| self.allocator.free(url); + if (info.search_id) |id| self.allocator.free(id); + self.last_error = null; + } + + /// Record `info` as the last failure, copying its strings. + fn fail(self: *Client, info: ErrorInfo) Allocator.Error!void { + const message = try self.allocator.dupe(u8, info.message); + errdefer self.allocator.free(message); + const url = if (info.url) |url| try self.allocator.dupe(u8, url) else null; + errdefer if (url) |u| self.allocator.free(u); + const search_id = if (info.search_id) |id| try self.allocator.dupe(u8, id) else null; + + self.clearLastError(); + self.last_error = .{ .message = message, .status = info.status, .url = url, .search_id = search_id }; + } + + fn setLastError(self: *Client, message: []const u8) Allocator.Error!void { + return self.fail(.{ .message = message }); + } + + /// Attach the URL of the request that just failed to the last error, + /// leaving out the api_key. + fn recordUrl(self: *Client, endpoint: []const u8, params: anytype, extra: []const Param) Allocator.Error!void { + const info = &(self.last_error orelse return); + const url = try self.buildUrlWith(self.allocator, endpoint, params, extra, .omit); + if (info.url) |old| self.allocator.free(old); + info.url = url; } /// Write one query parameter value, percent-encoding strings and @@ -362,40 +479,49 @@ pub const Client = struct { } } - /// Build the Search Archive path `/searches/.`, percent-encoding + /// Build the Search Archive path `/searches/.`, percent-encoding /// the id so it cannot escape the path. Caller owns the result. - fn archiveEndpoint(self: *const Client, search_id: []const u8, format: []const u8) Allocator.Error![]u8 { + fn archiveEndpoint(self: *const Client, search_id: []const u8, extension: []const u8) Allocator.Error![]u8 { var out: std.Io.Writer.Allocating = .init(self.allocator); errdefer out.deinit(); // an Allocating writer only ever fails to allocate - writeArchiveEndpoint(&out.writer, search_id, format) catch return error.OutOfMemory; + writeArchiveEndpoint(&out.writer, search_id, extension) catch return error.OutOfMemory; return out.toOwnedSlice(); } - fn writeArchiveEndpoint(w: *std.Io.Writer, search_id: []const u8, format: []const u8) std.Io.Writer.Error!void { + fn writeArchiveEndpoint(w: *std.Io.Writer, search_id: []const u8, extension: []const u8) std.Io.Writer.Error!void { try w.writeAll("/searches/"); try std.Uri.Component.percentEncode(w, search_id, isUrlSafe); try w.writeByte('.'); - try w.writeAll(format); + try w.writeAll(extension); } /// Build the full request URL: https://serpapi.com?. /// Precedence: call `params`, then `extra`, then constructor defaults. fn buildUrl(self: *const Client, allocator: Allocator, endpoint: []const u8, params: anytype, extra: []const Param) Allocator.Error![]u8 { + return self.buildUrlWith(allocator, endpoint, params, extra, .include); + } + + /// Whether a URL carries the `api_key`: the request URL does, the one + /// recorded for error reporting does not. + const ApiKeyMode = enum { include, omit }; + + fn buildUrlWith(self: *const Client, allocator: Allocator, endpoint: []const u8, params: anytype, extra: []const Param, comptime mode: ApiKeyMode) Allocator.Error![]u8 { var out: std.Io.Writer.Allocating = .init(allocator); errdefer out.deinit(); // an Allocating writer only ever fails to allocate - self.writeUrl(&out.writer, endpoint, params, extra) catch return error.OutOfMemory; + self.writeUrl(&out.writer, endpoint, params, extra, mode) catch return error.OutOfMemory; return out.toOwnedSlice(); } - fn writeUrl(self: *const Client, w: *std.Io.Writer, endpoint: []const u8, params: anytype, extra: []const Param) std.Io.Writer.Error!void { + fn writeUrl(self: *const Client, w: *std.Io.Writer, endpoint: []const u8, params: anytype, extra: []const Param, comptime mode: ApiKeyMode) std.Io.Writer.Error!void { try w.print("https://{s}{s}", .{ backend, endpoint }); var separator: u8 = '?'; inline for (@typeInfo(@TypeOf(params)).@"struct".fields) |field| { + if (mode == .omit and comptime std.mem.eql(u8, field.name, "api_key")) continue; try w.writeByte(separator); separator = '&'; try std.Uri.Component.percentEncode(w, field.name, isUrlSafe); @@ -410,6 +536,12 @@ pub const Client = struct { try w.writeByte('='); try std.Uri.Component.percentEncode(w, item.value, isUrlSafe); } + if (self.api_key) |key| if (mode == .include and !hasParam(params, "api_key")) { + try w.writeByte(separator); + separator = '&'; + try w.writeAll("api_key="); + try std.Uri.Component.percentEncode(w, key.reveal(), isUrlSafe); + }; for (self.params.items) |item| { if (hasParam(params, item.key) or containsKey(extra, item.key)) continue; try w.writeByte(separator); @@ -561,38 +693,51 @@ pub const Client = struct { } fn getJson(self: *Client, comptime T: type, endpoint: []const u8, params: anytype, extra: []const Param) !std.json.Parsed(T) { - const response = try self.get(endpoint, params, extra); + const response = try self.getChecked(endpoint, params, extra); defer self.allocator.free(response.body); - try self.checkResponse(response.body, response.status); - const parsed = std.json.parseFromSlice(T, self.allocator, response.body, .{ .allocate = .alloc_always, .ignore_unknown_fields = true, }) catch { - try self.setLastError(response.body); + try self.fail(.{ .message = response.body, .status = response.status }); + try self.recordUrl(endpoint, params, extra); return Error.JsonParseError; }; return parsed; } fn getRaw(self: *Client, endpoint: []const u8, params: anytype, extra: []const Param) ![]u8 { - const response = try self.get(endpoint, params, extra); + const response = try self.getChecked(endpoint, params, extra); + return response.body; + } + + /// `get`, then apply `checkResponse`. A failure the client recorded (an + /// error payload, a non-200 status, a timeout) also records the request + /// URL, without the api_key, for `lastError`. + fn getChecked(self: *Client, endpoint: []const u8, params: anytype, extra: []const Param) !Response { + const response = self.get(endpoint, params, extra) catch |err| { + if (err == Error.Timeout) try self.recordUrl(endpoint, params, extra); + return err; + }; errdefer self.allocator.free(response.body); - try self.checkResponse(response.body, response.status); - return response.body; + self.checkResponse(response.body, response.status) catch |err| { + if (err != error.OutOfMemory) try self.recordUrl(endpoint, params, extra); + return err; + }; + return response; } /// Apply the error rule shared by every decoder, recording the details - /// for `errorMessage`: + /// for `errorMessage` and `lastError`: /// * an `{"error": "..."}` payload is `SerpApiError`, whatever the /// HTTP status (serpapi.com uses 200 as well as 4xx for these); /// * otherwise a non-200 status is `HttpRequestFailed`. fn checkResponse(self: *Client, body: []const u8, status: std.http.Status) !void { - if (try self.captureErrorPayload(body)) return Error.SerpApiError; + if (try self.captureErrorPayload(body, status)) return Error.SerpApiError; if (status != .ok) { - try self.setLastError(if (body.len > 0) body else @tagName(status)); + try self.fail(.{ .message = if (body.len > 0) body else @tagName(status), .status = status }); return Error.HttpRequestFailed; } } @@ -601,10 +746,15 @@ pub const Client = struct { /// parse too (every other field is skipped) and leave `error` null. const ErrorPayload = struct { @"error": ?[]const u8 = null }; + /// Search id carried by an error payload. Parsed on its own so that an + /// unexpected `search_metadata` shape cannot hide the error itself. + const ErrorMetadata = struct { search_metadata: ?struct { id: ?[]const u8 = null } = null }; + /// If `body` is a JSON object carrying a string `error` field, store the - /// message as the last error and return true. Anything else (HTML, - /// Markdown, a JSON array, an object without `error`) returns false. - fn captureErrorPayload(self: *Client, body: []const u8) !bool { + /// message, `status` and search id as the last error and return true. + /// Anything else (HTML, Markdown, a JSON array, an object without + /// `error`) returns false. + fn captureErrorPayload(self: *Client, body: []const u8, status: std.http.Status) !bool { const parsed = std.json.parseFromSlice(ErrorPayload, self.allocator, body, .{ .ignore_unknown_fields = true, }) catch |err| switch (err) { @@ -613,7 +763,15 @@ pub const Client = struct { }; defer parsed.deinit(); const message = parsed.value.@"error" orelse return false; - try self.setLastError(message); + const metadata = std.json.parseFromSlice(ErrorMetadata, self.allocator, body, .{ + .ignore_unknown_fields = true, + }) catch |err| switch (err) { + error.OutOfMemory => return error.OutOfMemory, + else => null, + }; + defer if (metadata) |m| m.deinit(); + const search_id = if (metadata) |m| if (m.value.search_metadata) |meta| meta.id else null else null; + try self.fail(.{ .message = message, .status = status, .search_id = search_id }); return true; } }; @@ -1031,3 +1189,140 @@ test "persistent connection is reused after a chunked gzip response" { } try served.await(io); } + +test "format masks the api key like serpapi-ruby's inspect" { + var client = try Client.init(testing.allocator, .{ .api_key = "0123456789abcdef", .engine = "google" }); + defer client.deinit(); + + var out: std.Io.Writer.Allocating = .init(testing.allocator); + defer out.deinit(); + try out.writer.print("{f}", .{client}); + try testing.expectEqualStrings( + "serpapi.Client{ .engine = \"google\", .timeout = 120, .persistent = true, .api_key = \"0123****cdef\" }", + out.written(), + ); + + // a short key is masked whole + var short = try Client.init(testing.allocator, .{ .api_key = "12345678", .timeout = 5, .persistent = false }); + defer short.deinit(); + out.clearRetainingCapacity(); + try out.writer.print("{f}", .{short.*}); + try testing.expectEqualStrings( + "serpapi.Client{ .engine = null, .timeout = 5, .persistent = false, .api_key = \"****\" }", + out.written(), + ); + + var anonymous = try Client.init(testing.allocator, .{}); + defer anonymous.deinit(); + out.clearRetainingCapacity(); + try out.writer.print("{f}", .{anonymous}); + try testing.expect(std.mem.endsWith(u8, out.written(), ".api_key = null }")); +} + +test "the api key does not show up when printing the client state with {any}" { + var client = try Client.init(testing.allocator, .{ .api_key = "0123456789abcdef", .engine = "google" }); + defer client.deinit(); + + var out: std.Io.Writer.Allocating = .init(testing.allocator); + defer out.deinit(); + // well past the default depth: every byte that is reachable gets printed + try out.writer.printValue("any", .{}, client.params.items, 10); + try out.writer.printValue("any", .{}, client.api_key, 10); + try out.writer.printValue("any", .{}, client.last_error, 10); + + const printed = out.written(); + try testing.expect(std.mem.indexOf(u8, printed, "0123456789abcdef") == null); + // nor as the decimal byte values `{any}` prints for a []const u8 + try testing.expect(std.mem.indexOf(u8, printed, "48, 49, 50, 51") == null); + try testing.expect(std.mem.indexOf(u8, printed, "103, 111, 111, 103, 108, 101") != null); // "google" is printed + try testing.expectEqualStrings("0123456789abcdef", client.apiKey().?); +} + +test "lastError reports the status of a non-200 response" { + var client = try Client.init(testing.allocator, .{}); + defer client.deinit(); + + try testing.expectEqual(@as(?ErrorInfo, null), client.lastError()); + + try testing.expectError(Error.HttpRequestFailed, client.checkResponse("Not Found", .not_found)); + var info = client.lastError().?; + try testing.expectEqual(std.http.Status.not_found, info.status.?); + try testing.expectEqualStrings("Not Found", info.message); + try testing.expectEqual(@as(?[]const u8, null), info.search_id); + + try testing.expectError(Error.HttpRequestFailed, client.checkResponse("Bad Gateway", .bad_gateway)); + info = client.lastError().?; + try testing.expectEqual(std.http.Status.bad_gateway, info.status.?); + try testing.expectEqualStrings("Bad Gateway", info.message); + try testing.expectEqualStrings(info.message, client.errorMessage().?); +} + +test "lastError reports the search id of an error payload" { + var client = try Client.init(testing.allocator, .{}); + defer client.deinit(); + + try testing.expectError(Error.SerpApiError, client.checkResponse( + "{\"search_metadata\":{\"id\":\"68a0d7f2\",\"status\":\"Error\"},\"error\":\"Google hasn't returned any results for this query.\"}", + .ok, + )); + const info = client.lastError().?; + try testing.expectEqual(std.http.Status.ok, info.status.?); + try testing.expectEqualStrings("68a0d7f2", info.search_id.?); + try testing.expectEqualStrings("Google hasn't returned any results for this query.", info.message); + + // an unexpected search_metadata shape does not hide the error + try testing.expectError(Error.SerpApiError, client.checkResponse("{\"search_metadata\":[1],\"error\":\"boom\"}", .bad_request)); + try testing.expectEqualStrings("boom", client.errorMessage().?); + try testing.expectEqual(@as(?[]const u8, null), client.lastError().?.search_id); +} + +test "recordUrl leaves the api key out of the reported URL" { + var client = try Client.init(testing.allocator, .{ .api_key = "secret_key", .engine = "google" }); + defer client.deinit(); + + // nothing to attach the URL to without a failure + try client.recordUrl("/search", .{ .q = "coffee" }, &.{}); + try testing.expectEqual(@as(?ErrorInfo, null), client.lastError()); + + 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, + 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, + client.lastError().?.url.?, + ); + try testing.expectEqual(std.http.Status.unauthorized, client.lastError().?.status.?); + + // the request URL itself still carries the key, the call's first + 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, + url, + ); +} + +test "failure details clean up on allocation failure" { + try testing.checkAllAllocationFailures(testing.allocator, struct { + fn run(allocator: Allocator) !void { + var client = try Client.init(allocator, .{ .api_key = "secret_key" }); + defer client.deinit(); + + client.checkResponse("{\"search_metadata\":{\"id\":\"1\"},\"error\":\"boom\"}", .bad_request) catch |err| switch (err) { + Error.SerpApiError => {}, + else => return err, + }; + try client.recordUrl("/search", .{ .q = "coffee" }, &.{}); + client.checkResponse("Bad Gateway", .bad_gateway) catch |err| switch (err) { + Error.HttpRequestFailed => {}, + else => return err, + }; + } + }.run, .{}); +} diff --git a/src/root.zig b/src/root.zig index 5e89da4..3baba8b 100644 --- a/src/root.zig +++ b/src/root.zig @@ -12,6 +12,7 @@ pub const version = client.version; pub const Client = client.Client; pub const Param = client.Param; pub const Error = client.Error; +pub const ErrorInfo = client.ErrorInfo; test { std.testing.refAllDecls(@This()); diff --git a/test/integration.zig b/test/integration.zig index acbd44c..22fbdc3 100644 --- a/test/integration.zig +++ b/test/integration.zig @@ -5,7 +5,7 @@ //! * location API (persistent and non-persistent connections) //! * account API //! * search archive API -//! * error reporting on invalid input +//! * error reporting on invalid input (message, HTTP status, key-free URL) //! //! Tests that need an API key read the SERPAPI_KEY environment variable //! and are skipped otherwise (e.g. `SERPAPI_KEY=secret zig build itest`). @@ -157,6 +157,47 @@ test "search archive returns a past search" { try testing.expectEqualStrings(search_id, archived_id); } +test "search archive returns a past search as html, markdown, and typed results" { + const key = apiKey(testing.allocator) orelse return error.SkipZigTest; + defer testing.allocator.free(key); + + var client = try serpapi.Client.init(testing.allocator, .{ .api_key = key, .engine = "google" }); + defer client.deinit(); + + const Metadata = struct { search_metadata: struct { id: []const u8, status: []const u8 } }; + var original = try client.searchAs(Metadata, .{ .q = "coffee" }); + defer original.deinit(); + const search_id = original.value.search_metadata.id; + + var archived = try client.searchArchiveAs(Metadata, search_id); + defer archived.deinit(); + try testing.expectEqualStrings(search_id, archived.value.search_metadata.id); + try testing.expectEqualStrings("Success", archived.value.search_metadata.status); + + const page = try client.searchArchiveHtml(search_id); + defer testing.allocator.free(page); + try testing.expect(std.ascii.indexOfIgnoreCase(page, " 0); + try testing.expect(std.ascii.indexOfIgnoreCase(markdown, " 0); + try testing.expect(result.value.len <= 3); + try testing.expect(std.mem.startsWith(u8, result.value[0].name, "Austin")); + try testing.expect(result.value[0].canonical_name.len > 0); +} + test "invalid api key reports a serpapi error" { var client = try serpapi.Client.init(testing.allocator, .{ .api_key = "invalid_key", .engine = "google" }); defer client.deinit(); @@ -166,6 +207,42 @@ test "invalid api key reports a serpapi error" { try testing.expect(client.errorMessage() != null); } +test "lastError reports the status and a key-free url" { + var client = try serpapi.Client.init(testing.allocator, .{ .api_key = "invalid_key_0123456789", .engine = "google" }); + defer client.deinit(); + + try testing.expectError(serpapi.Error.SerpApiError, client.search(.{ .q = "coffee" })); + const info = client.lastError().?; + try testing.expectEqual(std.http.Status.unauthorized, info.status.?); + try testing.expectEqualStrings(client.errorMessage().?, info.message); + try testing.expect(std.mem.startsWith(u8, info.url.?, "https://serpapi.com/search?q=coffee&")); + try testing.expect(std.mem.indexOf(u8, info.url.?, "api_key") == null); + try testing.expect(std.mem.indexOf(u8, info.url.?, "invalid_key_0123456789") == null); + try testing.expect(std.mem.indexOf(u8, info.message, "invalid_key_0123456789") == null); + + // the client prints with its key masked + var out: std.Io.Writer.Allocating = .init(testing.allocator); + defer out.deinit(); + try out.writer.print("{f}", .{client}); + try testing.expect(std.mem.indexOf(u8, out.written(), "invalid_key_0123456789") == null); + try testing.expect(std.mem.indexOf(u8, out.written(), "inva****6789") != null); +} + +test "lastError reports a 404 from the search archive" { + const key = apiKey(testing.allocator) orelse return error.SkipZigTest; + defer testing.allocator.free(key); + + var client = try serpapi.Client.init(testing.allocator, .{ .api_key = key }); + defer client.deinit(); + + try testing.expectError(serpapi.Error.SerpApiError, client.searchArchive("0000000000000000000000ff")); + const info = client.lastError().?; + try testing.expectEqual(std.http.Status.not_found, info.status.?); + try testing.expectEqualStrings("Search not found.", info.message); + try testing.expect(std.mem.startsWith(u8, info.url.?, "https://serpapi.com/searches/0000000000000000000000ff.json")); + try testing.expect(std.mem.indexOf(u8, info.url.?, key) == null); +} + test "typed decoding reports a serpapi error instead of a parse error" { var client = try serpapi.Client.init(testing.allocator, .{ .api_key = "invalid_key", .engine = "google" }); defer client.deinit(); From 17f8a63981961e9f5414c9f202c7f7a67aafbe19 Mon Sep 17 00:00:00 2001 From: Victor Benarbia Date: Mon, 2 Nov 2026 20:29:43 -0600 Subject: [PATCH 2/3] Review fixes: lastError per request, master-only release, CHANGELOG - errorMessage() and lastError() describe the most recent request only: fetch clears the previous failure first, so a success or a transport error (DNS, connection, TLS) leaves them null instead of reporting an older 404. Offline test: 404, then success, then a refused connection - rake release:preflight also requires HEAD to be master, since release pushes master and the tag - CHANGELOG: the api_key leaving params and the new last_error type are Breaking changes; the per-request lastError is a Behavior change (D7) - recordUrl uses `if (self.last_error) |*info|`; the Client doc comment names lastError() as per-instance state too Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 13 +++++-- README.md | 4 +++ Rakefile | 7 +++- src/client.zig | 92 +++++++++++++++++++++++++++++++++++++++++++------- 4 files changed, 99 insertions(+), 17 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index af06837..1c7254b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -11,12 +11,19 @@ (`abcd****wxyz`, `****` for a key of eight characters or fewer) - README documents `engine()`, `apiKey()` and `serpapi.version` - `rake release` runs `lint`, `test`, `itest` and `oobt` before tagging, - and refuses to start unless `SERPAPI_KEY` is set and `git status - --porcelain` is empty (the previous `git diff --quiet` missed staged and - untracked files) + and refuses to start unless it runs from `master` with `SERPAPI_KEY` set + and an empty `git status --porcelain` (the previous `git diff --quiet` + missed staged and untracked files) ### Behavior changes +- `errorMessage()` and `lastError()` describe the most recent request only: + 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 + +### Breaking changes + - The API key is no longer kept in `Client.params`: it moved to its own `api_key` field, which `{any}` prints as an address, so dumping the client state no longer leaks it. `apiKey()` is unchanged; code that read diff --git a/README.md b/README.md index 305f5cf..50646a0 100644 --- a/README.md +++ b/README.md @@ -324,6 +324,10 @@ HTTP `status`, the request `url` with the `api_key` left out — safe to log — and the `search_id` when serpapi.com assigned one to the failed search. `status` is null when no response arrived (`error.Timeout`). +Both describe the most recent request only: every request clears them +first, so they are null after a success, and after a transport error (DNS, +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| { diff --git a/Rakefile b/Rakefile index bf4c698..ee78c16 100644 --- a/Rakefile +++ b/Rakefile @@ -128,8 +128,13 @@ namespace :install do end namespace :release do - desc 'fail fast unless the working tree is clean and SERPAPI_KEY is set' + desc 'fail fast unless on a clean master with SERPAPI_KEY set' task :preflight do + # release pushes master and the tag, so it must run from master + branch = `git rev-parse --abbrev-ref HEAD`.strip + raise 'git rev-parse failed' unless $?.success? + raise "release runs from master, not #{branch}" unless branch == 'master' + # `git diff --quiet` misses staged and untracked files; porcelain lists all dirty = `git status --porcelain` raise 'git status failed' unless $?.success? diff --git a/src/client.zig b/src/client.zig index 927c370..3329620 100644 --- a/src/client.zig +++ b/src/client.zig @@ -45,8 +45,12 @@ pub const Error = error{ }; /// Details of the last failed request, from `Client.lastError()`. The -/// strings are owned by the client and valid until its next failure or +/// strings are owned by the client and valid until its next request or /// `deinit`. +/// +/// Every request starts by clearing it, so it only ever describes the most +/// recent call: it is null after a success, and after a transport error +/// (DNS, connection, TLS), which carries no details beyond the Zig error. pub const ErrorInfo = struct { /// What went wrong; the same text as `Client.errorMessage()`. message: []const u8, @@ -102,8 +106,8 @@ const Secret = struct { /// defer result.deinit(); /// ``` /// -/// A `Client` is not thread-safe: `errorMessage()` reports the last failure -/// seen by the client, so use one instance per thread. +/// A `Client` is not thread-safe: `errorMessage()` and `lastError()` report +/// the last failure seen by the client, so use one instance per thread. pub const Client = struct { allocator: Allocator, /// Event loop / thread pool backing std.http. Heap-stable inside Client. @@ -329,17 +333,19 @@ pub const Client = struct { return key.reveal(); } - /// Description of the last failed request, if any: the error payload - /// from serpapi.com, the raw body of a non-200 response, or the client's - /// own message. See `lastError` for the HTTP status, URL and search id. + /// Description of the most recent request's failure, if any: the error + /// payload from serpapi.com, the raw body of a non-200 response, or the + /// client's own message. Null after a success or a transport error. See + /// `lastError` for the HTTP status, URL and search id. pub fn errorMessage(self: *const Client) ?[]const u8 { const info = self.last_error orelse return null; return info.message; } - /// Details of the last failed request, if any: message, HTTP status, - /// URL without the api_key, and search id. Mirrors the fields of - /// serpapi-ruby's `SerpApiError`. + /// Details of the most recent request's failure, if any: message, HTTP + /// status, URL without the api_key, and search id. Mirrors the fields of + /// serpapi-ruby's `SerpApiError`. Null after a success or a transport + /// error, see `ErrorInfo`. /// /// ```zig /// var results = client.search(.{ .q = "coffee" }) catch |err| { @@ -459,10 +465,11 @@ pub const Client = struct { /// Attach the URL of the request that just failed to the last error, /// leaving out the api_key. fn recordUrl(self: *Client, endpoint: []const u8, params: anytype, extra: []const Param) Allocator.Error!void { - const info = &(self.last_error orelse return); - const url = try self.buildUrlWith(self.allocator, endpoint, params, extra, .omit); - if (info.url) |old| self.allocator.free(old); - info.url = url; + if (self.last_error) |*info| { + const url = try self.buildUrlWith(self.allocator, endpoint, params, extra, .omit); + if (info.url) |old| self.allocator.free(old); + info.url = url; + } } /// Write one query parameter value, percent-encoding strings and @@ -598,7 +605,11 @@ pub const Client = struct { /// Issue the GET request, writing the body to `w`. When `timeout` is /// non-zero the request runs on its own thread and is canceled once the /// timer fires, so a stalled connection cannot block the caller forever. + /// + /// Every request goes through here, so this is where the previous + /// call's failure is forgotten: `lastError()` describes this call only. fn fetch(self: *Client, url: []const u8, w: *std.Io.Writer) !std.http.Status { + self.clearLastError(); if (self.timeout == 0) return fetchStatus(&self.http, url, w, self.persistent); const io = self.threaded.io(); @@ -1326,3 +1337,58 @@ test "failure details clean up on allocation failure" { } }.run, .{}); } + +test "lastError only describes the most recent request" { + 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, .{}); + var listening = true; + defer if (listening) server.deinit(io); + + const Answer = struct { + fn serve(server_ptr: *std.Io.net.Server, server_io: std.Io) !void { + 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); + while (true) { + const line = try reader.interface.takeDelimiterInclusive('\n'); + if (line.len <= 2) break; + } + 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: 11\r\nConnection: close\r\n\r\n{\"ok\":true}"); + try writer.interface.flush(); + } + }; + var answer = try io.concurrent(Answer.serve, .{ &server, io }); + defer _ = answer.cancel(io) catch {}; + + const port = server.socket.address.getPort(); + const url = try std.fmt.allocPrint(testing.allocator, "http://127.0.0.1:{d}/search", .{port}); + defer testing.allocator.free(url); + + // a 404 is recorded... + try testing.expectError(Error.HttpRequestFailed, client.checkResponse("Not Found", .not_found)); + try client.recordUrl("/search", .{ .q = "coffee" }, &.{}); + try testing.expectEqual(std.http.Status.not_found, client.lastError().?.status.?); + + // ...and forgotten as soon as the next request starts + var body: std.Io.Writer.Allocating = .init(testing.allocator); + defer body.deinit(); + try testing.expectEqual(std.http.Status.ok, try client.fetch(url, &body.writer)); + try answer.await(io); + try testing.expectEqual(@as(?ErrorInfo, null), client.lastError()); + try testing.expectEqual(@as(?[]const u8, null), client.errorMessage()); + + // a transport error leaves nothing behind either, not the older 404 + try testing.expectError(Error.HttpRequestFailed, client.checkResponse("Not Found", .not_found)); + server.deinit(io); // nobody listens on the port any more + listening = false; + body.clearRetainingCapacity(); + try testing.expectError(error.ConnectionRefused, client.fetch(url, &body.writer)); + try testing.expectEqual(@as(?ErrorInfo, null), client.lastError()); +} From 8afcb824b2ee6ceb0ac5c2a88e59b11a257ea986 Mon Sep 17 00:00:00 2001 From: Victor Benarbia Date: Tue, 3 Nov 2026 13:29:25 -0600 Subject: [PATCH 3/3] Bump version to 1.2.0 Breaking changes ship in this minor release by maintainer decision. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 4 +++- README.md | 4 ++-- build.zig.zon | 2 +- 3 files changed, 6 insertions(+), 4 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 1c7254b..9412819 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,6 +1,6 @@ # Changelog -## Unreleased +## 1.2.0 (unreleased) - `Client.lastError()` returns a `serpapi.ErrorInfo` with the details of the last failure, mirroring serpapi-ruby's `SerpApiError`: `message` (as @@ -24,6 +24,8 @@ ### Breaking changes +These ship in a minor release by decision; pin `v1.1.0` to keep the old API. + - The API key is no longer kept in `Client.params`: it moved to its own `api_key` field, which `{any}` prints as an address, so dumping the client state no longer leaks it. `apiKey()` is unchanged; code that read diff --git a/README.md b/README.md index 50646a0..6116ac2 100644 --- a/README.md +++ b/README.md @@ -173,7 +173,7 @@ 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.1.0", reported to serpapi.com +serpapi.version // the library version, "1.2.0", reported to serpapi.com ``` Printing the client masks the API key, as serpapi-ruby's `inspect` does — @@ -331,7 +331,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.1.0: Search not found. + // SerpApiError: HTTP 404 https://serpapi.com/searches/.json?source=serpapi-zig%3A1.2.0: 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, }); diff --git a/build.zig.zon b/build.zig.zon index c9554f1..5afd4c1 100644 --- a/build.zig.zon +++ b/build.zig.zon @@ -9,7 +9,7 @@ .name = .serpapi, // This is a [Semantic Version](https://semver.org/). // In a future version of Zig it will be used for package deduplication. - .version = "1.1.0", + .version = "1.2.0", // Together with name, this represents a globally unique package // identifier. This field is generated by the Zig toolchain when the // package is first created, and then *never changes*. This allows