GraphQL API and utilities for the rpdata project
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

126 lines
3.5 KiB

  1. package main
  2. import (
  3. "context"
  4. "fmt"
  5. "git.aiterp.net/rpdata/api/space"
  6. "log"
  7. "net/http"
  8. "runtime/debug"
  9. "strings"
  10. "git.aiterp.net/rpdata/api/database"
  11. "git.aiterp.net/rpdata/api/graph2"
  12. "git.aiterp.net/rpdata/api/internal/config"
  13. "git.aiterp.net/rpdata/api/internal/instrumentation"
  14. "git.aiterp.net/rpdata/api/models"
  15. "git.aiterp.net/rpdata/api/services"
  16. "github.com/99designs/gqlgen/handler"
  17. "github.com/prometheus/client_golang/prometheus/promhttp"
  18. )
  19. func main() {
  20. cfg := config.Global()
  21. db, err := database.Init(cfg.Database)
  22. if err != nil {
  23. log.Fatalln("Failed to init db:", err)
  24. }
  25. defer db.Close(context.Background())
  26. var spaceClient *space.Client
  27. if cfg.Space.Enabled {
  28. spaceClient, err = space.Connect(cfg.Space)
  29. if err != nil {
  30. log.Fatalln("Failed to init space:", err)
  31. }
  32. log.Println("Space loaded")
  33. } else {
  34. log.Println("Space is disabled, file upload will not work!")
  35. }
  36. serviceBundle := services.NewBundle(db, spaceClient)
  37. instrumentation.Register()
  38. http.Handle("/", handler.Playground("RPData API", "/graphql"))
  39. http.Handle("/graphql", queryHandler(serviceBundle))
  40. http.Handle("/metrics", promhttp.Handler())
  41. go func() {
  42. err := serviceBundle.Logs.RefreshAllLogCharacters(context.Background())
  43. if err != nil {
  44. log.Println("Refresh Characters:", err)
  45. }
  46. err = serviceBundle.Logs.FixImportDateBug(context.Background())
  47. if err != nil {
  48. log.Println("Fix date bug:", err)
  49. }
  50. }()
  51. go logListedChanges(serviceBundle.Changes)
  52. log.Fatal(http.ListenAndServe(":8081", nil))
  53. }
  54. func logListedChanges(changes *services.ChangeService) {
  55. sub := changes.Subscribe(context.Background(), models.ChangeFilter{})
  56. for change := range sub {
  57. log.Printf("Change: Author=%#+v Model=%#+v Op=%#+v", change.Author, change.Model, change.Op)
  58. for _, object := range change.Objects() {
  59. switch object := object.(type) {
  60. case models.Log:
  61. log.Printf("\tLog: %s (%s)", object.ID, object.ShortID)
  62. case models.Character:
  63. log.Printf("\tCharacter: %s", object.ID)
  64. case models.Channel:
  65. log.Printf("\tChannel: %s", object.Name)
  66. case models.Post:
  67. log.Printf("\tPost: %s", object.ID)
  68. case models.Story:
  69. log.Printf("\tStory: %s", object.ID)
  70. case models.Tag:
  71. log.Printf("\tTag: (%s,%s)", object.Kind, object.Name)
  72. case models.Chapter:
  73. log.Printf("\tChapter: %s", object.ID)
  74. case models.Comment:
  75. log.Printf("\tComment: %s", object.ID)
  76. }
  77. }
  78. }
  79. log.Println("Change subscription closed.")
  80. }
  81. func queryHandler(services *services.Bundle) http.HandlerFunc {
  82. handler := handler.GraphQL(
  83. graph2.New(services),
  84. handler.UploadMaxSize(10485760),
  85. handler.UploadMaxMemory(1048576),
  86. handler.RecoverFunc(func(ctx context.Context, err interface{}) error {
  87. log.Println(err)
  88. log.Println(string(debug.Stack()))
  89. return fmt.Errorf("The server failed to serve your request due to an internal error, it has been logged")
  90. }),
  91. handler.ComplexityLimit(300),
  92. handler.RequestMiddleware(instrumentation.RequestMiddleware()),
  93. handler.ResolverMiddleware(instrumentation.ResolverMiddleware()),
  94. )
  95. return func(w http.ResponseWriter, r *http.Request) {
  96. // >_>
  97. if strings.HasPrefix(r.Header.Get("Authorization"), "Bearer of the curse") {
  98. w.Header().Set("X-Emerald-Herald", "Seek souls. Larger, more powerful souls.")
  99. w.Header().Add("X-Emerald-Herald", "Seek the king, that is the only way.")
  100. w.Header().Add("X-Emerald-Herald", "Lest this land swallow you whole... As it has so many others.")
  101. }
  102. r = services.Auth.RequestWithToken(r)
  103. handler.ServeHTTP(w, r)
  104. }
  105. }