std.http: rename start->send and request->open to be more inline with operation

This commit is contained in:
Nameless 2023-10-07 20:27:39 -05:00
parent 544ed34d99
commit 363d0ee5e1
No known key found for this signature in database
GPG Key ID: A477BC03CAFCCAF7
5 changed files with 72 additions and 72 deletions

View File

@ -598,15 +598,15 @@ pub const Request = struct {
};
}
pub const StartError = Connection.WriteError || error{ InvalidContentLength, UnsupportedTransferEncoding };
pub const SendError = Connection.WriteError || error{ InvalidContentLength, UnsupportedTransferEncoding };
pub const StartOptions = struct {
/// Specifies that the uri should be used as is
pub const SendOptions = struct {
/// Specifies that the uri should be used as is. You guarantee that the uri is already escaped.
raw_uri: bool = false,
};
/// Send the HTTP request headers to the server.
pub fn start(req: *Request, options: StartOptions) StartError!void {
pub fn send(req: *Request, options: SendOptions) SendError!void {
if (!req.method.requestHasBody() and req.transfer_encoding != .none) return error.UnsupportedTransferEncoding;
const w = req.connection.?.writer();
@ -733,14 +733,14 @@ pub const Request = struct {
return index;
}
pub const WaitError = RequestError || StartError || TransferReadError || proto.HeadersParser.CheckCompleteHeadError || Response.ParseError || Uri.ParseError || error{ TooManyHttpRedirects, RedirectRequiresResend, HttpRedirectMissingLocation, CompressionInitializationFailed, CompressionNotSupported };
pub const WaitError = RequestError || SendError || TransferReadError || proto.HeadersParser.CheckCompleteHeadError || Response.ParseError || Uri.ParseError || error{ TooManyHttpRedirects, RedirectRequiresResend, HttpRedirectMissingLocation, CompressionInitializationFailed, CompressionNotSupported };
/// Waits for a response from the server and parses any headers that are sent.
/// This function will block until the final response is received.
///
/// If `handle_redirects` is true and the request has no payload, then this function will automatically follow
/// redirects. If a request payload is present, then this function will error with error.RedirectRequiresResend.
///
///
/// Must be called after `start` and, if any data was written to the request body, then also after `finish`.
pub fn wait(req: *Request) WaitError!void {
while (true) { // handle redirects
@ -845,7 +845,7 @@ pub const Request = struct {
try req.redirect(resolved_url);
try req.start(.{});
try req.send(.{});
} else {
req.response.skip = false;
if (!req.response.parser.done) {
@ -1223,7 +1223,7 @@ pub fn connectTunnel(
// we can use a small buffer here because a CONNECT response should be very small
var buffer: [8096]u8 = undefined;
var req = client.request(.CONNECT, uri, proxy.headers, .{
var req = client.open(.CONNECT, uri, proxy.headers, .{
.handle_redirects = false,
.connection = conn,
.header_strategy = .{ .static = buffer[0..] },
@ -1233,7 +1233,7 @@ pub fn connectTunnel(
};
defer req.deinit();
req.start(.{ .raw_uri = true }) catch |err| break :tunnel err;
req.send(.{ .raw_uri = true }) catch |err| break :tunnel err;
req.wait() catch |err| break :tunnel err;
if (req.response.status.class() == .server_error) {
@ -1266,9 +1266,9 @@ const ConnectErrorPartial = ConnectTcpError || error{ UnsupportedUrlScheme, Conn
pub const ConnectError = ConnectErrorPartial || RequestError;
/// Connect to `host:port` using the specified protocol. This will reuse a connection if one is already open.
///
///
/// If a proxy is configured for the client, then the proxy will be used to connect to the host.
///
///
/// This function is threadsafe.
pub fn connect(client: *Client, host: []const u8, port: u16, protocol: Connection.Protocol) ConnectError!*Connection {
// pointer required so that `supports_connect` can be updated if a CONNECT fails
@ -1304,7 +1304,7 @@ pub fn connect(client: *Client, host: []const u8, port: u16, protocol: Connectio
return client.connectTcp(host, port, protocol);
}
pub const RequestError = ConnectTcpError || ConnectErrorPartial || Request.StartError || std.fmt.ParseIntError || Connection.WriteError || error{
pub const RequestError = ConnectTcpError || ConnectErrorPartial || Request.SendError || std.fmt.ParseIntError || Connection.WriteError || error{
UnsupportedUrlScheme,
UriMissingHost,
@ -1350,7 +1350,7 @@ pub const protocol_map = std.ComptimeStringMap(Connection.Protocol, .{
///
/// The caller is responsible for calling `deinit()` on the `Request`.
/// This function is threadsafe.
pub fn request(client: *Client, method: http.Method, uri: Uri, headers: http.Headers, options: RequestOptions) RequestError!Request {
pub fn open(client: *Client, method: http.Method, uri: Uri, headers: http.Headers, options: RequestOptions) RequestError!Request {
const protocol = protocol_map.get(uri.scheme) orelse return error.UnsupportedUrlScheme;
const port: u16 = uri.port orelse switch (protocol) {
@ -1446,7 +1446,7 @@ pub const FetchResult = struct {
};
/// Perform a one-shot HTTP request with the provided options.
///
///
/// This function is threadsafe.
pub fn fetch(client: *Client, allocator: Allocator, options: FetchOptions) !FetchResult {
const has_transfer_encoding = options.headers.contains("transfer-encoding");
@ -1459,7 +1459,7 @@ pub fn fetch(client: *Client, allocator: Allocator, options: FetchOptions) !Fetc
.uri => |u| u,
};
var req = try request(client, options.method, uri, options.headers, .{
var req = try open(client, options.method, uri, options.headers, .{
.header_strategy = options.header_strategy,
.handle_redirects = options.payload == .none,
});
@ -1476,7 +1476,7 @@ pub fn fetch(client: *Client, allocator: Allocator, options: FetchOptions) !Fetc
.none => {},
}
try req.start(.{ .raw_uri = options.raw_uri });
try req.send(.{ .raw_uri = options.raw_uri });
switch (options.payload) {
.string => |str| try req.writeAll(str),

View File

@ -392,10 +392,10 @@ pub const Response = struct {
}
}
pub const StartError = Connection.WriteError || error{ UnsupportedTransferEncoding, InvalidContentLength };
pub const SendError = Connection.WriteError || error{ UnsupportedTransferEncoding, InvalidContentLength };
/// Send the HTTP response headers to the client.
pub fn start(res: *Response) StartError!void {
pub fn send(res: *Response) SendError!void {
switch (res.state) {
.waited => res.state = .responded,
.first, .start, .responded, .finished => unreachable,
@ -771,7 +771,7 @@ test "HTTP server handles a chunked transfer coding request" {
res.transfer_encoding = .{ .content_length = server_body.len };
try res.headers.append("content-type", "text/plain");
try res.headers.append("connection", "close");
try res.do();
try res.send();
var buf: [128]u8 = undefined;
const n = try res.readAll(&buf);

View File

@ -826,7 +826,7 @@ fn initResource(f: *Fetch, uri: std.Uri) RunError!Resource {
var h = std.http.Headers{ .allocator = gpa };
defer h.deinit();
var req = http_client.request(.GET, uri, h, .{}) catch |err| {
var req = http_client.open(.GET, uri, h, .{}) catch |err| {
return f.fail(f.location_tok, try eb.printString(
"unable to connect to server: {s}",
.{@errorName(err)},
@ -834,7 +834,7 @@ fn initResource(f: *Fetch, uri: std.Uri) RunError!Resource {
};
errdefer req.deinit(); // releases more than memory
req.start(.{}) catch |err| {
req.send(.{}) catch |err| {
return f.fail(f.location_tok, try eb.printString(
"HTTP request failed: {s}",
.{@errorName(err)},

View File

@ -518,11 +518,11 @@ pub const Session = struct {
defer headers.deinit();
try headers.append("Git-Protocol", "version=2");
var request = try session.transport.request(.GET, info_refs_uri, headers, .{
var request = try session.transport.open(.GET, info_refs_uri, headers, .{
.max_redirects = 3,
});
errdefer request.deinit();
try request.start(.{});
try request.send(.{});
try request.finish();
try request.wait();
@ -641,12 +641,12 @@ pub const Session = struct {
}
try Packet.write(.flush, body_writer);
var request = try session.transport.request(.POST, upload_pack_uri, headers, .{
var request = try session.transport.open(.POST, upload_pack_uri, headers, .{
.handle_redirects = false,
});
errdefer request.deinit();
request.transfer_encoding = .{ .content_length = body.items.len };
try request.start(.{});
try request.send(.{});
try request.writeAll(body.items);
try request.finish();
@ -740,12 +740,12 @@ pub const Session = struct {
try Packet.write(.{ .data = "done\n" }, body_writer);
try Packet.write(.flush, body_writer);
var request = try session.transport.request(.POST, upload_pack_uri, headers, .{
var request = try session.transport.open(.POST, upload_pack_uri, headers, .{
.handle_redirects = false,
});
errdefer request.deinit();
request.transfer_encoding = .{ .content_length = body.items.len };
try request.start(.{});
try request.send(.{});
try request.writeAll(body.items);
try request.finish();

View File

@ -29,11 +29,11 @@ fn handleRequest(res: *Server.Response) !void {
if (res.request.headers.contains("expect")) {
if (mem.eql(u8, res.request.headers.getFirstValue("expect").?, "100-continue")) {
res.status = .@"continue";
try res.start();
try res.send();
res.status = .ok;
} else {
res.status = .expectation_failed;
try res.start();
try res.send();
return;
}
}
@ -54,7 +54,7 @@ fn handleRequest(res: *Server.Response) !void {
try res.headers.append("content-type", "text/plain");
try res.start();
try res.send();
if (res.request.method != .HEAD) {
try res.writeAll("Hello, ");
try res.writeAll("World!\n");
@ -65,7 +65,7 @@ fn handleRequest(res: *Server.Response) !void {
} else if (mem.startsWith(u8, res.request.target, "/large")) {
res.transfer_encoding = .{ .content_length = 14 * 1024 + 14 * 10 };
try res.start();
try res.send();
var i: u32 = 0;
while (i < 5) : (i += 1) {
@ -92,14 +92,14 @@ fn handleRequest(res: *Server.Response) !void {
try testing.expectEqualStrings("14", res.request.headers.getFirstValue("content-length").?);
}
try res.start();
try res.send();
try res.writeAll("Hello, ");
try res.writeAll("World!\n");
try res.finish();
} else if (mem.eql(u8, res.request.target, "/trailer")) {
res.transfer_encoding = .chunked;
try res.start();
try res.send();
try res.writeAll("Hello, ");
try res.writeAll("World!\n");
// try res.finish();
@ -110,7 +110,7 @@ fn handleRequest(res: *Server.Response) !void {
res.status = .found;
try res.headers.append("location", "../../get");
try res.start();
try res.send();
try res.writeAll("Hello, ");
try res.writeAll("Redirected!\n");
try res.finish();
@ -120,7 +120,7 @@ fn handleRequest(res: *Server.Response) !void {
res.status = .found;
try res.headers.append("location", "/redirect/1");
try res.start();
try res.send();
try res.writeAll("Hello, ");
try res.writeAll("Redirected!\n");
try res.finish();
@ -133,7 +133,7 @@ fn handleRequest(res: *Server.Response) !void {
res.status = .found;
try res.headers.append("location", location);
try res.start();
try res.send();
try res.writeAll("Hello, ");
try res.writeAll("Redirected!\n");
try res.finish();
@ -143,7 +143,7 @@ fn handleRequest(res: *Server.Response) !void {
res.status = .found;
try res.headers.append("location", "/redirect/3");
try res.start();
try res.send();
try res.writeAll("Hello, ");
try res.writeAll("Redirected!\n");
try res.finish();
@ -154,11 +154,11 @@ fn handleRequest(res: *Server.Response) !void {
res.status = .found;
try res.headers.append("location", location);
try res.start();
try res.send();
try res.finish();
} else {
res.status = .not_found;
try res.start();
try res.send();
}
}
@ -244,10 +244,10 @@ pub fn main() !void {
const uri = try std.Uri.parse(location);
log.info("{s}", .{location});
var req = try client.request(.GET, uri, h, .{});
var req = try client.open(.GET, uri, h, .{});
defer req.deinit();
try req.start(.{});
try req.send(.{});
try req.wait();
const body = try req.reader().readAllAlloc(calloc, 8192);
@ -269,10 +269,10 @@ pub fn main() !void {
const uri = try std.Uri.parse(location);
log.info("{s}", .{location});
var req = try client.request(.GET, uri, h, .{});
var req = try client.open(.GET, uri, h, .{});
defer req.deinit();
try req.start(.{});
try req.send(.{});
try req.wait();
const body = try req.reader().readAllAlloc(calloc, 8192 * 1024);
@ -293,10 +293,10 @@ pub fn main() !void {
const uri = try std.Uri.parse(location);
log.info("{s}", .{location});
var req = try client.request(.HEAD, uri, h, .{});
var req = try client.open(.HEAD, uri, h, .{});
defer req.deinit();
try req.start(.{});
try req.send(.{});
try req.wait();
const body = try req.reader().readAllAlloc(calloc, 8192);
@ -319,10 +319,10 @@ pub fn main() !void {
const uri = try std.Uri.parse(location);
log.info("{s}", .{location});
var req = try client.request(.GET, uri, h, .{});
var req = try client.open(.GET, uri, h, .{});
defer req.deinit();
try req.start(.{});
try req.send(.{});
try req.wait();
const body = try req.reader().readAllAlloc(calloc, 8192);
@ -344,10 +344,10 @@ pub fn main() !void {
const uri = try std.Uri.parse(location);
log.info("{s}", .{location});
var req = try client.request(.HEAD, uri, h, .{});
var req = try client.open(.HEAD, uri, h, .{});
defer req.deinit();
try req.start(.{});
try req.send(.{});
try req.wait();
const body = try req.reader().readAllAlloc(calloc, 8192);
@ -370,10 +370,10 @@ pub fn main() !void {
const uri = try std.Uri.parse(location);
log.info("{s}", .{location});
var req = try client.request(.GET, uri, h, .{});
var req = try client.open(.GET, uri, h, .{});
defer req.deinit();
try req.start(.{});
try req.send(.{});
try req.wait();
const body = try req.reader().readAllAlloc(calloc, 8192);
@ -397,12 +397,12 @@ pub fn main() !void {
const uri = try std.Uri.parse(location);
log.info("{s}", .{location});
var req = try client.request(.POST, uri, h, .{});
var req = try client.open(.POST, uri, h, .{});
defer req.deinit();
req.transfer_encoding = .{ .content_length = 14 };
try req.start(.{});
try req.send(.{});
try req.writeAll("Hello, ");
try req.writeAll("World!\n");
try req.finish();
@ -429,10 +429,10 @@ pub fn main() !void {
const uri = try std.Uri.parse(location);
log.info("{s}", .{location});
var req = try client.request(.GET, uri, h, .{});
var req = try client.open(.GET, uri, h, .{});
defer req.deinit();
try req.start(.{});
try req.send(.{});
try req.wait();
const body = try req.reader().readAllAlloc(calloc, 8192);
@ -456,12 +456,12 @@ pub fn main() !void {
const uri = try std.Uri.parse(location);
log.info("{s}", .{location});
var req = try client.request(.POST, uri, h, .{});
var req = try client.open(.POST, uri, h, .{});
defer req.deinit();
req.transfer_encoding = .chunked;
try req.start(.{});
try req.send(.{});
try req.writeAll("Hello, ");
try req.writeAll("World!\n");
try req.finish();
@ -486,10 +486,10 @@ pub fn main() !void {
const uri = try std.Uri.parse(location);
log.info("{s}", .{location});
var req = try client.request(.GET, uri, h, .{});
var req = try client.open(.GET, uri, h, .{});
defer req.deinit();
try req.start(.{});
try req.send(.{});
try req.wait();
const body = try req.reader().readAllAlloc(calloc, 8192);
@ -510,10 +510,10 @@ pub fn main() !void {
const uri = try std.Uri.parse(location);
log.info("{s}", .{location});
var req = try client.request(.GET, uri, h, .{});
var req = try client.open(.GET, uri, h, .{});
defer req.deinit();
try req.start(.{});
try req.send(.{});
try req.wait();
const body = try req.reader().readAllAlloc(calloc, 8192);
@ -534,10 +534,10 @@ pub fn main() !void {
const uri = try std.Uri.parse(location);
log.info("{s}", .{location});
var req = try client.request(.GET, uri, h, .{});
var req = try client.open(.GET, uri, h, .{});
defer req.deinit();
try req.start(.{});
try req.send(.{});
try req.wait();
const body = try req.reader().readAllAlloc(calloc, 8192);
@ -558,10 +558,10 @@ pub fn main() !void {
const uri = try std.Uri.parse(location);
log.info("{s}", .{location});
var req = try client.request(.GET, uri, h, .{});
var req = try client.open(.GET, uri, h, .{});
defer req.deinit();
try req.start(.{});
try req.send(.{});
req.wait() catch |err| switch (err) {
error.TooManyHttpRedirects => {},
else => return err,
@ -580,10 +580,10 @@ pub fn main() !void {
const uri = try std.Uri.parse(location);
log.info("{s}", .{location});
var req = try client.request(.GET, uri, h, .{});
var req = try client.open(.GET, uri, h, .{});
defer req.deinit();
try req.start(.{});
try req.send(.{});
const result = req.wait();
// a proxy without an upstream is likely to return a 5xx status.
@ -628,12 +628,12 @@ pub fn main() !void {
const uri = try std.Uri.parse(location);
log.info("{s}", .{location});
var req = try client.request(.POST, uri, h, .{});
var req = try client.open(.POST, uri, h, .{});
defer req.deinit();
req.transfer_encoding = .chunked;
try req.start(.{});
try req.send(.{});
try req.wait();
try testing.expectEqual(http.Status.@"continue", req.response.status);
@ -662,12 +662,12 @@ pub fn main() !void {
const uri = try std.Uri.parse(location);
log.info("{s}", .{location});
var req = try client.request(.POST, uri, h, .{});
var req = try client.open(.POST, uri, h, .{});
defer req.deinit();
req.transfer_encoding = .chunked;
try req.start(.{});
try req.send(.{});
try req.wait();
try testing.expectEqual(http.Status.expectation_failed, req.response.status);
}
@ -682,7 +682,7 @@ pub fn main() !void {
defer calloc.free(requests);
for (0..total_connections) |i| {
var req = try client.request(.GET, uri, .{ .allocator = calloc }, .{});
var req = try client.open(.GET, uri, .{ .allocator = calloc }, .{});
req.response.parser.done = true;
req.connection.?.closing = false;
requests[i] = req;