wire

package
v0.0.2 Latest Latest
Warning

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

Go to latest
Published: Nov 23, 2026 License: Apache-2.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 wire encodes and decodes the client protocol of ADR 0005 (docs/content/docs/decisions/0005-client-protocol.md): request paths and bodies, SQL values, response frames, done fields, the limits object and errors. The HTTPS server and the Go driver share it. It does no I/O beyond the writer it is given, and knows nothing of channels, SQLite or authentication.

JSON is read with github.com/go-json-experiment/json/jsontext, which refuses invalid UTF-8 and lone surrogate escapes. Its duplicate-name check is turned off, because its memory per name is too large; this package finds duplicate names itself. This package adds the protocol's other rules: a body is exactly one object from its first byte to its last, nested at most MaxDepth deep, integers are exact and in range, REALs are finite, base64 is strict, and parameters bind exactly once. It writes JSON strings with its own escaping rule, not jsontext's.

Index

Constants

View Source
const ControlBodyBytes = 4096

ControlBodyBytes is the body limit of cancel, close and resolve, fixed by the protocol.

View Source
const DefaultFrameBytes = 1 << 20

DefaultFrameBytes is the default frame size: the largest frame the server encodes, except a row, or a results or params frame of one entry, that is larger by itself.

View Source
const MaxDepth = 16

MaxDepth is the deepest a body may nest arrays and objects, its root object counting as one level. A deeper body is refused before acceptance.

Variables

View Source
var ErrMalformed = errors.New("wire: malformed response")

ErrMalformed is wrapped by every error a Reader returns for a body that breaks the protocol. A body that ends before its terminal frame is io.ErrUnexpectedEOF instead.

Functions

func AppendCall

func AppendCall(dst []byte, k Kind, c *Call) ([]byte, error)

AppendCall appends the body of a request of kind k, which Parse accepts: a query, a describe, an open, a channel request with op begin, execute, commit, rollback or ping, a cancel or a close. It refuses a Call with fields k (and its op) does not allow, SQL that is empty, holds U+0000 or is not valid UTF-8, an empty, invalid or repeated parameter name, and a value AppendValue refuses. Its errors never hold a value or a token.

func AppendValue

func AppendValue(dst []byte, v any) ([]byte, error)

AppendValue appends the canonical encoding of v, one of the value types.

func CutMessage

func CutMessage(msg string, limit int) string

CutMessage returns the longest prefix of msg, cut at a character boundary, whose JSON string encoding, quotes included, takes at most limit bytes. Invalid UTF-8 in the prefix is replaced with U+FFFD, which the encoding needs; the replacement never makes the encoding longer.

func DecodeValue

func DecodeValue(data []byte) (any, error)

DecodeValue decodes data, which must be exactly one value with nothing before or after it.

func FormatReal

func FormatReal(f float64) string

FormatReal returns f as AppendValue writes it: for a finite double, the canonical REAL form, the shortest digits that parse back to f, as [-]d[.ddd]e[-]N; for an infinity, its tagged value. NaN has no encoding, and FormatReal panics on it; callers must not pass it.

func Parse

func Parse(kind Kind, body []byte, batchLimit int) (*Request, *Error)

Parse frames and identifies a request body before acceptance, and checks everything that needs no SQLite. batchLimit is the most entries a batch may have.

A refusal is an invalid_request error with the flags of an answer before acceptance. For a channel request, Parse refuses only a body that is not one well-formed JSON object or does not identify its channel and sequence number; every other problem is left for Validate, to be recorded. Every other kind is checked completely here.

func Path

func Path(k Kind, db string) string

Path returns the path of a request of kind k on database db, the inverse of Route. It returns "" for an invalid name or an unknown kind.

func Route

func Route(method, path string) (Kind, string, *Error)

Route returns the kind and database name of a request. path is the request's path as sent, without its query.

func ValidDatabaseName

func ValidDatabaseName(s string) bool

ValidDatabaseName reports whether s is 1 to 63 characters from a-z, 0-9 and -, starting with a letter or digit.

Types

type Args

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

Args are a statement's parameter values, kept as the position of their JSON array or object in the request body, so that a body of many small values decodes into little memory. The zero Args has no parameters.

type Call

type Call struct {
	SQL       string
	Params    []any      // positional values: element i binds parameter i+1
	Named     []NamedArg // named values; not with Params
	MinTxn    int64      // 0 is absent
	TimeoutMS int64      // 0 is absent
	Mode      Mode       // an open's
	Channel   string     // the token, of a channel request, a cancel and a close
	Seq       int64      // of a channel request and a cancel
	Op        Op         // of a channel request
}

Call is the body of a request a driver sends.

type Channel

