sonda/internal/api/http/handlers_peer.go
tgiachi a880b87a9e chore: move the module path to git.kmalloc.org/squid/sonda
Migrating hosting from Codeberg to git.kmalloc.org. Renames the
module path in go.mod, every internal import, and the OCI image
source label in the Dockerfile. Build and full test suite verified
green after the rename.
2026-11-15 17:30:29 +01:00

195 lines
6 KiB
Go

package httpapi
import (
"context"
"errors"
"net/http"
"strings"
"github.com/gin-gonic/gin"
"git.kmalloc.org/squid/sonda/internal/catalog"
"git.kmalloc.org/squid/sonda/internal/federation"
)
const (
peerPrefix = "/api/v1/peer/"
friendKey = "friend"
peerChunkSize = 32 << 10
)
// registerPeer adds the routes another Sonda server reads, to v1. A friend signs every request (see
// federation.Sign); what it can read is the catalogue and the files of the libraries that are shared, and nothing
// else: the services it is given are the ones that look only at those.
func registerPeer(v1 *gin.RouterGroup, d Deps) {
peer := v1.Group("/peer", requireFriend(d.Federation))
peer.GET("/info", (&peerInfoHandlers{fed: d.Federation, libs: d.Libraries}).info)
cat := &catalogHandlers{svc: d.PeerCatalog}
peer.GET("/artists", cat.listArtists)
peer.GET("/artists/:id", cat.getArtist)
peer.GET("/albums", cat.listAlbums)
peer.GET("/albums/:id", cat.getAlbum)
peer.GET("/tracks", cat.listTracks)
peer.GET("/tracks/:id", cat.getTrack)
peer.GET("/albums/:id/cover", (&peerCoverHandlers{fed: d.Federation, catalog: d.PeerCatalog, covers: &coverHandlers{svc: d.PeerCovers}}).album)
peer.GET("/tracks/:id/peaks", (&waveformHandlers{svc: d.PeerWaveform}).peaks)
peer.GET("/tracks/:id/stream", (&peerStreamHandlers{fed: d.Federation, inner: &streamHandlers{svc: d.PeerStreams}}).stream)
}
// requireFriend lets a request through only when a friend signed it. Everything that is not properly signed is
// the same 401, and while federation is off the routes are missing. Each request of a friend is logged afterwards:
// the route (never the query), the status and the bytes sent.
func requireFriend(fed federationService) gin.HandlerFunc {
return func(c *gin.Context) {
uri := c.Request.URL.RequestURI()
// A proxy may serve Sonda under a sub-path: what is signed starts at /api/v1/peer.
if i := strings.Index(uri, peerPrefix); i > 0 {
uri = uri[i:]
}
friend, err := fed.Authenticate(c.Request.Context(), federation.Signed{
KeyID: c.GetHeader(federation.HeaderKeyID),
Date: c.GetHeader(federation.HeaderDate),
Nonce: c.GetHeader(federation.HeaderNonce),
Signature: c.GetHeader(federation.HeaderSignature),
Method: c.Request.Method,
URI: uri,
})
switch {
case err == nil:
case errors.Is(err, federation.ErrOff):
writeError(c, http.StatusNotFound, "not_found", "no such route")
return
case errors.Is(err, federation.ErrUnauthorized):
writeError(c, http.StatusUnauthorized, "unauthorized", "the request is not signed by a friend")
return
case errors.Is(err, federation.ErrNotApproved):
writeError(c, http.StatusForbidden, "not_approved", "the friendship is not approved yet")
return
default:
_ = c.Error(err)
writeError(c, http.StatusInternalServerError, "internal", "internal error")
return
}
c.Set(friendKey, friend)
c.Next()
sent := int64(c.Writer.Size())
if sent < 0 {
sent = 0
}
fed.Record(c.Request.Context(), federation.FriendRequest{FriendID: friend.ID, Route: c.FullPath(), Status: c.Writer.Status(), Bytes: sent})
}
}
func friendOf(c *gin.Context) federation.Friend {
f, _ := c.Get(friendKey)
friend, _ := f.(federation.Friend)
return friend
}
type peerInfoHandlers struct {
fed federationService
libs libraryService
}
// info says who this server is and how many libraries are shared; no more.
func (h *peerInfoHandlers) info(c *gin.Context) {
st, err := h.fed.Status(c.Request.Context())
if err != nil {
writeFederationError(c, err)
return
}
libs, err := h.libs.List(c.Request.Context())
if err != nil {
writeLibraryError(c, err)
return
}
shared := 0
for _, l := range libs {
if l.Shared {
shared++
}
}
c.JSON(http.StatusOK, gin.H{"name": st.Name, "shared_libraries": shared})
}
// pacedWriter slows the body of an answer to what the friend's allowance says.
type pacedWriter struct {
gin.ResponseWriter
st *federation.Stream
ctx context.Context
}
func (w *pacedWriter) Write(p []byte) (int, error) {
written := 0
for len(p) > 0 {
n := min(len(p), peerChunkSize)
if err := w.st.Wait(w.ctx, n); err != nil {
return written, err
}
m, err := w.ResponseWriter.Write(p[:n])
written += m
if err != nil {
return written, err
}
p = p[n:]
}
return written, nil
}
type peerStreamHandlers struct {
fed federationService
inner *streamHandlers
}
// stream serves a track of a shared library to a friend, as a listener would get it, within the friend's
// allowance: a few streams at a time, and a number of bytes a second.
func (h *peerStreamHandlers) stream(c *gin.Context) {
st, err := h.fed.StartStream(c.Request.Context(), friendOf(c).ID)
if errors.Is(err, federation.ErrTooManyStreams) {
c.Header("Retry-After", "5")
writeError(c, http.StatusTooManyRequests, "too_many_streams", "this server already streams as much to you as it allows")
return
}
if err != nil {
_ = c.Error(err)
writeError(c, http.StatusInternalServerError, "internal", "internal error")
return
}
defer st.Close()
c.Writer = &pacedWriter{ResponseWriter: c.Writer, st: st, ctx: c.Request.Context()}
h.inner.stream(c)
}
type peerCoverHandlers struct {
fed federationService
catalog catalogService
covers *coverHandlers
}
// album serves a cover that was already built, for an album that has a track in a shared library.
func (h *peerCoverHandlers) album(c *gin.Context) {
id, ok := pathID(c)
if !ok {
return
}
if _, err := h.catalog.Album(c.Request.Context(), id); err != nil {
if errors.Is(err, catalog.ErrNotFound) {
writeError(c, http.StatusNotFound, "album_not_found", "no such album")
return
}
_ = c.Error(err)
writeError(c, http.StatusInternalServerError, "internal", "internal error")
return
}
st, err := h.fed.Pace(c.Request.Context(), friendOf(c).ID)
if err != nil {
_ = c.Error(err)
writeError(c, http.StatusInternalServerError, "internal", "internal error")
return
}
defer st.Close()
c.Writer = &pacedWriter{ResponseWriter: c.Writer, st: st, ctx: c.Request.Context()}
h.covers.album(c)
}