Documentation
¶
Overview ¶
Package plugin serves DRE's plugin protocol (docs/protocol.md) for the Go plugin packages: framing, the handshake, describe, validate, the request loop, and the error and exit rules.
From protocol 1, every reply carries its request's id; stdin is read on a goroutine so a `cancel` reaches a running request (see Cancelled and Canceller); log with log/slog (Serve sends the default logger's records to core as `log` messages) and report Progress; return an *Error to give core a failure's kind and code.
A package lists its roles. A source role opens a Session, which runs statements on one database session; a destination role delivers a file. Everything else (sign-in, the driver, the dialect) stays in the package. Results are normalised to DRE's type rule on the way out (see types.go), so every Go source sends the same Arrow types for the same kind of value.
Each plugin pins its own Arrow version for its driver; this module uses arrow-go v18, and a plugin whose driver returns another Arrow version passes its batches through Arrow IPC.
Index ¶
- Constants
- Variables
- func Bool(conn map[string]any, key string, def bool) (bool, error)
- func Cancelled() bool
- func CheckConnection(r Role, conn map[string]any, unresolved []string) (errs, warns []string)
- func Closest(key string, names []string) string
- func CompactJSON(c *array.String) arrow.Array
- func Convert(rec arrow.RecordBatch, schema *arrow.Schema) (arrow.RecordBatch, error)
- func DecodeRecords(b []byte) (*arrow.Schema, []arrow.RecordBatch, error)
- func EncodeRecord(rec arrow.RecordBatch) ([]byte, error)
- func Int(conn map[string]any, key string, def int64) (int64, error)
- func IsConnectionError(err error) bool
- func Loopback(host string) bool
- func Main(p Package)
- func Number(v any) (int, bool)
- func Optional(conn map[string]any, key string) string
- func OutputSchema(s *arrow.Schema) *arrow.Schema
- func ParseDuration(v any) (time.Duration, error)
- func Progress(message string, done, total int64)
- func Required(conn map[string]any, key string) (string, error)
- func Retry[T any](r Rules, what string, f func() (T, error)) (T, error)
- func RetryAfter(header string) time.Duration
- func SQLRows(recs []arrow.RecordBatch, literal func(arrow.Array, int) string) ([]string, int64)
- func Serve(stdin io.Reader, stdout io.Writer, p Package, r Role) (code int)
- func Strings(conn map[string]any, key string) []string
- func Unknown(conn map[string]any, fields []Field, also ...string) error
- func ValidName(name string) bool
- func WriteFileAtomic(path string, data []byte, perm os.FileMode) error
- func WriteFrame(w *bufio.Writer, tag byte, body []byte) error
- func WriteJSON(w *bufio.Writer, v any) error
- type Canceller
- type Caps
- type Delivered
- type Error
- type Field
- type Frame
- type IfExists
- type Loaded
- type OptionField
- type Package
- type Request
- type Resetter
- type Result
- type Role
- type Rules
- type SQLDialect
- type Session
- type Store
- type TemporaryError
Constants ¶
const ( TagJSON = 'J' TagArrow = 'A' )
const ( ProtocolMin = 1 ProtocolMax = 1 )
const ( CapSessions = "sessions" CapReadOnly = "read_only" CapCheck = "check" CapMultiFile = "multi_file" CapMessage = "message" CapMessageOnly = "message_only" CapLoad = "load" CapCatalog = "catalog" CapValidate = "validate" )
Capabilities a role may advertise.
Variables ¶
var Capabilities = []string{CapSessions, CapReadOnly, CapCheck, CapMultiFile, CapMessage, CapMessageOnly, CapLoad, CapCatalog, CapValidate}
Capabilities is every capability, in the schema's order.
var ErrEOF = errors.New("core closed the connection")
ErrEOF means core closed stdin between frames: a clean end.
var ErrExists = errors.New("a file is already there")
ErrExists means something is already at the path.
var ErrorKinds = []string{"config", "plugin", "refused", "connection", "auth", "query", "delivery", "internal", "cancelled", "timed_out"}
ErrorKinds is every kind an `error` reply may give, in the schema's order.
Functions ¶
func Cancelled ¶
func Cancelled() bool
Cancelled reports whether core has cancelled the request running now. Long loops check it between steps.
func CheckConnection ¶
CheckConnection checks conn against the role's Fields, then its ValidateConnection (when the generic checks passed). Keys in unresolved (an unset env_var()) count as set but aren't checked. Messages name fields, never values; secret values are redacted.
func CompactJSON ¶
CompactJSON re-encodes a column of JSON text (Snowflake's pretty-printed VARIANT, a JSON column) as compact, single-line JSON, keeping key order and number text. A value that isn't valid JSON is kept as it is.
func Convert ¶
func Convert(rec arrow.RecordBatch, schema *arrow.Schema) (arrow.RecordBatch, error)
Convert puts rec's columns under schema (from OutputSchema). The caller releases the result.
func DecodeRecords ¶
DecodeRecords reads every record of one IPC stream. The caller releases them.
func EncodeRecord ¶
func EncodeRecord(rec arrow.RecordBatch) ([]byte, error)
EncodeRecord writes one record as a self-contained IPC stream (schema, batch, end marker).
func IsConnectionError ¶
IsConnectionError is whether err is a connection failing (refused, reset, timed out, closed early), which trying again may fix.
func Loopback ¶
Loopback is whether host (a name or IP, without a port) is this machine: localhost or a loopback address. Plain-text credentials are only safe there.
func Main ¶
func Main(p Package)
Main serves the role the executable's name picks on stdin and stdout, and exits.
func Optional ¶
Optional is a string field, or "" when it isn't set. Numbers are given as their text.
func OutputSchema ¶
OutputSchema is the schema sent to core for a result whose columns are declared as s: the type rule applied, without driver metadata, every column nullable.
func ParseDuration ¶
ParseDuration reads `30s`, `5m`, `2h`, `1500ms`, or a bare number of seconds.
func Progress ¶
Progress tells core how far a long request has got (protocol 1; logged at info before).
func Retry ¶
Retry runs f, trying again while it returns a *TemporaryError, up to r.Retries more times, waiting r.Wait: the server's Retry-After or the backoff (about 1s, then 4s, then 16s), never more than r.MaxRetryWait. Each retry is logged at info level, naming what; a step that needed several tries is reported to core. Return a plain error for a failure trying again won't fix, or that might repeat something already done.
func RetryAfter ¶
RetryAfter is the Retry-After of a 429 or 503, in seconds (an HTTP date isn't read).
func SQLRows ¶
SQLRows renders records in order as parenthesized SQL rows. The caller supplies its warehouse's literal rules and retains ownership of the records.
func Serve ¶
Serve speaks the protocol on stdin and stdout as role until core closes, and returns the process exit code.
func Strings ¶
Strings is a field holding a list of strings, or one string (comma-separated values are split).
func Unknown ¶
Unknown names the fields of conn that aren't in fields (nor in also), so a misspelt profile field is an error rather than silently ignored.
func WriteFileAtomic ¶
WriteFileAtomic writes data to path so a reader, or a crash, sees the old file or the new one, never a part: a temporary file (.<name>.<pid>.<random>.tmp) in the same folder, flushed to disk, renamed over path, then the folder flushed (a folder that can't be, such as some network mounts, is logged at debug and ignored). The Rust side is dre_protocol::util::write_atomic.
Types ¶
type Canceller ¶
type Canceller interface {
Cancel()
}
Canceller is implemented by a Session (or set as a Role's Cancel) that can stop a running request on the server, such as cancelling a statement. It's called on the stdin goroutine while the request runs.
type Caps ¶
type Caps struct {
// CreateExclusive: Write with exclusive fails with ErrExists in the same step.
CreateExclusive bool
// RenameNoReplace: Rename without replace fails with ErrExists in the same step.
RenameNoReplace bool
// VisibleWhenComplete: a file only appears once it's complete (object stores), so no
// temporary name is needed.
VisibleWhenComplete bool
}
Caps is what a store can do in one step.
type Delivered ¶
type Delivered struct {
// Path is the final path (with IfExistsNumber, possibly report_2.xlsx).
Path string
// Attempts is how many tries it took (1 without a retry).
Attempts int
}
Delivered is where a delivery landed.
type Error ¶
Error is a failure with its kind (one of the protocol's error kinds: config, plugin, refused, connection, auth, query, delivery, internal, cancelled, timed_out) and, optionally, a code. The code is namespaced by the plugin on the way out (`bad-token` is sent as `databricks/bad-token`).
type Field ¶
type Field struct {
Name string `json:"name"`
Description string `json:"description"`
Required bool `json:"required"`
Secret bool `json:"secret"`
Default any `json:"default,omitempty"`
SameAsSource string `json:"same_as_source,omitempty"`
Manual bool `json:"manual,omitempty"`
// Kind is what the value must be: string, integer, boolean, path (a file that exists),
// duration or map. Checked by validate_connection and before open and deliver.
Kind string `json:"kind,omitempty"`
// Choices are the only values it may take.
Choices []string `json:"choices,omitempty"`
}
Field mirrors the protocol's `describe` entry for one profile field.
func DeliveryFields ¶
func DeliveryFields() []Field
DeliveryFields are the connection fields every network plugin shares.
func TimeoutFields ¶
func TimeoutFields() []Field
TimeoutFields are the timeouts every network plugin shares (connect_timeout, timeout); read them with RulesFrom.
type IfExists ¶
type IfExists string
IfExists is what to do when a file is already at the delivery path.
const ( // IfExistsOverwrite replaces it (the default: a rerun replaces a bad file). IfExistsOverwrite IfExists = "overwrite" // IfExistsError fails this delivery. IfExistsError IfExists = "error" // IfExistsNumber keeps both: the new file is saved as <name>_2.<ext>, _3, and so on. IfExistsNumber IfExists = "number" )
type OptionField ¶
type OptionField struct {
Name string `json:"name"`
Type string `json:"type"`
Description string `json:"description"`
Required bool `json:"required,omitempty"`
Default any `json:"default,omitempty"`
Choices []string `json:"choices,omitempty"`
}
OptionField mirrors the protocol's `describe` entry for one option a report's config block takes (a destination entry's keys). Type is one of the protocol's option types; the Go SDK checks `string` (with Choices) and `boolean`, and accepts any value for the others.
func DeliveryOptions ¶
func DeliveryOptions() []OptionField
DeliveryOptions are the options a destination entry takes for these rules: if_exists, atomic and temp_dir. A store whose files only appear once complete needs only if_exists.
type Package ¶
Package is one plugin program: its version and every role it provides, in `provides` order.
type Request ¶
type Request struct {
// contains filtered or unexported fields
}
Request gives each request a context that Cancel ends. A Session embeds it to be a Canceller, and passes the context Start returns to its driver calls.
type Resetter ¶
type Resetter interface {
Reset()
}
Resetter is a Store that drops a broken connection before Deliver tries again, so the next call makes a new one.
type Result ¶
type Result interface {
// Schema is the result's columns with the types the database declares for them; every
// batch is converted to it (see Convert).
Schema() (*arrow.Schema, error)
HasNext() bool
Next() (arrow.RecordBatch, error)
}
Result is one statement's result set, batch by batch.
type Role ¶
type Role struct {
Kind string // "source" or "destination"
Name string
Capabilities []string
Fields []Field
// IdentifierQuote is the source's identifier quote character.
IdentifierQuote string
// StringLiteral, when set, tells core how to spell a string holding ' or \ in SQL it writes
// (an inlined lookup): "backslash" for a database without chr(). Empty: chr(39)/chr(92).
StringLiteral string
// SQLDialect is required to enable core read-only query validation.
SQLDialect *SQLDialect
// Open starts a source session from the profile target's fields.
Open func(conn map[string]any) (Session, error)
// OpenReadOnly, when set, starts a session that refuses to change data, for an `open` with
// `read_only: true`; a role advertising the read_only capability sets it.
OpenReadOnly func(conn map[string]any) (Session, error)
// OpenSandboxed, when set, starts a read-only session for core's `dre query` (`sandbox:
// true`) that also refuses files, programs and the network outside the database where the
// engine can. Without it, such an open is read-only.
OpenSandboxed func(conn map[string]any) (Session, error)
// Options are what a report's config block for this role takes (checked before Deliver).
Options []OptionField
// Deliver sends one local file to remote, returning where it landed. opts is the
// destination entry's options, already checked against Options.
Deliver func(local, remote string, conn, opts map[string]any) (string, error)
// Cancel, when set, stops a running delivery (see Canceller).
Cancel func()
// Accepts are keys taken without being declared in Fields (dbt's other names, dbt-only
// keys), so they don't warn as unknown.
Accepts []string
// ValidateConnection, when set, checks what Fields can't express (two keys that can't go
// together), each a sentence naming the field, never its value. Static: no network. Run by
// validate_connection, and before Open and Deliver. A value set through an unset env_var()
// arrives as nil.
ValidateConnection func(conn map[string]any) []string
}
Role is one plugin a package serves.
type Rules ¶
type Rules struct {
IfExists IfExists
// Atomic writes under a temporary name, then renames.
Atomic bool
// TempDir is where the temporary file goes: absolute, or relative to the final file's
// folder. Empty: next to the final file.
TempDir string
// Retries is how many times to try again after a temporary error (0: never).
Retries int
// RetryWait is the first wait before trying again, doubling each try; 0: about 1s, then
// 4s, then 16s. A server's Retry-After wins.
RetryWait time.Duration
// MaxRetryWait is the longest wait between tries, Retry-After included.
MaxRetryWait time.Duration
// ConnectTimeout and Timeout are for the plugin's client: how long to wait for a
// connection, and how long a read or write may make no progress.
ConnectTimeout time.Duration
Timeout time.Duration
}
Rules are the rules for one delivery.
func DefaultRules ¶
func DefaultRules() Rules
DefaultRules are the rules a destination gets when nothing is set.
func RulesFrom ¶
func RulesFrom(base Rules, conn, opts map[string]any, aliases map[string]string) (Rules, []string, error)
RulesFrom reads the rules from a profile target's conn (connect_timeout, timeout, retries) and a destination entry's opts (if_exists, atomic, temp_dir), starting from base. aliases maps deprecated keys to these ({"upload_timeout": "timeout"}): an alias still works, with a warning. It returns the rules and the warnings.
type SQLDialect ¶
type SQLDialect struct {
Parser string `json:"parser"`
IdentifierQuote string `json:"identifier_quote"`
IdentifierCase string `json:"identifier_case"`
LiteralStyle string `json:"literal_style"`
HexLiteral *string `json:"hex_literal"`
DeniedFunctions []string `json:"denied_functions"`
FileFormats []string `json:"file_formats"`
ReadOnlyNotice *string `json:"read_only_notice"`
}
SQLDialect is the source-owned parsing and read-only policy advertised by describe. Missing fields fail closed in core; denied functions and file formats must be explicit.
type Session ¶
type Session interface {
// Run executes one statement and hands its result set to fn, or nil when the statement
// returned none. The result is only valid inside fn.
Run(sql string, fn func(Result) error) error
// Check verifies a statement without running it. A non-empty note (e.g. the bytes a
// statement would scan) is logged.
Check(sql string) (note string, err error)
// Load puts rows into a temporary table on the session. name is already checked to be a
// plain identifier.
Load(name string, schema *arrow.Schema, recs []arrow.RecordBatch) (Loaded, error)
Close()
}
Session is one database session: temp tables and settings made by one statement are there for the next. Tests use a fake.
type Store ¶
type Store interface {
Caps() Caps
// Write writes local to remote, creating its folders. With exclusive, it fails with ErrExists
// if something is there (only asked when Caps().CreateExclusive).
Write(local, remote string, exclusive bool) error
// Rename renames from to to, creating to's folders. Without replace, it fails with ErrExists
// if something is there (only asked when Caps().RenameNoReplace).
Rename(from, to string, replace bool) error
Exists(remote string) (bool, error)
// Delete removes remote; a missing file isn't an error.
Delete(remote string) error
}
Store is a destination's primitives. Paths are the destination's own (outbound/report.xlsx).
type TemporaryError ¶
TemporaryError is a failure trying again may fix: a dropped connection, a timeout before anything was accepted, a 429 or a 5xx. RetryAfter is the server's Retry-After.
func (*TemporaryError) Error ¶
func (e *TemporaryError) Error() string
func (*TemporaryError) Unwrap ¶
func (e *TemporaryError) Unwrap() error
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
Package plugintest drives a Go plugin's protocol loop over in-memory pipes, as core would.
|
Package plugintest drives a Go plugin's protocol loop over in-memory pipes, as core would. |