aboutsummaryrefslogtreecommitdiff
path: root/src/http/async_bio.zig
blob: 5e86da949044b5630bafff0213aa3d080ae2c941 (plain) (blame)
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
const boring = @import("boringssl");
const std = @import("std");
const AsyncIO = @import("io");
const Completion = AsyncIO.Completion;
const AsyncMessage = @import("./async_message.zig");
const AsyncBIO = @This();
const Output = @import("../global.zig").Output;
const extremely_verbose = @import("../http_client_async.zig").extremely_verbose;
const SOCKET_FLAGS = @import("../http_client_async.zig").SOCKET_FLAGS;
const getAllocator = @import("../http_client_async.zig").getAllocator;

bio: *boring.BIO = undefined,
socket_fd: std.os.socket_t = 0,
allocator: std.mem.Allocator,

read_buf_len: usize = 0,

read_wait: Wait = Wait.pending,
send_wait: Wait = Wait.pending,
recv_completion: AsyncIO.Completion = undefined,
send_completion: AsyncIO.Completion = undefined,

write_buffer: ?*AsyncMessage = null,

last_send_result: AsyncIO.SendError!usize = 0,

last_read_result: AsyncIO.RecvError!usize = 0,
next: ?*AsyncBIO = null,
pending_frame: PendingFrame = PendingFrame.init(),

pub const PendingFrame = std.fifo.LinearFifo(anyframe, .{ .Static = 8 });

pub inline fn pushPendingFrame(this: *AsyncBIO, frame: anyframe) void {
    this.pending_frame.writeItem(frame) catch {};
}

pub inline fn popPendingFrame(this: *AsyncBIO) ?anyframe {
    return this.pending_frame.readItem();
}

var method: ?*boring.BIO_METHOD = null;
var head: ?*AsyncBIO = null;

const async_bio_name: [:0]const u8 = "AsyncBIO";

const Wait = enum {
    pending,
    suspended,
    completed,
};

fn instance(allocator: std.mem.Allocator) *AsyncBIO {
    if (head) |head_| {
        var next = head_.next;
        var ret = head_;
        ret.read_wait = .pending;
        ret.send_wait = .pending;
        head = next;

        ret.pending_frame = PendingFrame.init();
        return ret;
    }

    var bio = allocator.create(AsyncBIO) catch unreachable;
    bio.* = AsyncBIO{
        .allocator = allocator,
        .read_wait = .pending,
        .send_wait = .pending,
    };

    return bio;
}

pub fn release(this: *AsyncBIO) void {
    if (head) |head_| {
        this.next = head_;
    }

    this.read_wait = .pending;
    this.last_read_result = 0;
    this.send_wait = .pending;
    this.last_read_result = 0;
    this.pending_frame = PendingFrame.init();

    if (this.write_buffer) |write| {
        write.release();
        this.write_buffer = null;
    }

    head = this;
}

pub fn init(allocator: std.mem.Allocator) !*AsyncBIO {
    var bio = instance(allocator);

    bio.bio = boring.BIO_new(
        method orelse brk: {
            method = boring.BIOMethod.init(async_bio_name, Bio.create, Bio.destroy, Bio.write, Bio.read, null, Bio.ctrl);
            break :brk method.?;
        },
    ) orelse return error.OutOfMemory;

    _ = boring.BIO_set_data(bio.bio, bio);
    return bio;
}

const WaitResult = enum {
    none,
    read,
    send,
};

const Sender = struct {
    pub fn onSend(this: *AsyncBIO, _: *Completion, result: AsyncIO.SendError!usize) void {
        this.last_send_result = result;
        this.send_wait = .completed;
        this.write_buffer.?.sent += @truncate(u32, result catch 0);

        if (extremely_verbose) {
            const read_result = result catch @as(usize, 999);
            Output.prettyErrorln("onSend: {d}", .{read_result});
            Output.flush();
        }

        if (this.pending_frame.readItem()) |frame| {
            resume frame;
        }
    }
};

pub fn enqueueSend(
    self: *AsyncBIO,
) void {
    if (self.write_buffer == null) return;
    var to_write = self.write_buffer.?.slice();
    if (to_write.len == 0) {
        return;
    }

    self.last_send_result = 0;

    AsyncIO.global.send(
        *AsyncBIO,
        self,
        Sender.onSend,
        &self.send_completion,
        self.socket_fd,
        to_write,
        SOCKET_FLAGS,
    );
    self.send_wait = .suspended;
    if (extremely_verbose) {
        Output.prettyErrorln("enqueueSend: {d}", .{to_write.len});
        Output.flush();
    }
}

const Reader = struct {
    pub fn onRead(this: *AsyncBIO, _: *Completion, result: AsyncIO.RecvError!usize) void {
        this.last_read_result = result;
        this.read_wait = .completed;
        if (extremely_verbose) {
            const read_result = result catch @as(usize, 999);
            Output.prettyErrorln("onRead: {d}", .{read_result});
            Output.flush();
        }
        if (this.pending_frame.readItem()) |frame| {
            resume frame;
        }
    }
};

