kvv1

import kvv1 "pocketone.dev/ext/contracts/kv/v1"

Package kvv1 is the kv/v1 contract: an app's key-value store. Named JSON values (an app's settings, an extension's state) kept without a collection or a migration, in PocketBase's own _params table, so they ride along in backups.

Two halves:

  • The helpers in this package (Get, Set, Delete, List) are how Go code (an extension, a hook) reads and writes the store. They work on the app's database directly, inside a transaction when given one, and need no provider.
  • The wire API at /api/_c/kv/v1 (superusers only) is how the CLI, MCP and a dashboard read and change values. Its provider (ext/kv) serves it over the same helpers, and gives page code $kv.

Each value is one _params row whose id is Prefix + its name ("kv:storytime/settings"), so a name can never meet PocketBase's own params ("settings") or another extension's rows. Names are 1 to MaxNameLength characters: letters, digits and _ - . : / , starting with a letter or digit. Use a prefix of your own ("myext/...") to keep your names apart from others'. A name starting with _ ("_myext/secret") is private: only Go code reaches it, through the helpers; the wire API and $kv never do.

Source: ext/contracts/kv/v1.

Constants

const MaxNameLength = 128

MaxNameLength is the longest name.

const MaxValueBytes = 1 << 20

MaxValueBytes is the largest value, as JSON.

const Prefix = "kv:"

Prefix starts the _params id of every value in the store: name "storytime/settings" is row "kv:storytime/settings".

const PrivatePrefix = "_"

PrivatePrefix starts a private name ("_llm/settings"): Go code reads and writes it through these helpers, but the wire API (HTTP, the CLI, MCP) and page code's $kv never reach or list it. Keep secrets (API keys, signing keys) there.

Variables

var Contract = extkit.NewContract[Store]("kv/v1", extkit.One)

Contract is kv/v1.

var ErrInvalidName = &extkit.Error{Code: "invalid_name", Message: "a name is 1 to 128 characters: letters, digits and _ - . : /, starting with a letter or digit (_ first makes it private)", Status: 400}

ErrInvalidName: the name is empty, too long or has a character names can't have.

var ErrInvalidValue = &extkit.Error{Code: "invalid_value", Message: "the value must be JSON of at most 1 MiB", Status: 400}

ErrInvalidValue: the value isn't JSON, or is bigger than MaxValueBytes.

var ErrNotFound = &extkit.Error{Code: "not_found", Message: "no value under that name", Status: 404}

ErrNotFound: no value under that name.

var ErrPrivate = &extkit.Error{Code: "private", Message: "names starting with _ are private to the app's Go code", Status: 403}

ErrPrivate: the name is private (starts with _), so only Go code on the app reaches it.

var W = extkit.NewWire(Contract, "kv", func(inner Store, g *extkit.Guard[Store]) Store {
	return &guardStore{inner, g}
},
	extkit.Op[Store]{
		Name:   "list",
		Desc:   "Returns the values whose names start with prefix (all of them when it's empty), sorted by name. Private names (starting with _) are left out.",
		Method: "GET",
		Path:   "",
		Scope:  "kv:read",
		In:     reflect.TypeOf(ListInput{}),
		Out:    extkit.OutJSON,
		Invoke: func(ctx context.Context, impl Store, a extkit.Auth, req extkit.OpRequest) (any, error) {
			var in ListInput
			if err := extkit.DecodeQuery(req.Query, &in); err != nil {
				return nil, err
			}
			return impl.List(ctx, a, in)
		},
	},
	extkit.Op[Store]{
		Name:   "get",
		Desc:   "Returns one value. A name with no value is a not_found error; a private name is a private error.",
		Method: "GET",
		Path:   "get",
		Scope:  "kv:read",
		In:     reflect.TypeOf(Key{}),
		Out:    extkit.OutJSON,
		Invoke: func(ctx context.Context, impl Store, a extkit.Auth, req extkit.OpRequest) (any, error) {
			var in Key
			if err := extkit.DecodeQuery(req.Query, &in); err != nil {
				return nil, err
			}
			return impl.Get(ctx, a, in)
		},
	},
	extkit.Op[Store]{
		Name:   "set",
		Desc:   "Stores a JSON value under a name, replacing any value it had.",
		Method: "POST",
		Path:   "set",
		Scope:  "kv",
		In:     reflect.TypeOf(SetInput{}),
		Out:    extkit.OutJSON,
		Invoke: func(ctx context.Context, impl Store, a extkit.Auth, req extkit.OpRequest) (any, error) {
			var in SetInput
			if err := extkit.DecodeInput(req.JSON, &in); err != nil {
				return nil, err
			}
			return impl.Set(ctx, a, in)
		},
	},
	extkit.Op[Store]{
		Name:   "delete",
		Desc:   "Removes a value. Deleting a name with no value is not an error.",
		Method: "POST",
		Path:   "delete",
		Scope:  "kv",
		In:     reflect.TypeOf(Key{}),
		Out:    extkit.OutJSON,
		Invoke: func(ctx context.Context, impl Store, a extkit.Auth, req extkit.OpRequest) (any, error) {
			var in Key
			if err := extkit.DecodeInput(req.JSON, &in); err != nil {
				return nil, err
			}
			return nil, impl.Delete(ctx, a, in)
		},
	},
)

W is kv/v1's wire side: routes at /api/_c/kv/v1/<op>, action hooks, MCP tools and the client.

Functions

Delete

func Delete(app core.App, name string) error

Delete removes name's value. Deleting a name with no value is not an error.

Example:

_ = kvv1.Delete(app, "myapp/settings")

Get

func Get(app core.App, name string, dst any) (found bool, err error)

