mygram

package module
v0.4.0 Latest Latest
Warning

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

Go to latest
Published: Jul 10, 2026 License: MIT Imports: 10 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.

README

go-mygram-client

CI Go Reference Go codecov License golangci-lint Zero Dependencies

Go client library for MygramDB — a high-performance in-memory full-text search engine with MySQL replication support.

Compatible with MygramDB v1.8 (unquoted raw boolean transport with OR groups nested under AND, date-only filter values), v1.7 (database-qualified tables, raw boolean search, runtime variables, on-demand sync), and v1.6 (BM25 scoring, HIGHLIGHT, FUZZY, FACET).

Overview

MygramDB provides 25-200x faster full-text search than MySQL FULLTEXT. This client communicates via MygramDB's TCP text protocol (memcached-style) with zero external dependencies.

MySQL FULLTEXT MygramDB
Search Speed Baseline 25-200x faster
Storage On-disk In-memory
Replication — MySQL binlog
Protocol MySQL TCP (memcached-style)
Features
  • Zero Dependencies — Standard library only
  • Context Support — All methods have context.Context variants
  • Search Expression Parser — Web-style search syntax (+required, -excluded, "phrase", OR, grouping)
  • Full Protocol Support — All MygramDB commands (SEARCH, COUNT, GET, INFO, etc.)
  • Input Validation — Built-in protection against control character injection
  • Thread Safe — Safe for concurrent use
  • Connection Pooling — Bounded Pool with reconnection and retry for high-throughput workloads
  • Resilience — Pool circuit breaker, observability events, TCP keep-alive, and client-level auto-reconnect

Installation

go get github.com/libraz/go-mygram-client

Quick Start

package main

import (
	"fmt"
	"log"

	mygram "github.com/libraz/go-mygram-client"
)

func main() {
	client := mygram.NewClient("localhost:11016")
	defer client.Close()

	if err := client.Connect(); err != nil {
		log.Fatal(err)
	}

	// Search
	resp, err := client.Search("articles", "hello", mygram.SearchOptions{
		Limit:      100,
		SortColumn: "created_at",
		SortDesc:   true,
	})
	if err != nil {
		log.Fatal(err)
	}
	fmt.Printf("Found %d results\n", resp.TotalCount)

	// Count
	count, err := client.Count("articles", "technology", mygram.CountOptions{})
	if err != nil {
		log.Fatal(err)
	}
	fmt.Printf("Count: %d\n", count.Count)

	// Get document by ID
	doc, err := client.Get("articles", "12345")
	if err != nil {
		log.Fatal(err)
	}
	fmt.Printf("Doc: %s %v\n", doc.PrimaryKey, doc.Fields)
}

Connection Pooling

A single Client wraps one connection and serializes commands, so it handles one request at a time. For concurrent workloads use a Pool, which lends out many connections up to a fixed cap and adds transparent reconnection and retry. It exposes the same command methods as Client, so it is a drop-in replacement.

pool := mygram.NewPool(mygram.PoolConfig{
	ClientConfig:    mygram.ClientConfig{Host: "localhost", Port: 11016},
	MaxOpenConns:    16,               // hard cap on total connections
	MaxIdleConns:    8,                // connections kept for reuse
	ConnMaxLifetime: 30 * time.Minute, // recycle old connections
})
defer pool.Close()

// Safe to call from many goroutines; each call borrows a connection.
resp, err := pool.Search("articles", "hello", mygram.SearchOptions{Limit: 100})

When every connection is busy, a call blocks until one is returned or its context is canceled — a natural backpressure signal. See Connection Pooling for sizing, retry semantics, and monitoring.

Documentation

  • Getting Started — install, configuration, and error handling
  • Search Expressions — parse web-style search input
  • API Reference — every method, option, and type
  • Advanced Usage — connection pooling with the v1.8 resilience features (circuit breaker, observability events, TCP keep-alive, auto-reconnect), and the MygramDB v1.6/v1.7 features (BM25 _score, fuzzy, highlighting, facets, multi-database, raw boolean search, runtime variables, on-demand sync)

Japanese docs live under docs/ja/. Package-level API docs are also on pkg.go.dev.

Development

make test       # Run unit tests
make test-race  # Run unit tests with race detector
make test-e2e   # Run e2e tests against a live MygramDB server
make test-e2e-docker # Spin up MySQL + MygramDB (docker compose), run e2e, tear down
make lint       # Run golangci-lint
make fmt        # Format code
make coverage   # Generate coverage report
End-to-end tests

make test-e2e exercises every public method against a running MygramDB instance. Tests are gated by the e2e build tag, so the default go test ./... (and CI) never connect to a server.

# Default: connect to 127.0.0.1:11016
make test-e2e

# Override the endpoint
MYGRAM_HOST=db.example.com MYGRAM_PORT=11016 make test-e2e

# Skip side-effect heavy suites
MYGRAM_E2E_SKIP_DUMP=1 MYGRAM_E2E_SKIP_REPLICATION=1 make test-e2e

If the server is unreachable, every e2e test is skipped (not failed). Suites that mutate global server state (replication start/stop, cache toggle, dump round-trip) restore the original state on exit.

Self-contained docker-compose stack

make test-e2e-docker brings up a throwaway MySQL + MygramDB stack (the server is pulled from ghcr.io/libraz/mygram-db), seeds it with a deterministic dataset, runs the e2e suite with MYGRAM_E2E_SEEDED=1, then tears everything down. No local server is required. See e2e/docker/ for knobs (MYGRAMDB_VERSION, KEEP_UP, ports). The TestE2ESeeded block asserts exact result sets (database-qualified identity, phrase + required-filter visibility, Japanese ngram matching, SearchRaw OR, facet counts).

License

MIT

Documentation

Overview

Package mygram is a Go client library for the MygramDB full-text search engine.

MygramDB is an in-memory full-text search engine using a memcached-style text protocol, providing 25-200x faster search performance compared to MySQL FULLTEXT.

Basic usage:

client := mygram.NewClient("localhost:11016")
defer client.Close()

if err := client.Connect(); err != nil {
    log.Fatal(err)
}

resp, err := client.Search("threads", "keyword", mygram.SearchOptions{
    Limit:      100,
    SortColumn: "created_at",
    SortDesc:   true,
})

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func ConvertSearchExpression

func ConvertSearchExpression(expression string) (string, error)

ConvertSearchExpression converts a search expression to a MygramDB query string.

func HasComplexExpression

func HasComplexExpression(expr *SearchExpression) bool