type Channel struct {
	Token  string
	ID     string
	Mode   Mode
	Epoch  int64
	Limits Limits
}

Channel is an open answer's channel object. Epoch is written for a write channel only.

type Code

type Code string

Code is an error code. The list is closed in protocol version 1.

const (
	CodeInvalidRequest       Code = "invalid_request"
	CodeUnauthenticated      Code = "unauthenticated"
	CodeForbidden            Code = "forbidden"
	CodeStatementForbidden   Code = "statement_forbidden"
	CodeDatabaseNotFound     Code = "database_not_found"
	CodeDatabaseExists       Code = "database_exists"
	CodeNeedsChannel         Code = "needs_channel"
	CodeChannelBusy          Code = "channel_busy"
	CodeInFlight             Code = "in_flight"
	CodeStaleSequence        Code = "stale_sequence"
	CodeSequenceGap          Code = "sequence_gap"
	CodeSequenceConflict     Code = "sequence_conflict"
	CodeChannelLost          Code = "channel_lost"
	CodeRequestTooLarge      Code = "request_too_large"
	CodeTooManyChannels      Code = "too_many_channels"
	CodeOverloaded           Code = "overloaded"
	CodeInvalidState         Code = "invalid_state"
	CodeTransactionAborted   Code = "transaction_aborted"
	CodeBusy                 Code = "busy"
	CodeTimeout              Code = "timeout"
	CodeCancelled            Code = "cancelled"
	CodeResultTooLarge       Code = "result_too_large"
	CodeSQLError             Code = "sql_error"
	CodeCommitFailed         Code = "commit_failed"
	CodeCommitOutcomeUnknown Code = "commit_outcome_unknown"
	CodeNoLeader             Code = "no_leader"
	CodeNotServing           Code = "not_serving"
	CodeOwnerUnreachable     Code = "owner_unreachable"
	CodeBehind               Code = "behind"
	CodeMaintenance          Code = "maintenance"
	CodeInternal             Code = "internal"
)

The error codes of ADR 0005.

func (Code) Recordable

func (c Code) Recordable() bool

Recordable reports whether an error with this code can be a channel request's recorded outcome.

func (Code) Status

func (c Code) Status() int

Status is the HTTP status of a response whose whole body is an error with this code. A code that only ever ends the response of an accepted request returns 200, the status of that response. An unknown code returns 500.

type Column

type Column struct {
	Name     string
	DeclType string
	Database string
	Table    string
	Origin   string
}

Column is one entry of a columns frame. An empty string is written as null.

type Done

type Done struct {
	Kind            DoneKind
	Seq             int64
	Txn             int64
	TxnState        TxnState
	ReadOnly        bool
	RowsAffected    int64
	LastInsertRowID int64
	Entries         int64
	ParamCount      int64
	Wrote           bool
	DataOmitted     bool // written only when true, on a sequenced request's replay
	Channel         *Channel
	LastSeq         int64
	Outcome         *Receipt
	Resolution      Resolution
	Epoch           int64
	SQLiteVersion   string
	Limits          *Limits
}

Done is a done frame. Kind decides which fields are written; every field it lists is written, zero or not.

type DoneKind

type DoneKind uint8

DoneKind selects the fields a done frame carries, one per row of ADR 0005's table of done fields.

const (
	DoneQuery           DoneKind = iota + 1 // txn, read_only, rows_affected, last_insert_rowid
	DoneDescribe                            // txn, param_count
	DoneOpen                                // txn, channel
	DoneBegin                               // seq, txn_state, txn: a begin without execute
	DoneExecute                             // seq, txn_state, txn, read_only, rows_affected, last_insert_rowid: execute, or begin with execute
	DoneBatch                               // seq, txn_state, txn, rows_affected, last_insert_rowid, entries
	DoneChannelDescribe                     // seq, txn_state, txn, param_count
	DoneCommit                              // seq, txn_state, txn, committed, wrote
	DoneRollback                            // seq, txn_state, txn: rollback and ping
	DoneCancel                              // seq, txn_state, outcome
	DoneClose                               // last_seq, and outcome unless last_seq is 0
	DoneResolve                             // resolution, txn
	DoneStatus                              // txn, epoch, sqlite_version, limits
	DonePut                                 // txn, epoch
)

The done kinds.

type Error

type Error struct {
	Code               Code
	NotExecuted        bool
	Final              bool
	Message            string
	RequestID          string
	ChannelID          string
	Seq                int64
	TxnState           TxnState
	SQLiteCode         int64
	SQLiteExtendedCode int64
	BatchIndex         *int64
	Cause              string // "maintenance" or empty
	Txn                int64
	Epoch              int64
}

Error is the error object of ADR 0005. A zero integer, an empty string and a nil BatchIndex are absent fields.

func NewError

