commit 3e0a3f9a95f1fd4de72ebf0347845dfcc81db47d
parent 24464e15632d2b76f0515e647a0cc687d8521069
Author: Natasha Kerensikova <natgh@instinctive.eu>
Date: Sun, 21 Sep 2025 17:23:26 +0000
NATS connections are re-used on reload
Diffstat:
M | natsbot.go | | | 38 | ++++++++++++++++++++++++++++++++++---- |
1 file changed, 34 insertions(+), 4 deletions(-)
diff --git a/natsbot.go b/natsbot.go
@@ -117,7 +117,7 @@ func Loop(cb NatsBot, mainScript string, capacity int) {
}
}
- stateClean(L)
+ stateClean(L, nil)
log.Println("natsbot finished")
}
@@ -220,6 +220,7 @@ const (
keySubsTable
keyTimerTable
keyReloadRequest
+ keyOldCfgMap
)
func registerState(L *lua.LState, evtChan chan *internalEvent, msgChan chan *nats.Msg) {
@@ -238,26 +239,38 @@ func registerState(L *lua.LState, evtChan chan *internalEvent, msgChan chan *nat
func stateReloadBegin(oldL, newL *lua.LState) {
evtChan := stateEvtChan(oldL)
msgChan := stateMsgChan(oldL)
+ cfgMap := stateCfgMap(oldL)
registerState(newL, evtChan, msgChan)
+ newL.RawSetInt(stateGet(newL), keyOldCfgMap, newUserData(newL, cfgMap))
}
func stateReloadAbort(oldL, newL *lua.LState) {
- stateClean(newL)
+ stateClean(newL, oldL)
}
func stateReloadEnd(oldL, newL *lua.LState) {
- stateClean(oldL)
+ stateClean(oldL, newL)
+ newL.RawSetInt(stateGet(newL), keyOldCfgMap, lua.LNil)
}
-func stateClean(L *lua.LState) {
+func stateClean(L, keptL *lua.LState) {
_, connIdx := stateConnTable(L)
st := stateGet(L)
L.RawSetInt(st, keyConnTable, newConnTbl(L))
L.RawSetInt(st, keySubsTable, newSubsTbl(L))
+ var keptConn connMap
+ if keptL != nil {
+ _, keptConn = stateConnTable(keptL)
+ }
+
for nc := range connIdx {
+ if _, found := keptConn[nc]; found {
+ continue
+ }
+
nc.SetClosedHandler(nil)
nc.SetDisconnectErrHandler(nil)
nc.SetDiscoveredServersHandler(nil)
@@ -333,6 +346,15 @@ func stateRequestReload(L *lua.LState, v lua.LValue) {
L.RawSetInt(stateGet(L), keyReloadRequest, v)
}
+func stateOldCfgMap(L *lua.LState) natsConfigMap {
+ v := stateValue(L, keyOldCfgMap)
+ if v == lua.LNil {
+ return nil
+ } else {
+ return v.(*lua.LUserData).Value.(natsConfigMap)
+ }
+}
+
func requestReload(L *lua.LState) int {
stateRequestReload(L, lua.LTrue)
return 0
@@ -529,6 +551,14 @@ func natsConnect(L *lua.LState) int {
}
}
+ if oldCfgMap := stateOldCfgMap(L); oldCfgMap != nil {
+ if nc, found := oldCfgMap[cfg]; found {
+ cfgMap[cfg] = nc
+ L.Push(wrapConn(L, nc, cbmap))
+ return 1
+ }
+ }
+
nc, err := newConn(stateEvtChan(L), pcfg)
if err != nil {
log.Println("newConn", err)