relay

package
v0.5.8 Latest Latest
Warning

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

Go to latest
Published: Nov 25, 2026 License: GPL-3.0 Imports: 15 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package relay is the client for the peer relay's wire contract (session record results/wire-contract.md): create a channel, join it, put and pull envelopes, deposit and take one-time prekeys.

The relay is untrusted: every answer is size-capped and validated, and a malformed envelope in a pull comes back as a Record with Err set, so the caller can skip it and still advance its cursor.

Index

Constants

View Source
const (
	MaxPrekeysPerPut = 100

	// MaxBlob is the relay's cap on one blob, in ciphertext bytes (64 MiB).
	MaxBlob = 64 << 20
)

Contract limits.

View Source
const (
	// MaxSealed is the relay's cap on one record's decoded body bytes.
	MaxSealed = 1 << 20
	// FeedIdx is the stanza idx of a feed's link; no member holds it.
	FeedIdx = 65535
)

Room contract limits.

View Source
const (
	AddAdmins  = "admins"
	AddMembers = "members"
)

The add settings a room is created with (who may mint a member).

View Source
const (
	RoleWrite = "write"
	RoleRead  = "read"
)

The member roles.

View Source
const (

	// PingEvery is the keepalive: Cloudflare drops a socket silent for
	// about 100 s, and the relay answers each ping with a pong.
	PingEvery = 30 * time.Second
)

Push frames (wire contract § WebSocket push).

Variables

View Source
var (
	ErrBadToken         = &Error{Status: 401, Code: "bad_token"}
	ErrTokenUsed        = &Error{Status: 409, Code: "token_used"}
	ErrNoSuchChannel    = &Error{Status: 404, Code: "no_such_channel"}
	ErrTooLarge         = &Error{Status: 413, Code: "too_large"}
	ErrBadRequest       = &Error{Status: 400, Code: "bad_request"}
	ErrRateLimited      = &Error{Status: 429, Code: "rate_limited"}
	ErrMethodNotAllowed = &Error{Status: 405, Code: "method_not_allowed"}
	ErrNoSuchRoute      = &Error{Status: 404, Code: "no_such_route"}
	ErrNoSuchBlob       = &Error{Status: 404, Code: "no_such_blob"}
)

The contract's error codes.

View Source
var (
	ErrStaleMembership = &Error{Status: 409, Code: "stale_membership"}
	ErrNoSuchRoom      = &Error{Status: 404, Code: "no_such_room"}
	ErrNoSuchMember    = &Error{Status: 404, Code: "no_such_member"}
	ErrNotAdmin        = &Error{Status: 403, Code: "not_admin"}
	ErrReadOnly        = &Error{Status: 403, Code: "read_only"}
	ErrRevoked         = &Error{Status: 401, Code: "revoked"}
)

The room codes, beside v1's.

View Source
var ErrAnswer = errors.New("relay: answer breaks the contract")

ErrAnswer means the relay's answer broke the contract.

View Source
var ErrNoPush = errors.New("relay: no WebSocket push on this relay")

ErrNoPush means the relay answered the upgrade with something other than a socket or a contract refusal — a relay without push. The pull is unaffected.

Functions

func ValidBlobID

func ValidBlobID(id string) bool

ValidBlobID reports whether id has the contract's blob form (32 lowercase hex).

func ValidChannelID

func ValidChannelID(id string) bool

ValidChannelID reports whether id has the contract's form (32 lowercase hex).

func ValidIdx added in v0.2.0

func ValidIdx(k int) bool

ValidIdx reports whether k can be a member's idx (a uint16 short of FeedIdx).

func ValidRoomID added in v0.2.0

func ValidRoomID(id string) bool

ValidRoomID reports whether id has the contract's room form (32 lowercase hex).

func ValidToken

func ValidToken(t string) bool

ValidToken reports whether t has the contract's form (43-char base64url).

Types

type Blob

type Blob struct {
	ID   string `json:"blob"`
	Size int64  `json:"size"`
}

Blob is a blob put answer: the id the relay gave it and its size.

type Channel

type Channel struct {
	ID          string `json:"id"`
	HostToken   string `json:"hostToken"`
	InviteToken string `json:"inviteToken"`
}

Channel is a create answer.

type Client

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

Client speaks to one relay base, e.g. https://example.com/peer.

func New

func New(base string, hc *http.Client) *Client

