sonda/internal/federation/limits.go
tgiachi 89826fcd07 feat(federation): shared libraries and the signed read API for friends
A friend's server can now read what an admin chose to share.

- A library has a shared flag, off by default (migration 0024), set with
  PATCH /libraries/{id}. Changing it never waits for a scan.
- Requests between friends are signed with each server's Ed25519 key: the
  method, the path and query from /api/v1/peer on, a date, a nonce and the
  hash of the empty body. A date more than two minutes off, a nonce used
  before, an unknown or removed key and a bad signature all get the same
  401. A friend still waiting for approval gets 403, and while federation is
  off the routes are missing.
- Routes under /api/v1/peer: info, artists, albums, tracks, covers and
  streaming with Range. The catalogue, the counts and the format come from
  the shared libraries only, and the file served is the one in a shared
  library. No path, library id, listen, taste, user or provider data is part
  of an answer.
- A friend never makes this server build a cover, read an audio file or ask
  a provider: only covers already built from the audio files are served.
- Per-friend limits, set by the admin: parallel streams (default 3) and KiB
  a second (default 4096, 0 for none), shared by all the streams of a friend.
- A log of the last requests friends made (route, status, bytes; never the
  query), kept for 7 days, in GET /federation/requests.
- POST /federation/friends/{id}/check lets the side that pasted an invite
  find out that the other admin approved; a signed call from a friend this
  server is waiting for makes it active too.
- Admin: a Shared with friends switch on each library, which asks first, and
  limits, recent requests and a Check button in the Federation section, in
  English and Italian.
- OpenAPI paths and schemas, contract test, two real servers checked end to
  end with tagged audio files.
2026-11-13 15:04:07 +01:00

123 lines
3.1 KiB
Go

package federation
import (
"context"
"sync"
"time"
)
// What a friend is held to while it reads: a few streams at a time, and a number of bytes a second shared by all
// of them. The numbers are the admin's (see Settings).
const (
minKiBPerSec = 64
maxKiBPerSec = 100 << 10
maxStreamsCap = 20
// A burst of this much time at the full rate is let through at once, so a small file is not slowed down.
pacerBurst = 250 * time.Millisecond
)
// pacer spaces out bytes: each Wait says when the allowance for those bytes is used up and sleeps until then.
type pacer struct {
mu sync.Mutex
kib int
next time.Time
perByte time.Duration
}
func newPacer(kib int) *pacer {
return &pacer{kib: kib, perByte: time.Second / time.Duration(kib*1024)}
}
func (p *pacer) wait(ctx context.Context, n int, now func() time.Time, sleep func(context.Context, time.Duration) error) error {
p.mu.Lock()
t := now()
if p.next.Before(t) {
p.next = t
}
p.next = p.next.Add(time.Duration(n) * p.perByte)
delay := p.next.Sub(t) - pacerBurst
p.mu.Unlock()
if delay <= 0 {
return nil
}
return sleep(ctx, delay)
}
// Stream is a place among the streams a friend may have open. Close it when the stream ends.
type Stream struct {
s *Service
friend int64
slot bool // a place is taken, to give back on Close
pace *pacer // nil: no limit
once sync.Once
}
// Wait is called before sending n bytes: it sleeps as long as the friend's allowance asks.
func (st *Stream) Wait(ctx context.Context, n int) error {
if st.pace == nil {
return nil
}
return st.pace.wait(ctx, n, st.s.now, st.s.sleep)
}
// Close gives the place back. It may be called more than once.
func (st *Stream) Close() {
st.once.Do(func() {
if !st.slot {
return
}
st.s.mu.Lock()
defer st.s.mu.Unlock()
if st.s.streams[st.friend] > 0 {
st.s.streams[st.friend]--
}
})
}
// StartStream takes a place for a friend, or says ErrTooManyStreams. The limits are read every time, so a change
// of the admin applies to the next stream.
func (s *Service) StartStream(ctx context.Context, friendID int64) (*Stream, error) {
return s.start(ctx, friendID, true)
}
// Pace is a Stream that takes no place among the streams, only a share of the bytes: for what is small and comes
// many at a time, like covers.
func (s *Service) Pace(ctx context.Context, friendID int64) (*Stream, error) {
return s.start(ctx, friendID, false)
}
func (s *Service) start(ctx context.Context, friendID int64, slot bool) (*Stream, error) {
set, err := s.load(ctx)
if err != nil {
return nil, err
}
s.mu.Lock()
defer s.mu.Unlock()
if slot {
if s.streams[friendID] >= set.MaxStreams {
return nil, ErrTooManyStreams
}
s.streams[friendID]++
}
st := &Stream{s: s, friend: friendID, slot: slot}
if set.MaxKiBPerSec > 0 {
p := s.pacers[friendID]
if p == nil || p.kib != set.MaxKiBPerSec {
p = newPacer(set.MaxKiBPerSec)
s.pacers[friendID] = p
}
st.pace = p
}
return st, nil
}
func sleepFor(ctx context.Context, d time.Duration) error {
t := time.NewTimer(d)
defer t.Stop()
select {
case <-t.C:
return nil
case <-ctx.Done():
return ctx.Err()
}
}