this repo has no description
1package knotserver
2
3import (
4 "context"
5 "encoding/json"
6 "fmt"
7 "log"
8 "net/http"
9
10 "github.com/go-chi/chi/v5"
11 "github.com/icyphox/bild/knotserver/config"
12 "github.com/icyphox/bild/knotserver/db"
13 "github.com/icyphox/bild/knotserver/jsclient"
14)
15
16type Handle struct {
17 c *config.Config
18 db *db.DB
19 js *jsclient.JetstreamClient
20}
21
22func Setup(ctx context.Context, c *config.Config, db *db.DB) (http.Handler, error) {
23 r := chi.NewRouter()
24
25 h := Handle{
26 c: c,
27 db: db,
28 }
29
30 err := h.StartJetstream(ctx)
31 if err != nil {
32 return nil, fmt.Errorf("failed to start jetstream: %w", err)
33 }
34
35 r.Get("/", h.Index)
36 r.Route("/{did}", func(r chi.Router) {
37 // Repo routes
38 r.Route("/{name}", func(r chi.Router) {
39 r.Get("/", h.RepoIndex)
40 r.Get("/info/refs", h.InfoRefs)
41 r.Post("/git-upload-pack", h.UploadPack)
42
43 r.Route("/tree/{ref}", func(r chi.Router) {
44 r.Get("/*", h.RepoTree)
45 })
46
47 r.Route("/blob/{ref}", func(r chi.Router) {
48 r.Get("/*", h.FileContent)
49 })
50
51 r.Get("/log/{ref}", h.Log)
52 r.Get("/archive/{file}", h.Archive)
53 r.Get("/commit/{ref}", h.Diff)
54 r.Get("/refs/", h.Refs)
55 })
56 })
57
58 r.Route("/repo", func(r chi.Router) {
59 r.Put("/new", h.NewRepo)
60 })
61
62 r.With(h.VerifySignature).Get("/health", h.Health)
63
64 r.Group(func(r chi.Router) {
65 r.Use(h.VerifySignature)
66 r.Get("/keys", h.Keys)
67 r.Put("/keys", h.Keys)
68 })
69
70 return r, nil
71}
72
73func (h *Handle) StartJetstream(ctx context.Context) error {
74 colections := []string{"sh.bild.publicKeys"}
75 dids := []string{}
76
77 h.js = jsclient.NewJetstreamClient(colections, dids)
78 messages, err := h.js.ReadJetstream(ctx)
79 if err != nil {
80 return fmt.Errorf("failed to read from jetstream: %w", err)
81 }
82
83 go func() {
84 for msg := range messages {
85 var data map[string]interface{}
86 if err := json.Unmarshal(msg, &data); err != nil {
87 log.Printf("error unmarshaling message: %v", err)
88 continue
89 }
90
91 if kind, ok := data["kind"].(string); ok && kind == "commit" {
92 log.Printf("commit event: %+v", data)
93 }
94 }
95 }()
96
97 return nil
98}
99
100func (h *Handle) Multiplex(w http.ResponseWriter, r *http.Request) {
101 path := chi.URLParam(r, "*")
102
103 if r.URL.RawQuery == "service=git-receive-pack" {
104 w.WriteHeader(http.StatusBadRequest)
105 w.Write([]byte("no pushing allowed!"))
106 return
107 }
108
109 fmt.Println(r.URL.RawQuery)
110 fmt.Println(r.Method)
111
112 if path == "info/refs" &&
113 r.URL.RawQuery == "service=git-upload-pack" &&
114 r.Method == "GET" {
115 h.InfoRefs(w, r)
116 } else if path == "git-upload-pack" && r.Method == "POST" {
117 h.UploadPack(w, r)
118 } else if r.Method == "GET" {
119 h.RepoIndex(w, r)
120 }
121}