New returns a client for base (the card's relay URL, ending in /peer). A nil hc uses a client with a 60 s timeout on the shared relay transport.

func (*Client) AddMember added in v0.2.0

func (c *Client) AddMember(ctx context.Context, id, token, role string) (Minted, error)

AddMember mints a member with role RoleWrite or RoleRead. token is an admin token, or under AddMembers any write token; otherwise ErrNotAdmin.

func (*Client) Create

func (c *Client) Create(ctx context.Context, login string) (Channel, error)

Create opens a channel; login is the ccc-pages owner login "<user>:<token>".

func (*Client) CreateRoom added in v0.2.0

func (c *Client) CreateRoom(ctx context.Context, login, add string) (Room, error)

CreateRoom opens a room; login is the ccc-pages owner login and add is AddAdmins or AddMembers ("" is AddAdmins). The relay keeps add.

func (*Client) FeedLanding added in v0.2.0

func (c *Client) FeedLanding(ctx context.Context, id string) (string, error)

FeedLanding fetches a feed's landing text (no token).

func (*Client) GetBlob

func (c *Client) GetBlob(ctx context.Context, id, token, blob string) ([]byte, error)

GetBlob reads a blob the other side put, whole; at most MaxBlob bytes.

func (*Client) GrantAdmin added in v0.2.0

func (c *Client) GrantAdmin(ctx context.Context, id, token string, idx int) (string, int64, error)

GrantAdmin mints an admin-flagged token for the live write idx k (an admin token's act) and returns it with the bumped membership version.

func (*Client) Join

func (c *Client) Join(ctx context.Context, id, inviteToken string) (string, error)

Join redeems the one-time invite token for this side's guest token.

func (*Client) Landing

func (c *Client) Landing(ctx context.Context, id string) (string, error)

Landing fetches the invite landing text for a channel.

func (*Client) LeaveRoom added in v0.2.0

func (c *Client) LeaveRoom(ctx context.Context, id, token string) (int64, error)

LeaveRoom revokes the caller's own idx — a read member's leave.

func (*Client) ListMembers added in v0.2.0

func (c *Client) ListMembers(ctx context.Context, id, token string) (Members, error)

ListMembers reads the room's members (an admin token's act) — how an admin's host sees a reader gone.

func (*Client) Pull

func (c *Client) Pull(ctx context.Context, id, token string, after int64) ([]Record, error)

Pull returns one page of the other side's envelopes with seq > after (after -1 for everything), ascending. An empty page means caught up.

func (*Client) PullAll

func (c *Client) PullAll(ctx context.Context, id, token string, after int64) ([]Record, error)

PullAll pulls page after page from after until the relay answers [].

func (*Client) PullRoom added in v0.2.0

func (c *Client) PullRoom(ctx context.Context, id, token string, after int64) (RoomPage, error)

PullRoom returns one page of the other members' records with seq > after (after -1 for everything the caller may read), ascending. The relay floors the page at the caller's from. An empty page means caught up.

func (*Client) PullRoomAll added in v0.2.0

func (c *Client) PullRoomAll(ctx context.Context, id, token string, after int64) (RoomPage, error)

PullRoomAll pulls page after page from after until the relay answers none; the membership is the last page's.

func (*Client) Put

func (c *Client) Put(ctx context.Context, id, token string, e envelope.Envelope) (Receipt, error)

Put stores one envelope on the caller's side. The envelope is checked first; one over 1 MiB never leaves the host.

func (*Client) PutBlob

func (c *Client) PutBlob(ctx context.Context, id, token string, data []byte) (Blob, error)

PutBlob stores data — an attachment's ciphertext, raw bytes — on the channel for the other side to get. One over MaxBlob never leaves the host.

func (*Client) PutPrekeys

func (c *Client) PutPrekeys(ctx context.Context, id, token string, keys []Prekey) (int, error)

PutPrekeys appends keys to the caller's side and returns how many that side now holds. A repeated id is ignored by the relay, so a retry is safe.

func (*Client) PutRecord added in v0.2.0

func (c *Client) PutRecord(ctx context.Context, id, token string, sealed []byte, membership int64, bump bool) (RoomReceipt, error)

PutRecord stores one sealed record, put at the membership version the sender sealed it under: below the relay's current one it is refused with ErrStaleMembership before anything is stored. bump (admin tokens only) appends the record and bumps the version in one transaction — the removal record travels so. A body over MaxSealed never leaves the host.

func (*Client) RemoveMember added in v0.2.0

func (c *Client) RemoveMember(ctx context.Context, id, token string, idx int) (int64, error)

RemoveMember revokes every token on idx (an admin token's act); the relay closes that idx's sockets with 4401. It returns the bumped membership version.

func (*Client) Resume added in v0.5.4

func (c *Client) Resume(ctx context.Context, id, token string, after int64) (*Socket, error)

Resume opens the push socket as Subscribe does, asking the relay to send first every envelope after seq after (-1 for all), one pull page, then a Synced record (Socket.Resumed says whether it will).

func (*Client) RoomState added in v0.4.0

func (c *Client) RoomState(ctx context.Context, id, token string, after int64) (RoomState, error)

RoomState reads the room's state and one page of the caller's view of the log with seq > after (after -1 for all of it), ascending; an empty page means the end. A relay without the route answers no_such_route.

func (*Client) RoomStateAll added in v0.4.0

func (c *Client) RoomStateAll(ctx context.Context, id, token string) (RoomState, error)

RoomStateAll reads the state page after page until the relay answers no record: the records of every page, and the state of the last.

func (*Client) Subscribe

func (c *Client) Subscribe(ctx context.Context, id, token string) (*Socket, error)

Subscribe opens the push socket on channel id with this side's token. A refusal before the upgrade is an *Error (bad_token, no_such_channel, rate_limited, too_many_sockets); an answer that is not an upgrade is ErrNoPush.

func (*Client) SubscribeRoom added in v0.2.0

func (c *Client) SubscribeRoom(ctx context.Context, id, token string) (*RoomSocket, error)

SubscribeRoom opens the push socket on room id with a member token. A refusal before the upgrade is an *Error (revoked, bad_token, no_such_room, rate_limited, too_many_sockets); an answer that is not an upgrade is ErrNoPush.

func (*Client) TakePrekey

func (c *Client) TakePrekey(ctx context.Context, id, token string) (k Prekey, ok bool, err error)

TakePrekey takes the other side's oldest one-time prekey; ok is false when that side holds none.

type Error

type Error struct {
	Status  int
	Code    string
	Message string
}

Error is a relay error answer {error, code}.

func (*Error) Error

func (e *Error) Error() string

func (*Error) Is

func (e *Error) Is(target error) bool

Is matches on Code, so errors.Is(err, relay.ErrBadToken) works.

type Member added in v0.2.0

type Member struct {
	Idx     int    `json:"idx"`
	Role    string `json:"role"`
	From    int64  `json:"from"`
	Admin   bool   `json:"admin"`
	Revoked bool   `json:"revoked"`
}

Member is one row of a members answer.

type Members added in v0.2.0

type Members struct {
	Membership int64
	Members    []Member
}

Members is a members answer.

type Minted added in v0.2.0

type Minted struct {
	Idx        int
	Token      string
	From       int64
	Membership int64
}

Minted is a member mint answer: the new idx, its token, its from (the log head: it reads no record below it) and the bumped membership version.

type Prekey

type Prekey struct {
	ID  uint32 `json:"id"`
	Pub []byte `json:"pub"`
}

Prekey is a one-time prekey: its id and serialized public key (0x05 || 32 bytes); JSON carries pub as standard base64.

type Receipt

type Receipt struct {
	Dir string `json:"dir"`
	Seq int64  `json:"seq"`
}

Receipt is a put answer: the direction the token names and its sequence.

type Record

type Record struct {
	Seq int64
	At  time.Time
	Env envelope.Envelope
	Err error
	// Synced marks a resumed push socket's end of catch-up (Socket.Next): no
	// envelope, Seq the last row the catch-up carried (the cursor it resumed
	// from when none), More when a pull page remains. Never set on a pull.
	Synced, More bool
}

Record is one pulled envelope. Err is set when the relay's bytes for this seq are malformed; Env is then zero and the seq still counts.

type Room added in v0.2.0

type Room struct {
	ID         string `json:"id"`
	AdminToken string `json:"adminToken"`
	Membership int64  `json:"membership"`
}

Room is a create answer: the room, the creator's admin-flagged token (idx 0, role write, from 0) and the membership version.

type RoomInfo added in v0.4.0

type RoomInfo struct {
	Created    int64  `json:"created"`
	Add        string `json:"add"`
	Membership int64  `json:"membership"`
	Next       int64  `json:"next"`
	Retention  int64  `json:"retention"`
	Alarm      *int64 `json:"alarm"` // nil: no retention alarm armed
}

RoomInfo is the room's own row on the relay. Times are the relay's epoch milliseconds; Next is the seq the next record takes.

type RoomLog added in v0.4.0

type RoomLog struct {
	Count  int64  `json:"count"`
	First  *int64 `json:"first"`
	Oldest *int64 `json:"oldest"`
}

RoomLog is what the caller's view (seq >= From) holds: First is its lowest seq and Oldest its earliest put, both nil when it holds none.

type RoomPage added in v0.2.0

type RoomPage struct {
	Membership int64
	Records    []RoomRecord
}

RoomPage is a pull answer: the relay's membership version and the records, ascending.

type RoomReceipt added in v0.2.0

type RoomReceipt struct {
	Seq        int64
	Membership int64
}

RoomReceipt is a record put answer.

type RoomRecord added in v0.2.0

type RoomRecord struct {
	Seq  int64
	Idx  int
	At   time.Time
	Body []byte
	Err  error
}

RoomRecord is one pulled or pushed room record: the relay's seq, the writer's idx, when the relay stored it and the sealed bytes. Err is set when the relay's bytes for this seq are malformed; Body is then nil and the seq still counts.

type RoomSeat added in v0.4.0

type RoomSeat struct {
	Idx     int    `json:"idx"`
	Role    string `json:"role"`
	From    int64  `json:"from"`
	Admin   bool   `json:"admin"`
	Sockets int    `json:"sockets"`
}

RoomSeat is the caller's member as the relay holds it; Admin is the token's flag, Sockets the push sockets open on the idx.

type RoomSocket added in v0.2.0

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

RoomSocket is one member's WebSocket on a room's records route: every record another idx puts while it is open arrives as a frame. It pings every PingEvery until it is closed.

func (*RoomSocket) Close added in v0.2.0

func (r *RoomSocket) Close() error

Close closes the socket from this side, without waiting on the relay.

func (*RoomSocket) Next added in v0.2.0

func (r *RoomSocket) Next(ctx context.Context) (RoomRecord, error)

Next returns the next pushed record, validated as a pulled one is. A close the relay sends for good — 4401 when the idx is revoked, 4404 — is ErrRevoked or ErrNoSuchRoom; any other close or failure is returned as it is and the caller reconnects. A frame without a seq is ErrAnswer.

type RoomState added in v0.4.0

type RoomState struct {
	Room    RoomInfo     `json:"room"`
	You     RoomSeat     `json:"you"`
	Log     RoomLog      `json:"log"`
	Records []RoomRecord `json:"-"`
}

RoomState is a state answer: the room as the relay holds it, the caller's seat, what the caller's view of the log holds, and one page of that log — every member's records, the caller's own included.

type Socket

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

Socket is one side's WebSocket on a channel's envelopes route: every envelope the other side puts while it is open arrives as a frame. It pings every PingEvery until it is closed.

func (*Socket) Close

func (s *Socket) Close() error

Close closes the socket from this side, without waiting on the relay.

func (*Socket) Next

func (s *Socket) Next(ctx context.Context) (Record, error)

Next returns the next pushed envelope, validated as a pulled row is: a malformed envelope comes back with Err set and its seq. The relay's pong is skipped. A close the relay sends for good — 4401, 4404 — is ErrBadToken or ErrNoSuchChannel; any other close or failure, or a socket that carried nothing for three pings, is returned as it is and the caller reconnects. A resumed socket's `synced` frame is a Record with Synced set, Seq the last catch-up row and More when a pull page remains. A frame without a seq breaks the contract (ErrAnswer): nothing in it can be placed.

func (*Socket) Resumed added in v0.5.4

func (s *Socket) Resumed() bool

Resumed reports whether the socket carries the catch-up from the cursor it was opened at, ended by a Synced record. False on a socket opened without one and on a relay from before resume: its client pulls the catch-up.

Directories

Path Synopsis
Package relaytest is an in-memory relay serving results/wire-contract.md for tests of the CLI: two parties on one httptest server.
Package relaytest is an in-memory relay serving results/wire-contract.md for tests of the CLI: two parties on one httptest server.

Jump to

Keyboard shortcuts

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