HasComplexExpression returns whether the expression contains OR or grouping.

func ParseTableIdentity added in v0.3.0

func ParseTableIdentity(identity string) (database, table string, err error)

ParseTableIdentity splits a (possibly database-qualified) table identity into its parts.

Bare names return an empty database and the table name; qualified names are split on the first '.' so "app_db.articles" yields ("app_db", "articles"). The identity is validated as a protocol identifier first.

func QualifyTableIdentity added in v0.3.0

func QualifyTableIdentity(table, database string) (string, error)

QualifyTableIdentity builds a database-qualified table identity ("database.table") for MygramDB v1.7+ multi-database deployments.

A single-database deployment continues to accept a bare table name, so an empty database returns just the validated table name. When a database is supplied, both parts are validated as identifiers and must not themselves contain a '.' separator; they are then joined as "database.table".

func ToQueryString

func ToQueryString(expr *SearchExpression) string

ToQueryString converts a SearchExpression to a MygramDB query string.

Types

type CacheStats

type CacheStats struct {
	Enabled        bool
	Hits           int
	Misses         int
	HitRate        float64
	CurrentEntries int
	MemoryBytes    int
	Evictions      int
}

CacheStats represents cache statistics.

type CircuitBreakerConfig added in v0.4.0

type CircuitBreakerConfig struct {
	// FailureThreshold is the number of consecutive network failures that open
	// the breaker. 0 or negative selects the default (5).
	FailureThreshold int

	// ResetTimeout is how long the breaker stays open before admitting a trial.
	// 0 or negative selects the default (10s).
	ResetTimeout time.Duration
}

CircuitBreakerConfig configures a Pool's circuit breaker. Consecutive connect/timeout failures up to FailureThreshold open the breaker; it stays open for ResetTimeout, then admits a single trial (half-open) before closing on success or re-opening on failure. Set PoolConfig.CircuitBreaker to enable it; a nil pointer disables it.

type CircuitOpenError added in v0.4.0

type CircuitOpenError struct {
	Message string
}

CircuitOpenError is returned by a Pool whose circuit breaker is open (or half-open with a trial already in flight). It is raised without touching the network so a caller fails fast instead of piling requests onto a server that is already unreachable. It is not classified as a network failure, so it does not itself drive the breaker.

func (*CircuitOpenError) Error added in v0.4.0

func (e *CircuitOpenError) Error() string

type Client

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

Client is a MygramDB client.

A Client wraps a single connection and serializes every command with an internal mutex, so it is safe for concurrent use but processes at most one request at a time. For concurrent workloads use a Pool, which lends out many Clients and adds reconnection and retry.

func NewClient

func NewClient(addr string) *Client

NewClient creates a new client for the given address. addr should be in "host:port" form; an address that does not parse as host:port is treated as a Unix socket path (so a bare "localhost" without a port becomes a socket path, not a TCP host).

The returned Client owns a single connection and must be connected with Connect (or ConnectContext) before issuing commands. Most applications should use NewPool instead, which manages many connections with reconnection and retry; use Client directly only to own and control a single connection.

func NewClientWithConfig

func NewClientWithConfig(config ClientConfig) *Client

NewClientWithConfig creates a new client with the given configuration.

func (*Client) CacheClear

func (c *Client) CacheClear(table string) error

CacheClear clears the cache. If table is specified, only that table's cache is cleared.

func (*Client) CacheClearContext

func (c *Client) CacheClearContext(ctx context.Context, table string) error

CacheClearContext clears the cache with the given context.

func (*Client) CacheDisable

func (c *Client) CacheDisable() error

CacheDisable disables the cache.

func (*Client) CacheDisableContext

func (c *Client) CacheDisableContext(ctx context.Context) error

CacheDisableContext disables the cache with the given context.

func (*Client) CacheEnable

func (c *Client) CacheEnable() error

CacheEnable enables the cache.

func (*Client) CacheEnableContext

func (c *Client) CacheEnableContext(ctx context.Context) error

CacheEnableContext enables the cache with the given context.

func (*Client) CacheStats

func (c *Client) CacheStats() (*CacheStats, error)

CacheStats retrieves cache statistics.

func (*Client) CacheStatsContext

func (c *Client) CacheStatsContext(ctx context.Context) (*CacheStats, error)

CacheStatsContext retrieves cache statistics with the given context.

func (*Client) Close

func (c *Client) Close() error

Close closes the connection.

func (*Client) Connect

func (c *Client) Connect() error

Connect establishes a connection to the server.

func (*Client) ConnectContext

func (c *Client) ConnectContext(ctx context.Context) error

ConnectContext establishes a connection to the server with the given context.

func (*Client) Count

func (c *Client) Count(table, query string, opts CountOptions) (*CountResponse, error)

Count returns the number of matching documents.

func (*Client) CountContext

func (c *Client) CountContext(ctx context.Context, table, query string, opts CountOptions) (*CountResponse, error)

CountContext performs a count query with the given context.

func (*Client) DisableDebug

func (c *Client) DisableDebug() error

DisableDebug disables debug mode.

func (*Client) DisableDebugContext

func (c *Client) DisableDebugContext(ctx context.Context) error

DisableDebugContext disables debug mode with the given context.

func (*Client) DumpInfo

func (c *Client) DumpInfo(filepath string) (string, error)

DumpInfo retrieves metadata of a dump file.

func (*Client) DumpInfoContext

func (c *Client) DumpInfoContext(ctx context.Context, filepath string) (string, error)

DumpInfoContext retrieves metadata of a dump file with the given context.

func (*Client) DumpLoad

func (c *Client) DumpLoad(filepath string) error

DumpLoad loads the index from a file.

func (*Client) DumpLoadContext

func (c *Client) DumpLoadContext(ctx context.Context, filepath string) error

DumpLoadContext loads the index from a file with the given context.

func (*Client) DumpSave

func (c *Client) DumpSave(filepath string) (string, error)

DumpSave saves the index to a file.

func (*Client) DumpSaveContext

func (c *Client) DumpSaveContext(ctx context.Context, filepath string) (string, error)

DumpSaveContext saves the index to a file with the given context.

func (*Client) DumpStatus

func (c *Client) DumpStatus() (*DumpStatus, error)

DumpStatus retrieves the status of a dump operation.

func (*Client) DumpStatusContext

func (c *Client) DumpStatusContext(ctx context.Context) (*DumpStatus, error)

DumpStatusContext retrieves the status of a dump operation with the given context.

func (*Client) DumpVerify

func (c *Client) DumpVerify(filepath string) (string, error)

