syncplay

package
v0.8.0-alpha Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 16, 2026 License: AGPL-3.0 Imports: 10 Imported by: 0

Documentation

Overview

Package syncplay is watch parties: people in different places watching the same thing at the same moment. A room holds one authoritative state ("item 12 was at 61.5 seconds at server time T, playing at normal speed"), and every member's player works out from that where it should be now. Nobody's player is the leader, so nobody's bad connection drags the others about.

The engine is plain data behind one lock. It doesn't know about HTTP or the library and never reads the real clock: the server hands it a clock, a way to ask whether an account may see an item, and calls Tick about once a second while rooms exist. That is what makes every rule here something a test can walk through second by second. docs/SYNCPLAY.md describes it for people writing clients.

Index

Constants

View Source
const (
	DriftStill   = 0.12 // closer than this: leave it alone
	DriftSettled = 0.04 // once nudging, carry on until this close
	DriftSeek    = 3.0  // this far off, or more: jump
	DriftRate    = 0.03 // play this much faster or slower to catch up or fall back
)

Drift thresholds, in seconds, and the rate change used to close a small gap. They are the ones the web player already keeps a live channel in step with, and every client is told them by GET /api/v1/syncplay, so none has to copy the numbers.

View Source
const (
	PolicyHost     = "host"
	PolicyEveryone = "everyone"
)

Who may play, pause and seek.

View Source
const (
	CmdPlay     = "play"
	CmdPause    = "pause"
	CmdSeek     = "seek"
	CmdNext     = "next"
	CmdPrevious = "previous"
	CmdSelect   = "select" // a place in the queue
	CmdRate     = "rate"
	CmdQueue    = "queue" // a new queue
)

Commands.

View Source
const (
	ReportReady     = "ready"     // loaded at the room's position, able to play
	ReportBuffering = "buffering" // stalled, or still loading
)

What a member's player says about itself.

View Source
const (
	MemberReady     = "ready"
	MemberLoading   = "loading"   // hasn't said it's ready since the last change
	MemberBuffering = "buffering" // said it stalled
	MemberLagging   = "lagging"   // the room stopped waiting for it
	MemberAway      = "away"      // not heard from lately; its seat is kept for a while
	MemberBlocked   = "blocked"   // may not see what's playing
	MemberTimeUp    = "time-up"   // its account's screen time is over for now
)

How a member appears to the others.

View Source
const CodeLen = 6

CodeLen is how long a room's code is: 31^6 is about 900 million, and tries are counted.

Variables

View Source
var (
	ErrNoRoom      = errors.New("no such watch party")
	ErrNotMember   = errors.New("you're not in that watch party")
	ErrNotHost     = errors.New("only the host can do that")
	ErrNotAllowed  = errors.New("only the host controls this watch party")
	ErrCantSee     = errors.New("this watch party is playing something this account can't watch")
	ErrFull        = errors.New("that watch party is full")
	ErrTooMany     = errors.New("too many watch parties are open already")
	ErrBadQueue    = errors.New("a watch party needs between one and the allowed number of things to watch")
	ErrEndOfQueue  = errors.New("there's nothing more in the queue that way")
	ErrBadCommand  = errors.New("that isn't a command a watch party knows")
	ErrBadValue    = errors.New("that value doesn't make sense")
	ErrStale       = errors.New("someone else changed the watch party first")
	ErrNoMember    = errors.New("no such member")
	ErrTooManyInvs = errors.New("too many people are invited already")
	ErrTimeUp      = errors.New("this profile's screen time is over")
)

Functions

func BestOffset

func BestOffset(samples []Sample) (offset, rtt float64, ok bool)

BestOffset picks, from several pings, the offset of the one with the shortest round trip: it was held up least on the way, so its two halves are most nearly equal, which is what the sum assumes. A ping that came back before it left (a clock that jumped) is ignored. ok is false with nothing usable.

func ClockOffset

