cmd/ismsrv: server for indie uploads
ci/woodpecker/push/deploy Pipeline was successful

This commit is contained in:
2026-11-28 08:43:29 -05:00
parent d06114fe9d
commit 4d85d9c7a8
10 changed files with 1144 additions and 0 deletions
+91
View File
@@ -0,0 +1,91 @@
package main
import (
"cmp"
"context"
"encoding/json/v2"
"log/slog"
"net/http"
"time"
"github.com/go-chi/chi/v5/middleware"
"zombiezen.com/go/sqlite"
"zombiezen.com/go/sqlite/sqlitemigration"
"git.sunturtle.xyz/zephyr/horse/ismdb"
"git.sunturtle.xyz/zephyr/horse/umadump/ism"
)
type API struct {
db *sqlitemigration.Pool
}
type apiLogKey struct{}
func logged(next http.Handler) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
t := time.Now().UTC()
log := slog.With(
slog.Group("request",
slog.String("remote", r.RemoteAddr),
slog.String("forwarded", r.Header.Get("X-Forwarded-For")),
slog.String("proto", r.Proto),
slog.String("method", r.Method),
slog.Any("path", r.URL),
slog.Time("start", t),
),
)
ww := middleware.NewWrapResponseWriter(w, r.ProtoMajor)
r = r.WithContext(context.WithValue(r.Context(), apiLogKey{}, log))
next.ServeHTTP(ww, r)
log.InfoContext(r.Context(), "served",
slog.Int("status", ww.Status()),
slog.Int("size", ww.BytesWritten()),
slog.Duration("duration", time.Since(t)),
)
}
}
func (api *API) PostCareer(w http.ResponseWriter, r *http.Request) {
log := r.Context().Value(apiLogKey{}).(*slog.Logger)
var career ism.WorkIdleSingleMode
err := json.UnmarshalRead(r.Body, &career, json.RejectUnknownMembers(true))
if err != nil {
http.Error(w, "invalid career", http.StatusBadRequest)
return
}
endTrainer, _ := career.Extra.TrainedChara["viewer_id"].(float64)
t := cmp.Or(career.Extra.ViewerID, int64(endTrainer))
if t == 0 {
http.Error(w, "no trainer ID in career (old umadump?)", http.StatusBadRequest)
return
}
conn, err := api.db.Take(r.Context())
defer api.db.Put(conn)
if err != nil {
log.ErrorContext(r.Context(), "db.Take", slog.Any("err", err))
http.Error(w, "internal server error", http.StatusInternalServerError)
return
}
if err := ismdb.Insert(r.Context(), conn, log, &career, t); err != nil {
switch res := sqlite.ErrCode(err); res {
case sqlite.ResultConstraintPrimaryKey:
// NOTE(zephyr): we shouldn't actually see this because
// package ismdb swallows it, but i might change that at some point
log.InfoContext(r.Context(), "career already present", slog.Int64("trainer", t), slog.Int("chara", int(career.End.Chara.SingleModeCharaID)))
fallthrough
case sqlite.ResultOK:
// happy path
w.WriteHeader(http.StatusNoContent)
case sqlite.ResultError:
log.ErrorContext(r.Context(), "insert", slog.Any("err", err))
http.Error(w, "internal server error", http.StatusInternalServerError)
default:
log.ErrorContext(r.Context(), "sqlite on insert", slog.Any("err", err))
http.Error(w, "internal server error", http.StatusInternalServerError)
}
}
}