DumpVerify verifies the integrity of a dump file.

func (*Client) DumpVerifyContext

func (c *Client) DumpVerifyContext(ctx context.Context, filepath string) (string, error)

DumpVerifyContext verifies the integrity of a dump file with the given context.

func (*Client) EnableDebug

func (c *Client) EnableDebug() error

EnableDebug enables debug mode.

func (*Client) EnableDebugContext

func (c *Client) EnableDebugContext(ctx context.Context) error

EnableDebugContext enables debug mode with the given context.

func (*Client) Facet added in v0.2.0

func (c *Client) Facet(table, column string, opts FacetOptions) (*FacetResponse, error)

Facet aggregates distinct values of a filter column with their document counts. Optionally scoped to a search result set via opts.Query and related options. Available on MygramDB >= v1.6.

func (*Client) FacetContext added in v0.2.0

func (c *Client) FacetContext(ctx context.Context, table, column string, opts FacetOptions) (*FacetResponse, error)

FacetContext is the context-aware variant of Facet.

func (*Client) Get

func (c *Client) Get(table, primaryKey string) (*Document, error)

Get retrieves a document by its primary key.

func (*Client) GetConfig

func (c *Client) GetConfig() (string, error)

GetConfig retrieves server configuration in YAML format.

func (*Client) GetConfigContext

func (c *Client) GetConfigContext(ctx context.Context) (string, error)

GetConfigContext retrieves server configuration with the given context.

func (*Client) GetContext

func (c *Client) GetContext(ctx context.Context, table, primaryKey string) (*Document, error)

GetContext retrieves a document by its primary key with the given context.

func (*Client) GetReplicationStatus

func (c *Client) GetReplicationStatus() (*ReplicationStatus, error)

GetReplicationStatus retrieves the replication status.

func (*Client) GetReplicationStatusContext

func (c *Client) GetReplicationStatusContext(ctx context.Context) (*ReplicationStatus, error)

GetReplicationStatusContext retrieves the replication status with the given context.

func (*Client) Info

func (c *Client) Info() (*ServerInfo, error)

Info retrieves server information.

func (*Client) InfoContext

func (c *Client) InfoContext(ctx context.Context) (*ServerInfo, error)

InfoContext retrieves server information with the given context.

func (*Client) IsConnected

func (c *Client) IsConnected() bool

IsConnected returns whether the client is currently connected.

func (*Client) Optimize

func (c *Client) Optimize(table string) error

Optimize optimizes the index. If table is specified, only that table's index is optimized.

func (*Client) OptimizeContext

func (c *Client) OptimizeContext(ctx context.Context, table string) error

OptimizeContext optimizes the index with the given context.

func (*Client) Search

func (c *Client) Search(table, query string, opts SearchOptions) (*SearchResponse, error)

Search performs a full-text search.

func (*Client) SearchContext

func (c *Client) SearchContext(ctx context.Context, table, query string, opts SearchOptions) (*SearchResponse, error)

SearchContext performs a full-text search with the given context.

func (*Client) SearchRaw added in v0.3.0

func (c *Client) SearchRaw(table, rawQuery string, opts SearchRawOptions) (*SearchResponse, error)

SearchRaw searches using a pre-built boolean expression (MygramDB >= v1.8).

The expression is sent verbatim (unquoted) so the server tokenizes it and its AST parser can interpret AND / OR / NOT / parentheses, including OR groups nested under AND such as "alpha AND (beta OR gamma)". A quoted expression would be treated by a v1.8 server as a single literal phrase, so quoting is intentionally not applied. Pair this with ConvertSearchExpression to preserve OR / grouping semantics that Search's AND/NOT decomposition cannot express.

func (*Client) SearchRawContext added in v0.3.0

func (c *Client) SearchRawContext(ctx context.Context, table, rawQuery string, opts SearchRawOptions) (*SearchResponse, error)

SearchRawContext is the context-aware variant of SearchRaw.

func (*Client) SearchRawWithHighlights added in v0.3.0

func (c *Client) SearchRawWithHighlights(table, rawQuery string, opts SearchRawOptions) (*SearchResponse, error)

SearchRawWithHighlights is a SearchRaw variant that requests highlighted snippets. Any highlight options passed in opts are preserved; otherwise server defaults are used.

func (*Client) SearchRawWithHighlightsContext added in v0.3.0

func (c *Client) SearchRawWithHighlightsContext(ctx context.Context, table, rawQuery string, opts SearchRawOptions) (*SearchResponse, error)

SearchRawWithHighlightsContext is the context-aware variant of SearchRawWithHighlights.

func (*Client) SearchWithHighlights added in v0.3.0

func (c *Client) SearchWithHighlights(table, query string, opts SearchOptions) (*SearchResponse, error)

SearchWithHighlights is a Search variant that requests highlighted snippets. Any highlight options passed in opts are preserved; otherwise server defaults are used. Snippets are returned in SearchResult.Snippet. Requires MygramDB >= v1.6.

func (*Client) SearchWithHighlightsContext added in v0.3.0

func (c *Client) SearchWithHighlightsContext(ctx context.Context, table, query string, opts SearchOptions) (*SearchResponse, error)

SearchWithHighlightsContext is the context-aware variant of SearchWithHighlights.

func (*Client) SendCommand

func (c *Client) SendCommand(command string) (string, error)

SendCommand sends a raw command to the server and returns the response.

func (*Client) SendCommandContext

func (c *Client) SendCommandContext(ctx context.Context, command string) (string, error)

SendCommandContext sends a raw command to the server with the given context.

The context bounds how long the call waits: its deadline, if any, caps the I/O timeout, and a context that is already canceled or past its deadline fails fast before anything is sent. Once the request is in flight, cancellation of a deadline-less context does not interrupt it; the command still completes or hits TimeoutMs.

func (*Client) SetVariable added in v0.3.0

func (c *Client) SetVariable(name, value string) error

SetVariable sets a runtime variable (MygramDB >= v1.7, MySQL-compatible SET).

func (*Client) SetVariableContext added in v0.3.0

func (c *Client) SetVariableContext(ctx context.Context, name, value string) error

SetVariableContext sets a runtime variable with the given context.

func (*Client) ShowVariables added in v0.3.0

func (c *Client) ShowVariables(likePattern string) (string, error)

ShowVariables shows runtime variables (MygramDB >= v1.7, MySQL-compatible SHOW VARIABLES). An empty likePattern lists every variable; a non-empty pattern is matched MySQL-style (e.g. "logging%"). The raw server response is returned unparsed.