func ClockOffset(t0, t1, t2, t3 float64) (offset, rtt float64)

ClockOffset is NTP's sum for one ping. t0: the client's clock when it sent; t1: the server's when that arrived; t2: the server's when it answered; t3: the client's when the answer arrived. All in milliseconds. offset is how far the server's clock is ahead of the client's, and rtt the time spent on the wire there and back.

func NormalCode

func NormalCode(s string) string

NormalCode is a code as people type it, made comparable: case, spaces and dashes don't matter.

Types

type Command

type Command struct {
	Type        string
	PositionSec float64 // seek
	Index       int     // select; and queue: where in the new queue to start
	Rate        float64 // rate
	Items       []int64 // queue
	// IfSeq, when not nil, refuses the command unless the room is still at that seq: the
	// way two people pressing "next" at the end of an episode skip one episode, not two.
	IfSeq *uint64
}

Command is play, pause, seek and the rest.

type Config

type Config struct {
	// Now is the clock. Nil: the real one.
	Now func() time.Time
	// CanSee says whether an account may see an item: its library and rating limits, asked
	// fresh each time. Nil: everyone sees everything (tests).
	CanSee func(userID, itemID int64) bool
	// NewID and NewCode make room and member ids, and the short codes people type.
	NewID   func() string
	NewCode func() string

	MaxRooms        int
	MaxRoomsPerUser int // rooms one account may host at once
	MaxMembers      int // in one room
	MaxQueue        int
	MaxInvites      int

	// MinLead and MaxLead bound how far in the future a start is set, so that the news of
	// it reaches everyone first. Between them it follows the slowest member's round trip.
	MinLead, MaxLead time.Duration
	// WaitTimeout: how long the room waits for members who are still loading before
	// going on without them. WaitCooldown: how long a member the room stopped waiting for
	// can't make it wait again.
	WaitTimeout, WaitCooldown time.Duration
	// Log receives what happens to rooms, each record with the session "party-"+room id.
	// Nil: nothing is logged. Room codes and member ids are never logged: a member id is
	// a seat, and a code lets anyone in.
	Log *slog.Logger

	// AwayAfter: a member not heard from for this long doesn't hold the room up.
	// SeatGrace: after this long their seat is given up. EmptyClose: a room with nobody in
	// it closes after this. MaxAge: and any room after this.
	AwayAfter, SeatGrace, EmptyClose, MaxAge time.Duration
}

Config is the engine's rules and its view of the world outside.

func DefaultConfig

func DefaultConfig() Config

DefaultConfig suits a home server.

type Engine

type Engine struct {
	// contains filtered or unexported fields
}

Engine holds the rooms. They live in memory only: a restart ends every watch party, which is right for something that lasts an evening and whose members' players would all have lost the server anyway.

func New

func New(cfg Config) *Engine

New makes an engine. Missing parts of cfg take DefaultConfig's.

func (*Engine) Close

func (e *Engine) Close(roomID, memberID string, userID int64, admin bool) error

Close ends a room for everyone. The host may; so may an administrator, who passes admin and needs no seat.

func (*Engine) Config

func (e *Engine) Config() Config

Config is the rules in force.

func (*Engine) Create

func (e *Engine) Create(by User, o Options) (View, error)

Create opens a room with its maker as host. The room starts paused at the start (or where Options says), so the host can wait for people before pressing play. The maker must be able to see everything in the queue: a queue is theirs to choose, and choosing what they can't see would be a way to learn it exists.

func (*Engine) Do

func (e *Engine) Do(roomID, memberID string, userID int64, c Command) (View, error)

Do applies a command to the room. Commands are taken one at a time, in the order they reach the server; that order is the truth, whatever order they were pressed in. A command that would change nothing (play while playing) is accepted and changes nothing.

func (*Engine) DropSeats

func (e *Engine) DropSeats(match func(User) bool) int

DropSeats takes away every seat that match says to: a sign-in that ended, an account that was deleted or may no longer use watch parties. It says how many went.

