plugin

package module
v0.0.0-...-47ebb28 Latest Latest
Warning

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

Go to latest
Published: Nov 26, 2026 License: GPL-3.0 Imports: 30 Imported by: 1 module, 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 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

View Source
const (
	TagJSON  = 'J'
	TagArrow = 'A'
)
View Source
const (
	ProtocolMin = 1
	ProtocolMax = 1
)
View Source
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

Capabilities is every capability, in the schema's order.

View Source
var ErrEOF = errors.New("core closed the connection")

ErrEOF means core closed stdin between frames: a clean end.

View Source
var ErrExists = errors.New("a file is already there")

ErrExists means something is already at the path.

View Source
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 Bool

func Bool(conn map[string]any, key string, def bool) (bool, error)

Bool is a boolean field (true/false, or yes/no/1/0 as text), def when it isn't set.

func Cancelled

func Cancelled() bool

Cancelled reports whether core has cancelled the request running now. Long loops check it between steps.

func CheckConnection

func CheckConnection(r Role, conn map[string]any, unresolved []string) (errs, warns []string)

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 Closest

func Closest(key string, names []string) string

Closest is the name nearest key, when it's near enough to be a typo; "" otherwise.

func CompactJSON

func CompactJSON(c *array.String) arrow.Array

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

func DecodeRecords(b []byte) (*arrow.Schema, []arrow.RecordBatch, error)

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 Int

func Int(conn map[string]any, key string, def int64) (int64, error)

Int is an integer field, def when it isn't set; a value that isn't a number is an error.

func IsConnectionError

func IsConnectionError(err error) bool

IsConnectionError is whether err is a connection failing (refused, reset, timed out, closed early), which trying again may fix.

func Loopback

func Loopback(host string) bool

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 Number

func Number(v any) (int, bool)

Number is an integer field given as a number or a string.

func Optional

func Optional(conn map[string]any, key string) string

Optional is a string field, or "" when it isn't set. Numbers are given as their text.

func OutputSchema

func OutputSchema(s *arrow.Schema) *arrow.Schema

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

func ParseDuration(v any) (time.Duration, error)

ParseDuration reads `30s`, `5m`, `2h`, `1500ms`, or a bare number of seconds.

func Progress

func Progress(message string, done, total int64)

Progress tells core how far a long request has got (protocol 1; logged at info before).

func Required

func Required(conn map[string]any, key string) (string, error)

Required is a string field that must be set.

func Retry

func Retry[T any](r Rules, what string, f func() (T, error)) (T, error)

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

func RetryAfter(header string) time.Duration

RetryAfter is the Retry-After of a 429 or 503, in seconds (an HTTP date isn't read).

func SQLRows

func SQLRows(recs []arrow.RecordBatch, literal func(arrow.Array, int) string) ([]string, int64)

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

func Serve(stdin io.Reader, stdout io.Writer, p Package, r Role) (code int)

Serve speaks the protocol on stdin and stdout as role until core closes, and returns the process exit code.

func Strings

func Strings(conn map[string]any, key string) []string

Strings is a field holding a list of strings, or one string (comma-separated values are split).

func Unknown

func Unknown(conn map[string]any, fields []Field, also ...string) error

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 ValidName

func ValidName(name string) bool

ValidName is true for a plain identifier: letters, digits and underscores.

func WriteFileAtomic

func WriteFileAtomic(path string, data []byte, perm os.FileMode) error

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.

func WriteFrame

func WriteFrame(w *bufio.Writer, tag byte, body []byte) error

func WriteJSON

func WriteJSON(w *bufio.Writer, v any) error

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.

func Deliver

func Deliver(s Store, local, remote string, r Rules) (Delivered, error)

Deliver delivers local to remote under rules. It fails with an *Error: of kind delivery (with code file-exists for a file already at the path with `if_exists: error`), unless the store returned an *Error of its own.

type Error

type Error struct {
	Kind    string
	Code    string
	Message string
}

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`).

func (*Error) Error

func (e *Error) Error() string

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 Frame

type Frame struct {
	Tag  byte
	Body []byte // without the tag byte
}

func ReadFrame

func ReadFrame(r io.Reader) (Frame, error)

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 Loaded

type Loaded struct {
	Relation string
	Rows     int64
	Warning  string
}

Loaded is a Load's outcome; Warning is shown to the person when it isn't empty.

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

type Package struct {
	Version string
	Roles   []Role
}

Package is one plugin program: its version and every role it provides, in `provides` order.

func (Package) RoleFor

func (p Package) RoleFor(exe string) Role

RoleFor picks the role when core's hello doesn't name one, from the executable's name: dre-<kind>-* serves the first role of that kind, anything else the first role.

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.

func (*Request) Cancel

func (r *Request) Cancel()

Cancel ends the running request's context, if a request is running.

func (*Request) Start

func (r *Request) Start(parent context.Context) (ctx context.Context, done func())

Start is the running request's context, derived from parent. Call done when the request ends.

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.

func (Role) ID

func (r Role) ID() string

ID is the role as the protocol writes a plugin: `<kind>/<name>`.

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.

func (Rules) Wait

func (r Rules) Wait(attempt int, retryAfter time.Duration) time.Duration

Wait is how long to wait before try attempt+1: the server's Retry-After, else RetryWait doubled each try (or the default backoff), never more than MaxRetryWait.

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

type TemporaryError struct {
	Err        error
	RetryAfter time.Duration
}

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

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.

Jump to

Keyboard shortcuts

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