diff --git a/src/main.zig b/src/main.zig index d06c524..cd50228 100644 --- a/src/main.zig +++ b/src/main.zig @@ -6,6 +6,7 @@ const stt = @import("stt.zig"); /// Global flag for signal handling var should_exit = std.atomic.Value(bool).init(false); +var fatal_error = std.atomic.Value(bool).init(false); // SAFETY: we are setting this value at top of main before use /// We need a global here to reclaim process when getting SIGCHLD @@ -265,6 +266,12 @@ const SpeechHandler = struct { else log.err("{s}", .{message}), } + + // Signal shutdown on fatal errors + if (!error_info.recoverable) { + fatal_error.store(true, .release); + should_exit.store(true, .release); + } } }; @@ -315,7 +322,7 @@ pub fn main() !void { if (std.posix.getenv("ALSA_CONFIG_PATH") == null) { std.fs.cwd().access("alsa.conf", .{}) catch { _ = std.fs.File.stderr().writeAll("Error: alsa.conf file not found. Please put alsa.conf in the current directory or set ALSA_CONFIG_PATH\n") catch {}; - std.process.exit(1); + return error.ConfigNotFound; }; const c = @cImport({ @cInclude("stdlib.h"); @@ -414,12 +421,12 @@ pub fn main() !void { } _ = try stderr.writeAll("Please download the model. A fine model can be downloaded from:\n"); _ = try stderr.writeAll("\thttps://alphacephei.com/vosk/models/vosk-model-small-en-us-0.15.zip\n"); - std.process.exit(1); + return error.ModelNotFound; } std.fs.cwd().access(model_path.?, .{}) catch { std.log.err("Model path does not exist: {s}", .{model_path.?}); - std.process.exit(1); + return error.ModelNotFound; }; // Initialize STT session with resolved model path @@ -438,7 +445,7 @@ pub fn main() !void { std.log.err(" - Audio device '{s}' is available", .{options.audio_device}); std.log.err(" - Model directory exists at: {s}", .{options.model_path}); std.log.err(" - You have permission to access the audio device", .{}); - return; + return err; }; defer session.deinit(); @@ -468,7 +475,7 @@ pub fn main() !void { std.log.err("Unexpected error during startup.", .{}); }, } - return; + return err; }; defer session.stop(); @@ -504,6 +511,8 @@ pub fn main() !void { std.log.err("✗ {d} fatal errors occurred during speech recognition.", .{handler.error_count}); _ = stdout.writeAll("Session completed successfully.\n") catch {}; + + if (fatal_error.load(.acquire)) return error.FatalError; } test "handler callbacks" {