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
|
const std = @import("std");
const Message = @import("./message_parser.zig").Message;
pub const ServerInfo = Message.ServerInfo;
const ClientState = @import("./client.zig").ClientState;
const Server = @This();
info: ServerInfo,
clients: std.AutoHashMapUnmanaged(usize, *ClientState) = .empty,
/// Map of subjects to a map of (client ID => SID)
subscriptions: std.StringHashMapUnmanaged(std.AutoHashMapUnmanaged(usize, []const u8)) = .empty,
var keep_running = std.atomic.Value(bool).init(true);
fn handleSigInt(sig: std.os.linux.SIG) callconv(.c) void {
_ = sig;
keep_running.store(false, .monotonic);
}
pub fn main(gpa: std.mem.Allocator, server_config: ServerInfo) !void {
// Configure the signal action
// const act = std.posix.Sigaction{
// .handler = .{ .handler = handleSigInt },
// .mask = std.posix.sigemptyset(),
// .flags = 0,
// };
// // Register the handler for SIGINT (Ctrl+C)
// std.posix.sigaction(std.posix.SIG.INT, &act, null);
var server: Server = .{
.info = server_config,
};
var threaded: std.Io.Threaded = .init(gpa);
defer threaded.deinit();
const io = threaded.io();
var tcp_server = try std.Io.net.IpAddress.listen(try std.Io.net.IpAddress.parse(
server.info.host,
server.info.port,
), io, .{});
defer tcp_server.deinit(io);
var id: usize = 0;
// Run until SIGINT is handled, then exit gracefully
while (keep_running.load(.monotonic)) : (id +%= 1) {
std.debug.print("in server loop\n", .{});
if (server.clients.contains(id)) continue;
const stream = try tcp_server.accept(io);
std.debug.print("accepted connection\n", .{});
_ = io.concurrent(handleConnection, .{ &server, gpa, io, id, stream }) catch {
std.debug.print("could not start concurrent handler for {d}\n", .{id});
stream.close(io);
};
}
std.debug.print("Exiting gracefully\n", .{});
}
fn addClient(server: *Server, allocator: std.mem.Allocator, id: usize, client: *ClientState) !void {
// server.clients.lockPointers();
try server.clients.put(allocator, id, client);
// server.clients.unlockPointers();
}
fn removeClient(server: *Server, allocator: std.mem.Allocator, id: usize) void {
// TODO: implement
_ = server;
_ = allocator;
_ = id;
}
fn handleConnection(
server: *Server,
server_allocator: std.mem.Allocator,
io: std.Io,
id: usize,
stream: std.Io.net.Stream,
) !void {
var client_allocator: std.heap.DebugAllocator(.{}) = .init;
client_allocator.backing_allocator = server_allocator;
defer {
std.debug.print("deinitializing debug allocator\n", .{});
_ = client_allocator.deinit();
}
const allocator = client_allocator.allocator();
defer stream.close(io);
var w_buffer: [4096]u8 = undefined;
var writer = stream.writer(io, &w_buffer);
const out = &writer.interface;
std.debug.print("out pointer in client handler: {*}\n", .{out});
var r_buffer: [8192]u8 = undefined;
var reader = stream.reader(io, &r_buffer);
const in = &reader.interface;
@import("./client.zig").writeInfo(out, server.info) catch return;
var connect_arena: std.heap.ArenaAllocator = .init(allocator);
defer connect_arena.deinit();
const connect = (Message.next(connect_arena.allocator(), in) catch return).connect;
var client_state: ClientState = try .init(io, allocator, id, connect, in, out);
defer client_state.deinit(io, allocator);
try server.addClient(allocator, id, &client_state);
defer server.removeClient(allocator, id);
while (client_state.next(allocator)) |msg| {
switch (msg) {
.ping => {
// Respond to ping with pong.
for (0..5) |_| {
if (try client_state.send(io, .pong)) {
break;
}
} else {}
},
.@"pub" => |@"pub"| {
try server.publishMessage(io, @"pub");
if (client_state.connect.connect.verbose) {
_ = try client_state.send(io, .@"+ok");
}
},
.sub => |sub| {
try server.subscribe(allocator, client_state.id, sub);
},
.unsub => |unsub| {
try server.unsubscribe(client_state.id, unsub);
},
else => |e| {
std.debug.panic("Unimplemented message: {any}\n", .{e});
},
}
} else |err| {
// This is probably going to be normal on disconnect
std.debug.print("Ran into error in client process loop: {}\n", .{err});
}
// client_state.task.await(io);
}
// // Result is owned by the caller
// fn subscribers(server: *Server, gpa: std.mem.Allocator, subject: []const u8) []ClientState {
// var acc: std.ArrayList(ClientState) = .empty;
// return acc.toOwnedSlice();
// }
fn publishMessage(server: *Server, io: std.Io, msg: Message.Pub) !void {
if (server.subscriptions.get(msg.subject)) |subs| {
var subs_iter = subs.iterator();
while (subs_iter.next()) |sub| {
const client_id = sub.key_ptr.*;
const sid = sub.value_ptr.*;
const client = server.clients.getPtr(client_id) orelse {
std.debug.print("trying to publish to a client that no longer exists: {d}", .{client_id});
continue;
};
_ = try client.*.send(io, .{ .msg = .{
.subject = msg.subject,
.sid = sid,
.reply_to = msg.reply_to,
.payload = msg.payload,
} });
}
} else {
std.debug.print("no subs on {s}\n", .{msg.subject});
}
}
fn subscribe(server: *Server, gpa: std.mem.Allocator, id: usize, msg: Message.Sub) !void {
std.debug.print("Recieved SUBSCRIBE message: {any}\n\n", .{msg});
var subs_for_subject: std.AutoHashMapUnmanaged(usize, []const u8) = if (server.subscriptions.fetchRemove(msg.subject)) |s| s.value else .empty;
try subs_for_subject.put(gpa, id, msg.sid);
try server.subscriptions.put(gpa, msg.subject, subs_for_subject);
}
fn unsubscribe(server: *Server, id: usize, msg: Message.Unsub) !void {
// Get the subscription in subscriptions by looping over all the subjects,
// and getting the SID for that subject for the current client ID.
// If the SID matches, remove the kv for the client ID from subscriptions for that subject.
// If the value for that subject is empty, remove the subject.
var subscriptions_iter = server.subscriptions.iterator();
while (subscriptions_iter.next()) |*subs_for_sub| {
if (subs_for_sub.value_ptr.get(id)) |client_sub| {
if (std.mem.eql(u8, client_sub, msg.sid)) {
_ = subs_for_sub.value_ptr.*.remove(id);
if (subs_for_sub.value_ptr.count() == 0) {
_ = server.subscriptions.remove(subs_for_sub.key_ptr.*);
}
break;
}
}
}
}
pub fn createId() []const u8 {
return "SERVERID";
}
pub fn createName() []const u8 {
return "SERVERNAME";
}
// TESTING
// fn initTestServer() Server {
// return .{
// .info = .{
// .server_id = "ABCD",
// .server_name = "test server",
// .version = "0.1.2",
// .max_payload = 1234,
// },
// };
// }
// fn initTestClient(
// io: std.Io,
// allocator: std.mem.Allocator,
// id: usize,
// data_from: []const u8,
// ) !struct {
// Client,
// *std.Io.Reader,
// *std.Io.Writer,
// } {
// return .init(io, allocator, id, .{}, in, out);
// }
// test {
// const gpa = std.testing.allocator;
// const io = std.testing.io;
// const server = initTestServer();
// const client: Client = .init(
// io,
// gpa,
// 1,
// .{},
// );
// }
|