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
const std = @import("std");
const builtin = @import("builtin");
const Connection = std.http.Client.Connection;
const Pool = std.http.Client.ConnectionPool;
pub fn release(io: std.Io, pool: *Pool, connection: *Connection) ?*Connection {
pool.mutex.lockUncancelable(io);
defer pool.mutex.unlock(io);
pool.used.remove(&connection.pool_node);
if (connection.closing or pool.free_size == 0) return connection;
var retired: ?*Connection = null;
if (pool.free_len >= pool.free_size) {
retired = @alignCast(@fieldParentPtr("pool_node", pool.free.popFirst().?));
pool.free_len -= 1;
}
if (connection.proxied) {
pool.free.prepend(&connection.pool_node);
} else {
pool.free.append(&connection.pool_node);
}
pool.free_len += 1;
return retired;
}
pub fn pop(io: std.Io, pool: *Pool) ?*Connection {
pool.mutex.lockUncancelable(io);
defer pool.mutex.unlock(io);
const node = pool.free.popFirst() orelse return null;
pool.free_len -= 1;
return @alignCast(@fieldParentPtr("pool_node", node));
}
pub fn hasTls(io: std.Io, pool: *Pool) bool {
pool.mutex.lockUncancelable(io);
defer pool.mutex.unlock(io);
var next = pool.free.first;
while (next) |node| : (next = node.next) {
const connection: *Connection = @alignCast(@fieldParentPtr("pool_node", node));
if (connection.protocol == .tls) return true;
}
return false;
}
/// Removes idle connections the peer has already closed and returns them for
/// the caller to destroy outside the lock. An idle HTTP/1.1 connection has
/// nothing to read, so readiness means a FIN, a reset or a TLS alert. Left in
/// the pool, such a socket sits in CLOSE_WAIT until it is picked for a request
/// and fails there.
pub fn takeClosed(io: std.Io, pool: *Pool) std.DoublyLinkedList {
var closed: std.DoublyLinkedList = .{};
if (comptime builtin.os.tag == .windows) return closed;
pool.mutex.lockUncancelable(io);
defer pool.mutex.unlock(io);
var next = pool.free.first;
while (next != null) {
var batch: [32]*Connection = undefined;
var fds: [32]std.posix.pollfd = undefined;
var len: usize = 0;
while (next) |node| : (next = node.next) {
if (len == batch.len) break;
const connection: *Connection = @alignCast(@fieldParentPtr("pool_node", node));
batch[len] = connection;
fds[len] = .{ .fd = connection.stream_reader.stream.socket.handle, .events = std.posix.POLL.IN, .revents = 0 };
len += 1;
}
const ready = std.posix.poll(fds[0..len], 0) catch return closed;
if (ready == 0) continue;
for (batch[0..len], fds[0..len]) |connection, fd| {
if (fd.revents == 0) continue;
pool.free.remove(&connection.pool_node);
pool.free_len -= 1;
closed.append(&connection.pool_node);
}
}
return closed;
}