From 3d670c420d770aaf15f7775e2afe8c7f7dd5e9f1 Mon Sep 17 00:00:00 2001 From: William Perron Date: Thu, 21 Dec 2023 18:27:48 -0500 Subject: [PATCH] optimize discord command registration for faster startup and shutdown --- cmd/themis-server/main.go | 33 +++++++++------------------------ 1 file changed, 9 insertions(+), 24 deletions(-) diff --git a/cmd/themis-server/main.go b/cmd/themis-server/main.go index b7438cc..6cf921d 100644 --- a/cmd/themis-server/main.go +++ b/cmd/themis-server/main.go @@ -37,6 +37,9 @@ var ( type Handler func(s *discordgo.Session, i *discordgo.InteractionCreate) func main() { + log.Info().Msg("startup.") + start := time.Now() + ctx, cancel := signal.NotifyContext(context.Background(), syscall.SIGTERM, syscall.SIGKILL, syscall.SIGINT) defer cancel() @@ -47,8 +50,7 @@ func main() { zerolog.SetGlobalLevel(zerolog.DebugLevel) } log.Logger = log.Output(zerolog.ConsoleWriter{Out: os.Stdout}) - - log.Info().Msg("startup.") + zerolog.DurationFieldUnit = time.Millisecond go func() { if err := serve(":8080"); err != nil { @@ -632,19 +634,12 @@ func main() { } defer discord.Close() - total := len(commands) - registeredCommands := make([]*discordgo.ApplicationCommand, total) - log.Debug().Int("total", total).Msg("registering commands with Discord") - for i, c := range commands { - log.Debug().Msg(fmt.Sprintf("registering command %d of %d", i+1, total)) - command, err := discord.ApplicationCommandCreate(appId, guildId, c) - if err != nil { - log.Fatal().Err(err).Msg("failed to register command") - } - registeredCommands[i] = command + log.Debug().Int("count", len(commands)).Msg("registering commands via bulk overwrite") + created, err := discord.ApplicationCommandBulkOverwrite(appId, guildId, commands) + if err != nil { + log.Fatal().Err(err).Msg("failed to register commands with discord") } - - log.Info().Int("count", len(registeredCommands)).Msg("registered commands") + log.Info().Int("count", len(created)).Dur("startup_latency_ms", time.Since(start)).Msg("registered commands, ready to operate") go notifier.NotifyFunc(ctx, func() { log.Info().Msg("sending weekly reminder") @@ -674,16 +669,6 @@ func main() { <-ctx.Done() log.Info().Msg("context cancelled, exiting") - - log.Debug().Int("total", total).Msg("deregistering commands with Discord") - for i, c := range registeredCommands { - log.Debug().Msg(fmt.Sprintf("registering command %d of %d", i+1, total)) - err = discord.ApplicationCommandDelete(appId, guildId, c.ID) - if err != nil { - log.Error().Err(err).Msg("failed to deregister commands") - } - } - log.Info().Msg("deregistered commands, exiting") os.Exit(0) }