Get decodes name's value into dst (as json.Unmarshal). found is false, and dst untouched, when it has none.

var s Settings
if _, err := kvv1.Get(app, "storytime/settings", &s); err != nil { ... }

Example:

var settings struct{ Theme string }
found, err := kvv1.Get(app, "myapp/settings", &settings)
if err != nil {
	return
}
if !found {
	settings.Theme = "light"
}
fmt.Println(settings.Theme)

IsPrivate

func IsPrivate(name string) bool

IsPrivate says whether name is private (starts with PrivatePrefix).

MoveParam

func MoveParam(app core.App, fromID, name string) (moved bool, err error)

MoveParam moves the _params row fromID (an extension's own row from before kv/v1) to name, once: when name has no value yet, it gets the row's value and times, and the row is deleted. When name already has one, a leftover row is just deleted. moved says whether a value was moved. PocketBase's own rows and the store's rows can't be moved.

MoveParamOnce

func MoveParamOnce(app core.App, fromID, name string) error

MoveParamOnce is MoveParam at most once per app and row, for a load path that runs often: after the first call that succeeds, later ones return at once.

OnDelete

func OnDelete(owner any, fn func(e *extkit.CallEvent, in *Key) error)

OnDelete binds fn to delete calls on owner (an app, or a host's scope for calls the host answers). Call e.Next() to continue; return an error to refuse. in is the call's input; changes reach the provider.

OnGet

func OnGet(owner any, fn func(e *extkit.CallEvent, in *Key) error)

OnGet binds fn to get calls on owner (an app, or a host's scope for calls the host answers). Call e.Next() to continue; return an error to refuse. in is the call's input; changes reach the provider.

OnList

func OnList(owner any, fn func(e *extkit.CallEvent, in *ListInput) error)

OnList binds fn to list calls on owner (an app, or a host's scope for calls the host answers). Call e.Next() to continue; return an error to refuse. in is the call's input; changes reach the provider.

OnSet

func OnSet(owner any, fn func(e *extkit.CallEvent, in *SetInput) error)

OnSet binds fn to set calls on owner (an app, or a host's scope for calls the host answers). Call e.Next() to continue; return an error to refuse. in is the call's input; changes reach the provider.

ParamID

func ParamID(name string) string

ParamID is the _params id that holds name's value.

Set

func Set(app core.App, name string, v any) error

Set stores v (as json.Marshal) under name, replacing any value it had.

Example:

err := kvv1.Set(app, "myapp/settings", map[string]any{"theme": "dark"})
if err != nil {
	return
}

ValidName

func ValidName(name string) error

ValidName returns ErrInvalidName unless name can name a value: after an optional PrivatePrefix, a letter or digit, then letters, digits and _ - . : / , at most MaxNameLength in all.

Types

Client

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

Client is kv/v1 over HTTP, for the CLI and other apps. It implements Store; the token it was made with is the credential, so the extkit.Auth argument is ignored.

NewClient

func NewClient(baseURL, token string, hc *http.Client) *Client

NewClient calls kv/v1 on the app at baseURL with token (a PocketBase auth token or an API token).

Client.Delete

func (c *Client) Delete(ctx context.Context, _ extkit.Auth, in Key) error

Client.Get

func (c *Client) Get(ctx context.Context, _ extkit.Auth, in Key) (Entry, error)

Client.List

func (c *Client) List(ctx context.Context, _ extkit.Auth, in ListInput) (Listing, error)

Client.Set

func (c *Client) Set(ctx context.Context, _ extkit.Auth, in SetInput) (Entry, error)

Entry

type Entry struct {
	Name    string          `json:"name"`
	Value   json.RawMessage `json:"value"`
	Created time.Time       `json:"created"`
	Updated time.Time       `json:"updated"`
}

Entry is one stored value.

List

func List(app core.App, prefix string) ([]Entry, error)

List returns the values whose names start with prefix (every value when it's empty), sorted by name.

Example:

entries, err := kvv1.List(app, "myapp/")
if err != nil {
	return
}
for _, e := range entries {
	fmt.Println(e.Name, e.Updated)
}

Lookup

func Lookup(app core.App, name string) (e Entry, found bool, err error)

Lookup returns name's stored value; found is false when it has none.

SetRaw

func SetRaw(app core.App, name string, raw json.RawMessage) (Entry, error)

SetRaw stores raw JSON under name and returns the stored entry.

Key

type Key struct {
	Name string `json:"name"`
}

Key names a value.

ListInput

type ListInput struct {
	Prefix string `json:"prefix,omitempty"`
}

ListInput picks the values to list.

Listing

type Listing struct {
	Entries []Entry `json:"entries"`
}

Listing is the values Store.List found.

SetInput

type SetInput struct {
	Name  string          `json:"name"`
	Value json.RawMessage `json:"value"`
}

SetInput is a value to store.

Store

type Store interface {
	// List returns the values whose names start with prefix (all of them when it's empty), sorted by name. Private names
	// (starting with _) are left out.
	//
	//op: GET / scope=kv:read
	List(ctx context.Context, a extkit.Auth, in ListInput) (Listing, error)

	// Get returns one value. A name with no value is a not_found error; a private name is a private error.
	//
	//op: GET get scope=kv:read
	Get(ctx context.Context, a extkit.Auth, in Key) (Entry, error)

	// Set stores a JSON value under a name, replacing any value it had.
	//
	//op: POST set scope=kv
	Set(ctx context.Context, a extkit.Auth, in SetInput) (Entry, error)

	// Delete removes a value. Deleting a name with no value is not an error.
	//
	//op: POST delete scope=kv
	Delete(ctx context.Context, a extkit.Auth, in Key) error
}

Store reads and changes the app's key-value store.