func (*Client) ShowVariablesContext added in v0.3.0

func (c *Client) ShowVariablesContext(ctx context.Context, likePattern string) (string, error)

ShowVariablesContext is the context-aware variant of ShowVariables.

func (*Client) StartReplication

func (c *Client) StartReplication() error

StartReplication starts replication.

func (*Client) StartReplicationContext

func (c *Client) StartReplicationContext(ctx context.Context) error

StartReplicationContext starts replication with the given context.

func (*Client) StopReplication

func (c *Client) StopReplication() error

StopReplication stops replication.

func (*Client) StopReplicationContext

func (c *Client) StopReplicationContext(ctx context.Context) error

StopReplicationContext stops replication with the given context.

func (*Client) Sync added in v0.3.0

func (c *Client) Sync(table string) (string, error)

Sync starts an on-demand sync (full reload) of a table (MygramDB >= v1.7). The raw server acknowledgement is returned.

func (*Client) SyncContext added in v0.3.0

func (c *Client) SyncContext(ctx context.Context, table string) (string, error)

SyncContext is the context-aware variant of Sync.

func (*Client) SyncStatus added in v0.3.0

func (c *Client) SyncStatus() (string, error)

SyncStatus retrieves the status of in-flight and recent sync operations (MygramDB >= v1.7). The raw SYNC_STATUS report is returned unparsed.

func (*Client) SyncStatusContext added in v0.3.0

func (c *Client) SyncStatusContext(ctx context.Context) (string, error)

SyncStatusContext is the context-aware variant of SyncStatus.

func (*Client) SyncStop added in v0.3.0

func (c *Client) SyncStop(table string) (string, error)

SyncStop stops a running sync (MygramDB >= v1.7). With an empty table, every in-flight sync is stopped; with a table, only that table's sync is stopped.

func (*Client) SyncStopContext added in v0.3.0

func (c *Client) SyncStopContext(ctx context.Context, table string) (string, error)

SyncStopContext is the context-aware variant of SyncStop.

type ClientConfig

type ClientConfig struct {
	// Host is the server hostname or IP address. Default is "127.0.0.1".
	Host string

	// Port is the server port number. Default is 11016.
	Port int

	// SocketPath is the Unix domain socket path. When specified, it takes priority over TCP.
	SocketPath string

	// TimeoutMs is the command timeout in milliseconds. Default is 5000.
	//
	// This field is milliseconds (an int) for parity with the other language
	// clients. The pool-level limits (PoolConfig.ConnMaxLifetime and friends)
	// are time.Duration; mind the difference when configuring both.
	TimeoutMs int

	// RecvBufferSize is the receive buffer size. Default is 65536.
	RecvBufferSize int

	// MaxQueryLength is the maximum length of a query expression. 0 means unlimited. Default is 128.
	MaxQueryLength int

	// MaxResponseSize is the maximum accepted response size in bytes. When a
	// response exceeds it, the read is aborted with a ProtocolError and the
	// connection is closed (its stream position is no longer known). 0 means
	// unlimited, which is the default for backward compatibility. A bounded
	// value (for example 64<<20) is recommended to guard against a runaway or
	// malformed response exhausting memory.
	MaxResponseSize int

	// AutoReconnect transparently re-establishes a dropped connection. When
	// enabled, SendCommandContext reconnects once and resends the command if
	// the socket is found dead *before* the request is written. A disconnect
	// that occurs *after* the request was sent is surfaced as a ConnectionError
	// without resending, since the command may already have been applied
	// server-side. Default is false (legacy behavior). A Pool always enables it
	// on the connections it owns so a transient drop is absorbed on the slot.
	AutoReconnect bool

	// DisableTCPKeepAlive turns off the client's SO_KEEPALIVE idle override on
	// TCP connections. The zero value keeps keep-alive enabled with the
	// TCPKeepAliveIdle period, so a silently dropped peer is detected without
	// waiting for the next command's read timeout. Set it to true to leave the
	// dialer's built-in keep-alive default in place instead. Ignored for
	// Unix-socket connections. Defaulting keep-alive on this way keeps the
	// behavior identical whether a client is built with NewClient or with
	// NewClientWithConfig/NewPool.
	DisableTCPKeepAlive bool

	// TCPKeepAliveIdle is the idle period before keep-alive probing begins.
	// Applies unless DisableTCPKeepAlive is set. 0 selects the default (60s).
	TCPKeepAliveIdle time.Duration
}

ClientConfig holds connection settings for the MygramDB server.

func DefaultConfig

func DefaultConfig() ClientConfig

DefaultConfig returns the default configuration.

type ConnectionError

type ConnectionError struct {
	Message string
	Err     error
	// contains filtered or unexported fields
}

ConnectionError is an error returned when a connection fails.

func (*ConnectionError) Error

func (e *ConnectionError) Error() string

func (*ConnectionError) Unwrap

func (e *ConnectionError) Unwrap() error

type CountOptions

type CountOptions struct {
	// AndTerms is a list of additional keywords combined with AND.
	AndTerms []string

	// NotTerms is a list of keywords to exclude with NOT.
	NotTerms []string

	// Filters is a map of column filter conditions (key=value).
	Filters map[string]string
}

CountOptions holds options for a count request.

type CountResponse

type CountResponse struct {
	// Count is the number of matched documents.
	Count int

	// Debug contains debug information (only available when debug mode is enabled).
	Debug *DebugInfo
}

CountResponse represents a count response.

type DebugInfo

type DebugInfo struct {
	QueryTimeMs       float64
	IndexTimeMs       float64
	FilterTimeMs      float64
	Terms             int
	Ngrams            int
	Candidates        int
	AfterIntersection int
	AfterNot          int
	AfterFilters      int
	Final             int
	Optimization      string
	Sort              string
	Cache             string
	CacheAgeMs        float64
	CacheSavedMs      float64
	Limit             int
	Offset            int
}

DebugInfo holds query metrics from debug mode.

type Document

type Document struct {
	// PrimaryKey is the document's primary key.
	PrimaryKey string

	// Fields is a map of filter column key-value pairs.
	Fields map[string]string
}

Document represents a document retrieved by GET.

type DumpStatus

type DumpStatus struct {
	SaveInProgress  bool
	LoadInProgress  bool
	Status          string
	Filepath        string
	TablesProcessed int
	TablesTotal     int
	CurrentTable    string
	ElapsedSeconds  float64
	ResultFilepath  string
	Error           string
}

DumpStatus represents the status of a dump operation.

