Safely close databases

This commit is contained in:
Yasuhiro Matsumoto
2023-12-25 00:07:17 +09:00
committed by fiatjaf_
parent 5e40dc96ba
commit ba7261eee8
2 changed files with 22 additions and 9 deletions

22
main.go
View File

@@ -7,6 +7,7 @@ import (
"html/template" "html/template"
"net/http" "net/http"
"os" "os"
"os/signal"
"strings" "strings"
eventstore_badger "github.com/fiatjaf/eventstore/badger" eventstore_badger "github.com/fiatjaf/eventstore/badger"
@@ -73,10 +74,12 @@ func main() {
tailwindDebugStuff = template.HTML(fmt.Sprintf("<script src=\"https://cdn.tailwindcss.com?plugins=typography\"></script><script>\n%s</script><style type=\"text/tailwindcss\">%s</style>", config, style)) tailwindDebugStuff = template.HTML(fmt.Sprintf("<script src=\"https://cdn.tailwindcss.com?plugins=typography\"></script><script>\n%s</script><style type=\"text/tailwindcss\">%s</style>", config, style))
} }
initCache() deinitCache := initCache()
defer deinitCache()
// initialize routines // initialize routines
ctx := context.Background() ctx, cancel := context.WithCancel(context.Background())
defer cancel()
go updateArchives(ctx) go updateArchives(ctx)
go deleteOldCachedEvents(ctx) go deleteOldCachedEvents(ctx)
@@ -110,11 +113,18 @@ func main() {
mux.HandleFunc("/", renderEvent) mux.HandleFunc("/", renderEvent)
log.Print("listening at http://0.0.0.0:" + s.Port) log.Print("listening at http://0.0.0.0:" + s.Port)
if err := http.ListenAndServe("0.0.0.0:"+s.Port, cors.Default().Handler(relay)); err != nil { server := &http.Server{Addr: "0.0.0.0:" + s.Port, Handler: cors.Default().Handler(relay)}
log.Fatal().Err(err).Msg("") go func() {
} server.ListenAndServe()
if err := server.ListenAndServe(); err != nil {
log.Error().Err(err).Msg("")
}
}()
select {} sc := make(chan os.Signal, 1)
signal.Notify(sc, os.Interrupt)
<-sc
server.Close()
} }
func initCache() func() { func initCache() func() {

View File

@@ -17,11 +17,10 @@ func updateArchives(ctx context.Context) {
select { select {
case <-ctx.Done(): case <-ctx.Done():
return return
default: case <-time.After(24 * time.Hour):
loadNpubsArchive(ctx) loadNpubsArchive(ctx)
loadRelaysArchive(ctx) loadRelaysArchive(ctx)
} }
time.Sleep(24 * time.Hour)
} }
} }
@@ -29,7 +28,11 @@ func deleteOldCachedEvents(ctx context.Context) {
wdb := eventstore.RelayWrapper{Store: db} wdb := eventstore.RelayWrapper{Store: db}
for { for {
time.Sleep(time.Hour) select {
case <-ctx.Done():
return
case <-time.After(time.Hour):
}
log.Debug().Msg("deleting old cached events") log.Debug().Msg("deleting old cached events")
now := time.Now().Unix() now := time.Now().Unix()
for _, key := range cache.GetPaginatedKeys("ttl:", 1, 500) { for _, key := range cache.GetPaginatedKeys("ttl:", 1, 500) {