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.

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