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
- Variables
- func AppendCall(dst []byte, k Kind, c *Call) ([]byte, error)
- func AppendValue(dst []byte, v any) ([]byte, error)
- func CutMessage(msg string, limit int) string
- func DecodeValue(data []byte) (any, error)
- func FormatReal(f float64) string
- func Parse(kind Kind, body []byte, batchLimit int) (*Request, *Error)
- func Path(k Kind, db string) string
- func Route(method, path string) (Kind, string, *Error)
- func ValidDatabaseName(s string) bool
- type Args
- type Call
- type Channel
- type Code
- type Column
- type Done
- type DoneKind
- type Error
- type Frame
- type FrameKind
- type Kind
- type Limits
- type Mode
- type NamedArg
- type Op
- type Reader
- type Receipt
- type Request
- type Resolution
- type Result
- type Statement
- type TxnState
- type Writer
- func (w *Writer) Columns(cols []Column) error
- func (w *Writer) Done(d *Done) error
- func (w *Writer) Error(e *Error) error
- func (w *Writer) Keepalive() error
- func (w *Writer) Params(names []string) error
- func (w *Writer) Results(entries []Result) error
- func (w *Writer) Row(values []any) error
- func (w *Writer) Written() int64
Constants ¶
const ControlBodyBytes = 4096
ControlBodyBytes is the body limit of cancel, close and resolve, fixed by the protocol.
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.
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 ¶
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 ¶
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 ¶
AppendValue appends the canonical encoding of v, one of the value types.
func CutMessage ¶
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 ¶
DecodeValue decodes data, which must be exactly one value with nothing before or after it.
func FormatReal ¶
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 ¶
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 ¶
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 ¶
Route returns the kind and database name of a request. path is the request's path as sent, without its query.
func ValidDatabaseName ¶
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 ¶
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 ¶
Recordable reports whether an error with this code can be a channel request's recorded outcome.
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 ¶
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.
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 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.
type NamedArg ¶
NamedArg is a named parameter value. Name is the parameter's name without its prefix: it binds :Name, @Name and $Name.
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 ¶
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 ¶
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.
type Receipt ¶
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 ¶
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.
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 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 ¶
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 ¶
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 ¶
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 ¶
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) Params ¶
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 ¶
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.