pub fn enqueueRead(self: *AsyncBIO, read_buf: []u8, off: u64) void {
    var read_buffer = read_buf[off..];
    if (read_buffer.len == 0) {
        return;
    }

    self.last_read_result = 0;
    AsyncIO.global.recv(*AsyncBIO, self, Reader.onRead, &self.recv_completion, self.socket_fd, read_buffer);
    self.read_wait = .suspended;
    if (extremely_verbose) {
        Output.prettyErrorln("enqueuedRead: {d}", .{read_buf.len});
        Output.flush();
    }
}

pub const Bio = struct {
    inline fn cast(bio: *boring.BIO) *AsyncBIO {
        return @ptrCast(*AsyncBIO, @alignCast(@alignOf(*AsyncBIO), boring.BIO_get_data(bio)));
    }

    pub fn create(this_bio: *boring.BIO) callconv(.C) c_int {
        boring.BIO_set_init(this_bio, 1);
        return 1;
    }
    pub fn destroy(this_bio: *boring.BIO) callconv(.C) c_int {
        boring.BIO_set_init(this_bio, 0);

        if (boring.BIO_get_data(this_bio) != null) {
            var this = cast(this_bio);
            this.release();
        }

        return 0;
    }
    pub fn write(this_bio: *boring.BIO, ptr: [*c]const u8, len: c_int) callconv(.C) c_int {
        std.debug.assert(@ptrToInt(ptr) > 0 and len >= 0);

        var buf = ptr[0..@intCast(usize, len)];
        boring.BIO_clear_flags(this_bio, boring.BIO_FLAGS_RWS | boring.BIO_FLAGS_SHOULD_RETRY);

        if (len <= 0) {
            return 0;
        }

        var this = cast(this_bio);
        if (this.read_wait == .suspended) {
            boring.BIO_set_flags(this_bio, (boring.BIO_FLAGS_RWS | boring.BIO_FLAGS_SHOULD_RETRY));
            return -1;
        }

        switch (this.send_wait) {
            .pending => {
                var write_buffer = this.write_buffer orelse brk: {
                    this.write_buffer = AsyncMessage.get(getAllocator());
                    break :brk this.write_buffer.?;
                };

                _ = write_buffer.writeAll(buf);
                boring.BIO_set_flags(this_bio, (boring.BIO_FLAGS_RWS | boring.BIO_FLAGS_SHOULD_RETRY));

                return -1;
            },
            .suspended => {
                boring.BIO_set_flags(this_bio, (boring.BIO_FLAGS_RWS | boring.BIO_FLAGS_SHOULD_RETRY));

                return -1;
            },
            .completed => {
                this.send_wait = .pending;
                const written = this.last_send_result catch |err| {
                    Output.prettyErrorln("HTTPS error: {s}", .{@errorName(err)});
                    Output.flush();
                    boring.BIO_set_flags(this_bio, (boring.BIO_FLAGS_RWS | boring.BIO_FLAGS_SHOULD_RETRY));
                    return -1;
                };
                this.last_send_result = 0;
                return @intCast(c_int, written);
            },
        }

        unreachable;
    }

    pub fn read(this_bio: *boring.BIO, ptr: [*c]u8, len: c_int) callconv(.C) c_int {
        std.debug.assert(@ptrToInt(ptr) > 0 and len >= 0);
        var this = cast(this_bio);

        var buf = ptr[0..@maximum(@intCast(usize, len), this.read_buf_len)];

        boring.BIO_clear_flags(this_bio, boring.BIO_FLAGS_RWS | boring.BIO_FLAGS_SHOULD_RETRY);

        switch (this.read_wait) {
            .pending => {
                this.enqueueRead(buf, 0);
                boring.BIO_set_flags(this_bio, (boring.BIO_FLAGS_WRITE | boring.BIO_FLAGS_SHOULD_RETRY));
                return -1;
            },
            .suspended => {
                boring.BIO_set_flags(this_bio, (boring.BIO_FLAGS_WRITE | boring.BIO_FLAGS_SHOULD_RETRY));
                return -1;
            },
            .completed => {
                this.read_wait = .pending;
                const read_len = this.last_read_result catch |err| {
                    Output.prettyErrorln("HTTPS error: {s}", .{@errorName(err)});
                    Output.flush();
                    boring.BIO_set_flags(this_bio, (boring.BIO_FLAGS_WRITE | boring.BIO_FLAGS_SHOULD_RETRY));
                    return -1;
                };
                this.last_read_result = 0;
                return @intCast(c_int, read_len);
            },
        }
        unreachable;
    }
    pub fn ctrl(_: *boring.BIO, cmd: c_int, _: c_long, _: ?*anyopaque) callconv(.C) c_long {
        return switch (cmd) {
            boring.BIO_CTRL_PENDING, boring.BIO_CTRL_WPENDING => 0,
            else => 1,
        };
    }
};