protocol

package
v0.3.0 Latest Latest
Warning

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

Go to latest
Published: Nov 14, 2026 License: AGPL-3.0 Imports: 8 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 protocol holds the wire types and pure helpers shared by daemon and server.

Index

Constants

View Source
const (
	MaxCompressedBody   = 8 << 20
	MaxDecompressedBody = 64 << 20
	MaxPathLen          = 1024
	MaxLinesPerRequest  = 20000
	MaxFilesPerRequest  = 5000 // the daemon never sends more entries than lines per batch
)

Body and path size limits.

View Source
const (
	ChunkSize = MaxCompressedBody / 8
	// MaxLineBytes caps one line or snapshot: derive, the viewer and Postgres assemble it in memory.
	// Larger ones are never uploaded (the daemon records them as skipped).
	MaxLineBytes = 256 << 20
	// MaxReadLine caps what derive and the line viewer load into memory; larger stored lines are
	// counted or shown as a placeholder.
	MaxReadLine = 64 << 20
)

Chunking of lines and snapshots too large for one request. ChunkSize raw bytes escape to at most six times as many JSON bytes, so a request holding one chunk stays below MaxCompressedBody (and MaxDecompressedBody) even uncompressed and at worst-case escaping.

View Source
const (
	DefaultFilesLimit = 500
	MaxFilesLimit     = 1000
)

Page sizes of GET /v1/files.

View Source
const GrantTypeDeviceCode = "urn:ietf:params:oauth:grant-type:device_code"

GrantTypeDeviceCode is the RFC 8628 grant type.

View Source
const HeaderVersion = "Braid-Protocol"

HeaderVersion is the HTTP header carrying the protocol version.

View Source
const TokenPrefix = "braid_dev_"

TokenPrefix prefixes every device token.

View Source
const UserCodeAlphabet = "BCDFGHJKLMNPQRSTVWXZ"

UserCodeAlphabet is the character set of user codes (no vowels, no look-alikes).

View Source
const Version = 1

Version is the wire protocol version.

Variables

View Source
var ErrBadLine = errors.New("protocol: line must set exactly one of text or b64")

ErrBadLine means a Line has both or neither of Text and B64 set.

View Source
var ErrTooManyFiles = errors.New("protocol: too many files in request")

ErrTooManyFiles means a request carries more than MaxFilesPerRequest file entries.

View Source
var ErrTooManyLines = errors.New("protocol: too many lines in request")

ErrTooManyLines means a request carries more than MaxLinesPerRequest lines in total.

Functions

func EndOffset

func EndOffset(from int64, lines [][]byte) int64

EndOffset returns from + sum(len(line)+1).

func HashHex

func HashHex(b []byte) string

HashHex returns the lowercase hex SHA-256 of b.

func NormalizeUserCode

func NormalizeUserCode(s string) (string, error)

NormalizeUserCode uppercases, strips spaces and '-', and requires exactly 8 alphabet characters.

func ValidPath

func ValidPath(p string, k Kind) error

ValidPath accepts relative, '/'-separated paths whose extension matches k.

func ValidText

func ValidText(s string, maxRunes int) bool

ValidText reports whether s is 1..maxRunes runes of valid UTF-8 that is safe to show to a human: no control (Cc), format (Cf, e.g. bidi overrides, zero-width) or line/paragraph separator characters and not only whitespace.

Types

type DeviceCodeRequest

type DeviceCodeRequest struct {
	Hostname      string `json:"hostname"`
	OS            string `json:"os"`
	Arch          string `json:"arch"`
	OSUser        string `json:"os_user"`
	DaemonVersion string `json:"daemon_version"`
}

DeviceCodeRequest is the body of POST /v1/device/code.

func (DeviceCodeRequest) Validate

func (r DeviceCodeRequest) Validate() error

Validate requires each field to be 1..128 bytes of valid text (see ValidText).

type DeviceCodeResponse

type DeviceCodeResponse struct {
	DeviceCode              string `json:"device_code"`
	UserCode                string `json:"user_code"`
	VerificationURI         string `json:"verification_uri"`
	VerificationURIComplete string `json:"verification_uri_complete"`
	ExpiresIn               int    `json:"expires_in"`
	Interval                int    `json:"interval"`
}

DeviceCodeResponse is the RFC 8628 device authorization response.

type ErrorResponse

type ErrorResponse struct {
	Error  string `json:"error"`
	Server int    `json:"server,omitempty"`
	Min    int    `json:"min,omitempty"`
}

ErrorResponse is the JSON error body; Server and Min report version mismatches.

type FileBatch