func NewError(code Code, msg string) *Error

NewError returns an error with the flags of an answer given before acceptance: not executed and not final, except that sequence_conflict is final and commit_outcome_unknown is not "not executed". A running request interrupted with channel_lost must also clear NotExecuted; a recorded failure takes its flags from Recorded.

func (*Error) Error

func (e *Error) Error() string

func (*Error) Recorded

func (e *Error) Recorded(txnStatement bool) *Error

Recorded sets the flags of a recorded failure and returns e: final, and not executed unless the failure is of an execute or batch accepted while a transaction was open (txnStatement). It panics if the code is never recorded, which is a bug in the caller.

type Frame

type Frame struct {
	Kind    FrameKind
	Columns []Column
	Row     []any
	Params  []string // this frame's names; "" for a parameter without one
	Done    *Done
	Error   *Error
}

Frame is one frame of a response. Only the member of its Kind is set. Columns, Row and Params are valid until the next call to Next.

type FrameKind

type FrameKind uint8

FrameKind is the kind of a frame a Reader returns.

const (
	FrameColumns FrameKind = iota + 1
	FrameRow
	FrameParams
	FrameDone  // terminal
	FrameError // terminal
)

The frame kinds. Keepalives and unknown frames are skipped by Next.

type Kind

type Kind uint8

Kind is what a request's method and path ask for.

const (
	KindQuery    Kind = iota + 1 // POST /v1/databases/{db}/query
	KindDescribe                 // POST /v1/databases/{db}/describe
	KindOpen                     // POST /v1/databases/{db}/channels
	KindChannel                  // POST /v1/databases/{db}/channel
	KindCancel                   // POST /v1/databases/{db}/channel/cancel
	KindClose                    // POST /v1/databases/{db}/channel/close
	KindResolve                  // POST /v1/databases/{db}/resolve
	KindStatus                   // GET /v1/databases/{db}
	KindPut                      // PUT /v1/databases/{db}
)

The request kinds, one per row of ADR 0005's path table.

type Limits

type Limits struct {
	RequestBodyBytes     int64
	HeaderBlockBytes     int64
	BatchEntries         int64
	FrameEntries         int64
	ResultBytes          int64
	HeldResultBytes      int64
	TerminalFrameBytes   int64
	ErrorMessageBytes    int64
	RetainedRequestBytes int64
	ResolveBound         int64
	StatementMS          int64
	ResponseMS           int64
	KeepaliveMS          int64
	LockWaitMS           int64
	CatchUpMS            int64
	ChannelIdleMS        int64
	WriteTxnIdleMS       int64
	WriteTxnLifetimeMS   int64
	ReadTxnIdleMS        int64
	ReadTxnLifetimeMS    int64
}

Limits is the limits object. Every member is always present.

func DefaultLimits

func DefaultLimits() Limits

DefaultLimits returns the defaults of ADR 0005 decision 9.

func (*Limits) Validate

func (l *Limits) Validate() error

Validate checks l against the limits object's ranges: every member from 1 to 2^63-1, or to 2^31-1 in milliseconds, and the error message bound (at least 2 bytes, the empty message), the batch limit and the entries per frame at most their defaults, which are maxima.

type Mode

type Mode uint8

Mode is a channel's kind.

const (
	ModeWrite Mode = iota + 1
	ModeReadOnly
)

The channel modes.

func (Mode) String

func (m Mode) String() string

type NamedArg

type NamedArg struct {
	Name  string
	Value any
}

NamedArg is a named parameter value. Name is the parameter's name without its prefix: it binds :Name, @Name and $Name.

type Op

type Op uint8

Op is a sequenced request's operation.

const (
	OpUnknown Op = iota
	OpBegin
	OpExecute
	OpBatch
	OpDescribe
	OpCommit
	OpRollback
	OpPing
)

The operations. OpUnknown is an op the protocol does not define.

type Reader

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

Reader reads a response body one frame at a time, as it arrives, and keeps at most one frame in memory. It checks the order of ADR 0005's grammar, the row widths, the continuity of params entries, the members of the terminal frame the request's kind expects, the terminal frame's size, and that nothing follows the terminal frame. It skips keepalives, frames whose only member is unknown, and unknown members of known objects.

func NewReader

func NewReader(r io.Reader, k DoneKind, maxFrame int) (*Reader, error)

NewReader returns a Reader of a response to a request whose done frame is of kind k, reading frames of at most maxFrame bytes, newline included.

func (*Reader) LimitResult

func (r *Reader) LimitResult(n int64)

LimitResult makes Next refuse a response whose frames before the terminal frame pass n bytes, newlines included: a channel's advertised result_bytes, which its owner never exceeds.

func (*Reader) Next