type FacetOptions added in v0.2.0

type FacetOptions struct {
	// Query, when non-empty, scopes the facet aggregation to documents
	// matching the given search text (same semantics as SEARCH).
	Query string

	// AndTerms is a list of additional keywords combined with AND.
	AndTerms []string

	// NotTerms is a list of keywords to exclude with NOT.
	NotTerms []string

	// Filters is a map of column filter conditions (key=value).
	Filters map[string]string

	// Limit bounds the number of returned (value, count) pairs.
	// 0 means "no limit".
	Limit int
}

FacetOptions holds options for a FACET request. Introduced in MygramDB v1.6.

type FacetResponse added in v0.2.0

type FacetResponse struct {
	// Results is the list of (value, count) pairs ordered by count
	// descending.
	Results []FacetValue
}

FacetResponse is the response to a FACET command.

type FacetValue added in v0.2.0

type FacetValue struct {
	// Value is the facet column's distinct value as a string.
	Value string

	// Count is the number of documents that have this value.
	Count int64
}

FacetValue is a single aggregated (value, count) pair returned by the FACET command.

type HighlightOptions added in v0.2.0

type HighlightOptions struct {
	// OpenTag is the tag inserted before each matched term. When empty
	// the server default ("<em>") is used.
	OpenTag string

	// CloseTag is the tag inserted after each matched term. When empty
	// the server default ("</em>") is used.
	//
	// OpenTag and CloseTag must be set (or unset) together.
	CloseTag string

	// SnippetLen is the maximum number of code points per snippet
	// fragment. Valid range is 1..10000. 0 means "use server default"
	// (100).
	SnippetLen int

	// MaxFragments is the maximum number of snippet fragments joined by
	// ellipsis. Valid range is 1..100. 0 means "use server default" (3).
	MaxFragments int
}

HighlightOptions configures the HIGHLIGHT clause introduced in MygramDB v1.6. A zero-value HighlightOptions requests default highlighting ("<em>"/"</em>" tags, 100 code point snippets, up to 3 fragments).

type Pool added in v0.4.0

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

Pool is a bounded pool of MygramDB connections. It exposes the same command methods as Client; for each call it borrows a connection, runs the request, and returns the connection to the pool, transparently reconnecting and retrying where it is safe to do so. A Pool is safe for concurrent use.

The token accounting maintains the invariant that the number of open connections (idle plus in use) never exceeds MaxOpenConns: every connection holds exactly one slot in sem from the moment it is dialed until it is closed. Idle connections keep their slot while parked in the idle channel.

func NewPool added in v0.4.0

func NewPool(cfg PoolConfig) *Pool

NewPool creates a pool with the given configuration. It performs no I/O; connections are opened lazily on first use.

func (*Pool) CacheClear added in v0.4.0

func (p *Pool) CacheClear(table string) error

CacheClear clears the cache.

func (*Pool) CacheClearContext added in v0.4.0

func (p *Pool) CacheClearContext(ctx context.Context, table string) error

CacheClearContext clears the cache with the given context.

func (*Pool) CacheDisable added in v0.4.0

func (p *Pool) CacheDisable() error

CacheDisable disables the cache.

func (*Pool) CacheDisableContext added in v0.4.0

func (p *Pool) CacheDisableContext(ctx context.Context) error

CacheDisableContext disables the cache with the given context.

func (*Pool) CacheEnable added in v0.4.0

func (p *Pool) CacheEnable() error

CacheEnable enables the cache.

func (*Pool) CacheEnableContext added in v0.4.0

func (p *Pool) CacheEnableContext(ctx context.Context) error

CacheEnableContext enables the cache with the given context.

func (*Pool) CacheStats added in v0.4.0

func (p *Pool) CacheStats() (*CacheStats, error)

CacheStats retrieves cache statistics.

func (*Pool) CacheStatsContext added in v0.4.0

func (p *Pool) CacheStatsContext(ctx context.Context) (*CacheStats, error)

CacheStatsContext retrieves cache statistics with the given context.

func (*Pool) Close added in v0.4.0

func (p *Pool) Close() error

Close closes the pool. Idle connections are closed immediately; connections currently in use are closed when they are returned. After Close, command methods return a ConnectionError. Close is idempotent.

func (*Pool) Count added in v0.4.0

func (p *Pool) Count(table, query string, opts CountOptions) (*CountResponse, error)

Count returns the number of matching documents.

func (*Pool) CountContext added in v0.4.0

func (p *Pool) CountContext(ctx context.Context, table, query string, opts CountOptions) (*CountResponse, error)

CountContext performs a count query with the given context.

func (*Pool) DisableDebug added in v0.4.0

func (p *Pool) DisableDebug() error

DisableDebug disables debug mode.

func (*Pool) DisableDebugContext added in v0.4.0

func (p *Pool) DisableDebugContext(ctx context.Context) error

DisableDebugContext disables debug mode with the given context.

func (*Pool) DumpInfo added in v0.4.0

func (p *Pool) DumpInfo(filepath string) (string, error)

DumpInfo retrieves metadata of a dump file.

func (*Pool) DumpInfoContext added in v0.4.0

func (p *Pool) DumpInfoContext(ctx context.Context, filepath string) (string, error)

DumpInfoContext retrieves metadata of a dump file with the given context.

func (*Pool) DumpLoad added in v0.4.0

func (p *Pool) DumpLoad(filepath string) error

DumpLoad loads the index from a file.

func (*Pool) DumpLoadContext added in v0.4.0

func (p *Pool) DumpLoadContext(ctx context.Context, filepath string) error

DumpLoadContext loads the index from a file with the given context.

func (*Pool) DumpSave added in v0.4.0

func (p *Pool) DumpSave(filepath string) (string, error)

DumpSave saves the index to a file.

func (*Pool) DumpSaveContext added in v0.4.0

func (p *Pool) DumpSaveContext(ctx context.Context, filepath string) (string, error)

DumpSaveContext saves the index to a file with the given context.

func (*Pool) DumpStatus added in v0.4.0

func (p *Pool) DumpStatus() (*DumpStatus, error)

DumpStatus retrieves the status of a dump operation.

func (*Pool) DumpStatusContext added in v0.4.0

func (p *Pool) DumpStatusContext(ctx context.Context) (*DumpStatus, error)

DumpStatusContext retrieves the status of a dump operation with the given context.

func (*Pool) DumpVerify added in v0.4.0

func (p *Pool) DumpVerify(filepath string) (string, error)

DumpVerify verifies the integrity of a dump file.