func (*Engine) Invite

func (e *Engine) Invite(roomID, memberID string, userID int64, users []int64) error

Invite lets accounts join by the room's id, from their own list of invitations, with no code to type. It doesn't let them see anything: joining still asks.

func (*Engine) Join

func (e *Engine) Join(by User, key string) (View, error)

Join seats someone. key is the room's code, or its id for someone invited or coming back to their seat. A person who may not see what is playing is refused, and told only that: not what it is.

Coming back from the same sign-in within the grace period is the same seat, host's included. A late joiner doesn't hold a playing room up: it gets the state and catches up, and counts towards "wait for everyone" once it has said it's ready.

func (*Engine) Kick

func (e *Engine) Kick(roomID, memberID string, userID int64, whom string) error

Kick takes another member's seat away. They can come back with the code; a host who minds closes the room and opens another.

func (*Engine) Leave

func (e *Engine) Leave(roomID, memberID string, userID int64) error

Leave gives a seat up.

func (*Engine) Listen

func (e *Engine) Listen(roomID, memberID string, userID int64) (<-chan struct{}, error)

Listen is a member's stream opening. The channel says "look again" and closes when the seat or the room is gone; View then says which. One seat has one stream: a second one closes the first.

func (*Engine) Ping

func (e *Engine) Ping(roomID, memberID string, userID int64, rttMs float64) error

Ping is a member's heartbeat, with the round trip its last ping measured (in ms; 0 or less when it hasn't one yet). The caller answers with the server's time; see ClockOffset.

func (*Engine) Recheck

func (e *Engine) Recheck(userID int64)

Recheck asks again what an account may see, in every room it has a seat in: after its limits changed. A member who may no longer see what is playing is blocked at once, like one who never could.

func (*Engine) Report

func (e *Engine) Report(roomID, memberID string, userID int64, what string, rev uint64) error

Report is a member's player saying how it is doing. rev is the room's rev it has caught up with: "ready" for anything older than the last seek or change of item is about a place the room has since left, and is ignored.

func (*Engine) Rooms

func (e *Engine) Rooms() int

Rooms is how many are open.

func (*Engine) RoomsFor

func (e *Engine) RoomsFor(by User) []Listing

RoomsFor lists an account's rooms and invitations.

func (*Engine) Seated

func (e *Engine) Seated() []int64

Seated is every account with a seat in some room, once each. The server asks it so as to look at those accounts' screen time and switches, and nobody else's.

func (*Engine) Set

func (e *Engine) Set(roomID, memberID string, userID int64, s Settings) error

Set changes a room's settings.

func (*Engine) SetTimeUp

func (e *Engine) SetTimeUp(userID int64, up bool)

SetTimeUp says whether an account's screen time is over. While it is, its seats sit out: the room doesn't wait for them, they can't steer it, and they aren't told what it plays. They keep their seats, so that more time from a parent puts them straight back.

func (*Engine) Tick

func (e *Engine) Tick()

Tick moves time on: it stops waiting for members who have taken too long, notices who has gone quiet, gives up seats nobody came back to, hands on a room whose host left, and closes rooms that are empty or too old. The server calls it about once a second while there are rooms.

func (*Engine) Transfer

func (e *Engine) Transfer(roomID, memberID string, userID int64, to string) error

Transfer makes another member the host.

func (*Engine) Uninvite

func (e *Engine) Uninvite(userID int64)

Uninvite takes back every invitation an account has: it was deleted, or may no longer use watch parties.

func (*Engine) Unlisten

func (e *Engine) Unlisten(roomID, memberID string, ch <-chan struct{})

Unlisten is that stream closing. The member is "away" at once, so the room doesn't wait for someone who has gone, but keeps the seat for SeatGrace.

func (*Engine) View

func (e *Engine) View(roomID, memberID string, userID int64) (View, error)

View is the room as a member sees it now.

type Listing

