configstore

package
v0.1.21 Latest Latest
Warning

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

Go to latest
Published: Oct 21, 2026 License: MIT Imports: 19 Imported by: 0

Documentation

Overview

Package configstore persists configuration revisions in SQLite or in a PostgreSQL, MySQL or OceanBase database. Every table uses the smcp_ prefix; the store keeps its own schema version and fails closed on an unknown one.

Index

Constants

View Source
const MaxAdminTokens = 20

MaxAdminTokens bounds the tokens of one administrator.

View Source
const SchemaVersion = 6

SchemaVersion is the store table layout this build understands. Version 2 added administrator accounts, version 3 the scanned catalog, plan templates and administrator tokens, version 4 token scopes and scan batch items as rows, version 5 administrators' workspaces, version 6 the database constraint of at most one published revision.

View Source
const TablePrefix = config.StoreTablePrefix

TablePrefix prefixes every store table; see config.StoreTablePrefix.

Variables

View Source
var (
	ErrAdminExists   = errors.New("configstore: admin account already exists")
	ErrAdminNotFound = errors.New("configstore: admin account not found")
)

Admin account errors.

View Source
var (
	ErrInvalidSpec    = errors.New("configstore: invalid store spec")
	ErrNotInitialized = errors.New("configstore: store is not initialized; run `sql-mcp-server store init`")
	ErrNewerSchema    = errors.New("configstore: store schema is newer than this build")
	// ErrStoreCorrupt is a store whose rows break its invariants: a missing
	// lock or counter row, or more than one published revision.
	ErrStoreCorrupt = errors.New("configstore: store is corrupt")
)

Errors returned when opening a store.

View Source
var (
	ErrTemplateNotFound = errors.New("configstore: plan template not found")
	ErrTemplateExists   = errors.New("configstore: a plan template with this name exists")
	// ErrTemplateConflict: the template changed since the version the caller
	// edited.
	ErrTemplateConflict = errors.New("configstore: plan template changed since it was read")
)

Plan template errors.

View Source
var (
	ErrTokenNotFound  = errors.New("configstore: admin token not found")
	ErrTooManyTokens  = fmt.Errorf("configstore: an administrator has at most %d tokens", MaxAdminTokens)
	ErrTokenNameTaken = errors.New("configstore: the administrator has a token with this name")
)

Admin token errors.

Functions

func Init

func Init(ctx context.Context, spec Spec, resolve Resolver) error

Init creates the store tables when absent; it is a no-op on an initialized store of the same version. An Init that stopped part way runs again: the tables are created if absent and the missing metadata rows written. Inits running at the same time, in any process, run one after another (see dialect.lockInit): each after the first finds the store initialized.

Types

type AdminAccount

type AdminAccount struct {
	Username     string
	PasswordHash string
	Permissions  []string
	Disabled     bool
	CreatedAt    time.Time
	UpdatedAt    time.Time
}

AdminAccount is an administrator of the admin API. Accounts are stored outside configuration revisions, so changes take effect immediately and a configuration publish never alters administrator access.

type AdminToken added in v0.1.13

type AdminToken struct {
	ID        string
	Username  string
	Name      string
	TokenHash string
	CreatedAt time.Time
	// ExpiresAt is when the token stops working; zero never.
	ExpiresAt time.Time
	// LastUsedAt is when the token last authenticated a request; zero never.
	LastUsedAt time.Time
	Scope      TokenScope
}

AdminToken is a named token of an administrator for the configuration MCP endpoint, one per client; the token itself is shown once and only its hash is stored.

type PendingState added in v0.1.13

type PendingState struct {
	Key       string
	Status    string
	Owner     string
	Reason    string
	Until     time.Time
	UpdatedBy string
	UpdatedAt time.Time
}

