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.

119 lines
3.4 KiB

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