fediglam/src/main/main.zig

149 lines
4.9 KiB
Zig

const std = @import("std");
const builtin = @import("builtin");
const sql = @import("sql");
const http = @import("http");
const util = @import("util");
const api = @import("api");
const migrations = @import("./migrations.zig");
const Uuid = util.Uuid;
const c = @import("./controllers.zig");
// this thing is overcomplicated and weird. stop this
const Router = http.Router(*RequestServer);
const Route = Router.Route;
const RouteArgs = http.RouteArgs;
const router = Router{
.routes = &[_]Route{
Route.new(.GET, "/healthcheck", &c.healthcheck),
prepare(c.auth.login),
prepare(c.auth.verify_login),
prepare(c.communities.create),
prepare(c.invites.create),
prepare(c.users.create),
prepare(c.notes.create),
prepare(c.notes.get),
//prepare(c.communities.query),
//Route.new(.GET, "/notes/:id/reacts", &c.notes.reacts.list),
//Route.new(.POST, "/notes/:id/reacts", &c.notes.reacts.create),
//Route.new(.GET, "/actors/:id", &c.actors.get),
//Route.new(.GET, "/admin/invites/:id", &c.admin.invites.get),
//Route.new(.GET, "/admin/communities/:host", &c.admin.communities.get),
},
};
fn prepare(comptime route_desc: type) Route {
return Route.new(route_desc.method, route_desc.path, &route_desc.handler);
}
pub const RequestServer = struct {
alloc: std.mem.Allocator,
api: *api.ApiSource,
config: Config,
fn init(alloc: std.mem.Allocator, src: *api.ApiSource, config: Config) !RequestServer {
return RequestServer{
.alloc = alloc,
.api = src,
.config = config,
};
}
fn listenAndRun(self: *RequestServer, addr: std.net.Address) !void {
var srv = http.Server.listen(addr) catch unreachable;
defer srv.shutdown();
while (true) {
const buf = try self.alloc.alloc(u8, 1 << 28); // 4mb
defer self.alloc.free(buf);
var fba = std.heap.FixedBufferAllocator.init(buf);
const alloc = fba.allocator();
var ctx = try srv.accept(alloc);
defer ctx.close();
router.dispatch(self, &ctx, ctx.request.method, ctx.request.path) catch |err| switch (err) {
error.NotFound, error.RouteNotApplicable => c.notFound(self, &ctx),
else => {
std.log.err("Unhandled error in controller ({s}): {}\nStack Trace\n{?}", .{ ctx.request.path, err, @errorReturnTrace() });
c.internalServerError(self, &ctx);
},
};
}
}
};
pub const Config = struct {
db: sql.Config,
};
fn loadConfig(alloc: std.mem.Allocator) !Config {
var file = try std.fs.cwd().openFile("config.json", .{});
defer file.close();
const bytes = try file.reader().readAllAlloc(alloc, 1 << 63);
defer alloc.free(bytes);
var ts = std.json.TokenStream.init(bytes);
return std.json.parse(Config, &ts, .{ .allocator = alloc });
}
const admin_origin_envvar = "CLUSTER_ADMIN_ORIGIN";
const admin_username_envvar = "CLUSTER_ADMIN_USERNAME";
const admin_password_envvar = "CLUSTER_ADMIN_PASSWORD";
fn runAdminSetup(db: sql.Db, alloc: std.mem.Allocator) !void {
const origin = std.os.getenv(admin_origin_envvar) orelse return error.MissingArgument;
const username = std.os.getenv(admin_username_envvar) orelse return error.MissingArgument;
const password = std.os.getenv(admin_password_envvar) orelse return error.MissingArgument;
try api.setupAdmin(db, origin, username, password, alloc);
}
fn prepareDb(db: sql.Db, alloc: std.mem.Allocator) !void {
try migrations.up(db);
if (!try api.isAdminSetup(db)) {
std.log.info("Performing first-time admin creation...", .{});
runAdminSetup(db, alloc) catch |err| switch (err) {
error.MissingArgument => {
std.log.err(
\\First time setup required but arguments not provided.
\\Please provide the following arguments via environment variable:
\\- {s}: The origin to serve the cluster admin panel at (ex: https://admin.example.com)
\\- {s}: The username for the initial cluster operator
\\- {s}: The password for the initial cluster operator
,
.{ admin_origin_envvar, admin_username_envvar, admin_password_envvar },
);
std.os.exit(1);
},
else => return err,
};
}
}
pub fn main() !void {
try util.seedThreadPrng();
var gpa = std.heap.GeneralPurposeAllocator(.{}){};
var cfg = try loadConfig(gpa.allocator());
var db_conn = try sql.Conn.open(cfg.db);
try prepareDb(try db_conn.acquire(), gpa.allocator());
var api_src = try api.ApiSource.init(&db_conn);
var srv = try RequestServer.init(gpa.allocator(), &api_src, cfg);
return srv.listenAndRun(std.net.Address.parseIp("0.0.0.0", 8080) catch unreachable);
}