func (*Pool) DumpVerifyContext added in v0.4.0

func (p *Pool) DumpVerifyContext(ctx context.Context, filepath string) (string, error)

DumpVerifyContext verifies the integrity of a dump file with the given context.

func (*Pool) EnableDebug added in v0.4.0

func (p *Pool) EnableDebug() error

EnableDebug enables debug mode.

func (*Pool) EnableDebugContext added in v0.4.0

func (p *Pool) EnableDebugContext(ctx context.Context) error

EnableDebugContext enables debug mode with the given context.

func (*Pool) Facet added in v0.4.0

func (p *Pool) Facet(table, column string, opts FacetOptions) (*FacetResponse, error)

Facet aggregates distinct values of a filter column with their document counts.

func (*Pool) FacetContext added in v0.4.0

func (p *Pool) FacetContext(ctx context.Context, table, column string, opts FacetOptions) (*FacetResponse, error)

FacetContext is the context-aware variant of Facet.

func (*Pool) Get added in v0.4.0

func (p *Pool) Get(table, primaryKey string) (*Document, error)

Get retrieves a document by its primary key.

func (*Pool) GetConfig added in v0.4.0

func (p *Pool) GetConfig() (string, error)

GetConfig retrieves server configuration in YAML format.

func (*Pool) GetConfigContext added in v0.4.0

func (p *Pool) GetConfigContext(ctx context.Context) (string, error)

GetConfigContext retrieves server configuration with the given context.

func (*Pool) GetContext added in v0.4.0

func (p *Pool) GetContext(ctx context.Context, table, primaryKey string) (*Document, error)

GetContext retrieves a document by its primary key with the given context.

func (*Pool) GetReplicationStatus added in v0.4.0

func (p *Pool) GetReplicationStatus() (*ReplicationStatus, error)

GetReplicationStatus retrieves the replication status.

func (*Pool) GetReplicationStatusContext added in v0.4.0

func (p *Pool) GetReplicationStatusContext(ctx context.Context) (*ReplicationStatus, error)

GetReplicationStatusContext retrieves the replication status with the given context.

func (*Pool) Info added in v0.4.0

func (p *Pool) Info() (*ServerInfo, error)

Info retrieves server information.

func (*Pool) InfoContext added in v0.4.0

func (p *Pool) InfoContext(ctx context.Context) (*ServerInfo, error)

InfoContext retrieves server information with the given context.

func (*Pool) Optimize added in v0.4.0

func (p *Pool) Optimize(table string) error

Optimize optimizes the index.

func (*Pool) OptimizeContext added in v0.4.0

func (p *Pool) OptimizeContext(ctx context.Context, table string) error

OptimizeContext optimizes the index with the given context.

func (*Pool) Search added in v0.4.0

func (p *Pool) Search(table, query string, opts SearchOptions) (*SearchResponse, error)

Search performs a full-text search.

func (*Pool) SearchContext added in v0.4.0

func (p *Pool) SearchContext(ctx context.Context, table, query string, opts SearchOptions) (*SearchResponse, error)

SearchContext performs a full-text search with the given context.

func (*Pool) SearchRaw added in v0.4.0

func (p *Pool) SearchRaw(table, rawQuery string, opts SearchRawOptions) (*SearchResponse, error)

SearchRaw searches using a pre-built boolean expression.

func (*Pool) SearchRawContext added in v0.4.0

func (p *Pool) SearchRawContext(ctx context.Context, table, rawQuery string, opts SearchRawOptions) (*SearchResponse, error)

SearchRawContext is the context-aware variant of SearchRaw.

func (*Pool) SearchRawWithHighlights added in v0.4.0

func (p *Pool) SearchRawWithHighlights(table, rawQuery string, opts SearchRawOptions) (*SearchResponse, error)

SearchRawWithHighlights is a SearchRaw variant that requests highlighted snippets.

func (*Pool) SearchRawWithHighlightsContext added in v0.4.0

func (p *Pool) SearchRawWithHighlightsContext(ctx context.Context, table, rawQuery string, opts SearchRawOptions) (*SearchResponse, error)

SearchRawWithHighlightsContext is the context-aware variant of SearchRawWithHighlights.

func (*Pool) SearchWithHighlights added in v0.4.0

func (p *Pool) SearchWithHighlights(table, query string, opts SearchOptions) (*SearchResponse, error)

SearchWithHighlights is a Search variant that requests highlighted snippets.

func (*Pool) SearchWithHighlightsContext added in v0.4.0

func (p *Pool) SearchWithHighlightsContext(ctx context.Context, table, query string, opts SearchOptions) (*SearchResponse, error)

SearchWithHighlightsContext is the context-aware variant of SearchWithHighlights.

func (*Pool) SendCommand added in v0.4.0

func (p *Pool) SendCommand(command string) (string, error)

SendCommand sends a raw command to the server and returns the response.

func (*Pool) SendCommandContext added in v0.4.0

func (p *Pool) SendCommandContext(ctx context.Context, command string) (string, error)

SendCommandContext sends a raw command with the given context. Raw commands are treated as state-changing and are never retried after they reach the server.

func (*Pool) SetVariable added in v0.4.0

func (p *Pool) SetVariable(name, value string) error

SetVariable sets a runtime variable.

func (*Pool) SetVariableContext added in v0.4.0

func (p *Pool) SetVariableContext(ctx context.Context, name, value string) error

SetVariableContext sets a runtime variable with the given context.

func (*Pool) ShowVariables added in v0.4.0

func (p *Pool) ShowVariables(likePattern string) (string, error)

ShowVariables shows runtime variables.

func (*Pool) ShowVariablesContext added in v0.4.0

func (p *Pool) ShowVariablesContext(ctx context.Context, likePattern string) (string, error)

ShowVariablesContext is the context-aware variant of ShowVariables.

func (*Pool) StartReplication added in v0.4.0

func (p *Pool) StartReplication() error

StartReplication starts replication.

func (*Pool) StartReplicationContext added in v0.4.0

func (p *Pool) StartReplicationContext(ctx context.Context) error

StartReplicationContext starts replication with the given context.

func (*Pool) Stats added in v0.4.0

func (p *Pool) Stats() PoolStats

Stats returns a snapshot of the pool's current statistics.

func (*Pool) StopReplication added in v0.4.0

func (p *Pool) StopReplication() error

StopReplication stops replication.

func (*Pool) StopReplicationContext added in v0.4.0

func (p *Pool) StopReplicationContext(ctx context.Context) error

StopReplicationContext stops replication with the given context.

