summaryrefslogtreecommitdiff
path: root/src/main.zig
blob: 6ebd11eb797cb5cf6d74abe223e74db0b40ec890 (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
const std = @import("std");
const zits = @import("zits");
const clap = @import("clap");

const SubCommands = enum {
    help,
    serve,
    @"pub",
};

const main_parsers = .{
    .command = clap.parsers.enumeration(SubCommands),
};

// The parameters for `main`. Parameters for the subcommands are specified further down.
const main_params = clap.parseParamsComptime(
    \\-h, --help  Display this help and exit.
    \\<command>
    \\
);

// To pass around arguments returned by clap, `clap.Result` and `clap.ResultEx` can be used to
// get the return type of `clap.parse` and `clap.parseEx`.
const MainArgs = clap.ResultEx(clap.Help, &main_params, main_parsers);

pub fn main() !void {
    var dba = std.heap.DebugAllocator(.{}){};
    defer _ = dba.deinit();
    const gpa = dba.allocator();

    var iter = try std.process.ArgIterator.initWithAllocator(gpa);
    defer iter.deinit();

    _ = iter.next();

    var diag = clap.Diagnostic{};
    var res = clap.parseEx(clap.Help, &main_params, main_parsers, &iter, .{
        .diagnostic = &diag,
        .allocator = gpa,

        // Terminate the parsing of arguments after parsing the first positional (0 is passed
        // here because parsed positionals are, like slices and arrays, indexed starting at 0).
        //
        // This will terminate the parsing after parsing the subcommand enum and leave `iter`
        // not fully consumed. It can then be reused to parse the arguments for subcommands.
        .terminating_positional = 0,
    }) catch |err| {
        try diag.reportToFile(.stderr(), err);
        return err;
    };
    defer res.deinit();

    if (res.args.help != 0)
        return clap.helpToFile(.stderr(), clap.Help, &main_params, .{});

    const command = res.positionals[0] orelse return error.MissingCommand;
    switch (command) {
        .help => return clap.helpToFile(.stderr(), clap.Help, &main_params, .{}),
        .serve => try serverMain(gpa, &iter, res),
        .@"pub" => unreachable,
    }
}

const ServerInfo = struct {
    /// The unique identifier of the NATS server.
    server_id: []const u8,
    /// The name of the NATS server.
    server_name: []const u8,
    /// The version of NATS.
    version: []const u8,
    /// The version of golang the NATS server was built with.
    go: []const u8 = "0.0.0",
    /// The IP address used to start the NATS server,
    /// by default this will be 0.0.0.0 and can be
    /// configured with -client_advertise host:port.
    host: []const u8 = "0.0.0.0",
    /// The port number the NATS server is configured
    /// to listen on.
    port: u16 = 6868,
    /// Whether the server supports headers.
    headers: bool = false,
    /// Maximum payload size, in bytes, that the server
    /// will accept from the client.
    max_payload: u64,
    /// An integer indicating the protocol version of
    /// the server. The server version 1.2.0 sets this
    /// to 1 to indicate that it supports the "Echo"
    /// feature.
    proto: u32 = 1,
};

fn serverMain(gpa: std.mem.Allocator, iter: *std.process.ArgIterator, main_args: MainArgs) !void {
    _ = iter;
    _ = main_args;

    var threaded: std.Io.Threaded = .init(gpa);
    defer threaded.deinit();
    const io = threaded.io();

    const info: ServerInfo = .{
        .server_id = "NBEK5DBBB4ZO5LTBGPXACZSB2QUTODC6GGN5NLOSPIGSRFWJID4XU52C",
        .server_name = "bar",
        .version = "2.11.8",
        .go = "go1.24.6",
        .headers = true,
        .max_payload = 1048576,
    };

    // const info: ServerInfo = .{
    //     .server_id = "foo",
    //     .server_name = "bar",
    //     .version = "6.9.0",
    //     .max_payload = 6969,
    // };

    var server = try std.Io.net.IpAddress.listen(.{
        .ip4 = .{
            .bytes = .{ 0, 0, 0, 0 },
            .port = info.port,
        },
    }, io, .{});
    defer server.deinit(io);

    var group: std.Io.Group = .init;
    defer group.wait(io);
    for (0..5) |_| {
        const stream = try server.accept(io);
        group.async(io, handleConnection, .{ io, stream, info });
    }
}

fn handleConnection(io: std.Io, stream: std.Io.net.Stream, info: ServerInfo) void {
    defer stream.close(io);
    var w_buffer: [1024]u8 = undefined;
    var writer = stream.writer(io, &w_buffer);
    const out = &writer.interface;

    var r_buffer: [1024]u8 = undefined;
    var reader = stream.reader(io, &r_buffer);
    const in = &reader.interface;

    processClient(in, out, info) catch |err| {
        std.debug.print("Error processing client: {}\n", .{err});
    };

    // var stdout_buffer: [1024]u8 = undefined;
    // const stdout_file = std.fs.File.stdout();
    // var stdout_file_writer = stdout_file.writer(&stdout_buffer);
    // const stdout_writer = &stdout_file_writer.interface;

    // var timeout = io.async(std.Io.sleep, .{ io, .fromSeconds(10), .real });
    // defer timeout.cancel(io) catch {};

    // var user_res = io.async(std.Io.Reader.streamRemaining, .{ in, stdout_writer });
    // defer _ = user_res.cancel(io) catch {};

    // switch (io.select(.{
    //     .timeout = &timeout,
    //     .data = &user_res,
    // }) catch unreachable) {
    //     .timeout => std.debug.print("timeout\n", .{}),
    //     .data => |_| {
    //         stdout_writer.flush() catch |err| {
    //             std.debug.print("Could not flush stdout: {}\n", .{err});
    //         };
    //         // std.debug.print("received data {any}\n", .{d});
    //     },
    // }
}

fn processClient(in: *std.Io.Reader, out: *std.Io.Writer, info: ServerInfo) !void {
    try writeInfo(out, info);

    const ClientState = struct {
        verbose: bool = false,
        pedantic: bool = false,
        tls_required: bool = false,
        auth_token: ?[]const u8 = null,
        user: ?[]const u8 = null,
        pass: ?[]const u8 = null,
        name: ?[]const u8 = null,
        lang: []const u8,
        version: []const u8,
        protocol: u32,
        echo: ?bool = null,
        sig: ?[]const u8 = null,
        jwt: ?[]const u8 = null,
        no_responders: ?bool = null,
        headers: ?bool = null,
        nkey: ?[]const u8 = null,
    };

    const MessageType = enum {
        info,
        connect,
        @"pub",
        hpub,
        sub,
        unsub,
        msg,
        hmsg,
        ping,
        pong,
        @"+ok",
        @"-err",

        // fn parse(input: []u8) !MessageType {
        //     // if (std.mem.eql(u8, "INFO", input)) return .info;
        //     if (std.mem.eql(u8, "CONNECT", input)) return .connect;
        //     if (std.mem.eql(u8, "PUB", input)) return .@"pub";
        //     if (std.mem.eql(u8, "HPUB", input)) return .hpub;
        //     if (std.mem.eql(u8, "SUB", input)) return .sub;
        //     if (std.mem.eql(u8, "UNSUB", input)) return .unsub;
        //     // if (std.mem.eql(u8, "MSG", input)) return .msg;
        //     // if (std.mem.eql(u8, "HMSG", input)) return .hmsg;
        //     if (std.mem.eql(u8, "PING", input)) return .ping;
        //     if (std.mem.eql(u8, "PONG", input)) return .pong;
        //     // if (std.mem.eql(u8, "@"+OK"", input)) return .@"+ok";
        //     // if (std.mem.eql(u8, "@"-ERR"", input)) return .@"-err";
        //     return error.InvalidMessageType;
        // }

        const client_types = std.StaticStringMap(@This()).initComptime(
            .{
                // {"INFO", .info},
                .{ "CONNECT", .connect },
                .{ "PUB", .@"pub" },
                .{ "HPUB", .hpub },
                .{ "SUB", .sub },
                .{ "UNSUB", .unsub },
                // {"MSG", .msg},
                // {"HMSG", .hmsg},
                .{ "PING", .ping },
                .{ "PONG", .pong },
                // {"+OK", .@"+ok"},
                // {"-ERR", .@"-err"},
            },
        );
        fn parse(input: []u8) !@This() {
            return client_types.get(input) orelse return error.InvalidMessageType;
        }
    };

    const initial_message_type = try MessageType.parse((in.takeDelimiter(' ') catch return error.InvalidMessageType) orelse return error.InvalidMessageType);
    if (initial_message_type != .connect) return error.InvalidMessageType;

    // move this inside client_state declaration
    var json_parse_buf: [1024]u8 = undefined;
    var json_parse_alloc_fb: std.heap.FixedBufferAllocator = std.heap.FixedBufferAllocator.init(&json_parse_buf);
    var json_parse_alloc = json_parse_alloc_fb.allocator();
    var json_reader: std.json.Reader = .init(json_parse_alloc, in);

    std.debug.print("buffered:{s}\n", .{in.buffered()});

    var client_state = try std.json.parseFromTokenSourceLeaky(ClientState, json_parse_alloc, &json_reader, .{});

    std.debug.print("client_state: {any}\n", .{client_state});

    while (true) {
        // Rebase the next message to the start of the buffer
        // in.rebase(in.buffer.len);
        const next_message_type = try MessageType.parse((in.takeDelimiter(' ') catch return error.InvalidMessageType) orelse return error.InvalidMessageType);

        switch (next_message_type) {
            .connect => {
                json_parse_alloc_fb = std.heap.FixedBufferAllocator.init(&json_parse_buf);
                json_parse_alloc = json_parse_alloc_fb.allocator();
                json_reader = .init(json_parse_alloc, in);
                client_state = try std.json.parseFromTokenSourceLeaky(ClientState, json_parse_alloc, &json_reader, .{});
                std.debug.print("client_state: {any}\n", .{client_state});
            },
            else => |msg| std.debug.print("received {}\n", .{msg}),
        }
    }
}

fn writeInfo(out: *std.Io.Writer, info: ServerInfo) !void {
    _ = try out.write("INFO ");
    try std.json.Stringify.value(info, .{}, out);
    _ = try out.write("\r\n");
    try out.flush();
}