func (r *Reader) Next() (*Frame, error)

Next returns the next frame. After the terminal frame it returns io.EOF.

type Receipt

type Receipt struct {
	Done  *Done
	Error *Error
}

Receipt is a sequenced request's recorded outcome: Done for a success, of a sequenced kind, or Error for a failure.

type Request

type Request struct {
	Kind       Kind
	Channel    string
	Seq        int64
	Op         Op
	Mode       Mode
	MinTxn     int64
	TimeoutMS  int64
	Statement             // sql with params or named, of query, describe, execute and a batch with param_sets
	Execute    *Statement // a begin's first statement
	ParamSets  []Args     // a batch of one statement
	Statements []Statement
	// contains filtered or unexported fields
}

Request is a parsed request body. Absent integers are zero; an absent timeout_ms is zero. It refers to the body it was parsed from, which must not change while the Request is used.

func (*Request) Bind

func (r *Request) Bind(a Args, names []string, set func(index int, v any) error) error

Bind passes a statement's argument values to set, by parameter index from 1, after checking that they bind every parameter exactly once: set is not called unless they do. names holds the statement's parameter names by index from 1, names[0] being that of parameter 1, with their prefix as sqlite3_bind_parameter_name reports them, or "" for a parameter without a name. A channel request that Validate finds invalid returns Validate's error before anything else. A binding mismatch is an invalid_request *Error with the flags of an answer before acceptance; an error from set is returned unchanged. Bind decodes one value at a time and keeps none.

func (*Request) Validate

func (r *Request) Validate() *Error

Validate returns the first problem Parse found in a channel request after identifying it, as an invalid_request error with the flags of an answer before acceptance; the owner records it with Recorded. It returns nil for a valid request.

type Resolution

type Resolution string

Resolution is a resolve answer.

const (
	ResolutionCommitted    Resolution = "committed"
	ResolutionNotCommitted Resolution = "not_committed"
	ResolutionPending      Resolution = "pending"
	ResolutionUnknown      Resolution = "unknown"
)

The resolutions.

type Result

type Result struct {
	RowsAffected    int64
	LastInsertRowID int64
}

Result is one entry of a results frame.

type Statement

type Statement struct {
	SQL  string
	Args Args
}

Statement is one SQL statement and its arguments.

type TxnState

type TxnState string

TxnState is a channel's transaction state.

const (
	TxnNone    TxnState = "none"
	TxnOpen    TxnState = "open"
	TxnAborted TxnState = "aborted"
)

The transaction states.

type Writer

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

Writer writes a response body: frames in the order ADR 0005's grammar allows, ending with one terminal frame. It is not safe for concurrent use.

func NewWriter

func NewWriter(w io.Writer, frameBytes int, l Limits) (*Writer, error)

NewWriter returns a Writer that writes each frame to w with one Write call. frameBytes is the frame size; l supplies the entries per frame, the result size, which counts every byte before the terminal frame, the terminal frame reservation and the error message bound. The held-result bound, which counts rows and results frames only, is the caller's to apply. NewWriter refuses a frame size below 1 and limits that Validate refuses.

func (*Writer) Columns

func (w *Writer) Columns(cols []Column) error

Columns writes a columns frame, which must come first. A columns frame above the frame size is refused with result_too_large.

func (*Writer) Done

func (w *Writer) Done(d *Done) error

Done writes a done frame, ending the response. It refuses, writing nothing, a Done whose kind is unknown, that lacks the Channel, Outcome or Limits its kind writes, whose outcome is not one Done of a sequenced request's kind or one Error, or that sets DataOmitted on an answer that is not a sequenced request's.

func (*Writer) Error

func (w *Writer) Error(e *Error) error

Error writes an error frame, ending the response. The message is cut to the error message bound. It refuses, writing nothing, an error whose code is not in the list or whose request ID is not 1 to 64 characters from A-Z a-z 0-9 _ -.

func (*Writer) Keepalive

func (w *Writer) Keepalive() error

Keepalive writes a keepalive frame.

func (*Writer) Params

func (w *Writer) Params(names []string) error

Params writes a describe answer's parameter names, continuing from those already written, split as Results splits. They must follow the columns frame, which a describe answer always has. An empty name is written as null.

func (*Writer) Results

func (w *Writer) Results(entries []Result) error

Results writes a batch's results entries, continuing from the entries already written, in frames of at most FrameEntries entries that end before an entry that would take them past the frame size. Results may not follow params.

func (*Writer) Row

func (w *Writer) Row(values []any) error

Row writes a row, which must follow the columns frame and have one value per column. A row is never split, whatever its size.

func (*Writer) Written

func (w *Writer) Written() int64

Written returns the bytes written before the terminal frame.

Jump to

Keyboard shortcuts

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