fix kv store persistence on server shutdown

This commit is contained in:
Sky Johnson 2025-07-24 22:44:52 -05:00
parent f09c9f345a
commit e05369431c
5 changed files with 29 additions and 1 deletions

View File

@ -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()

View File

@ -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)
}
}

View File

@ -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)
}()

View File

@ -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

3
todo_sessions.json Normal file
View File

@ -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}]}"
}