func (*Pool) Sync added in v0.4.0

func (p *Pool) Sync(table string) (string, error)

Sync starts an on-demand sync (full reload) of a table.

func (*Pool) SyncContext added in v0.4.0

func (p *Pool) SyncContext(ctx context.Context, table string) (string, error)

SyncContext is the context-aware variant of Sync.

func (*Pool) SyncStatus added in v0.4.0

func (p *Pool) SyncStatus() (string, error)

SyncStatus retrieves the status of in-flight and recent sync operations.

func (*Pool) SyncStatusContext added in v0.4.0

func (p *Pool) SyncStatusContext(ctx context.Context) (string, error)

SyncStatusContext is the context-aware variant of SyncStatus.

func (*Pool) SyncStop added in v0.4.0

func (p *Pool) SyncStop(table string) (string, error)

SyncStop stops a running sync.

func (*Pool) SyncStopContext added in v0.4.0

func (p *Pool) SyncStopContext(ctx context.Context, table string) (string, error)

SyncStopContext is the context-aware variant of SyncStop.

func (*Pool) WithConn added in v0.4.0

func (p *Pool) WithConn(ctx context.Context, fn func(c *Client) error) error

WithConn borrows a single connection and runs fn against it. Use it to run a sequence of requests on one connection, or a request whose retry semantics you want to control yourself. The pool applies no retries around fn. The connection is returned to the pool afterwards, or discarded if fn reports a connection-level failure.

type PoolConfig added in v0.4.0

type PoolConfig struct {
	ClientConfig

	// MaxOpenConns bounds the total number of connections (idle plus in use).
	// A borrow that would exceed it blocks until a connection is returned or
	// the context is canceled. 0 or negative means the default (10). There is
	// deliberately no "unlimited" option: an explicit cap is the point.
	MaxOpenConns int

	// MaxIdleConns bounds how many idle connections are retained for reuse.
	// 0 or negative means "same as MaxOpenConns". Values above MaxOpenConns are
	// clamped to MaxOpenConns.
	MaxIdleConns int

	// ConnMaxLifetime is the maximum age of a connection measured from when it
	// was opened. Expired connections are discarded on borrow, and a background
	// reaper also sweeps idle ones so a quiet pool does not keep them open. 0
	// means no limit.
	ConnMaxLifetime time.Duration

	// ConnMaxIdleTime is the maximum time a connection may sit idle before it
	// is discarded. It is enforced both on borrow and by the background reaper.
	// 0 means no limit.
	ConnMaxIdleTime time.Duration

	// Retry is the retry policy for idempotent and never-sent commands. A zero
	// value selects the default policy.
	Retry RetryPolicy

	// CircuitBreaker configures a circuit breaker around the command API. It
	// sits outside the retry policy, so an open breaker fails fast without
	// retrying or touching the network. A nil pointer disables it.
	CircuitBreaker *CircuitBreakerConfig

	// OnEvent, when set, receives observability events (see PoolEvent). It is
	// called synchronously on the pool's hot path, so it must not block; a
	// panic in the callback is recovered and ignored.
	OnEvent func(event PoolEvent, payload map[string]any)
}

PoolConfig configures a Pool. The embedded ClientConfig is applied to every connection the pool opens. Time-based limits use time.Duration (the pool is Go-native), whereas the embedded ClientConfig keeps its millisecond fields for parity with the other language clients.

type PoolEvent added in v0.4.0

type PoolEvent string

PoolEvent identifies an observability event emitted by a Pool through PoolConfig.OnEvent. The payload map varies by event; see each constant.

const (
	// EventAcquire is emitted when a connection is handed out. Payload:
	// {"wait_seconds": float64} — time the borrow spent waiting (0 if it did
	// not wait).
	EventAcquire PoolEvent = "acquire"

	// EventConnectionDiscarded is emitted when a connection is dropped after
	// failing validation, expiring, or overflowing the idle limit. Empty payload.
	EventConnectionDiscarded PoolEvent = "connection_discarded"

	// EventRetry is emitted before a request retry's backoff. Payload:
	// {"attempt": int, "error": string}.
	EventRetry PoolEvent = "retry"

	// EventBreakerStateChange is emitted when the circuit breaker changes state.
	// Payload: {"state": string} — one of "closed", "open", "half_open".
	EventBreakerStateChange PoolEvent = "breaker_state_change"
)

type PoolStats added in v0.4.0

type PoolStats struct {
	// Open is the number of open connections (idle plus in use).
	Open int
	// Idle is the number of connections currently available for reuse.
	Idle int
	// InUse is the number of connections currently borrowed.
	InUse int
	// WaitCount is the approximate number of borrows that had to wait for a
	// connection. It counts entries into the waiting path, some of which may
	// then complete without actually blocking, so it slightly overstates
	// contention.
	WaitCount int64
	// WaitDuration is the cumulative time borrows spent in the waiting path.
	WaitDuration time.Duration
	// Discarded is the number of connections closed instead of being reused
	// (unhealthy, expired, or beyond the idle limit).
	Discarded int64
	// Retries is the number of request retries performed.
	Retries int64
}

PoolStats is a snapshot of a Pool's runtime statistics.

type ProtocolError

type ProtocolError struct {
	Message string
}

ProtocolError is an error returned when a protocol violation occurs.

func (*ProtocolError) Error

func (e *ProtocolError) Error() string

type ReplicationStatus

type ReplicationStatus struct {
	// Running is true when replication is active.
	Running bool

	// GTID is the current GTID position.
	GTID string

	// StatusStr is the raw response string.
	StatusStr string

	// ProcessedEvents is the total number of binlog events processed since
	// startup. Populated only by the multi-line REPLICATION STATUS response.
	ProcessedEvents int

	// QueueSize is the number of events currently pending in the
	// replication apply queue. Populated only by the multi-line response.
	QueueSize int
}

ReplicationStatus represents the replication state.

type RetryPolicy added in v0.4.0

type RetryPolicy struct {
	// MaxRetries is the maximum number of additional attempts after the first.
	// The zero value selects the default of 1 (so up to two total attempts). A
	// negative value explicitly disables retries (zero additional attempts);
	// use it when a workload must never re-issue a command, even a safe one.
	MaxRetries int

	// BaseBackoff is the base delay for the exponential-with-full-jitter
	// backoff between attempts. Default is 50ms.
	BaseBackoff time.Duration
}

RetryPolicy controls how the pool retries failed commands. Only failures that are safe to retry are ever retried: a command whose write never reached the server (any command), or a read-phase failure of an idempotent command. Server errors, validation errors and timeouts are never retried.

