const std = @import("std"); const fs_utils = @import("../fs_utils.zig"); const json_read = @import("../json/read.zig"); const Config = @import("state.zig").Config; const Synchronous = @import("state.zig").Synchronous; const Allocator = std.mem.Allocator; pub const ConfigLoader = struct { pub fn load(io: std.Io, environ: *const std.process.Environ.Map, allocator: Allocator, path: []const u8) !Config { const file_content = std.Io.Dir.cwd().readFileAlloc( io, path, allocator, .limited(10 * 1024 * 1024), ) catch |err| { if (err == error.FileNotFound) { std.log.info("Config file not found, using defaults", .{}); return loadDefaults(allocator); } return err; }; defer allocator.free(file_content); const substituted = try substituteEnvVars(environ, allocator, file_content); defer allocator.free(substituted); const parsed = try std.json.parseFromSlice( std.json.Value, allocator, substituted, .{}, ); defer parsed.deinit(); var config = try buildConfig(allocator, parsed.value); errdefer config.deinit(); try validateConfig(io, &config); return config; } pub fn loadDefaults(allocator: Allocator) !Config { return Config{ .server = .{ .host = try allocator.dupe(u8, "0.0.0.0"), }, .authentication = .{ .jwt_algorithm = try allocator.dupe(u8, "HS256"), .jwt_subject_claim = try allocator.dupe(u8, "sub"), .anonymous_subject_prefix = try allocator.dupe(u8, "anon:"), }, .security = .{}, .logging = .{}, .performance = .{}, .storage = .{}, .data_dir = try allocator.dupe(u8, "./data"), .schema_file = try allocator.dupe(u8, "./schema.json"), .authorization_file = null, .allocator = allocator, }; } fn substituteEnvVars(environ: *const std.process.Environ.Map, allocator: Allocator, content: []const u8) ![]const u8 { var result: std.ArrayListUnmanaged(u8) = .empty; errdefer result.deinit(allocator); var i: usize = 0; while (i < content.len) { if (i + 2 < content.len and content[i] == '$' and content[i + 1] == '{') { const start = i + 2; var end = start; while (end < content.len and content[end] != '}') { end += 1; } if (end < content.len) { const var_name = content[start..end]; if (environ.get(var_name)) |value| { try result.appendSlice(allocator, value); } else { try result.appendSlice(allocator, content[i .. end + 1]); } i = end + 1; continue; } } try result.append(allocator, content[i]); i += 1; } return result.toOwnedSlice(allocator); } fn buildConfig(allocator: Allocator, json: std.json.Value) !Config { var config = Config{ .server = .{ .host = try allocator.dupe(u8, "0.0.0.0"), }, .authentication = .{ .jwt_algorithm = try allocator.dupe(u8, "HS256"), .jwt_subject_claim = try allocator.dupe(u8, "sub"), .anonymous_subject_prefix = try allocator.dupe(u8, "anon:"), }, .security = .{}, .logging = .{}, .performance = .{}, .storage = .{}, .data_dir = try allocator.dupe(u8, "./data"), .schema_file = try allocator.dupe(u8, "./schema.json"), .authorization_file = null, .allocator = allocator, }; errdefer config.deinit(); if (json != .object) return error.InvalidConfigFormat; const obj = json.object; try parseServer(allocator, &config, obj); try parseAuthentication(allocator, &config, obj); try parseDataAndSchema(allocator, &config, obj); try parseSecurity(allocator, &config, obj); try parseLogging(allocator, &config, obj); try parsePerformance(allocator, &config, obj); try parseStorage(allocator, &config, obj); return config; } fn parseServer(allocator: Allocator, config: *Config, obj: std.json.ObjectMap) !void { const server_obj = (try json_read.getObject(obj, "server")) orelse return; const port_opt = try json_read.getInt(server_obj, "port"); if (port_opt) |port| { if (port < 0 or port > 65535) return error.InvalidPort; config.server.port = @intCast(port); } const idle_timeout_opt = try json_read.getInt(server_obj, "idleTimeoutSeconds"); if (idle_timeout_opt) |idle_timeout_seconds| { if (idle_timeout_seconds < 2 or idle_timeout_seconds > 239) return error.InvalidIdleTimeout; config.server.idle_timeout_seconds = @intCast(idle_timeout_seconds); } try json_read.replaceString(allocator, &config.server.host, server_obj, "host"); try parseTls(allocator, config, server_obj); } fn parseTls(allocator: Allocator, config: *Config, server_obj: std.json.ObjectMap) !void { if (server_obj.get("tls")) |v| { if (v == .null) return error.TypeMismatch; } const tls = (try json_read.getObject(server_obj, "tls")) orelse return; try json_read.setString(allocator, &config.server.tls_cert_file, tls, "certFile"); try json_read.setString(allocator, &config.server.tls_key_file, tls, "keyFile"); const cert = config.server.tls_cert_file orelse return error.InvalidTlsConfig; const key = config.server.tls_key_file orelse return error.InvalidTlsConfig; if (cert.len == 0 or key.len == 0 or std.mem.indexOfScalar(u8, cert, 0) != null or std.mem.indexOfScalar(u8, key, 0) != null) { return error.InvalidTlsConfig; } } fn parseAuthentication(allocator: Allocator, config: *Config, obj: std.json.ObjectMap) !void { const auth_obj = (try json_read.getObject(obj, "authentication")) orelse return; try parseAuthJwt(allocator, &config.authentication, auth_obj); try parseAuthTicket(allocator, &config.authentication, auth_obj); try parseAuthAnonymous(allocator, &config.authentication, auth_obj); try parseAuthSession(allocator, &config.authentication, auth_obj); } fn parseAuthJwt(allocator: Allocator, auth: *Config.AuthConfig, auth_obj: std.json.ObjectMap) !void { const jwt_obj = (try json_read.getObject(auth_obj, "jwt")) orelse return; try json_read.setString(allocator, &auth.jwt_secret, jwt_obj, "secret"); try json_read.replaceString(allocator, &auth.jwt_algorithm, jwt_obj, "algorithm"); try json_read.setString(allocator, &auth.jwt_issuer, jwt_obj, "issuer"); try json_read.setString(allocator, &auth.jwt_audience, jwt_obj, "audience"); try json_read.setString(allocator, &auth.jwt_jwks_url, jwt_obj, "jwksUrl"); try json_read.replaceString(allocator, &auth.jwt_subject_claim, jwt_obj, "subjectClaim"); } fn parseAuthTicket(allocator: Allocator, auth: *Config.AuthConfig, auth_obj: std.json.ObjectMap) !void { const ticket_obj = (try json_read.getObject(auth_obj, "ticket")) orelse return; try json_read.setString(allocator, &auth.ticket_secret, ticket_obj, "secret"); try json_read.setInt(u32, &auth.ticket_ttl_seconds, ticket_obj, "ttlSeconds"); } fn parseAuthAnonymous(allocator: Allocator, auth: *Config.AuthConfig, auth_obj: std.json.ObjectMap) !void { const anon_obj = (try json_read.getObject(auth_obj, "anonymous")) orelse return; try json_read.setBool(&auth.anonymous_enabled, anon_obj, "enabled"); try json_read.replaceString(allocator, &auth.anonymous_subject_prefix, anon_obj, "subjectPrefix"); } fn parseAuthSession(allocator: Allocator, auth: *Config.AuthConfig, auth_obj: std.json.ObjectMap) !void { const session_obj = (try json_read.getObject(auth_obj, "session")) orelse return; const claims_obj = (try json_read.getObject(session_obj, "claims")) orelse return; var it = claims_obj.iterator(); while (it.next()) |entry| { if (entry.value_ptr.* != .string) continue; const jwt_claim = try allocator.dupe(u8, entry.key_ptr.*); errdefer allocator.free(jwt_claim); const session_var = try allocator.dupe(u8, entry.value_ptr.*.string); errdefer allocator.free(session_var); try auth.session.claims.put(allocator, jwt_claim, session_var); } } fn parseDataAndSchema(allocator: Allocator, config: *Config, obj: std.json.ObjectMap) !void { try json_read.replaceString(allocator, &config.data_dir, obj, "dataDir"); if (obj.get("schema")) |schema_val| { switch (schema_val) { .string => |s| { const new_schema_file = try allocator.dupe(u8, s); allocator.free(config.schema_file); config.schema_file = new_schema_file; }, .object => |schema_obj| { _ = schema_obj; config.schema_content = try std.json.Stringify.valueAlloc(allocator, schema_val, .{}); }, else => {}, } } try json_read.setString(allocator, &config.authorization_file, obj, "authorization"); if (try json_read.getObject(obj, "migrations")) |migrations_obj| { try json_read.setString(allocator, &config.migrations.dir, migrations_obj, "dir"); try json_read.setBool(&config.migrations.snapshot, migrations_obj, "snapshot"); } } fn parseSecurity(allocator: Allocator, config: *Config, obj: std.json.ObjectMap) !void { const security_obj = (try json_read.getObject(obj, "security")) orelse return; const origins_opt = try json_read.getArray(security_obj, "allowedOrigins"); if (origins_opt) |origins| { var origin_list: std.ArrayListUnmanaged([]const u8) = .empty; errdefer { for (origin_list.items) |origin| { allocator.free(origin); } origin_list.deinit(allocator); } for (origins.items) |origin| { if (origin == .string) { const duped = try allocator.dupe(u8, origin.string); errdefer allocator.free(duped); try origin_list.append(allocator, duped); } } config.security.allowed_origins = try origin_list.toOwnedSlice(allocator); } try json_read.setBool(&config.security.allow_localhost, security_obj, "allowLocalhost"); try json_read.setInt(u32, &config.security.max_messages_per_second, security_obj, "maxMessagesPerSecond"); try json_read.setInt(u32, &config.security.max_connections, security_obj, "maxConnections"); try json_read.setInt(usize, &config.security.max_message_size, security_obj, "maxMessageSize"); try json_read.setInt(usize, &config.security.max_query_response_size, security_obj, "maxQueryResponseSize"); try json_read.setInt(u32, &config.security.violation_threshold, security_obj, "violationThreshold"); } fn parseLogging(allocator: Allocator, config: *Config, obj: std.json.ObjectMap) !void { _ = allocator; const logging_obj = (try json_read.getObject(obj, "logging")) orelse return; const level_opt = try json_read.getString(logging_obj, "level"); if (level_opt) |level| { config.logging.level = std.meta.stringToEnum(Config.LoggingConfig.LogLevel, level) orelse return error.InvalidLogLevel; } const format_opt = try json_read.getString(logging_obj, "format"); if (format_opt) |format| { config.logging.format = std.meta.stringToEnum(Config.LoggingConfig.LogFormat, format) orelse return error.InvalidLogFormat; } } fn parsePerformance(allocator: Allocator, config: *Config, obj: std.json.ObjectMap) !void { _ = allocator; const perf_obj = (try json_read.getObject(obj, "performance")) orelse return; try json_read.setInt(usize, &config.performance.message_buffer_size, perf_obj, "messageBufferSize"); try json_read.setBool(&config.performance.batch_writes, perf_obj, "batchWrites"); try json_read.setInt(usize, &config.performance.batch_size, perf_obj, "batchSize"); try json_read.setInt(u32, &config.performance.batch_timeout, perf_obj, "batchTimeout"); try json_read.setInt(u32, &config.performance.presence_batch_timeout, perf_obj, "presenceBatchTimeoutMs"); try json_read.setInt(usize, &config.performance.presence_batch_max_updates, perf_obj, "presenceBatchMaxUpdates"); try json_read.setInt(usize, &config.performance.statement_cache_size, perf_obj, "statementCacheSize"); } fn parseStorage(allocator: Allocator, config: *Config, obj: std.json.ObjectMap) !void { _ = allocator; const storage_obj = (try json_read.getObject(obj, "storage")) orelse return; const sync_opt = try json_read.getString(storage_obj, "synchronous"); if (sync_opt) |sync| { config.storage.synchronous = std.meta.stringToEnum(Synchronous, sync) orelse return error.InvalidSynchronousMode; } } fn validateConfig(io: std.Io, config: *Config) !void { if (config.server.port == 0 or config.server.port > 65535) { return error.InvalidPort; } fs_utils.createDirPathBounded(io, config.data_dir) catch return error.InvalidDataDir; if (config.schema_content == null) { if (config.schema_file.len == 0) { return error.InvalidSchemaFile; } std.Io.Dir.cwd().access(io, config.schema_file, .{}) catch |err| { if (err != error.FileNotFound) return error.SchemaFileNotFound; std.log.info("Schema file not found, using implicit users-only schema", .{}); }; } if (config.authorization_file) |auth_file| { std.Io.Dir.cwd().access(io, auth_file, .{}) catch { return error.AuthRulesFileNotFound; }; } if (config.performance.message_buffer_size == 0) { return error.InvalidBufferSize; } if (config.performance.batch_size == 0) { return error.InvalidBatchSize; } if (config.performance.statement_cache_size == 0) { return error.InvalidStatementCacheSize; } if (config.security.max_message_size == 0) { return error.InvalidMaxMessageSize; } if (config.security.max_query_response_size == 0) { return error.InvalidMaxQueryResponseSize; } } };