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
- Variables
- func BestOffset(samples []Sample) (offset, rtt float64, ok bool)
- func ClockOffset(t0, t1, t2, t3 float64) (offset, rtt float64)
- func NormalCode(s string) string
- type Command
- type Config
- type Engine
- func (e *Engine) Close(roomID, memberID string, userID int64, admin bool) error
- func (e *Engine) Config() Config
- func (e *Engine) Create(by User, o Options) (View, error)
- func (e *Engine) Do(roomID, memberID string, userID int64, c Command) (View, error)
- func (e *Engine) DropSeats(match func(User) bool) int
- func (e *Engine) Invite(roomID, memberID string, userID int64, users []int64) error
- func (e *Engine) Join(by User, key string) (View, error)
- func (e *Engine) Kick(roomID, memberID string, userID int64, whom string) error
- func (e *Engine) Leave(roomID, memberID string, userID int64) error
- func (e *Engine) Listen(roomID, memberID string, userID int64) (<-chan struct{}, error)
- func (e *Engine) Ping(roomID, memberID string, userID int64, rttMs float64) error
- func (e *Engine) Recheck(userID int64)
- func (e *Engine) Report(roomID, memberID string, userID int64, what string, rev uint64) error
- func (e *Engine) Rooms() int
- func (e *Engine) RoomsFor(by User) []Listing
- func (e *Engine) Seated() []int64
- func (e *Engine) Set(roomID, memberID string, userID int64, s Settings) error
- func (e *Engine) SetTimeUp(userID int64, up bool)
- func (e *Engine) Tick()
- func (e *Engine) Transfer(roomID, memberID string, userID int64, to string) error
- func (e *Engine) Uninvite(userID int64)
- func (e *Engine) Unlisten(roomID, memberID string, ch <-chan struct{})
- func (e *Engine) View(roomID, memberID string, userID int64) (View, error)
- type Listing
- type MemberView
- type Options
- type Sample
- type Settings
- type State
- type Step
- type User
- type View
Constants ¶
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.
const ( PolicyHost = "host" PolicyEveryone = "everyone" )
Who may play, pause and seek.
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.
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.
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.
const CodeLen = 6
CodeLen is how long a room's code is: 31^6 is about 900 million, and tries are counted.
Variables ¶
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 ¶
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 ¶
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 ¶
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.
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 (*Engine) Close ¶
Close ends a room for everyone. The host may; so may an administrator, who passes admin and needs no seat.
func (*Engine) Create ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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) Listen ¶
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 ¶
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 ¶
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 ¶
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) Seated ¶
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) SetTimeUp ¶
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) Uninvite ¶
Uninvite takes back every invitation an account has: it was deleted, or may no longer use watch parties.
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 Settings ¶
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 ¶
PositionAt is where a player should be at a server time, in milliseconds.
type Step ¶
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).
type User ¶
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.