Documentation
¶
Overview ¶
Package protocol declares the wire-format types for pyrycode's mobile WebSocket protocol v1. The package is pure data: no I/O, no socket handling, no context plumbing. Consumers (internal/relay-client, internal/dispatch, future cmd/pyry-relay) marshal/unmarshal these types against the wire and dispatch on Envelope.Type.
The single source of truth for field names, optionality, and wire semantics is docs/protocol-mobile.md. When that document changes, this package changes; the test fixtures under testdata/ pin the round-trip shape.
Index ¶
- Constants
- Variables
- func IsV1Compatible(env Envelope) error
- type AckPayload
- type BackfillDonePayload
- type BackfillSincePayload
- type ConversationCreatedPayload
- type ConversationSummary
- type ConversationUpdatedPayload
- type ConversationsPayload
- type CreateConversationPayload
- type Envelope
- type ErrorPayload
- type HelloAckPayload
- type HelloClientPayload
- type HelloServerPayload
- type InnerFrameV2
- type ListConversationsPayload
- type MessageChunkPayload
- type MessagePayload
- type PromoteConversationPayload
- type RegisterPushTokenPayload
- type RoutingEnvelope
- type SendMessagePayload
Constants ¶
const ( // Protocol errors. CodeProtocolUnknownType = "protocol.unknown_type" CodeProtocolMalformed = "protocol.malformed" CodeProtocolUnsupported = "protocol.unsupported" // Auth errors. CodeAuthInvalidToken = "auth.invalid_token" CodeAuthTokenRevoked = "auth.token_revoked" // Server errors. CodeServerBinaryOffline = "server.binary_offline" CodeServerBinaryBusy = "server.binary_busy" // Conversation errors. CodeConversationNotFound = "conversation.not_found" CodeConversationAlreadyPromoted = "conversation.already_promoted" // Message errors. CodeMessageTooLong = "message.too_long" // Relay errors. CodeRelayNoServer = "relay.no_server" CodeRelayServerIDConflict = "relay.server_id_conflict" )
Error-code constants — wire values for the "code" field of error payloads (docs/protocol-mobile.md § Error codes). The naming convention is Code<Category><Reason>, matching the dotted-string structure category.reason. Grouped by category in spec-table order.
const ( // Handshake and control. TypeHello = "hello" TypeHelloAck = "hello_ack" TypeError = "error" TypeAck = "ack" // Messaging. TypeSendMessage = "send_message" TypeMessage = "message" // Conversations. TypeListConversations = "list_conversations" TypeConversations = "conversations" TypeCreateConversation = "create_conversation" TypeConversationCreated = "conversation_created" TypePromoteConversation = "promote_conversation" TypeConversationUpdated = "conversation_updated" // Backfill. TypeBackfillSince = "backfill_since" TypeMessageChunk = "message_chunk" TypeBackfillDone = "backfill_done" // Push. TypeRegisterPushToken = "register_push_token" )
Envelope-type constants — wire values for Envelope.Type (docs/protocol-mobile.md § Message types). The set is closed in v1; new types require a v2 envelope per the protocol's versioning policy.
const ( TypeNoiseInit = "noise_init" TypeNoiseResp = "noise_resp" TypeNoiseMsg = "noise_msg" )
Inner-frame discriminator values for InnerFrameV2.Type (docs/protocol-mobile.md § Wire shapes table).
const ( // TypeRekeyRequest is the Mobile Protocol v2 control envelope either // side may emit to nudge the peer toward initiating a re-key // handshake (docs/protocol-mobile.md § Re-key). It is informational // from the binary's perspective: the binary is the IK responder per // ADR 024, so an inbound rekey_request takes no transport action. // // MUST NOT be added to v1TypeSet in internal/protocol/envelope.go: a // leak into that set would route the envelope to dispatch.Route's // handler chain, violating the v2 control / v1 application boundary // enforced by internal/relay's v2 session manager. The drift detector // in internal/protocol/compat_test.go partitions Type* constants // between v1TypeSet and v2OnlyTypes; this constant lives in the // latter. TypeRekeyRequest = "rekey_request" )
Mobile Protocol v2 control-envelope types. These are NOT v1 application types; they MUST NOT appear in v1TypeSet (internal/protocol/envelope.go). The v2 session manager intercepts them at the dispatch boundary (internal/relay/v2session.go's dispatchAppFrame) before internal/dispatch.Route is called, so handler-table lookup never sees them.
const V2Version = 2
V2Version is the major version number carried in InnerFrameV2.Version. Receivers MUST reject mismatched values with WS close 4421 (protocol mismatch).
Variables ¶
var ( ErrUnknownType = errors.New("protocol: unknown envelope type") ErrUnsupported = errors.New("protocol: unsupported envelope feature") )
Sentinel errors returned by IsV1Compatible. Callers (the future WS dispatch layer) distinguish refusal cases via errors.Is and map each sentinel to its dotted-string wire code at the call site:
ErrUnknownType -> CodeProtocolUnknownType ErrUnsupported -> CodeProtocolUnsupported
Functions ¶
func IsV1Compatible ¶
IsV1Compatible reports whether env is acceptable under wire-protocol v1. Returns nil when env.Type is in the v1 type set and env.PayloadEncrypted is false. Returns ErrUnsupported when env.PayloadEncrypted is true (reserved for v2; docs/protocol-mobile.md § Reserved for v2). Returns ErrUnknownType when env.Type is empty or not in the v1 set.
Check order: PayloadEncrypted first, Type second. A frame failing both checks reports as ErrUnsupported — the stricter rejection wins.
IsV1Compatible does not validate Payload contents, ID monotonicity, or TS skew; those are dispatcher concerns.
Types ¶
type AckPayload ¶
type AckPayload struct{}
AckPayload is the body of a generic "ack" envelope; empty by spec (docs/protocol-mobile.md § Message types).
type BackfillDonePayload ¶
type BackfillDonePayload struct {
Delivered int `json:"delivered"`
}
BackfillDonePayload is the body of an Envelope whose Type == TypeBackfillDone (docs/protocol-mobile.md § backfill_done). Binary → phone direction; sent after the last message_chunk to mark completion.
type BackfillSincePayload ¶
type BackfillSincePayload struct {
SinceTS time.Time `json:"since_ts"`
ConversationID *string `json:"conversation_id"` // *string + no omitempty: spec wire shows literal `null` (meaning "all conversations"); omitempty would drop the key.
MaxMessages int `json:"max_messages"`
}
BackfillSincePayload is the body of an Envelope whose Type == TypeBackfillSince (docs/protocol-mobile.md § backfill_since). Phone → binary direction. SinceTS is RFC3339Nano per the envelope timestamp rule; MaxMessages is the phone's advisory cap on returned-message count.
type ConversationCreatedPayload ¶
type ConversationCreatedPayload struct {
ID string `json:"id"`
IsPromoted bool `json:"is_promoted"`
Cwd string `json:"cwd"`
Name *string `json:"name"`
LastUsedAt time.Time `json:"last_used_at"`
}
ConversationCreatedPayload is the body of a conversation_created frame (docs/protocol-mobile.md § conversation_created). Binary → phone, sent in reply to a create_conversation. ID, IsPromoted, Cwd, LastUsedAt are spec-required and non-nilable. Name is a pointer because the spec example shows "name": null (an unnamed scratch conversation); see the rationale on CreateConversationPayload for why omitempty is omitted.
type ConversationSummary ¶
type ConversationSummary struct {
ID string `json:"id"`
Name *string `json:"name"`
IsPromoted bool `json:"is_promoted"`
Cwd string `json:"cwd"`
LastMessageTS time.Time `json:"last_message_ts"`
LastUsedAt time.Time `json:"last_used_at"`
}
ConversationSummary is one row of a ConversationsPayload (docs/protocol-mobile.md § conversations). Name is a pointer because the spec admits null on the wire (an unnamed scratch conversation), and is intentionally not tagged json:",omitempty": the spec example shows "name": null explicitly, and omitempty on a nil pointer would drop the key entirely, breaking byte-equivalent round-trip.
type ConversationUpdatedPayload ¶
type ConversationUpdatedPayload struct {
ID string `json:"id"`
IsPromoted bool `json:"is_promoted"`
Name *string `json:"name"`
Cwd string `json:"cwd"`
LastUsedAt time.Time `json:"last_used_at"`
}
ConversationUpdatedPayload is the body of a conversation_updated frame (docs/protocol-mobile.md § conversation_updated). Binary → phone, broadcast to all phones on this server-id. ID, IsPromoted, Cwd, LastUsedAt are required. Name is spec-optional (a previously unnamed conversation can be updated without acquiring a name) and is a pointer for the same round-trip reason given on CreateConversationPayload.
type ConversationsPayload ¶
type ConversationsPayload struct {
Conversations []ConversationSummary `json:"conversations"`
}
ConversationsPayload is the body of a conversations frame (docs/protocol-mobile.md § conversations). Binary → phone, sent in reply to a list_conversations request. Order of the Conversations slice is preserved from the wire — the binary is the source of truth for ordering (e.g. most-recently-used first); this type does not reorder.
type CreateConversationPayload ¶
type CreateConversationPayload struct {
IsPromoted *bool `json:"is_promoted"`
Name *string `json:"name"`
Cwd *string `json:"cwd"`
}
CreateConversationPayload is the body of a create_conversation frame (docs/protocol-mobile.md § create_conversation). Phone → binary. All three fields are spec-optional — the binary fills server-side defaults when null is on the wire.
Fields are pointers without omitempty so a nil value round-trips as JSON null (matching the spec example's "name": null / "cwd": null) and a pointer-to-zero round-trips as the zero scalar (matching the spec example's "is_promoted": false). omitempty on a nil pointer would drop the key entirely, breaking byte-equivalent round-trip.
type Envelope ¶
type Envelope struct {
ID uint64 `json:"id"`
Type string `json:"type"`
TS time.Time `json:"ts"`
Payload json.RawMessage `json:"payload"`
InReplyTo *uint64 `json:"in_reply_to,omitempty"`
PayloadEncrypted bool `json:"payload_encrypted,omitempty"`
}
Envelope is the outer wire shape every application frame conforms to (docs/protocol-mobile.md § Message envelope). The Payload field carries the per-type body as a deferred-decode json.RawMessage; per-type structs land in a sibling ticket and slot in via a second-pass json.Unmarshal.
type ErrorPayload ¶
type ErrorPayload struct {
Code string `json:"code"`
Message string `json:"message"`
Retryable bool `json:"retryable"`
RetryAfterS *int `json:"retry_after_s,omitempty"`
}
ErrorPayload is the body of an "error" envelope (docs/protocol-mobile.md § Message types, § Error codes). RetryAfterS is optional and advisory; it is meaningful only when Retryable is true.
type HelloAckPayload ¶
type HelloAckPayload struct {
ProtocolVersion string `json:"protocol_version"`
ServerID string `json:"server_id"`
ConnID string `json:"conn_id"`
}
HelloAckPayload is the body of a "hello_ack" envelope sent in response to "hello" (docs/protocol-mobile.md § Message types). ConnID echoes the relay-assigned id back to the phone for diagnostics only.
type HelloClientPayload ¶
type HelloClientPayload struct {
Role string `json:"role"`
DeviceName string `json:"device_name"`
ClientVersion string `json:"client_version"`
ProtocolVersions []string `json:"protocol_versions"`
LastSeenTS *time.Time `json:"last_seen_ts,omitempty"`
Token string `json:"token,omitempty"`
}
HelloClientPayload is the body of a "hello" envelope sent by the phone after WS upgrade (docs/protocol-mobile.md § Message types). Role is always "client". LastSeenTS is optional; when present it triggers a backfill (docs/protocol-mobile.md § Backfill semantics).
Token is the in-band carrier of the device-pairing token under v2 (docs/protocol-mobile.md § Authentication, line 420). Empty under v1 (carried as RoutingEnvelope.Token instead); the omitempty keeps v1 round-trip byte-identical for existing fixtures. SECURITY: Token is plaintext credential material — MUST NOT be logged at any level.
type HelloServerPayload ¶
type HelloServerPayload struct {
Role string `json:"role"`
ServerID string `json:"server_id"`
BinaryVersion string `json:"binary_version"`
ProtocolVersions []string `json:"protocol_versions"`
}
HelloServerPayload is the body of a "hello" envelope sent by the binary after WS upgrade (docs/protocol-mobile.md § Message types). Role is always "server".
type InnerFrameV2 ¶ added in v0.14.0
type InnerFrameV2 struct {
Version int `json:"v"`
Type string `json:"type"`
Data string `json:"data"`
}
InnerFrameV2 is the v2 inner-frame shape carried inside RoutingEnvelope.Frame (docs/protocol-mobile.md § Wire shapes).
type ListConversationsPayload ¶
type ListConversationsPayload struct{}
ListConversationsPayload is the body of a list_conversations frame (docs/protocol-mobile.md § list_conversations). Phone → binary. The payload is empty by spec; the type exists so the dispatcher can decode into a concrete value rather than a json.RawMessage.
type MessageChunkPayload ¶
type MessageChunkPayload struct {
Messages []MessagePayload `json:"messages"`
}
MessageChunkPayload is the body of an Envelope whose Type == TypeMessageChunk (docs/protocol-mobile.md § message_chunk). Binary → phone direction; streamed during a backfill response. Messages reuses MessagePayload directly — the spec says "same shape as message.payload, multiple."
type MessagePayload ¶
type MessagePayload struct {
ConversationID string `json:"conversation_id"`
MessageID string `json:"message_id"`
Role string `json:"role"`
Text string `json:"text"`
}
MessagePayload is the body of an Envelope whose Type == TypeMessage (docs/protocol-mobile.md § message). Binary → phone direction; carries either a user-message echo (to other paired devices) or an assistant reply. Role is one of "user", "assistant", "system" per the spec's field table; the type stays string (not a named Role enum) because the binary already treats role-strings as string-typed elsewhere.
type PromoteConversationPayload ¶
type PromoteConversationPayload struct {
ConversationID string `json:"conversation_id"`
Name string `json:"name"`
Cwd string `json:"cwd"`
}
PromoteConversationPayload is the body of a promote_conversation frame (docs/protocol-mobile.md § promote_conversation). Phone → binary. All three fields are spec-required: a promoted conversation must carry a name and an effective cwd, and the conversation_id must resolve to an existing row.
type RegisterPushTokenPayload ¶
type RegisterPushTokenPayload struct {
Platform string `json:"platform"`
Token string `json:"token"`
DeviceName string `json:"device_name"`
}
RegisterPushTokenPayload is the body of a register_push_token frame (docs/protocol-mobile.md § register_push_token). Phone → binary, sent on every WS connect; the binary persists (platform, token, device_name) in devices.json and de-duplicates against the stored triple.
Platform is "fcm" (Android) or "apns" (iOS). The wire type stays a plain string: an enum would force a converter at every internal call site for no observable wire-format gain, and per-spec the dispatcher is the validation point.
All three fields are required (no omitempty, no pointers).
type RoutingEnvelope ¶
type RoutingEnvelope struct {
ConnID string `json:"conn_id"`
Frame json.RawMessage `json:"frame"`
// Token carries the phone's device-pairing token from the relay to
// the binary on the FIRST phone→binary frame for a given ConnID
// only. Empty on subsequent frames and on every binary→phone frame.
// Populated by the relay from the phone's x-pyrycode-token HTTP
// header at WS upgrade; never echoed back to the phone. Wire spec:
// docs/protocol-mobile.md § Routing envelope.
//
// SECURITY: the binary's dispatcher and gate closure MUST NOT log
// Token at any level. The token is plaintext credential material;
// AuthenticateFirstFrame is the only consumer.
Token string `json:"token,omitempty"`
// CloseCode, when non-zero on a binary→relay routing envelope, asks
// the relay to forward Frame (if non-empty) to the phone and then
// close that phone's WS with this WS close code. Zero on every
// phone→binary frame; the dispatcher ignores CloseCode on inbound
// (phone→binary) frames. Wire spec: docs/protocol-mobile.md
// § Routing envelope, § Error codes (close-code row 4401).
CloseCode uint16 `json:"close_code,omitempty"`
}
RoutingEnvelope wraps an Envelope with the relay-prepended conn_id used on the binary↔relay leg only (docs/protocol-mobile.md § Routing envelope). Phones never see it; the relay strips it before forwarding frames to phones and prepends it before forwarding frames to the binary.
Frame is json.RawMessage so the relay can splice without parsing payloads — a structural property of the design (the relay holds zero per-user state).
Token and CloseCode are direction-restricted relay-prepended fields, both omitempty so existing fixtures and wire bytes for non-auth / non-close paths are byte-identical to the pre-#308 shape.
type SendMessagePayload ¶
type SendMessagePayload struct {
ConversationID string `json:"conversation_id"`
MessageID string `json:"message_id"`
Text string `json:"text"`
}
SendMessagePayload is the body of an Envelope whose Type == TypeSendMessage (docs/protocol-mobile.md § send_message). Phone → binary direction.