Skip to content

Commit

Permalink
Simplify tlserver command
Browse files Browse the repository at this point in the history
  • Loading branch information
irees committed Jan 26, 2024
1 parent 68bf9c2 commit cf81c27
Show file tree
Hide file tree
Showing 3 changed files with 14 additions and 74 deletions.
3 changes: 1 addition & 2 deletions cmd/tlserver/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,6 @@ import (
"github.com/interline-io/transitland-lib/dmfr/sync"
"github.com/interline-io/transitland-lib/dmfr/unimporter"
"github.com/interline-io/transitland-lib/tl"
"github.com/interline-io/transitland-server/server"
)

///////////////
Expand Down Expand Up @@ -62,7 +61,7 @@ func main() {
case "fetch":
r = &fetch.Command{}
case "server":
r = &server.Command{}
r = &Command{}
default:
log.Print("%q is not valid command.", subc)
return
Expand Down
84 changes: 13 additions & 71 deletions server/server_cmd.go → cmd/tlserver/server_cmd.go
Original file line number Diff line number Diff line change
@@ -1,21 +1,17 @@
package server
package main

import (
"context"
"errors"
"flag"
"fmt"
"os/signal"
"syscall"
"time"

"net/http"
"net/http/pprof"
"os"

"github.com/go-chi/chi/middleware"
"github.com/go-chi/chi/v5"
"github.com/go-chi/cors"
"github.com/go-redis/redis/v8"
"github.com/interline-io/log"
"github.com/interline-io/transitland-dbutil/dbutil"
Expand All @@ -39,18 +35,8 @@ type Command struct {
LongQueryDuration int
Port string
RestPrefix string
DisableImage bool
DisableGraphql bool
DisableRest bool
EnablePlayground bool
EnableAdminApi bool
EnableJobsApi bool
EnableWorkers bool
EnableProfiler bool
EnableRateLimits bool
LoadAdmins bool
ValidateLargeFiles bool
QueuePrefix string
SecretsFile string
Storage string
RTStorage string
Expand All @@ -65,28 +51,17 @@ func (cmd *Command) Parse(args []string) error {
log.Print("Usage: server")
fl.PrintDefaults()
}

// Base config
fl.StringVar(&cmd.DBURL, "dburl", "", "Database URL (default: $TL_DATABASE_URL)")
fl.StringVar(&cmd.RedisURL, "redisurl", "", "Redis URL (default: $TL_REDIS_URL)")
fl.StringVar(&cmd.Storage, "storage", "", "Static storage backend")
fl.StringVar(&cmd.RTStorage, "rt-storage", "", "RT storage backend")
fl.BoolVar(&cmd.ValidateLargeFiles, "validate-large-files", false, "Allow validation of large files")
fl.StringVar(&cmd.RestPrefix, "rest-prefix", "", "REST prefix for generating pagination links")
fl.BoolVar(&cmd.DisableImage, "disable-image", false, "Disable image generation")

// Server config
fl.StringVar(&cmd.Port, "port", "8080", "")
fl.StringVar(&cmd.SecretsFile, "secrets", "", "DMFR file containing secrets")
fl.StringVar(&cmd.QueuePrefix, "queue", "", "Job name prefix")
fl.IntVar(&cmd.Timeout, "timeout", 60, "")
fl.IntVar(&cmd.LongQueryDuration, "long-query", 1000, "Log queries over this duration (ms)")
fl.BoolVar(&cmd.DisableGraphql, "disable-graphql", false, "Disable GraphQL endpoint")
fl.BoolVar(&cmd.DisableRest, "disable-rest", false, "Disable REST endpoint")
fl.BoolVar(&cmd.EnablePlayground, "enable-playground", false, "Enable GraphQL playground")
fl.BoolVar(&cmd.EnableProfiler, "enable-profile", false, "Enable profiling")
fl.BoolVar(&cmd.LoadAdmins, "load-admins", false, "Load admin polygons from database into memory")

fl.Parse(args)

// DB
Expand Down Expand Up @@ -159,22 +134,11 @@ func (cmd *Command) Run() error {
Storage: cmd.Storage,
RTStorage: cmd.RTStorage,
ValidateLargeFiles: cmd.ValidateLargeFiles,
DisableImage: cmd.DisableImage,
RestPrefix: cmd.RestPrefix,
}

// Setup router
root := chi.NewRouter()
root.Use(middleware.RequestID)
root.Use(middleware.RealIP)
root.Use(middleware.Recoverer)
root.Use(middleware.StripSlashes)
root.Use(cors.Handler(cors.Options{
AllowedOrigins: []string{"https://*", "http://*"},
AllowedMethods: []string{"GET", "POST", "DELETE", "OPTIONS"},
AllowedHeaders: []string{"content-type", "apikey", "authorization"},
AllowCredentials: true,
}))

// Finders config
root.Use(model.AddConfig(cfg))
Expand All @@ -188,40 +152,35 @@ func (cmd *Command) Run() error {
}))

// Profiling
if cmd.EnableProfiler {
root.HandleFunc("/debug/pprof/", pprof.Index)
root.HandleFunc("/debug/pprof/cmdline", pprof.Cmdline)
root.HandleFunc("/debug/pprof/profile", pprof.Profile)
root.HandleFunc("/debug/pprof/symbol", pprof.Symbol)
}
root.HandleFunc("/debug/pprof/", pprof.Index)
root.HandleFunc("/debug/pprof/cmdline", pprof.Cmdline)
root.HandleFunc("/debug/pprof/profile", pprof.Profile)
root.HandleFunc("/debug/pprof/symbol", pprof.Symbol)

// GraphQL API
graphqlServer, err := gql.NewServer()
if err != nil {
return err
}
if !cmd.DisableGraphql {
// Mount with user permissions required
if true {
r := chi.NewRouter()
r.Mount("/", graphqlServer)
root.Mount("/query", r)
}

// REST API
if !cmd.DisableRest {
restServer, err := rest.NewServer(graphqlServer)
if err != nil {
return err
}
restServer, err := rest.NewServer(graphqlServer)
if err != nil {
return err
}
if true {
r := chi.NewRouter()
r.Mount("/", restServer)
root.Mount("/rest", r)
}

// GraphQL Playground
if cmd.EnablePlayground && !cmd.DisableGraphql {
root.Handle("/", playground.Handler("GraphQL playground", "/query"))
}
root.Handle("/", playground.Handler("GraphQL playground", "/query"))

// Start server
timeOut := time.Duration(cmd.Timeout) * time.Second
Expand All @@ -233,22 +192,5 @@ func (cmd *Command) Run() error {
WriteTimeout: 2 * timeOut,
ReadTimeout: 2 * timeOut,
}
go func() {
srv.ListenAndServe()
}()

// Listen for shutdown
signalChan := make(chan os.Signal, 1)
signal.Notify(
signalChan,
syscall.SIGHUP,
syscall.SIGINT,
syscall.SIGQUIT,
)
<-signalChan
// Start http server shutdown with 5 second timeout
// Run this in main thread so we block for shutdown to succeed
gracefullCtx, cancelShutdown := context.WithTimeout(context.Background(), 5*time.Second)
defer cancelShutdown()
return srv.Shutdown(gracefullCtx)
return srv.ListenAndServe()
}
1 change: 0 additions & 1 deletion server/server_test.go

This file was deleted.

0 comments on commit cf81c27

Please sign in to comment.