type Listing struct {
	ID       string `json:"id"`
	Name     string `json:"name"`
	HostName string `json:"hostName"`
	Members  int    `json:"members"`
	// MemberID is their seat, when they have one from this sign-in.
	MemberID string `json:"memberId,omitempty"`
	Invited  bool   `json:"invited,omitempty"`
}

Listing is a room in someone's list: one they sit in, or are invited to. It names the room and its host, never what is playing.

type MemberView

type MemberView struct {
	ID     string `json:"id"`
	UserID int64  `json:"userId"`
	Name   string `json:"name"`
	Host   bool   `json:"host"`
	You    bool   `json:"you,omitempty"`
	State  string `json:"state"`
	// RTTMs: their round trip to the server, as their last ping measured it.
	RTTMs int `json:"rttMs"`
}

MemberView is one person in the room.

type Options

type Options struct {
	Name        string
	Items       []int64
	Index       int
	Policy      string
	WaitForAll  *bool // nil: yes
	PositionSec float64
}

Options are what a room is made with. Items is the queue; the first plays first.

type Sample

type Sample struct{ T0, T1, T2, T3 float64 }

Sample is one ping's four times.

type Settings

type Settings struct {
	Name       *string
	Policy     *string
	WaitForAll *bool
}

Settings are what the host may change about a running room. Nil leaves a thing alone.

type State

type State struct {
	// Rev goes up with every change. Seq goes up with every command; send it back as ifSeq
	// to have a command refused when someone else got in first.
	Rev uint64 `json:"rev"`
	Seq uint64 `json:"seq"`
	// ItemID is what's playing: 0 for a member who may not see it.
	ItemID int64 `json:"itemId"`
	Index  int   `json:"index"`
	// PositionSec was (or will be) the position at AtMs, in server milliseconds.
	PositionSec float64 `json:"positionSec"`
	AtMs        int64   `json:"atMs"`
	Paused      bool    `json:"paused"`
	// Waiting: the room wants to play, and is holding for members who are still loading.
	Waiting bool    `json:"waiting"`
	Rate    float64 `json:"rate"`
}

State is the room's state as sent to clients. Everything a player needs to know where to be is here: see PositionAt.

func (State) PositionAt

func (s State) PositionAt(serverMs int64) float64

PositionAt is where a player should be at a server time, in milliseconds.

type Step

type Step struct {
	Rate   float64
	SeekBy float64
}

Step is what a player should do about being out of step: play at Rate, or jump by SeekBy seconds (and then play at 1).

func Correct

func Correct(behind float64, nudging bool) Step

Correct is the drift rule. behind: seconds this player is behind where the room is (negative: ahead). nudging: whether it is already playing faster or slower, which carries on until it's settled rather than stopping the moment it is merely close.

type User

type User struct {
	ID   int64
	Name string
	Seat string
}

User is who is acting: an account, and the device it is on. Seat is what makes a seat theirs when they come back: the same account from the same sign-in gets the same seat.

type View

type View struct {
	ID         string `json:"id"`
	Code       string `json:"code"`
	Name       string `json:"name"`
	Policy     string `json:"policy"`
	WaitForAll bool   `json:"waitForAll"`
	HostID     string `json:"hostId"`
	You        string `json:"you"`
	CanControl bool   `json:"canControl"`
	Blocked    bool   `json:"blocked"` // you may not see what's playing now
	// TimeUp: your screen time is over. The room goes on without you, and you are told
	// nothing more of what it plays until you have time again.
	TimeUp  bool         `json:"timeUp,omitempty"`
	Members []MemberView `json:"members"`
	// Queue holds item ids, with 0 where this member may not see the item.
	Queue        []int64 `json:"queue"`
	State        State   `json:"state"`
	ServerTimeMs int64   `json:"serverTimeMs"`
	LeadMs       int64   `json:"leadMs"`
}

View is a room as one member sees it. What they may not see isn't in it.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL