diff --git a/CHANGELOG.md b/CHANGELOG.md index 603e9c9..cbddcfc 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -29,6 +29,13 @@ - 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 + +### 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 - 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 @@ -37,20 +44,13 @@ 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 - -- `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 - 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 +- Fix: a `source` passed to the constructor is sent once, as given, with + searches and image uploads alike. 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 6d87a0b..ea10283 100644 --- a/README.md +++ b/README.md @@ -180,7 +180,8 @@ 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. +yourself, to the constructor or a call, is sent as given, with searches and +image uploads alike. 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, `****` diff --git a/src/client.zig b/src/client.zig index bbba174..22bcbc1 100644 --- a/src/client.zig +++ b/src/client.zig @@ -734,11 +734,11 @@ pub const Client = struct { } /// Write the Image API multipart/form-data body: the call `params`, - /// 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. + /// then the constructor `api_key` and `source` unless they override + /// them, 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, @@ -755,11 +755,13 @@ pub const Client = struct { try writeFormValue(w, @field(params, field.name)); try w.writeAll("\r\n"); } - if (!hasParam(params, "api_key")) if (self.apiKey()) |key| { - try writeFormFieldHead(w, boundary, "api_key"); - try w.writeAll(key); - try w.writeAll("\r\n"); - }; + inline for (.{ "api_key", "source" }) |key| { + if (!hasParam(params, key)) if (self.param(key)) |value| { + try writeFormFieldHead(w, boundary, key); + try w.writeAll(value); + try w.writeAll("\r\n"); + }; + } try w.print("--{s}\r\nContent-Disposition: form-data; name=\"image\"; filename=\"", .{boundary}); try writeQuoted(w, file_name); @@ -1764,6 +1766,32 @@ test "writeImageForm call parameters override the constructor key" { try testing.expect(std.mem.indexOf(u8, body.written(), "default") == null); } +test "writeImageForm sends a constructor source once, and a call source overrides it" { + var client = try Client.init(testing.allocator, .{ .api_key = "secret", .engine = "google_lens", .source = "my-app" }); + defer client.deinit(); + + var body: std.Io.Writer.Allocating = .init(testing.allocator); + defer body.deinit(); + try client.writeImageForm(&body.writer, "B", "data", "image.jpg", .{}); + try testing.expectEqualStrings( + "--B\r\nContent-Disposition: form-data; name=\"api_key\"\r\n\r\nsecret\r\n" ++ + "--B\r\nContent-Disposition: form-data; name=\"source\"\r\n\r\nmy-app\r\n" ++ + "--B\r\nContent-Disposition: form-data; name=\"image\"; filename=\"image.jpg\"\r\n" ++ + "Content-Type: image/jpeg\r\n\r\ndata\r\n--B--\r\n", + body.written(), + ); + + body.clearRetainingCapacity(); + try client.writeImageForm(&body.writer, "B", "data", "image.jpg", .{ .source = "my-call" }); + try testing.expectEqualStrings( + "--B\r\nContent-Disposition: form-data; name=\"source\"\r\n\r\nmy-call\r\n" ++ + "--B\r\nContent-Disposition: form-data; name=\"api_key\"\r\n\r\nsecret\r\n" ++ + "--B\r\nContent-Disposition: form-data; name=\"image\"; filename=\"image.jpg\"\r\n" ++ + "Content-Type: image/jpeg\r\n\r\ndata\r\n--B--\r\n", + body.written(), + ); +} + test "uploadImageBytes rejects an image over the size limit before sending it" { // no api_key and no network: the size check fails first var client = try Client.init(testing.allocator, .{}); @@ -1974,7 +2002,14 @@ test "userAgent names the library, the Zig version and the platform" { } test "every request identifies the library in the User-Agent header" { - var client = try Client.init(testing.allocator, .{ .timeout = 30 }); + try expectUserAgentOnEveryRequest(true); + try expectUserAgentOnEveryRequest(false); +} + +/// Send a GET and a POST to a local server, with or without a persistent +/// connection, and check both carry `user_agent`. +fn expectUserAgentOnEveryRequest(persistent: bool) !void { + var client = try Client.init(testing.allocator, .{ .timeout = 30, .persistent = persistent }); defer client.deinit(); const io = client.threaded.io(); diff --git a/test/integration.zig b/test/integration.zig index b183711..495a5fb 100644 --- a/test/integration.zig +++ b/test/integration.zig @@ -288,22 +288,24 @@ test "persistent connection performs multiple searches" { } } -test "searches identify the library in the User-Agent, and a caller's source goes through" { +test "a caller's source is sent once, and the library adds none" { 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" }); + // serpapi.com echoes neither the User-Agent (checked offline) nor + // `source` back, so read the sent URL from lastError(): an archive + // lookup of an unknown id is a 404 that costs no search credit. + var client = try serpapi.Client.init(testing.allocator, .{ .api_key = key, .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); + try testing.expectError(serpapi.Error.SerpApiError, client.searchArchive("0000000000000000000000fe")); + const info = client.lastError().?; + try testing.expectEqual(std.http.Status.not_found, info.status.?); + const url = info.url.?; + try testing.expect(std.mem.startsWith(u8, url, "https://serpapi.com/searches/0000000000000000000000fe.json?")); + try testing.expectEqual(@as(usize, 1), std.mem.count(u8, url, "source=")); + try testing.expect(std.mem.indexOf(u8, url, "source=serpapi-zig-itest") != null); + try testing.expect(std.mem.indexOf(u8, url, "serpapi-zig%3A") == null); } /// Smallest valid PNG: a 1x1 transparent pixel.