From 26a11e556595c1d00e79c321134716ed2f78b3a2 Mon Sep 17 00:00:00 2001 From: Ben Date: Tue, 4 Feb 2025 16:25:38 +0100 Subject: [PATCH] Sets up application starting and stopping --- codexcrawler.nim | 61 ++++++++++++++++++++++++++++++++++++++++--- codexcrawler/main.nim | 18 +++++++++++++ codexcrawler/todo.nim | 2 -- 3 files changed, 76 insertions(+), 5 deletions(-) create mode 100644 codexcrawler/main.nim delete mode 100644 codexcrawler/todo.nim diff --git a/codexcrawler.nim b/codexcrawler.nim index c690b76..ba1589e 100644 --- a/codexcrawler.nim +++ b/codexcrawler.nim @@ -1,5 +1,60 @@ -import - ./codexcrawler/todo +import pkg/chronicles +import pkg/chronos + +import ./codexcrawler/main +when defined(posix): + import system/ansi_c + +type + ApplicationStatus {.pure.} = enum + Stopped, + Stopping, + Running + + Application = ref object + status: ApplicationStatus + +proc run(app: Application) = + app.status = ApplicationStatus.Running + + waitFor runApplication() + + while app.status == ApplicationStatus.Running: + try: + chronos.poll() + except Exception as exc: + error "Unhandled exception", msg = exc.msg + quit QuitFailure + notice "Done" when isMainModule: - run() + let app = Application() + + # Stopping code must be in scope of app declaration. + # Else capture of the instance is not allowed due to {.noconv.}. + proc onStopSignal() = + app.status = ApplicationStatus.Stopping + notice "Stopping Crawler..." + + proc controlCHandler() {.noconv.} = + when defined(windows): + # workaround for https://github.com/nim-lang/Nim/issues/4057 + try: + setupForeignThreadGc() + except Exception as exc: raiseAssert exc.msg + notice "Shutting down after having received SIGINT" + onStopSignal() + + try: + setControlCHook(controlCHandler) + except Exception as exc: + warn "Cannot set ctrl-c handler", msg = exc.msg + + when defined(posix): + proc SIGTERMHandler(signal: cint) {.noconv.} = + notice "Shutting down after having received SIGTERM" + onStopSignal() + + c_signal(ansi_c.SIGTERM, SIGTERMHandler) + + app.run() diff --git a/codexcrawler/main.nim b/codexcrawler/main.nim new file mode 100644 index 0000000..72260a9 --- /dev/null +++ b/codexcrawler/main.nim @@ -0,0 +1,18 @@ +import pkg/chronicles +import pkg/chronos + +logScope: + topics = "main" + +proc runApplication*() {.async.} = + proc aaa() {.async.} = + while true: + notice "a" + await sleepAsync(1000) + + asyncSpawn aaa() + + await sleepAsync(1000) + + notice "b" + diff --git a/codexcrawler/todo.nim b/codexcrawler/todo.nim deleted file mode 100644 index d59f01f..0000000 --- a/codexcrawler/todo.nim +++ /dev/null @@ -1,2 +0,0 @@ -proc run*() = - echo "Run!"