type SearchExpression

type SearchExpression struct {
	// RequiredTerms contains keywords marked as required with +.
	RequiredTerms []string

	// ExcludedTerms contains keywords marked for exclusion with -.
	ExcludedTerms []string

	// OptionalTerms contains keywords without any modifier.
	OptionalTerms []string

	// RawExpression holds the original expression when it contains OR/grouping (complex expressions).
	RawExpression string
}

SearchExpression represents a parsed search expression.

func ParseSearchExpression

func ParseSearchExpression(expression string) (*SearchExpression, error)

ParseSearchExpression parses a web-search-style search expression.

Supported syntax:

  • +term: required keyword
  • -term: excluded keyword
  • "phrase": phrase search
  • OR: logical OR
  • (expr): grouping

type SearchOptions

type SearchOptions struct {
	// Limit is the maximum number of results to return. Default is 1000.
	Limit int

	// Offset is the number of results to skip. Default is 0.
	Offset int

	// AndTerms is a list of additional keywords combined with AND.
	AndTerms []string

	// NotTerms is a list of keywords to exclude with NOT.
	NotTerms []string

	// Filters is a map of column filter conditions (key=value).
	Filters map[string]string

	// SortColumn is the column name to sort by.
	//
	// Use the special value "_score" to sort by BM25 relevance score
	// (requires verify_text=ascii|all on the server, MygramDB >= v1.6).
	SortColumn string

	// SortDesc indicates descending sort order when true.
	SortDesc bool

	// Fuzzy enables fuzzy (Levenshtein) matching with the given edit
	// distance. Valid values are 0 (disabled), 1 and 2. Requires
	// MygramDB >= v1.6.
	Fuzzy int

	// Highlight, when non-nil, enables the HIGHLIGHT clause so that
	// matching snippets are returned alongside each primary key.
	// Requires verify_text=ascii|all on the server and MygramDB >= v1.6.
	Highlight *HighlightOptions
}

SearchOptions holds options for a search request.

type SearchRawOptions added in v0.3.0

type SearchRawOptions struct {
	// Limit is the maximum number of results to return. 0 means the server
	// default.
	Limit int

	// Offset is the number of results to skip. Default is 0.
	Offset int

	// Highlight, when non-nil, enables the HIGHLIGHT clause so that matching
	// snippets are returned alongside each primary key.
	Highlight *HighlightOptions
}

SearchRawOptions holds options for a raw search request that sends a pre-built boolean expression. Introduced in MygramDB v1.7; since v1.8 the expression is sent verbatim (unquoted) so the server's AST parser interprets AND/OR/NOT and grouping (see Client.SearchRaw). Unlike SearchOptions, a raw search exposes only pagination and highlight controls — AND/NOT/FILTER refinements belong inside the expression itself.

type SearchResponse

type SearchResponse struct {
	// Results is the list of search results.
	Results []SearchResult

	// TotalCount is the total number of matches after filtering.
	TotalCount int

	// Debug contains debug information (only available when debug mode is enabled).
	Debug *DebugInfo
}

SearchResponse represents a search response.

type SearchResult

type SearchResult struct {
	// PrimaryKey is the document's primary key.
	PrimaryKey string

	// Snippet contains the highlighted text fragment for this result,
	// populated only when SearchOptions.Highlight was set (MygramDB
	// >= v1.6). Empty otherwise.
	Snippet string
}

SearchResult represents a single search result.

type ServerError

type ServerError struct {
	Message string
}

ServerError is an error returned when the server responds with ERROR.

func (*ServerError) Error

func (e *ServerError) Error() string

type ServerInfo

type ServerInfo struct {
	// Version is the server version.
	Version string

	// UptimeSeconds is the number of seconds since server startup.
	UptimeSeconds int

	// TotalRequests is the total number of processed requests.
	TotalRequests int

	// ActiveConnections is the current number of client connections.
	ActiveConnections int

	// IndexSizeBytes is the memory used by the index in bytes.
	IndexSizeBytes int

	// DocCount is the total number of documents in the index.
	DocCount int

	// Tables is the list of table names.
	Tables []string
}

ServerInfo represents server information.

type SimplifiedExpression

type SimplifiedExpression struct {
	// MainTerm is the main search keyword.
	MainTerm string

	// AndTerms is a list of additional keywords combined with AND.
	AndTerms []string

	// NotTerms is a list of keywords to exclude with NOT.
	NotTerms []string
}

SimplifiedExpression represents a simplified search expression.

func SimplifySearchExpression

func SimplifySearchExpression(expression string) (*SimplifiedExpression, error)

SimplifySearchExpression decomposes a search expression into MainTerm/AndTerms/NotTerms. The result maps directly to the MygramDB SEARCH command format.

OR-only or parenthesized sub-expressions (e.g. "python OR ruby" or "(a OR b)") are surfaced as a single parenthesized MainTerm so the OR semantics survive when the caller AND-composes the result. Mixed expressions that combine required terms with an OR sub-expression keep the required terms; the OR sub-expression is currently not surfaced.

type TimeoutError

type TimeoutError struct {
	Message string

	// Err is the underlying cause, if any (for example context.DeadlineExceeded
	// when the caller's context deadline elapsed). It is nil for a timeout
	// driven purely by the configured TimeoutMs.
	Err error
	// contains filtered or unexported fields
}

TimeoutError is an error returned when an operation times out.

It satisfies net.Error (Timeout reports true), so existing code that checks for timeouts via net.Error keeps working. When the timeout was caused by the caller's context deadline, Err is context.DeadlineExceeded and is exposed via Unwrap, so errors.Is(err, context.DeadlineExceeded) matches.

func (*TimeoutError) Error

func (e *TimeoutError) Error() string

func (*TimeoutError) Temporary added in v0.4.0

func (e *TimeoutError) Temporary() bool

Temporary satisfies net.Error. A command timeout is not treated as a transient condition (matching os.ErrDeadlineExceeded), so it returns false.

func (*TimeoutError) Timeout added in v0.4.0

func (e *TimeoutError) Timeout() bool

Timeout reports that this error represents a timeout, satisfying net.Error.

func (*TimeoutError) Unwrap added in v0.4.0

func (e *TimeoutError) Unwrap() error

type ValidationError

type ValidationError struct {
	Message string
}

ValidationError is an error returned when input validation fails.

func (*ValidationError) Error

func (e *ValidationError) Error() string

Jump to

Keyboard shortcuts

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