gotelem/internal/api/http.go

249 lines
6.6 KiB
Go
Raw Normal View History

package api
2023-06-23 20:52:52 +00:00
// this file defines the HTTP handlers and routes.
import (
2023-06-27 23:22:24 +00:00
"encoding/json"
"fmt"
2023-06-23 20:52:52 +00:00
"net/http"
"log/slog"
2023-06-23 20:52:52 +00:00
"github.com/go-chi/chi/v5"
"github.com/go-chi/chi/v5/middleware"
2023-06-27 23:22:24 +00:00
"github.com/google/uuid"
"github.com/kschamplin/gotelem"
2023-06-30 16:51:06 +00:00
"github.com/kschamplin/gotelem/internal/db"
2023-06-23 20:52:52 +00:00
"github.com/kschamplin/gotelem/skylab"
"nhooyr.io/websocket"
2023-07-06 02:16:12 +00:00
"nhooyr.io/websocket/wsjson"
2023-06-23 20:52:52 +00:00
)
func TelemRouter(log *slog.Logger, broker *gotelem.Broker, db *db.TelemDb) http.Handler {
2023-06-23 20:52:52 +00:00
r := chi.NewRouter()
2023-06-29 00:23:08 +00:00
r.Use(middleware.RequestID)
r.Use(middleware.RealIP)
2023-06-30 12:40:50 +00:00
r.Use(middleware.Logger) // TODO: integrate with slog instead of go default logger.
2023-06-23 20:52:52 +00:00
r.Use(middleware.Recoverer)
2023-06-24 05:15:42 +00:00
// heartbeat request.
2023-06-23 20:52:52 +00:00
r.Get("/ping", func(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("pong"))
})
2023-06-24 05:15:42 +00:00
2023-06-27 23:22:24 +00:00
r.Mount("/api/v1", apiV1(broker, db))
2023-06-23 20:52:52 +00:00
// To future residents - you can add new API calls/systems in /api/v2
// Don't break anything in api v1! keep legacy code working!
return r
}
// define API version 1 routes.
func apiV1(broker *gotelem.Broker, tdb *db.TelemDb) chi.Router {
2023-06-23 20:52:52 +00:00
r := chi.NewRouter()
2023-06-30 12:40:50 +00:00
// this API only accepts JSON.
r.Use(middleware.AllowContentType("application/json"))
// no caching - always get the latest data.
// TODO: add a smart short expiry cache for queries that take a while.
2023-06-30 12:40:50 +00:00
r.Use(middleware.NoCache)
2023-06-23 20:52:52 +00:00
r.Get("/schema", func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
2023-06-30 12:40:50 +00:00
// return the Skylab JSON definitions
2023-06-23 20:52:52 +00:00
w.Write([]byte(skylab.SkylabDefinitions))
})
2023-06-27 23:22:24 +00:00
r.Route("/packets", func(r chi.Router) {
r.Get("/subscribe", apiV1PacketSubscribe(broker, tdb))
2023-06-27 23:22:24 +00:00
r.Post("/", func(w http.ResponseWriter, r *http.Request) {
2024-02-13 16:03:39 +00:00
var pkgs []skylab.BusEvent
2023-06-27 23:22:24 +00:00
decoder := json.NewDecoder(r.Body)
2023-06-29 00:23:08 +00:00
if err := decoder.Decode(&pkgs); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
2024-03-02 06:46:24 +00:00
tdb.AddEvents(pkgs...)
2023-06-29 00:23:08 +00:00
})
2024-03-02 06:46:24 +00:00
// general packet history get.
r.Get("/", apiV1GetPackets(tdb))
2023-06-29 00:23:08 +00:00
2024-03-02 06:46:24 +00:00
// this is to get a single field from a packet.
r.Get("/{name:[a-z_]+}/{field:[a-z_]+}", apiV1GetValues(tdb))
2023-06-29 00:23:08 +00:00
})
// records are driving segments/runs.
r.Route("/records", func(r chi.Router) {
r.Get("/", apiV1GetRecords(tdb)) // get all runs
r.Get("/active", apiV1GetActiveRecord(tdb)) // get current run (no end time)
r.Post("/", apiV1StartRecord(tdb)) // create a new run (with note). Ends active run if any, and creates new active run (no end time)
r.Get("/{id}", apiV1GetRecord(tdb)) // get details on a specific run
r.Put("/{id}", apiV1UpdateRecord(tdb)) // update a specific run. Can only be used to add notes/metadata, and not to change time/id.
2023-06-29 00:23:08 +00:00
2023-06-27 23:22:24 +00:00
})
2023-09-19 19:17:22 +00:00
r.Get("/stats", func(w http.ResponseWriter, r *http.Request) {
}) // v1 api stats (calls, clients, xbee connected, meta health ok)
2023-06-27 23:22:24 +00:00
2023-06-23 20:52:52 +00:00
return r
}
2023-06-27 23:22:24 +00:00
// apiV1Subscriber is a websocket session for the v1 api.
type apiV1Subscriber struct {
nameFilter []string // names of packets we care about.
2023-06-27 23:22:24 +00:00
}
// this is a websocket stream.
func apiV1PacketSubscribe(broker *gotelem.Broker, db *db.TelemDb) http.HandlerFunc {
2023-06-27 23:22:24 +00:00
return func(w http.ResponseWriter, r *http.Request) {
conn_id := r.RemoteAddr + uuid.New().String()
sub, err := broker.Subscribe(conn_id)
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
fmt.Fprintf(w, "error subscribing: %s", err)
return
}
defer broker.Unsubscribe(conn_id)
c, err := websocket.Accept(w, r, nil)
if err != nil {
2024-03-02 06:46:24 +00:00
http.Error(w, err.Error(), http.StatusInternalServerError)
2023-06-27 23:22:24 +00:00
return
}
2024-03-02 06:46:24 +00:00
c.Ping(r.Context())
2023-06-27 23:22:24 +00:00
2023-06-29 00:23:08 +00:00
// TODO: use K/V with session token?
2023-06-27 23:22:24 +00:00
sess := &apiV1Subscriber{}
for {
select {
2023-06-29 00:23:08 +00:00
case <-r.Context().Done():
2023-06-27 23:22:24 +00:00
return
case msgIn := <-sub:
if len(sess.nameFilter) == 0 {
2023-06-27 23:22:24 +00:00
// send it.
2023-07-06 02:16:12 +00:00
wsjson.Write(r.Context(), c, msgIn)
2023-06-27 23:22:24 +00:00
}
for _, name := range sess.nameFilter {
if name == msgIn.Name {
2023-06-27 23:22:24 +00:00
// send it
wsjson.Write(r.Context(), c, msgIn)
2023-07-06 02:16:12 +00:00
break
2023-06-27 23:22:24 +00:00
}
}
}
2024-03-02 06:46:24 +00:00
}
}
}
func apiV1GetPackets(tdb *db.TelemDb) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
// this should use http query params to return a list of packets.
bef, err := extractBusEventFilter(r)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
lim, err := extractLimitModifier(r)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
// TODO: is the following check needed?
var res []skylab.BusEvent
if lim != nil {
res, err = tdb.GetPackets(r.Context(), *bef, lim)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
2023-06-27 23:22:24 +00:00
2024-03-02 06:46:24 +00:00
} else {
res, err = tdb.GetPackets(r.Context(), *bef)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
2023-06-27 23:22:24 +00:00
}
2024-03-02 06:46:24 +00:00
b, err := json.Marshal(res)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
w.Write(b)
2023-06-27 23:22:24 +00:00
}
}
2023-06-30 12:40:50 +00:00
2024-02-24 22:48:19 +00:00
// apiV1GetValues is a function that creates a handler for
// getting the specific value from a packet.
// this is useful for OpenMCT or other viewer APIs
func apiV1GetValues(db *db.TelemDb) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
var err error
bef, err := extractBusEventFilter(r)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
2024-02-24 22:48:19 +00:00
}
lim, err := extractLimitModifier(r)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
2024-02-24 22:48:19 +00:00
}
2024-03-02 06:46:24 +00:00
// get the URL parameters, these are guaranteed to exist.
2024-02-24 22:48:19 +00:00
name := chi.URLParam(r, "name")
field := chi.URLParam(r, "field")
// override the bus event filter name option
bef.Names = []string{name}
2024-02-24 22:48:19 +00:00
res, err := db.GetValues(r.Context(), *bef, field, lim)
2024-02-24 22:48:19 +00:00
if err != nil {
// 500 server error:
2024-03-02 06:46:24 +00:00
http.Error(w, err.Error(), http.StatusInternalServerError)
2024-02-29 19:11:49 +00:00
return
2024-02-24 22:48:19 +00:00
}
b, err := json.Marshal(res)
2024-02-28 20:10:40 +00:00
if err != nil {
2024-03-02 06:46:24 +00:00
http.Error(w, err.Error(), http.StatusInternalServerError)
2024-02-29 19:11:49 +00:00
return
2024-02-28 20:10:40 +00:00
}
2024-02-24 22:48:19 +00:00
w.Write(b)
}
}
2023-06-30 12:40:50 +00:00
// TODO: rename. record is not a clear name. Runs? drives? segments?
2023-06-30 16:51:06 +00:00
func apiV1GetRecords(db *db.TelemDb) http.HandlerFunc {
2023-06-30 12:40:50 +00:00
return func(w http.ResponseWriter, r *http.Request) {
}
}
2023-06-30 16:51:06 +00:00
func apiV1GetActiveRecord(db *db.TelemDb) http.HandlerFunc {
2023-06-30 12:40:50 +00:00
return func(w http.ResponseWriter, r *http.Request) {
}
}
2023-06-30 16:51:06 +00:00
func apiV1StartRecord(db *db.TelemDb) http.HandlerFunc {
2023-06-30 12:40:50 +00:00
return func(w http.ResponseWriter, r *http.Request) {}
}
2023-06-30 16:51:06 +00:00
func apiV1GetRecord(db *db.TelemDb) http.HandlerFunc {
2023-06-30 12:40:50 +00:00
return func(w http.ResponseWriter, r *http.Request) {}
}
2023-06-30 16:51:06 +00:00
func apiV1UpdateRecord(db *db.TelemDb) http.HandlerFunc {
2023-06-30 12:40:50 +00:00
return func(w http.ResponseWriter, r *http.Request) {}
}