1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
//! XRPC Client - AT Protocol RPC calls
//!
//! simplifies calling AT Protocol endpoints.
//! handles query (GET) and procedure (POST) methods.
//!
//! see: https://atproto.com/specs/xrpc
const std = @import("std");
const Nsid = @import("../syntax/nsid.zig").Nsid;
const HttpTransport = @import("zttp").Client;
const default_user_agent = @import("user_agent.zig").default_user_agent;
const json_helpers = @import("json.zig");
pub const XrpcClient = struct {
allocator: std.mem.Allocator,
transport: HttpTransport,
/// pds or appview host (e.g., "https://bsky.social")
host: []const u8,
/// bearer token for authenticated requests
access_token: ?[]const u8 = null,
/// atproto JWTs are ~1KB; buffer needs room for "Bearer " prefix
const max_auth_header_len = 2048;
/// One URL query parameter. Use a slice of these with queryParams when an
/// XRPC method needs repeated names for array-valued parameters.
pub const QueryParam = struct {
name: []const u8,
value: []const u8,
};
pub fn init(io: std.Io, allocator: std.mem.Allocator, host: []const u8) XrpcClient {
return .{
.allocator = allocator,
.transport = HttpTransport.initWithUserAgent(io, allocator, default_user_agent),
.host = host,
};
}
/// Same as `init`, naming the calling application in the User-Agent rather
/// than zat. Anything issuing XRPC at scale should use this: the operator
/// on the other end wants to know which service is calling, not which
/// library it happens to be built on.
pub fn initWithUserAgent(
io: std.Io,
allocator: std.mem.Allocator,
host: []const u8,
user_agent: []const u8,
) XrpcClient {
var client = init(io, allocator, host);
if (user_agent.len > 0) client.transport.user_agent = user_agent;
return client;
}
pub fn deinit(self: *XrpcClient) void {
self.transport.deinit();
}
/// set bearer token for authenticated requests
pub fn setAuth(self: *XrpcClient, token: []const u8) void {
self.access_token = token;
}
/// call a query method (GET)
pub fn query(self: *XrpcClient, nsid: Nsid, params: ?std.StringHashMap([]const u8)) !Response {
const url = try self.buildUrl(nsid, params);
defer self.allocator.free(url);
return try self.doRequest(.GET, url, null);
}
/// Call a query method with ordered parameters. Repeating a name encodes
/// an array-valued XRPC parameter, e.g. authors=alice&authors=bob.
pub fn queryParams(self: *XrpcClient, nsid: Nsid, params: []const QueryParam) !Response {
const url = try self.buildUrlFromParams(nsid, params);
defer self.allocator.free(url);
return try self.doRequest(.GET, url, null);
}
/// call a procedure method (POST)
pub fn procedure(self: *XrpcClient, nsid: Nsid, body: ?[]const u8) !Response {
const url = try self.buildUrl(nsid, null);
defer self.allocator.free(url);
return try self.doRequest(.POST, url, body);
}
pub fn queryChecked(
self: *XrpcClient,
nsid: Nsid,
params: ?std.StringHashMap([]const u8),
retry_policy: RetryPolicy,
) !Result {
const url = try self.buildUrl(nsid, params);
defer self.allocator.free(url);
return try self.requestCheckedUrl(.GET, url, null, retry_policy);
}
pub fn queryParamsChecked(
self: *XrpcClient,
nsid: Nsid,
params: []const QueryParam,
retry_policy: RetryPolicy,
) !Result {
const url = try self.buildUrlFromParams(nsid, params);
defer self.allocator.free(url);
return try self.requestCheckedUrl(.GET, url, null, retry_policy);
}
pub fn procedureChecked(
self: *XrpcClient,
nsid: Nsid,
body: ?[]const u8,
retry_policy: RetryPolicy,
) !Result {
const url = try self.buildUrl(nsid, null);
defer self.allocator.free(url);
return try self.requestCheckedUrl(.POST, url, body, retry_policy);
}
fn buildUrl(self: *XrpcClient, nsid: Nsid, params: ?std.StringHashMap([]const u8)) ![]u8 {
var url = try self.buildUrlBase(nsid);
errdefer url.deinit(self.allocator);
if (params) |p| {
var first = true;
var it = p.iterator();
while (it.next()) |entry| {
try self.appendQueryParam(&url, if (first) '?' else '&', .{
.name = entry.key_ptr.*,
.value = entry.value_ptr.*,
});
first = false;
}
}
return try url.toOwnedSlice(self.allocator);
}
fn buildUrlFromParams(self: *XrpcClient, nsid: Nsid, params: []const QueryParam) ![]u8 {
var url = try self.buildUrlBase(nsid);
errdefer url.deinit(self.allocator);
for (params, 0..) |param, index| {
try self.appendQueryParam(&url, if (index == 0) '?' else '&', param);
}
return try url.toOwnedSlice(self.allocator);
}
fn buildUrlBase(self: *XrpcClient, nsid: Nsid) !std.ArrayList(u8) {
var url: std.ArrayList(u8) = .empty;
errdefer url.deinit(self.allocator);
try url.appendSlice(self.allocator, self.host);
try url.appendSlice(self.allocator, "/xrpc/");
try url.appendSlice(self.allocator, nsid.raw);
return url;
}
fn appendQueryParam(
self: *XrpcClient,
url: *std.ArrayList(u8),
separator: u8,
param: QueryParam,
) !void {
try url.append(self.allocator, separator);
try url.appendSlice(self.allocator, param.name);
try url.append(self.allocator, '=');
for (param.value) |c| {
if (std.ascii.isAlphanumeric(c) or c == '-' or c == '_' or c == '.' or c == '~') {
try url.append(self.allocator, c);
} else {
try url.print(self.allocator, "%{X:0>2}", .{c});
}
}
}
fn doRequest(self: *XrpcClient, method: std.http.Method, url: []const u8, body: ?[]const u8) !Response {
var auth_header_buf: [max_auth_header_len]u8 = undefined;
const auth_value: ?[]const u8 = if (self.access_token) |token|
std.fmt.bufPrint(&auth_header_buf, "Bearer {s}", .{token}) catch null
else
null;
const result = try self.transport.fetch(.{
.url = url,
.method = method,
.payload = body,
.content_type = if (body != null) "application/json" else null,
.authorization = auth_value,
});
return .{
.allocator = self.allocator,
.status = result.status,
.body = result.body,
.rate_limit = result.rate_limit,
};
}
fn requestCheckedUrl(self: *XrpcClient, method: std.http.Method, url: []const u8, body: ?[]const u8, retry_policy: RetryPolicy) !Result {
const attempts = @max(@as(u8, 1), retry_policy.max_attempts);
var attempt: u8 = 0;
while (true) : (attempt += 1) {
var response = self.doRequest(method, url, body) catch |err| {
if (attempt + 1 >= attempts or !retry_policy.retry_transient_errors or !isRetryableTransportErrorForMethod(method, err)) {
return err;
}
try retry_policy.sleepBeforeRetry(self.transport.io, attempt, null);
continue;
};
if (response.ok()) {
return .{ .ok = response };
}
if (attempt + 1 < attempts and retry_policy.isRetryableStatusForMethod(method, response.status)) {
const rate_limit = response.rate_limit;
response.deinit();
try retry_policy.sleepBeforeRetry(self.transport.io, attempt, rate_limit);
continue;
}
return .{ .err = try XrpcError.fromResponse(response) };
}
}
pub const Response = struct {
allocator: std.mem.Allocator,
status: std.http.Status,
body: []u8,
rate_limit: HttpTransport.RateLimitHeaders = .{},
pub fn deinit(self: *Response) void {
self.allocator.free(self.body);
}
/// check if request succeeded
pub fn ok(self: Response) bool {
return self.status.class() == .success;
}
/// parse body as json
pub fn json(self: Response) !std.json.Parsed(std.json.Value) {
return try std.json.parseFromSlice(std.json.Value, self.allocator, self.body, .{});
}
};
pub const Result = union(enum) {
ok: Response,
err: XrpcError,
pub fn deinit(self: *Result) void {
switch (self.*) {
.ok => |*response| response.deinit(),
.err => |*xrpc_error| xrpc_error.deinit(),
}
}
};
pub const XrpcError = struct {
allocator: std.mem.Allocator,
status: std.http.Status,
error_name: ?[]u8 = null,
message: ?[]u8 = null,
body: []u8,
rate_limit: HttpTransport.RateLimitHeaders = .{},
pub fn fromResponse(response: Response) !XrpcError {
var result: XrpcError = .{
.allocator = response.allocator,
.status = response.status,
.body = response.body,
.rate_limit = response.rate_limit,
};
errdefer result.deinit();
var parsed = std.json.parseFromSlice(std.json.Value, response.allocator, response.body, .{}) catch return result;
defer parsed.deinit();
if (json_helpers.getString(parsed.value, "error")) |name| {
result.error_name = try response.allocator.dupe(u8, name);
}
if (json_helpers.getString(parsed.value, "message")) |message| {
result.message = try response.allocator.dupe(u8, message);
}
return result;
}
pub fn deinit(self: *XrpcError) void {
if (self.error_name) |name| self.allocator.free(name);
if (self.message) |message| self.allocator.free(message);
self.allocator.free(self.body);
}
};
pub const RetryPolicy = struct {
max_attempts: u8 = 3,
base_delay_ms: u64 = 500,
max_delay_ms: u64 = 30_000,
jitter_percent: u8 = 20,
retry_transient_errors: bool = true,
pub fn none() RetryPolicy {
return .{ .max_attempts = 1 };
}
pub fn isRetryableStatus(_: RetryPolicy, status: std.http.Status) bool {
return switch (@backingInt(status)) {
429, 500, 502, 503, 504 => true,
else => false,
};
}
pub fn isRetryableStatusForMethod(self: RetryPolicy, method: std.http.Method, status: std.http.Status) bool {
if (!self.isRetryableStatus(status)) return false;
if (method == .POST and status != .too_many_requests) return false;
return true;
}
pub fn delayMillis(self: RetryPolicy, attempt: u8, rate_limit: ?HttpTransport.RateLimitHeaders) u64 {
return self.delayMillisAt(attempt, rate_limit, null);
}
pub fn delayMillisAt(
self: RetryPolicy,
attempt: u8,
rate_limit: ?HttpTransport.RateLimitHeaders,
now_unix_seconds: ?u64,
) u64 {
if (rate_limit) |headers| {
if (headers.retry_after) |seconds| {
const milliseconds = std.math.mul(u64, seconds, std.time.ms_per_s) catch return self.max_delay_ms;
return @min(milliseconds, self.max_delay_ms);
}
if (now_unix_seconds) |now| {
if (headers.retry_after_at) |at| {
if (self.millisUntil(at, now)) |milliseconds| return milliseconds;
}
if (headers.reset) |reset| {
if (self.millisUntil(reset, now)) |milliseconds| return milliseconds;
}
}
}
const shift: u6 = @intCast(@min(attempt, 16));
const base = self.base_delay_ms * (@as(u64, 1) << shift);
return @min(base, self.max_delay_ms);
}
fn millisUntil(self: RetryPolicy, at: i64, now: u64) ?u64 {
if (@as(i128, at) <= now) return null;
const seconds: u64 = @intCast(@as(i128, at) - now);
const milliseconds = std.math.mul(u64, seconds, std.time.ms_per_s) catch return self.max_delay_ms;
return @min(milliseconds, self.max_delay_ms);
}
pub fn sleepBeforeRetry(self: RetryPolicy, io: std.Io, attempt: u8, rate_limit: ?HttpTransport.RateLimitHeaders) !void {
const now_seconds: ?u64 = if (rate_limit != null)
@intCast(@max(@as(i64, 0), std.Io.Clock.real.now(io).toSeconds()))
else
null;
var delay_ms = self.delayMillisAt(attempt, rate_limit, now_seconds);
delay_ms = self.jitteredDelayMillis(io, delay_ms);
if (delay_ms == 0) return;
try io.sleep(std.Io.Duration.fromMilliseconds(@intCast(delay_ms)), .awake);
}
fn jitteredDelayMillis(self: RetryPolicy, io: std.Io, delay_ms: u64) u64 {
if (delay_ms == 0 or self.jitter_percent == 0) return delay_ms;
const spread = delay_ms * @as(u64, self.jitter_percent) / 100;
if (spread == 0) return delay_ms;
var source: std.Random.IoSource = .{ .io = io };
const random = source.interface();
const min = delay_ms - spread;
const max = std.math.add(u64, delay_ms, spread) catch std.math.maxInt(u64);
return @min(random.intRangeAtMost(u64, min, max), self.max_delay_ms);
}
};
};
fn isRetryableTransportErrorForMethod(method: std.http.Method, err: anyerror) bool {
if (method == .POST) {
return err == error.ConnectionRefused;
}
return switch (err) {
error.ConnectionRefused,
error.ConnectionResetByPeer,
error.HostUnreachable,
error.NetworkUnreachable,
error.NetworkDown,
error.Timeout,
error.TlsInitializationFailed,
error.Unexpected,
error.ReadFailed,
error.WriteFailed,
=> true,
else => false,
};
}
// === tests ===
test "client user agent override reaches the transport" {
const testing = std.testing;
var named = XrpcClient.initWithUserAgent(std.Options.debug_io, testing.allocator, "https://bsky.social", "stream/1.2.3 (+https://example.invalid)");
defer named.deinit();
try testing.expectEqualStrings("stream/1.2.3 (+https://example.invalid)", named.transport.user_agent);
var empty = XrpcClient.initWithUserAgent(std.Options.debug_io, testing.allocator, "https://bsky.social", "");
defer empty.deinit();
try testing.expectEqualStrings(default_user_agent, empty.transport.user_agent);
}
test "build url without params" {
var client = XrpcClient.init(std.Options.debug_io, std.testing.allocator, "https://bsky.social");
defer client.deinit();
const nsid = Nsid.parse("app.bsky.actor.getProfile").?;
const url = try client.buildUrl(nsid, null);
defer std.testing.allocator.free(url);
try std.testing.expectEqualStrings("https://bsky.social/xrpc/app.bsky.actor.getProfile", url);
}
test "build url with params" {
var client = XrpcClient.init(std.Options.debug_io, std.testing.allocator, "https://bsky.social");
defer client.deinit();
var params = std.StringHashMap([]const u8).init(std.testing.allocator);
defer params.deinit();
try params.put("actor", "did:plc:test123");
const nsid = Nsid.parse("app.bsky.actor.getProfile").?;
const url = try client.buildUrl(nsid, params);
defer std.testing.allocator.free(url);
try std.testing.expect(std.mem.startsWith(u8, url, "https://bsky.social/xrpc/app.bsky.actor.getProfile?"));
try std.testing.expect(std.mem.indexOf(u8, url, "actor=did%3Aplc%3Atest123") != null);
}
test "build url with repeated ordered params" {
var client = XrpcClient.init(std.Options.debug_io, std.testing.allocator, "https://api.bsky.app");
defer client.deinit();
const params = [_]XrpcClient.QueryParam{
.{ .name = "query", .value = "zig language" },
.{ .name = "authors", .value = "alice.test" },
.{ .name = "authors", .value = "bob.test" },
};
const nsid = Nsid.parse("app.bsky.feed.searchPostsV2").?;
const url = try client.buildUrlFromParams(nsid, ¶ms);
defer std.testing.allocator.free(url);
try std.testing.expectEqualStrings(
"https://api.bsky.app/xrpc/app.bsky.feed.searchPostsV2?query=zig%20language&authors=alice.test&authors=bob.test",
url,
);
}
test "xrpc error parses atproto error envelope and rate limits" {
const body = try std.testing.allocator.dupe(u8,
\\{"error":"RateLimitExceeded","message":"slow down"}
);
const response: XrpcClient.Response = .{
.allocator = std.testing.allocator,
.status = .too_many_requests,
.body = body,
.rate_limit = .{
.limit = 3000,
.remaining = 0,
.reset = 1710000000,
.retry_after = 2,
},
};
var xrpc_error = try XrpcClient.XrpcError.fromResponse(response);
defer xrpc_error.deinit();
try std.testing.expectEqual(.too_many_requests, xrpc_error.status);
try std.testing.expectEqualStrings("RateLimitExceeded", xrpc_error.error_name.?);
try std.testing.expectEqualStrings("slow down", xrpc_error.message.?);
try std.testing.expectEqual(@as(?u64, 3000), xrpc_error.rate_limit.limit);
try std.testing.expectEqual(@as(?u64, 0), xrpc_error.rate_limit.remaining);
try std.testing.expectEqual(@as(i128, 1710000000), @as(i128, xrpc_error.rate_limit.reset.?));
try std.testing.expectEqual(@as(?u64, 2), xrpc_error.rate_limit.retry_after);
}
test "retry policy is conservative and deterministic" {
const policy: XrpcClient.RetryPolicy = .{
.base_delay_ms = 100,
.max_delay_ms = 1000,
.jitter_percent = 0,
};
try std.testing.expect(policy.isRetryableStatus(.too_many_requests));
try std.testing.expect(policy.isRetryableStatus(.internal_server_error));
try std.testing.expect(policy.isRetryableStatus(.bad_gateway));
try std.testing.expect(policy.isRetryableStatus(.service_unavailable));
try std.testing.expect(policy.isRetryableStatus(.gateway_timeout));
try std.testing.expect(!policy.isRetryableStatus(.bad_request));
try std.testing.expect(!policy.isRetryableStatus(.unauthorized));
try std.testing.expect(!policy.isRetryableStatus(.not_found));
try std.testing.expect(policy.isRetryableStatusForMethod(.GET, .service_unavailable));
try std.testing.expect(policy.isRetryableStatusForMethod(.GET, .too_many_requests));
try std.testing.expect(!policy.isRetryableStatusForMethod(.POST, .service_unavailable));
try std.testing.expect(policy.isRetryableStatusForMethod(.POST, .too_many_requests));
try std.testing.expect(isRetryableTransportErrorForMethod(.GET, error.ConnectionResetByPeer));
try std.testing.expect(isRetryableTransportErrorForMethod(.POST, error.ConnectionRefused));
try std.testing.expect(!isRetryableTransportErrorForMethod(.POST, error.ConnectionResetByPeer));
try std.testing.expectEqual(@as(u64, 100), policy.delayMillis(0, null));
try std.testing.expectEqual(@as(u64, 200), policy.delayMillis(1, null));
try std.testing.expectEqual(@as(u64, 1000), policy.delayMillis(10, null));
try std.testing.expectEqual(@as(u64, 1000), policy.delayMillis(0, .{ .retry_after = 5 }));
try std.testing.expectEqual(@as(u64, 1000), policy.delayMillisAt(0, .{ .reset = 1005 }, 1000));
try std.testing.expectEqual(@as(u64, 100), policy.delayMillisAt(0, .{ .reset = 999 }, 1000));
}
test "retry-after in its http-date form delays the retry" {
const policy: XrpcClient.RetryPolicy = .{ .base_delay_ms = 0, .max_delay_ms = 60_000, .jitter_percent = 0 };
try std.testing.expectEqual(@as(u64, 7000), policy.delayMillisAt(0, .{ .retry_after_at = 1007 }, 1000));
try std.testing.expectEqual(@as(u64, 7000), policy.delayMillisAt(0, .{ .retry_after_at = 1007, .reset = 1030 }, 1000));
try std.testing.expectEqual(@as(u64, 30_000), policy.delayMillisAt(0, .{ .retry_after_at = 990, .reset = 1030 }, 1000));
try std.testing.expectEqual(@as(u64, 0), policy.delayMillisAt(0, .{ .retry_after_at = 990 }, 1000));
try std.testing.expectEqual(@as(u64, 0), policy.delayMillisAt(0, .{ .retry_after_at = 1007 }, null));
}