Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ OPTIONS:

## Development

Make sure you have `zig 0.14.1`
Make sure you have `zig 0.15.1`

```sh
git clone https://github.com/UnknownRori/raphael-zig
Expand Down
2 changes: 1 addition & 1 deletion external/flag.zig
Submodule flag.zig updated 2 files
+6 −5 src/main.zig
+6 −6 src/root.zig
2 changes: 1 addition & 1 deletion external/yaml.zig
Submodule yaml.zig updated 3 files
+2 −0 README.md
+2 −2 src/main.zig
+29 −29 src/parser.zig
32 changes: 16 additions & 16 deletions src/app.zig
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,8 @@ pub fn search(allocator: std.mem.Allocator, term: []const u8) !void {
var tfi = try lib.load_index(allocator);
defer tfi.deinit();

const result = try tfi.search(allocator, term);
defer result.deinit();
var result = try tfi.search(allocator, term);
defer result.deinit(allocator);
for (result.items) |item| {
item.print();
}
Expand All @@ -26,7 +26,7 @@ pub fn index(allocator: std.mem.Allocator, dir: []const u8) !void {
pub fn serve(allocator: std.mem.Allocator) !void {
const tfi = try lib.load_index(allocator);

var router = lib.Http.Router.init(allocator);
var router = try lib.Http.Router.init(allocator);

var raphael_controller = try RaphaelController.init(tfi);
defer raphael_controller.deinit();
Expand Down Expand Up @@ -72,7 +72,7 @@ pub const RaphaelController = struct {
}

pub fn load_favico(ctx: *anyopaque, req: *Request, res: *Response) !void {
const self: *Self = @alignCast(@ptrCast(ctx));
const self: *Self = @ptrCast(@alignCast(ctx));

const contents = read_file(res.arena.allocator(), self.dir, "statics/favicon.ico") catch |err| {
std.debug.print("[-] {any}\n", .{err});
Expand All @@ -85,7 +85,7 @@ pub const RaphaelController = struct {
}

pub fn load_sw(ctx: *anyopaque, req: *Request, res: *Response) !void {
const self: *Self = @alignCast(@ptrCast(ctx));
const self: *Self = @ptrCast(@alignCast(ctx));

const contents = read_file(res.arena.allocator(), self.dir, "statics/sw.js") catch |err| {
std.debug.print("[-] {any}\n", .{err});
Expand All @@ -99,7 +99,7 @@ pub const RaphaelController = struct {

pub fn assets(ctx: *anyopaque, req: *Request, res: *Response) !void {
// TODO : Create abstraction for this thing
const self: *Self = @alignCast(@ptrCast(ctx));
const self: *Self = @ptrCast(@alignCast(ctx));
const dir = self.dir;

const path = try std.mem.replaceOwned(u8, res.arena.allocator(), req.path[1..], "../", "");
Expand All @@ -120,7 +120,7 @@ pub const RaphaelController = struct {
}

pub fn show(ctx: *anyopaque, req: *Request, res: *Response) !void {
const self: *Self = @alignCast(@ptrCast(ctx));
const self: *Self = @ptrCast(@alignCast(ctx));
const allocator = res.arena.allocator(); // Borrowing shit

var data = std.json.parseFromSlice(std.json.Value, allocator, req.body.?.items, .{}) catch |err| {
Expand All @@ -133,8 +133,8 @@ pub const RaphaelController = struct {
defer data.deinit();

const query_input = data.value.object.get("file").?.string;
const result = try self.tfi.search(allocator, query_input);
defer result.deinit();
var result = try self.tfi.search(allocator, query_input);
defer result.deinit(allocator);

const dir = try std.fs.cwd().openDir(std.fs.path.dirname(query_input).?, .{ .iterate = true });
const contents = read_file(res.arena.allocator(), dir, std.fs.path.basename(query_input)) catch |err| {
Expand All @@ -146,7 +146,7 @@ pub const RaphaelController = struct {
}

pub fn query(ctx: *anyopaque, req: *Request, res: *Response) !void {
const self: *Self = @alignCast(@ptrCast(ctx));
const self: *Self = @ptrCast(@alignCast(ctx));
const allocator = res.arena.allocator(); // Borrowing shit

// TODO : Refactor this into paginator.zig
Expand All @@ -173,10 +173,10 @@ pub const RaphaelController = struct {
defer data.deinit();

const query_input = data.value.object.get("query").?.string;
const result = try self.tfi.search(allocator, query_input);
defer result.deinit();
var result = try self.tfi.search(allocator, query_input);
defer result.deinit(allocator);

var result_item = std.ArrayList(QueryResult).init(allocator);
var result_item = try std.ArrayList(QueryResult).initCapacity(allocator, 10);
var temp_result = result.items;

var max_offset = offset + item_per_page;
Expand All @@ -190,9 +190,9 @@ pub const RaphaelController = struct {
}

for (temp_result) |item| {
var tags = std.ArrayList([]u8).init(allocator);
var tags = try std.ArrayList([]u8).initCapacity(allocator, 1);
for (item.metadata.tags.items) |tag| {
try tags.append(tag.items);
try tags.append(allocator, tag.items);
}

const data_query: QueryResult = .{
Expand All @@ -205,7 +205,7 @@ pub const RaphaelController = struct {
.weight = item.weight,
};

try result_item.append(data_query);
try result_item.append(allocator, data_query);
}

try res.json(.Ok, .{
Expand Down
18 changes: 9 additions & 9 deletions src/document.zig
Original file line number Diff line number Diff line change
Expand Up @@ -25,27 +25,27 @@ pub const Document = struct {

pub fn parse(allocator: Allocator, contents: []const u8) !Self {
// TODO : Refactor this stuff
var metadata = Metadata.init(allocator);
var metadata = try Metadata.init(allocator);
if (std.mem.startsWith(u8, contents, "---")) {
var skipHeader = std.mem.splitSequence(u8, contents, "---");
_ = skipHeader.next().?;
const header = skipHeader.next().?;
var parser = try YAMLParser.init(allocator, header);
const meta = try parser.parse(allocator);
defer meta.deinit();
var meta = try parser.parse(allocator);
defer meta.deinit(allocator);
for (meta.items) |item| {
switch (item) {
.Scalar => |n| {
if (std.mem.eql(u8, n.key.items, "description")) {
try metadata.description.appendSlice(n.value.items);
try metadata.description.appendSlice(allocator, n.value.items);
}
},
.Sequence => |n| {
if (std.mem.eql(u8, n.key.items, "tags")) {
for (n.value.items) |tag| {
var tag_temp = try std.ArrayList(u8).initCapacity(allocator, tag.items.len);
try tag_temp.appendSlice(tag.items);
try metadata.tags.append(tag_temp);
try tag_temp.appendSlice(allocator, tag.items);
try metadata.tags.append(allocator, tag_temp);
}
}
},
Expand All @@ -55,7 +55,7 @@ pub const Document = struct {
}

if (metadata.description.items.len <= 0) {
try metadata.description.appendSlice("No description provided");
try metadata.description.appendSlice(allocator, "No description provided");
}
const tf_map = try tf.TermFreq.parse(allocator, contents);

Expand Down Expand Up @@ -175,7 +175,7 @@ pub const TermFreqDocuments = struct {
}

pub fn search(self: *Self, allocator: Allocator, term: []const u8) !std.ArrayList(SearchResult) {
var result = std.ArrayList(SearchResult).init(allocator);
var result = try std.ArrayList(SearchResult).initCapacity(allocator, 10);

var tfi_iter = self.map.iterator();
const term_uppercase = try std.ascii.allocUpperString(allocator, term);
Expand All @@ -191,7 +191,7 @@ pub const TermFreqDocuments = struct {
// We don't give a frick with infinite rank like ur mom
if (std.math.isInf(rank) or std.math.isNan(rank) or rank <= 0) continue;

try result.append(SearchResult.init(e.key_ptr.*, e.value_ptr.metadata, rank));
try result.append(allocator, SearchResult.init(e.key_ptr.*, e.value_ptr.metadata, rank));
}

std.mem.sort(SearchResult, result.items, {}, SearchResult.compareAsc);
Expand Down
10 changes: 5 additions & 5 deletions src/http/request.zig
Original file line number Diff line number Diff line change
Expand Up @@ -94,17 +94,17 @@ pub const Request = struct {
};
}

pub fn parseBody(self: *Self, reader: anytype) !void {
pub fn parseBody(self: *Self, reader: *std.Io.Reader) !void {
const length_option = self.headers.get("Content-Length");
var length: i32 = 0;
if (length_option != null) length = try std.fmt.parseInt(u8, length_option.?, 10);

var str = std.ArrayList(u8).init(self.allocator);
var str = try std.ArrayList(u8).initCapacity(self.allocator, 256);
while (length > 0) {
length -= 1;

const byte = try reader.readByte();
try str.append(byte);
const byte = try reader.takeByte();
try str.append(self.allocator, byte);
}
self.body = str;
}
Expand All @@ -113,6 +113,6 @@ pub const Request = struct {
self.headers.deinit();
self.query.deinit();
self.params.deinit();
if (self.body != null) self.body.?.deinit();
if (self.body != null) self.body.?.deinit(self.allocator);
}
};
17 changes: 10 additions & 7 deletions src/http/response.zig
Original file line number Diff line number Diff line change
Expand Up @@ -50,31 +50,34 @@ pub const Response = struct {
}

pub fn json(self: *Self, code: HTTPStatus, content: anytype) !void {
const data = try std.json.stringifyAlloc(self.arena.allocator(), content, .{});
try self.response(code, .JSON, data);
var buffer_allocating = std.Io.Writer.Allocating.init(self.arena.allocator());
var writer = buffer_allocating.writer;
var jw = std.json.Stringify{ .writer = &writer, .options = .{ .whitespace = .minified } };
try jw.write(content);
try self.response(code, .JSON, buffer_allocating.toArrayList().items);
}

pub fn send(self: *Self, stream: std.net.Stream) !void {
var strResponse = try std.ArrayList(u8).initCapacity(self.arena.allocator(), 1024);
defer strResponse.deinit();
defer strResponse.deinit(self.arena.allocator());

const httpCode = try std.fmt.allocPrint(self.arena.allocator(), "HTTP/1.1 {} {s}\r\n", .{
@intFromEnum(self.status),
self.status.to_string(),
});
defer self.arena.allocator().free(httpCode);
try strResponse.appendSlice(httpCode);
try strResponse.appendSlice(self.arena.allocator(), httpCode);

if (self.body != null) {
const content_type = try std.fmt.allocPrint(self.arena.allocator(), "Content-Type: {s}\r\n", .{self.content_type.to_string()});
try strResponse.appendSlice(content_type);
try strResponse.appendSlice(self.arena.allocator(), content_type);
defer self.arena.allocator().free(content_type);

const content_length = try std.fmt.allocPrint(self.arena.allocator(), "Content-Length: {}\r\n\r\n", .{self.body.?.len});
try strResponse.appendSlice(content_length);
try strResponse.appendSlice(self.arena.allocator(), content_length);
defer self.arena.allocator().free(content_length);

try strResponse.appendSlice(self.body.?);
try strResponse.appendSlice(self.arena.allocator(), self.body.?);
}

_ = try stream.write(strResponse.items);
Expand Down
10 changes: 5 additions & 5 deletions src/http/router.zig
Original file line number Diff line number Diff line change
Expand Up @@ -15,20 +15,20 @@ pub const Router = struct {

const Self = @This();

pub fn init(allocator: Allocator) Self {
pub fn init(allocator: Allocator) !Self {
return Self{
.routes = std.ArrayList(Route).init(allocator),
.routes = try std.ArrayList(Route).initCapacity(allocator, 10),
.allocator = allocator,
.not_found = null,
};
}

pub fn deinit(self: Self) void {
self.routes.deinit();
pub fn deinit(self: *Self) void {
self.routes.deinit(self.allocator);
}

pub fn add(self: *Self, path: []const u8, method: Method, ctx: *anyopaque, handler: anytype) !void {
try self.routes.append(Route.init(path, method, ctx, handler));
try self.routes.append(self.allocator, Route.init(path, method, ctx, handler));
}

pub fn get(self: *Self, path: []const u8, ctx: *anyopaque, handler: anytype) !void {
Expand Down
29 changes: 11 additions & 18 deletions src/http/server.zig
Original file line number Diff line number Diff line change
Expand Up @@ -34,8 +34,8 @@ pub const Server = struct {
}

pub fn listen(self: *Self) !void {
var server = try self.addr.listen(.{ .reuse_address = true, .reuse_port = true });
std.debug.print("Listening at {}\n", .{server.listen_address});
var server = try self.addr.listen(.{ .reuse_address = true });
std.debug.print("Listening at {any}\n", .{server.listen_address.in});
defer server.deinit();

// TODO : MEM LEAK SOMEWHERE
Expand All @@ -57,31 +57,24 @@ fn handle(parent_allocator: Allocator, router: Router, client: net.Server.Connec
const allocator = arena.allocator();
defer arena.deinit();

var buffer = String.init(allocator);
defer buffer.deinit();
const writer = buffer.writer();

var buffered_reader = std.io.bufferedReader(client.stream.reader());
var reader = buffered_reader.reader();
var buffer = std.Io.Writer.Allocating.init(allocator);
buffer.deinit();
var writer = buffer.writer;

var buf: [1024]u8 = undefined;
var reader = client.stream.reader(&buf).interface_state;

while (true) {
const line = reader.readUntilDelimiter(&buf, '\n') catch {
_ = reader.stream(&writer, .unlimited) catch {
break;
};
const trimmed = std.mem.trimRight(u8, line, "\r");

if (trimmed.len == 0) break;

_ = try writer.write(trimmed);
_ = try writer.write("\r\n");
}

var request = try Request.parseHeader(allocator, buffer.items);
var request = try Request.parseHeader(allocator, buffer.toArrayList().items);
defer request.deinit();
try request.parseBody(reader);
try request.parseBody(&reader);

std.debug.print("[{s}] {} - {s}\n", .{ request.method.to_string(), client.address, request.path });
std.debug.print("[{s}] {any} - {s}\n", .{ request.method.to_string(), client.address.in, request.path });

var response = Response.init(allocator);
defer response.deinit();
Expand Down
13 changes: 8 additions & 5 deletions src/main.zig
Original file line number Diff line number Diff line change
Expand Up @@ -12,9 +12,11 @@ pub fn main() !void {
defer _ = gpa.deinit();
const allocator = gpa.allocator();

const stderr = std.io.getStdErr().writer();
const stderr_file = std.fs.File.stderr();
// For some reason it fail in here if using buffer
var stderr = stderr_file.writer(&.{}).interface;

var args = flag.ArgsParser.init(allocator);
var args = try flag.ArgsParser.init(allocator);
defer args.deinit();
const prog = args.program();
const dir = try args.flag_str("index", null, "Index a directory");
Expand All @@ -24,17 +26,17 @@ pub fn main() !void {

const parse_result = !try args.parse();
if (parse_result) {
try usage(stderr, &args, prog.*.?);
try usage(&stderr, &args, prog.*.?);
return;
}

if (help.*) {
try usage(stderr, &args, prog.*.?);
try usage(&stderr, &args, prog.*.?);
return;
}

if (search.* != null) {
try app.index(allocator, dir.*.?);
try app.search(allocator, search.*.?);
} else if (serve.*) {
try app.serve(allocator);
} else if (dir.* != null) {
Expand All @@ -46,4 +48,5 @@ fn usage(stdout: anytype, args: *flag.ArgsParser, program: []const u8) !void {
try stdout.print("USAGE: {s} [OPTIONS]\n", .{program});
try stdout.print("OPTIONS:\n", .{});
try args.options_print(stdout);
try stdout.flush();
}
Loading