PendingState is how administrators handle one pending item (a recurring template's proposal, a table whose fields differ, ...): open, snoozed until a time, or ignored for a reason, and who owns it. Every change is logged.

type PlanTemplate added in v0.1.13

type PlanTemplate struct {
	Name      string
	Plan      []byte
	Recurring bool
	Version   int
	Author    string
	UpdatedAt time.Time
}

PlanTemplate is a saved plan: a scope and rules the console and the configuration MCP endpoint evaluate again on demand. Recurring marks one whose new matches are proposed for review after each scan. Every save is a new version; earlier ones are kept.

type Resolver

type Resolver func(string) (string, error)

Resolver expands DSN placeholders.

type SQLStore

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

SQLStore is a revision.Store backed by database/sql. IDs come from a counter row and every publish or rollback first updates a lock row, so all state transitions serialize on a row lock in every supported backend.

func Open

func Open(ctx context.Context, spec Spec, resolve Resolver) (*SQLStore, error)

Open connects to an initialized store. It fails with ErrNotInitialized when the tables or metadata rows are missing (an Init that stopped part way), with ErrStoreCorrupt when an initialized store lost a table or one with revisions a metadata row, and with ErrNewerSchema on a newer layout.

func (*SQLStore) AdminTokenByHash added in v0.1.13

func (s *SQLStore) AdminTokenByHash(ctx context.Context, hash string) (AdminToken, bool, error)

AdminTokenByHash returns the token with a hash; false when none.

func (*SQLStore) AdminTokens added in v0.1.13

func (s *SQLStore) AdminTokens(ctx context.Context, username string) ([]AdminToken, error)

AdminTokens returns an administrator's tokens, oldest first.

func (*SQLStore) Batch added in v0.1.13

func (s *SQLStore) Batch(ctx context.Context, id string) (catalog.Batch, bool, error)

Batch implements catalog.BatchStore.

func (*SQLStore) BatchCanceled added in v0.1.21

func (s *SQLStore) BatchCanceled(ctx context.Context, id string) (bool, error)

BatchCanceled implements catalog.BatchStore.

func (*SQLStore) Batches added in v0.1.13

func (s *SQLStore) Batches(ctx context.Context, datasource string, limit int) ([]catalog.Batch, error)

Batches implements catalog.BatchStore.

func (*SQLStore) BatchesWithItems added in v0.1.21

func (s *SQLStore) BatchesWithItems(ctx context.Context, datasource string, limit int) ([]catalog.Batch, error)

BatchesWithItems implements catalog.BatchStore in two statements: a batch pruned between them is listed without items.

func (*SQLStore) CancelBatch added in v0.1.13

func (s *SQLStore) CancelBatch(ctx context.Context, id string) error

CancelBatch implements catalog.BatchStore.

func (*SQLStore) CatalogList added in v0.1.13

func (s *SQLStore) CatalogList(ctx context.Context, source string) (catalog.List, bool, error)

CatalogList implements catalog.Store.

func (*SQLStore) CatalogSchemas added in v0.1.13

func (s *SQLStore) CatalogSchemas(ctx context.Context, source string, names []string) ([]catalog.Schema, error)

CatalogSchemas implements catalog.Store.

func (*SQLStore) CatalogVersions added in v0.1.13

func (s *SQLStore) CatalogVersions(ctx context.Context, source string) ([]catalog.Version, error)

CatalogVersions implements catalog.Store.

func (*SQLStore) ClaimBatch added in v0.1.13

func (s *SQLStore) ClaimBatch(ctx context.Context, id, owner string, staleBefore, now time.Time) (bool, error)

ClaimBatch implements catalog.BatchStore with one conditional update.

func (*SQLStore) Close

func (s *SQLStore) Close() error

Close implements revision.Store.

func (*SQLStore) Create

Create implements revision.Store.

func (*SQLStore) CreateAdminToken added in v0.1.13

func (s *SQLStore) CreateAdminToken(ctx context.Context, t AdminToken) (AdminToken, error)

CreateAdminToken stores a new token of t.Username, named uniquely among its tokens, and returns it with its creation time.

func (*SQLStore) CreateBatch added in v0.1.13

func (s *SQLStore) CreateBatch(ctx context.Context, b catalog.Batch, maxOpen int) (catalog.Batch, bool, error)

CreateBatch implements catalog.BatchStore: the checks and the inserts run in one transaction under the store lock, serializing creations across processes.

func (*SQLStore) DeleteAdminToken added in v0.1.13

func (s *SQLStore) DeleteAdminToken(ctx context.Context, username, id string) error

DeleteAdminToken revokes one of an administrator's tokens.

func (*SQLStore) DeleteCatalogSchemas added in v0.1.13

func (s *SQLStore) DeleteCatalogSchemas(ctx context.Context, source string, names []string, before time.Time) error

DeleteCatalogSchemas implements catalog.Store.

func (*SQLStore) DeletePlanTemplate added in v0.1.13

func (s *SQLStore) DeletePlanTemplate(ctx context.Context, name string) error

DeletePlanTemplate removes a template and its versions, under the store lock as saving one is.

func (*SQLStore) Discard added in v0.1.13

func (s *SQLStore) Discard(ctx context.Context, id int64) (revision.Revision, error)

Discard implements revision.Store.

func (*SQLStore) FinishBatch added in v0.1.13

func (s *SQLStore) FinishBatch(ctx context.Context, id, owner string, at time.Time) error

FinishBatch implements catalog.BatchStore.

func (*SQLStore) Get

func (s *SQLStore) Get(ctx context.Context, id int64) (revision.Revision, error)

Get implements revision.Store.

func (*SQLStore) GetAdmin

func (s *SQLStore) GetAdmin(ctx context.Context, username string) (AdminAccount, error)

GetAdmin returns one account.

func (*SQLStore) ImportHistory

func (s *SQLStore) ImportHistory(ctx context.Context, revs []revision.Revision) error

ImportHistory implements revision.Store.

func (*SQLStore) List

func (s *SQLStore) List(ctx context.Context, limit int) ([]revision.Revision, error)

List implements revision.Store.

func (*SQLStore) ListAdmins

func (s *SQLStore) ListAdmins(ctx context.Context) ([]AdminAccount, error)

ListAdmins returns every account ordered by username.

func (*SQLStore) MoveItem added in v0.1.13

func (s *SQLStore) MoveItem(
	ctx context.Context, id, owner string, now time.Time, item catalog.BatchItem, from ...string,
) (bool, error)

MoveItem implements catalog.BatchStore.

func (*SQLStore) MutateAdmins

func (s *SQLStore) MutateAdmins(
	ctx context.Context, fn func(all []AdminAccount) ([]AdminAccount, error),
) ([]AdminAccount, error)

MutateAdmins is the only way to change accounts. In one transaction serialized by the store lock it reads every account, calls fn, and writes the accounts fn returns: new usernames are inserted, known ones replaced. Concurrent calls run one after another, so a rule fn checks across all accounts (such as keeping an account manager) holds when it commits. It returns the written accounts with their timestamps.

func (*SQLStore) PendingLog added in v0.1.13

func (s *SQLStore) PendingLog(ctx context.Context, key string) ([]PendingState, error)

PendingLog returns the changes of an item's state, newest first.

func (*SQLStore) PendingStates added in v0.1.13

func (s *SQLStore) PendingStates(ctx context.Context) ([]PendingState, error)

PendingStates returns the state of every item handled so far.

func (*SQLStore) PlanTemplateVersions added in v0.1.13

func (s *SQLStore) PlanTemplateVersions(ctx context.Context, name string) ([]PlanTemplate, error)

PlanTemplateVersions returns every version of a template, newest first.

func (*SQLStore) PlanTemplates added in v0.1.13

func (s *SQLStore) PlanTemplates(ctx context.Context) ([]PlanTemplate, error)

PlanTemplates returns the current version of every template, by name.

func (*SQLStore) PruneCatalog added in v0.1.13

func (s *SQLStore) PruneCatalog(ctx context.Context, datasource, keep string, before time.Time) error

PruneCatalog implements catalog.Store.

func (*SQLStore) Publish

func (s *SQLStore) Publish(ctx context.Context, id, expectedCurrent int64, _ revision.Meta) (revision.Revision, error)

Publish implements revision.Store.

func (*SQLStore) Published

func (s *SQLStore) Published(ctx context.Context) (revision.Revision, error)

Published implements revision.Store.

func (*SQLStore) PublishedSummary added in v0.1.17

func (s *SQLStore) PublishedSummary(ctx context.Context) (revision.Revision, error)

PublishedSummary implements revision.Store.

func (*SQLStore) PutCatalogList added in v0.1.13

func (s *SQLStore) PutCatalogList(ctx context.Context, source, datasource string, l catalog.List) error

PutCatalogList implements catalog.Store.

func (*SQLStore) PutCatalogSchemas added in v0.1.13

func (s *SQLStore) PutCatalogSchemas(ctx context.Context, source, datasource string, schemas []catalog.Schema) error

PutCatalogSchemas implements catalog.Store. Each schema is one upsert, in the order of their names, so concurrent puts of the same schemas wait on one another instead of failing on the key or deadlocking.

func (*SQLStore) PutPendingState added in v0.1.13

func (s *SQLStore) PutPendingState(ctx context.Context, p PendingState) (PendingState, error)

PutPendingState sets an item's state and logs the change, in one transaction. Both writes are upserts: concurrent puts of one key (template keys are deterministic) each succeed, the last committed one is the state; two changes of a key in the same microsecond keep one log entry.

func (*SQLStore) PutPlanTemplate added in v0.1.13

func (s *SQLStore) PutPlanTemplate(ctx context.Context, t PlanTemplate, expected int) (PlanTemplate, error)

PutPlanTemplate saves a new version of a template. expected is the version the caller edited: 0 creates the template and fails with ErrTemplateExists when the name is taken; otherwise the current version must still be expected, or it fails with ErrTemplateConflict.

func (*SQLStore) PutWorkspace added in v0.1.13

func (s *SQLStore) PutWorkspace(
	ctx context.Context, w workspace.Workspace, expected int64, entry workspace.LogEntry,
) (workspace.Workspace, error)

PutWorkspace implements workspace.Store, writing over the version expected.

func (*SQLStore) Rollback

func (s *SQLStore) Rollback(
	ctx context.Context, expectedCurrent, target int64, m revision.Meta,
) (revision.Revision, error)

Rollback implements revision.Store.

func (*SQLStore) Sequence added in v0.1.13

func (s *SQLStore) Sequence(ctx context.Context) (int64, error)

Sequence implements revision.Store: the next ID (grown by every revision created) plus the count of the other revision writes. Writes of anything else (workspaces, tokens, accounts) leave it as it is.

func (*SQLStore) TouchAdminToken added in v0.1.13

func (s *SQLStore) TouchAdminToken(ctx context.Context, id string, at time.Time) error

TouchAdminToken records a use of a token.

func (*SQLStore) UnfinishedBatches added in v0.1.13

func (s *SQLStore) UnfinishedBatches(ctx context.Context) ([]catalog.Batch, error)

UnfinishedBatches implements catalog.BatchStore.

func (*SQLStore) Workspace added in v0.1.13

func (s *SQLStore) Workspace(ctx context.Context, username string) (workspace.Workspace, bool, error)

Workspace implements workspace.Store. A large workspace takes long to decode and every operation reads it: the one last read or written is kept, and returned while the stored one is still at its version.

func (*SQLStore) WorkspaceLog added in v0.1.13

func (s *SQLStore) WorkspaceLog(ctx context.Context, username string, limit int) ([]workspace.LogEntry, error)

WorkspaceLog implements workspace.Store.

type Spec

type Spec struct {
	Driver string // sqlite | postgres | mysql | oceanbase
	DSN    string
}

Spec is a parsed "<driver>:<dsn>" store location.

func ParseSpec

func ParseSpec(raw string) (Spec, error)

ParseSpec parses "<driver>:<dsn>". The DSN may contain ${ENV} or ${file:/path} placeholders, resolved by Open.

func (Spec) String

func (s Spec) String() string

String returns the spec without its DSN, safe for logs.

type TokenScope added in v0.1.13

type TokenScope struct {
	// Datasources limits the token to these datasources; nil does not.
	Datasources []string `json:"datasources,omitempty"`
	// ReadOnly marks a token created read only, which is no longer
	// offered: such a token is refused rather than given the administrator's
	// write permissions. New tokens never set it.
	ReadOnly bool `json:"readOnly,omitempty"`
}

TokenScope narrows what a token may do below its administrator's permissions.

Jump to

Keyboard shortcuts

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