type FileBatch struct {
	Kind       Kind   `json:"kind"`
	Path       string `json:"path"`
	HeadHash   string `json:"head_hash"`
	FromOffset int64  `json:"from_offset"`
	Lines      []Line `json:"lines,omitempty"`
	Content    *Line  `json:"content,omitempty"`
	Scope      Scope  `json:"scope,omitempty"`
	// AllowGap lets from_offset exceed the server's end: the daemon skipped a line or snapshot
	// the protocol can never carry (see MaxLineJSON) and keeps it locally.
	AllowGap bool `json:"allow_gap,omitempty"`
}

FileBatch is one file's update inside an ingest request.

type FileResult

type FileResult struct {
	Path      string     `json:"path"`
	HeadHash  string     `json:"head_hash"`
	Status    FileStatus `json:"status"`
	EndOffset int64      `json:"end_offset"`
}

FileResult reports the server state of one ingested file.

type FileStatus

type FileStatus string

FileStatus is the server's verdict for one file.

const (
	StatusOK       FileStatus = "ok"
	StatusGap      FileStatus = "gap"
	StatusConflict FileStatus = "conflict"
	StatusPending  FileStatus = "pending" // a part was stored; the line is not complete yet
)

Known file statuses.

type FilesPage

type FilesPage struct {
	Files []RemoteFile `json:"files"`
	Next  string       `json:"next,omitempty"`
}

FilesPage is the response of GET /v1/files?after=<cursor>&limit=<n>; Next is the cursor of the next page, empty on the last.

type IngestRequest

type IngestRequest struct {
	Files []FileBatch `json:"files"`
}

IngestRequest is the body of POST /v1/ingest.

func (IngestRequest) Validate

func (r IngestRequest) Validate() error

Validate checks a whole request. An append entry with zero lines is valid.

type IngestResponse

type IngestResponse struct {
	Files []FileResult `json:"files"`
}

IngestResponse is the response of POST /v1/ingest.

type Kind

type Kind string

Kind is the sync mode of a file: append-only log or whole-file snapshot.

const (
	KindAppend   Kind = "append"
	KindSnapshot Kind = "snapshot"
)

Known file kinds.

type Line

type Line struct {
	Text *string `json:"text,omitempty"`
	B64  []byte  `json:"b64,omitempty"`
	Part *Part   `json:"part,omitempty"`
}

Line carries raw bytes: Text when valid UTF-8, otherwise B64. With Part set, the bytes are one chunk.

func EncodeLine

func EncodeLine(raw []byte) Line

EncodeLine wraps raw bytes as Text when valid UTF-8, otherwise as B64.

func SplitLine

func SplitLine(raw []byte, size int) []Line

SplitLine cuts raw into chunks of at most size bytes, on rune boundaries when raw is valid UTF-8.

func (Line) Bytes

func (l Line) Bytes() ([]byte, error)

Bytes returns the raw bytes, or ErrBadLine if both or neither field is set.

type OAuthError

type OAuthError struct {
	Error string `json:"error"`
}

OAuthError is an RFC 8628 error body; Error is one of authorization_pending|slow_down|expired_token|access_denied|invalid_grant|invalid_request.

type Part

type Part struct {
	Index    int    `json:"index"`
	Count    int    `json:"count"`
	TotalLen int64  `json:"total_len"`
	SHA256   string `json:"sha256"`
}

Part marks a Line as one chunk of a longer line (or snapshot): chunk Index of Count, of a line of TotalLen bytes with the given hex SHA-256. A request carries one part entry alone.

type RemoteFile

type RemoteFile struct {
	Path        string `json:"path"`
	HeadHash    string `json:"head_hash"`
	Kind        Kind   `json:"kind"`
	EndOffset   int64  `json:"end_offset"`
	ContentHash string `json:"content_hash,omitempty"` // hex sha256 of latest snapshot
	Scope       Scope  `json:"scope,omitempty"`
	TailOffset  int64  `json:"tail_offset,omitempty"` // append: offset of the stored line with the highest offset
	TailHash    string `json:"tail_hash,omitempty"`   // hex sha256 of that line
}

RemoteFile is one entry of GET /v1/files.

type Scope

type Scope string

Scope selects the identity of an append file: "" = per user, ScopeDevice = per (user, device).

const ScopeDevice Scope = "device"

ScopeDevice is the fallback after a conflict (01 section 3.4).

type TokenRequest

type TokenRequest struct {
	GrantType  string `json:"grant_type"` // must be GrantTypeDeviceCode
	DeviceCode string `json:"device_code"`
}

TokenRequest is the body of POST /v1/device/token.

type TokenResponse

type TokenResponse struct {
	AccessToken string `json:"access_token"`
	TokenType   string `json:"token_type"`
	Scope       string `json:"scope"`
	DeviceID    string `json:"device_id"`
}

TokenResponse is the successful device token response.

Jump to

Keyboard shortcuts

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