#cannot handle read request following accept request on io_uring tcp server

1 messages · Page 1 of 1 (latest)

wooden panther
#

code in msg format for ease of reading/access:

const std = @import("std");
const posix = std.posix;
const request = @import("request.zig");
const linux = std.os.linux;

const Response = @import("response.zig").Response;
const Address = std.net.Address;

const EventType = enum(u8) { ACCEPT, READ, WRITE };

const Client = struct {
    allocator: *std.mem.Allocator,
    client_socket: posix.socket_t,
    buffer: []u8,

    fn init(allocator: *std.mem.Allocator, socket: posix.socket_t) !Client {
        const buffer = try allocator.alloc(u8, 4096);
        @memset(buffer, 0); //done to make buffer readable

        return .{
            .allocator = allocator,
            .client_socket = socket,
            .buffer = buffer,
        };
    }

    fn deinit(self: *Client, allocator: *std.mem.Allocator) void {
        allocator.free(self.buffer);
        allocator.destroy(self);
    }
};

const Event = struct {
    ptr: ?*Client,
    event_type: EventType,

    fn init(ptr: ?*Client, event_type: EventType) Event {
        return .{ .ptr = ptr, .event_type = event_type };
    }
};

fn addAcceptRequest(ring: *linux.IoUring, listener: posix.socket_t, allocator: *std.mem.Allocator) !void {
    const event = try allocator.create(Event);
    event.* = Event.init(null, .ACCEPT);

    var address: posix.sockaddr = undefined;
    var address_len: posix.socklen_t = @sizeOf(posix.sockaddr);

    const user_data: usize = @intFromPtr(event);
    std.debug.print("ACCEPT - user_data: {any}\n", .{user_data});
    _ = try ring.accept(user_data, listener, &address, &address_len, 0);
    const num_submitted = try ring.submit();
    std.debug.print("ACCEPT - num_submitted: {any}\n", .{num_submitted});
}
#
fn addReadRequest(ring: *linux.IoUring, client_socket: posix.socket_t, allocator: *std.mem.Allocator) !void {
    const client = try allocator.create(Client);
    client.* = try Client.init(allocator, client_socket);

    const event = try allocator.create(Event);
    event.* = Event.init(client, .READ);

    const read_buffer = linux.IoUring.ReadBuffer{ .buffer = client.buffer[0..] };
    const user_data: usize = @intFromPtr(event);

    _ = try ring.read(user_data, client.client_socket, read_buffer, 0);
    const num_submitted = try ring.submit();
    std.debug.print("READ - num_submitted: {any}\n", .{num_submitted});
}

fn handleRequest(client: *Client) void {
    _ = request.parse_request(client.buffer) catch |err| {
        std.log.err("Invalid request when parsing: {any}", .{err});
        return;
    };

    std.debug.print("\nClient Request\n{s}\n\n", .{client.buffer}); //view contents of buffer after reading/parsing is done
}