From e05369431cfd76e405b84e2a5d3141fa23782ed0 Mon Sep 17 00:00:00 2001 From: Sky Johnson Date: Thu, 24 Jul 2025 22:44:52 -0500 Subject: [PATCH] fix kv store persistence on server shutdown --- modules/http/http.lua | 4 +++- modules/kv/kv.go | 13 +++++++++++++ moonshark.go | 5 +++++ state/state.go | 5 +++++ todo_sessions.json | 3 +++ 5 files changed, 29 insertions(+), 1 deletion(-) create mode 100644 todo_sessions.json diff --git a/modules/http/http.lua b/modules/http/http.lua index be487a5..93101c3 100644 --- a/modules/http/http.lua +++ b/modules/http/http.lua @@ -156,7 +156,9 @@ function Session:save() local config = _G._http_session_config local session_json = json.encode(self._data) - return kv.set(config.store_name, "session:" .. self.id, session_json) + local success = kv.set(config.store_name, "session:" .. self.id, session_json) + + return success end function Session:destroy() diff --git a/modules/kv/kv.go b/modules/kv/kv.go index 002be78..cf528f5 100644 --- a/modules/kv/kv.go +++ b/modules/kv/kv.go @@ -490,3 +490,16 @@ func (store *Store) save() error { return nil } + +// CloseAllStores saves and closes all open stores +func CloseAllStores() { + mutex.Lock() + defer mutex.Unlock() + + for name, store := range stores { + if store.filename != "" { + store.save() + } + delete(stores, name) + } +} diff --git a/moonshark.go b/moonshark.go index bbc8056..8b8bb66 100644 --- a/moonshark.go +++ b/moonshark.go @@ -59,6 +59,11 @@ func runOnce(scriptPath string) { go func() { <-sigChan fmt.Println("\nShutting down...") + + // Close main state first (saves KV stores) + luaState.Close() + // Then stop servers (closes worker states) + http.StopAllServers() os.Exit(0) }() diff --git a/state/state.go b/state/state.go index 4333c2d..698f414 100644 --- a/state/state.go +++ b/state/state.go @@ -7,6 +7,7 @@ import ( "Moonshark/modules" "Moonshark/modules/http" + "Moonshark/modules/kv" luajit "git.sharkk.net/Sky/LuaJIT-to-Go" ) @@ -284,6 +285,10 @@ func (s *State) IsWorker() bool { // Close cleans up the state and releases resources func (s *State) Close() { if s.State != nil { + if !s.isWorker { + kv.CloseAllStores() + } + s.Cleanup() s.State.Close() s.State = nil diff --git a/todo_sessions.json b/todo_sessions.json new file mode 100644 index 0000000..61a1bb3 --- /dev/null +++ b/todo_sessions.json @@ -0,0 +1,3 @@ +{ + "session:x5joQraQyEkfzzRMrcP4o8yK0xjgwtCW": "{\"todos\":[{\"text\":\"asdasd\",\"completed\":true,\"id\":\"1753414744_8147\",\"created_at\":1753414744},{\"text\":\"fsdf\",\"completed\":true,\"id\":\"1753414748_8147\",\"created_at\":1753414748},{\"text\":\"asdasd\",\"completed\":false,\"id\":\"1753415063_8147\",\"created_at\":1753415063},{\"id\":\"1753415066_8147\",\"completed\":false,\"text\":\"asdkjfhaslkjdhflkasjhdf\",\"created_at\":1753415066},{\"text\":\"alsdhnfpuihawepiufhbpioweHBFIOEWBSF\",\"completed\":false,\"id\":\"1753415069_8147\",\"created_at\":1753415069}]}" +}