storage

package
v0.6.1 Latest Latest
Warning

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

Go to latest
Published: Oct 21, 2026 License: MIT Imports: 32 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

Index

Constants

View Source
const (
	OpEq       = "$eq"
	OpNe       = "$ne"
	OpLt       = "$lt"
	OpLte      = "$lte"
	OpGt       = "$gt"
	OpGte      = "$gte"
	OpContains = "$contains"
)

Filter operators supported on item lists.

View Source
const ProposalApplying = "applying"

ProposalApplying marks a proposal being decided, so two reviewers cannot apply it twice. A claim older than claimTimeout (a crashed server) can be taken over.

Variables

View Source
var (
	// ErrLocaleNotFound is returned for a locale that is not configured.
	ErrLocaleNotFound = errors.New("locale not found")
	// ErrLocaleExists is returned when adding a locale twice.
	ErrLocaleExists = errors.New("locale already exists")
	// ErrDefaultLocale is returned when deleting the default locale.
	ErrDefaultLocale = errors.New("the default locale cannot be deleted")
)
View Source
var (
	// ErrProposalNotFound is returned for an unknown proposal.
	ErrProposalNotFound = errors.New("proposal not found")
	// ErrProposalDecided is returned when approving or rejecting a proposal
	// that is no longer pending.
	ErrProposalDecided = errors.New("this proposal was already decided")
	// ErrProposalStale is returned when approving a proposal whose item
	// changed since the agent proposed it (approve with force to apply it
	// anyway).
	ErrProposalStale = errors.New("the item changed since the agent proposed this")
)
View Source
var (
	// ErrRevisionNotFound is returned for an unknown revision.
	ErrRevisionNotFound = errors.New("revision not found")
	// ErrRunHasNoChanges is returned when reverting a run that changed no content.
	ErrRunHasNoChanges = errors.New("this run made no content changes")
)
View Source
var (
	// ErrRoleNotFound is returned for an unknown role.
	ErrRoleNotFound = errors.New("role not found")
	// ErrRoleExists is returned when a role name is taken.
	ErrRoleExists = errors.New("a role with this name already exists")
	// ErrBuiltinRole is returned when changing admin, editor or viewer.
	ErrBuiltinRole = errors.New("built-in roles (admin, editor, viewer) cannot be changed")
	// ErrPublicRole is returned when deleting the public role or giving it
	// to an account or a token.
	ErrPublicRole = errors.New("the public role is for anonymous requests: it cannot be deleted or given to accounts and tokens")
)
View Source
var DefaultLocaleCode = "en"

DefaultLocaleCode is the default locale used until one is stored (set from i18n.default_locale at startup).

View Source
var ErrComponentInUse = errors.New("component is in use")

ErrComponentInUse is returned when deleting or renaming a component that attributes still reference.

View Source
var ErrDefaultLocaleWrite = errors.New("this is the default locale: write the entry itself")

ErrDefaultLocaleWrite is returned when a translation is written in the default locale (its content is the entry's main data).

View Source
var ErrDraftAndPublishDisabled = errors.New("this collection does not use draft and publish")

ErrDraftAndPublishDisabled is returned when publishing an item of a collection that does not use draft and publish.

View Source
var ErrInvalidToken = errors.New("invalid API token")

ErrInvalidToken is returned for unknown, revoked or expired secrets.

View Source
var ErrItemNotFound = errors.New("item not found")

ErrItemNotFound is returned when an item does not exist in a collection.

View Source
var ErrMediaNotFound = errors.New("media not found")

ErrMediaNotFound is returned for unknown media IDs.

View Source
var ErrNoMediaStore = errors.New("media uploads are not configured")

ErrNoMediaStore is returned when no store is configured.

View Source
var ErrProposalUnappliable = errors.New("the proposal can no longer be applied")

ErrProposalUnappliable is returned when a proposal can no longer be applied (its collection, item or locale changed); the proposal is marked failed.

View Source
var ErrRunNotFound = errors.New("run not found")

ErrRunNotFound is returned for unknown runs.

View Source
var ErrTokenNotFound = errors.New("token not found")

ErrTokenNotFound is returned for unknown token IDs.

View Source
var ErrWebhookNotFound = errors.New("webhook not found")

ErrWebhookNotFound is returned for unknown webhook IDs.

View Source
var RevisionLimit = 100

RevisionLimit is how many revisions are kept per entry; older ones are pruned when a new one is recorded. 0 keeps every revision.

View Source
var SystemActor = Actor{Kind: models.ActorSystem, Name: "system"}

SystemActor is used for changes nobody in particular made (imports, tests, internal jobs).

Functions

func AddAgentRunStep added in v0.5.0

func AddAgentRunStep(s *agents.AgentRunStep)

AddAgentRunStep records one step of a run.

func ApproveProposal added in v0.6.0

func ApproveProposal(id uint, reviewer Actor, data models.JSONMap, force bool) (p *models.Proposal, item *models.Item, err error)

ApproveProposal applies a pending proposal. Without data, the agent's change is applied as the agent, in its run, so its history and a run revert include it; with data (values a reviewer edited), the reviewer makes the change. A stale proposal is refused unless force is set; then only the attributes the agent changed are applied over the item as it is now. A failed change marks the proposal failed and returns the error.

func AssignableRole added in v0.6.0

func AssignableRole(name string) (*models.UserRole, error)

AssignableRole returns a role that accounts and tokens may have.

func AuthenticateAPIToken added in v0.5.0

func AuthenticateAPIToken(secret string) (*models.APIToken, error)

AuthenticateAPIToken returns the active token matching secret, and records its use (at most once a minute, to avoid a write per request).

func CheckItemWrite added in v0.6.0

func CheckItemWrite(ct models.Collection, action string, itemID uint, locale string, data models.JSONMap) error

CheckItemWrite validates a change without applying it: the same checks as the real write, in a transaction that is rolled back (nested items a relation would create are not kept). It returns ErrItemNotFound or an *ItemValidationError.

func ComponentReferences added in v0.4.0

func ComponentReferences(tx *gorm.DB, name string) ([]string, error)

ComponentReferences lists the attributes (as "collection.attribute", "singleton.attribute" or "component.attribute") that use the component.

func CountUsers

func CountUsers() (int64, error)

CountUsers returns the total number of (non-deleted) users.

func CountUsersWithRole added in v0.5.0

func CountUsersWithRole(roleName string) (int64, error)

CountUsersWithRole counts the users that have the role.

func CreateAPIToken added in v0.5.0

func CreateAPIToken(in NewAPITokenInput) (*models.APIToken, string, error)

CreateAPIToken stores a new token and returns it with its secret, which is not kept and cannot be shown again.

func CreateAgentRun added in v0.5.0

func CreateAgentRun(r *agents.AgentRun) error

CreateAgentRun records the start of a run.

func CreateComponent

func CreateComponent(cmp *models.Component) error

CreateComponent stores a new Component definition in the DB, including its attributes.

func CreateItems added in v0.4.0

func CreateItems(actor Actor, collection models.Collection, inputs []ItemInput) ([]*models.Item, error)

CreateItems validates and creates several items atomically: either all are stored or none. Nested relations created during validation are part of the same transaction, and the stored data is the processed (validated) data. Each item gets its first revision. Events are published only after a successful commit.

func CreateLocale added in v0.5.0

func CreateLocale(code, name string) (*models.Locale, error)

CreateLocale adds a locale.

func CreateSingleItem

func CreateSingleItem(actor Actor, st *models.Singleton, itemData map[string]any) (*models.SingleItem, error)

CreateSingleItem creates a new SingleItem for a given Singleton and records its first revision. Returns an error if an item already exists for that Singleton (one-to-one).

func CreateUser

func CreateUser(user *models.User) error

func CreateWebhook added in v0.5.0

func CreateWebhook(w *models.Webhook) error

CreateWebhook stores a webhook.

func DefaultLocale added in v0.5.0

func DefaultLocale() (string, error)

DefaultLocale returns the default locale's code.

func DeleteAgent

func DeleteAgent(agentID uint) error

DeleteAgent deletes an agent from the database by its ID.

func DeleteAgentRuns added in v0.5.0

func DeleteAgentRuns(agentID uint) error

DeleteAgentRuns removes all runs of an agent.

func DeleteCollection

func DeleteCollection(collectionID uint) error

DeleteCollection deletes a collection and all associated data by its ID.

func DeleteComponent

func DeleteComponent(name string) error

DeleteComponent removes a component definition by name. It refuses to delete a component that attributes still use.

func DeleteCustomRole added in v0.5.0

func DeleteCustomRole(name string) error

DeleteCustomRole removes a custom role nobody uses.

func DeleteItem

func DeleteItem(actor Actor, id uint) error

DeleteItem deletes an item and records a "delete" revision holding the data it had, so the item can be restored. It returns ErrItemNotFound for an unknown item and publishes item:deleted after the commit.

func DeleteLocale added in v0.5.0

func DeleteLocale(code string, purge bool) (int64, error)

DeleteLocale removes a locale. Entries with content in it are counted and the delete is refused (LocaleInUseError) unless purge is set, which deletes that content too.

func DeleteMedia added in v0.4.0

func DeleteMedia(ctx context.Context, id uint) error

DeleteMedia removes a media file and its content. Items that referenced it then show null, like a deleted related item. The record goes first, so a failure to delete the content leaves an orphan object (logged), never a record pointing at nothing.

func DeleteRole

func DeleteRole(id uint) error

DeleteRole deletes a role by ID.

func DeleteSingleItem

func DeleteSingleItem(actor Actor, SingletonName string) error

DeleteSingleItem removes the SingleItem for a given single type name and records a "delete" revision holding its data, so it can be restored.

func DeleteSingleton

func DeleteSingleton(SingletonID uint) error

DeleteSingleton permanently deletes a single type by its ID (including attributes). Note: Strapi typically doesn't expose DELETE for single types, but you can implement it if needed.

func DeleteUser

func DeleteUser(id uint) error

DeleteUser removes a user from the database by ID.

func DeleteWebhook added in v0.5.0

func DeleteWebhook(id uint) error

DeleteWebhook removes a webhook and its delivery log.

func EnsureDefaultLocale added in v0.5.0

func EnsureDefaultLocale(code string) error

EnsureDefaultLocale stores the default locale when no locale is stored yet (first start, or an upgrade from a version without locales).

func EnsurePublicRole added in v0.6.0

func EnsurePublicRole() error

EnsurePublicRole creates the public role (granting nothing) when missing.

func FailQueuedRun added in v0.6.0

func FailQueuedRun(id uint, reason string)

FailQueuedRun marks a run that never started as failed.

func FetchNestedRelations

func FetchNestedRelations(collection models.Collection, data models.JSONMap, level uint) (models.JSONMap, error)

FetchNestedRelations replaces relation IDs in data with the related items, down to level levels, including drafts. See PopulateRelations.

func FindAgentsByEventTrigger

func FindAgentsByEventTrigger(collectionName string, eventType string) ([]models.Agent, error)

FindAgentsByEventTrigger returns the agents subscribed to a collection event. Agents are few, so they are filtered here rather than with dialect-specific JSON SQL (and "trigger" is a reserved word in MySQL).

func FlattenEntry added in v0.5.0

func FlattenEntry(data, translations models.JSONMap) models.JSONMap

FlattenEntry merges an entry's data and translations into one map for diffs: translated values are keyed "<attribute>@<locale>".

func GetAPIToken added in v0.5.0

func GetAPIToken(id uint) (*models.APIToken, error)

GetAPIToken returns a token by ID.

func GetAgentByID

func GetAgentByID(id uint) (*models.Agent, error)

GetAgentByID retrieves an agent by its ID.

func GetAgentByName

func GetAgentByName(name string) (*models.Agent, error)

GetAgentByName retrieves an agent by its name.

func GetAgentRun added in v0.5.0

func GetAgentRun(agentID, runID uint) (*agents.AgentRun, error)

GetAgentRun returns one run of an agent with its steps in order.

func GetAllAgents

func GetAllAgents(filters map[string]any, rangeValues []int) ([]models.Agent, int, error)

func GetAllCollections

func GetAllCollections(filters map[string]any, sortValues []string, rangeValues []int) ([]models.Collection, int, error)

func GetAllComponents

func GetAllComponents() ([]models.Component, error)

GetAllComponents returns every component definition with its attributes, ordered by name.

func GetAllRoles

func GetAllRoles() ([]models.UserRole, error)

GetAllRoles retrieves all roles from the database.

func GetAllSingletons

func GetAllSingletons() ([]models.Singleton, error)

GetAllSingletons returns every singleton definition with its attributes, ordered by name.

func GetAllUsers

func GetAllUsers() ([]models.User, error)

GetAllUsers retrieves all users from the database.

func GetCollectionByID

func GetCollectionByID(id uint) (*models.Collection, error)

GetCollectionByID retrieves a collection by its ID.

func GetCollectionByName

func GetCollectionByName(name string) (*models.Collection, error)

GetCollectionByName retrieves a collection by its name.

func GetCollectionSchema

func GetCollectionSchema(id int) (map[string]any, error)

GetCollectionSchema retrieves the schema definition of a collection by name.

func GetComponentByName

func GetComponentByName(name string) (*models.Component, error)

GetComponentByName retrieves a component definition by its name.

func GetConversationHistory

func GetConversationHistory(agentID uint) ([]llm.Message, error)

GetConversationHistory retrieves the messages for an agent.

func GetItemByID

func GetItemByID(collectionID uint, itemID uint) (*models.Item, error)

GetItemByID fetches an item by its ID and collection ID.

func GetItems

func GetItems(collectionID uint, page, pageSize int) ([]models.Item, int, error)

GetItems lists items using page/pageSize pagination (page starts at 1).

func GetItemsByOffset

func GetItemsByOffset(ct models.Collection, offset, limit int, status string) ([]models.Item, int, error)

GetItemsByOffset lists items using offset/limit pagination (as GraphQL does). status filters draft-and-publish collections: "" (all), models.StatusPublished or models.StatusDraft.

func GetMedia added in v0.4.0

func GetMedia(id uint) (*models.Media, error)

GetMedia returns a media file by ID.

func GetProposal added in v0.6.0

func GetProposal(id uint) (*models.Proposal, error)

GetProposal returns one proposal.

func GetRevision added in v0.5.0

func GetRevision(entityType string, entityID, version uint) (*models.Revision, error)

GetRevision returns one revision of an entry, with its data.

func GetRoleByID

func GetRoleByID(id uint) (*models.UserRole, error)

GetRoleByID retrieves a role by its ID.

func GetRoleByName

func GetRoleByName(name string) (*models.UserRole, error)

GetRoleByName retrieves a role by its name.

func GetSingleItemByType

func GetSingleItemByType(SingletonName string) (*models.SingleItem, error)

GetSingleItemByType retrieves the SingleItem for a given single type name.

func GetSingletonByName

func GetSingletonByName(name string) (*models.Singleton, error)

GetSingletonByName retrieves a single type by its name (including associated attributes).

func GetUserByID

func GetUserByID(id uint) (*models.User, error)

GetUserByID retrieves a user by their ID.

func GetUserByUsername

func GetUserByUsername(username string) (*models.User, error)

GetUserByUsername retrieves a user by their username.

func GetVisibleItem added in v0.4.0

func GetVisibleItem(ct models.Collection, itemID uint, publishedOnly bool) (*models.Item, error)

GetVisibleItem fetches an item of the collection. With publishedOnly, a draft of a draft-and-publish collection is reported as not found.

func GetWebhook added in v0.5.0

func GetWebhook(id uint) (*models.Webhook, error)

GetWebhook returns a webhook by ID.

func HashAPIToken added in v0.5.0

func HashAPIToken(secret string) string

HashAPIToken returns the stored form of a token secret. Tokens carry 256 bits of randomness, so a fast hash is enough (unlike passwords).

func InitMediaStore added in v0.4.0

func InitMediaStore(s media.Store)

InitMediaStore sets the store used for uploads and media URLs.

func InitQueue added in v0.6.0

func InitQueue(client queue.Client)

func InvalidateComponentCache added in v0.4.0

func InvalidateComponentCache()

InvalidateComponentCache drops cached component definitions.

func IsReferencedByOtherCollections

func IsReferencedByOtherCollections(collectionName string, tx *gorm.DB) ([]models.Attribute, error)

func ItemCollectionName added in v0.5.0

func ItemCollectionName(itemID uint) (string, error)

ItemCollectionName returns the name of the collection an item belongs to.

func LatestRevision added in v0.5.0

func LatestRevision(entityType string, entityID uint) (*models.Revision, error)

LatestRevision returns the newest revision of an entry.

func ListAPITokens added in v0.5.0

func ListAPITokens() ([]models.APIToken, error)

ListAPITokens returns every token, newest first.

func ListAgentRuns added in v0.5.0

func ListAgentRuns(agentID uint, q RunQuery) ([]agents.AgentRun, int, error)

ListAgentRuns returns an agent's runs, newest first (without steps).

func ListAllRuns added in v0.5.0

func ListAllRuns(q RunQuery) ([]agents.AgentRun, int, error)

ListAllRuns lists the runs of every agent, newest first (without steps).

func ListLocales added in v0.5.0

func ListLocales() ([]models.Locale, error)

ListLocales returns the locales, the default first.

func ListMedia added in v0.4.0

func ListMedia(q MediaQuery) ([]models.Media, int, error)

ListMedia lists media files, newest first.

func ListProposals added in v0.6.0

func ListProposals(q ProposalQuery) ([]models.Proposal, int, error)

ListProposals lists proposals, newest first.

func ListRevisions added in v0.5.0

func ListRevisions(q RevisionQuery) ([]models.Revision, int, error)

ListRevisions lists revisions, newest first, without their data.

func ListWebhookDeliveries added in v0.5.0

func ListWebhookDeliveries(webhookID uint, limit int) ([]models.WebhookDelivery, error)

ListWebhookDeliveries returns the newest delivery records of a webhook.

func ListWebhooks added in v0.5.0

func ListWebhooks() ([]models.Webhook, error)

ListWebhooks returns every webhook, oldest first.

func LocaleExists added in v0.5.0

func LocaleExists(code string) bool

LocaleExists reports whether a locale is configured.

func MediaStore added in v0.4.0

func MediaStore() media.Store

MediaStore returns the configured store (nil when uploads are disabled).

func MediaURL added in v0.4.0

func MediaURL(ctx context.Context, m models.Media) string

MediaURL returns the download URL of a media file.

func NestedWriteTargets added in v0.5.0

func NestedWriteTargets(ct models.Collection, data map[string]any) ([]string, error)

NestedWriteTargets lists the collections that writing data into ct may look up or create items in: relations given as objects without an "id" are matched against, or created in, their target (see models.ValidateItemValues). Raw IDs and {"id": …} only link items.

func NormalizePermissions added in v0.5.0

func NormalizePermissions(p auth.Permissions) (auth.Permissions, error)

NormalizePermissions validates permissions against the content model and returns them cleaned up: actions sorted and deduplicated, read added to any type with another action.

func PopulateMedia added in v0.4.0

func PopulateMedia(ctx context.Context, attrs []models.Attribute, data models.JSONMap) models.JSONMap

PopulateMedia replaces media IDs in an item's data (including inside components) with media objects.

func PopulateRelations added in v0.4.0

func PopulateRelations(collection models.Collection, data models.JSONMap, level uint, publishedOnly bool) (models.JSONMap, error)

PopulateRelations replaces relation IDs in data with the related items (in the API's flat item shape), down to level levels. With publishedOnly, drafts of draft-and-publish target collections are left out, as are related items that no longer exist.

func PopulateRelationsIn added in v0.5.0

func PopulateRelationsIn(collection models.Collection, data models.JSONMap, level uint, publishedOnly bool, loc ReadLocale) (models.JSONMap, error)

PopulateRelationsIn is PopulateRelations with related entries read in a locale (their localized attributes, and their locale fields).

func ProposalIsStale added in v0.6.0

func ProposalIsStale(p *models.Proposal) bool

ProposalIsStale reports whether the proposal's item changed since it was proposed.

func ProposeItemWrite added in v0.6.0

func ProposeItemWrite(actor Actor, ct models.Collection, action string, itemID uint, locale string, data models.JSONMap, reason string) (*models.Proposal, error)

ProposeItemWrite validates a change an agent wants to make and stores it as a pending proposal instead of applying it. action is models.ProposalCreate, ProposalUpdate or ProposalDelete; locale (update only) targets a translation.

func PruneAgentRuns added in v0.5.0

func PruneAgentRuns(agentID uint, keep int)

PruneAgentRuns keeps the newest keep runs of an agent (and their steps). Runs still in progress are never pruned.

func PublicAccessEnabled added in v0.6.0

func PublicAccessEnabled() bool

PublicAccessEnabled reports whether the public role grants anything, so anonymous requests are let in.

func QueryItems

func QueryItems(ct models.Collection, q ItemQuery) ([]models.Item, int, error)

QueryItems lists the items of a collection with optional filters and sort. Every field is validated against the collection schema; attribute names and values are always bound as SQL parameters.

func RecordWebhookDelivery added in v0.5.0

func RecordWebhookDelivery(d *models.WebhookDelivery)

RecordWebhookDelivery logs an attempt, updates the webhook's last status and trims old records.

func RejectProposal added in v0.6.0

func RejectProposal(id uint, reviewer, note string) (*models.Proposal, error)

RejectProposal discards a pending proposal.

func RenameLocale added in v0.5.0

func RenameLocale(code, name string) (*models.Locale, error)

RenameLocale changes a locale's display name.

func ResolveLocale added in v0.5.0

func ResolveLocale(requested string) (locale, defaultLocale string, err error)

ResolveLocale checks a requested locale and returns it with the default locale. "" means the default locale.

func ResolveMediaValue added in v0.4.0

func ResolveMediaValue(ctx context.Context, v any, multiple bool) any

ResolveMediaValue converts one stored media value (an ID, a list of IDs, or URL strings) to API objects; GraphQL uses it.

func RestoreOutcome added in v0.5.0

func RestoreOutcome(ct models.Collection, itemID, version uint) (undelete, published bool, err error)

RestoreOutcome tells whether restoring a version of an item would bring it back from deletion, and whether it would be published afterwards.

func RevokeAPIToken added in v0.5.0

func RevokeAPIToken(id uint) (*models.APIToken, error)

RevokeAPIToken makes a token unusable immediately. The record stays, so the audit trail (name, creator, last use) is kept.

func SaveAgent

func SaveAgent(agent *models.Agent) error

SaveAgent persists an Agent to the database, handling both new and soft-deleted records.

func SaveAgentRun added in v0.5.0

func SaveAgentRun(r *agents.AgentRun) error

SaveAgentRun stores the run's current state (usage, status, output). It only updates: a run deleted meanwhile (agent deleted) is not re-created.

func SaveCollection

func SaveCollection(ct *models.Collection) error

SaveCollection persists a Collection to the database, handling both new and soft-deleted records.

func SaveConversationHistory

func SaveConversationHistory(agentID uint, messages []llm.Message) error

SaveConversationHistory replaces the old history with the new one for an agent.

func SaveItem

func SaveItem(actor Actor, collection models.Collection, itemData models.JSONMap) (*models.Item, error)

SaveItem validates and creates a single item, then publishes an 'item:created' event once the transaction has committed.

func SaveItems

func SaveItems(actor Actor, collection models.Collection, batch []models.JSONMap) ([]*models.Item, error)

SaveItems validates and creates several items atomically, as drafts in draft-and-publish collections. See CreateItems.

func SaveMedia added in v0.4.0

func SaveMedia(ctx context.Context, in UploadFile, policy UploadPolicy) (*models.Media, error)

SaveMedia checks a file against the policy, stores its content and records it. The type is detected from the content, not from the client.

func SaveOrUpdateSingleton

func SaveOrUpdateSingleton(st *models.Singleton) error

SaveOrUpdateSingleton either creates a new single type or updates/restores a previously soft-deleted record with the same name.

This mimics the "single type" behavior in Strapi (one record per name).

func SaveRole

func SaveRole(role *models.UserRole) error

CreateRole creates a new role.

func SaveWebhook added in v0.5.0

func SaveWebhook(w *models.Webhook) error

SaveWebhook updates every field of a webhook.

func SetDefaultLocale added in v0.5.0

func SetDefaultLocale(code string) (*models.Locale, error)

SetDefaultLocale makes another locale the default. Entries' main data is in the default locale, so this only relabels it: it is refused while any entry has a translation in the new default (that content would be hidden), and the old default becomes a locale without translations.

func SetItemPublished added in v0.4.0

func SetItemPublished(actor Actor, collection models.Collection, itemID uint, publish bool) (*models.Item, error)

SetItemPublished publishes or unpublishes an item of a draft-and-publish collection. Publishing an already published item keeps its publishedAt.

func SetItemTranslation added in v0.5.0

func SetItemTranslation(actor Actor, ct models.Collection, itemID uint, locale string, data map[string]any, publish *bool) (*models.Item, error)

SetItemTranslation replaces an item's values in a locale other than the default. data holds localized attributes only; an empty object removes the translation. publish changes the publication state like an update.

func SetSingletonTranslation added in v0.5.0

func SetSingletonTranslation(actor Actor, st *models.Singleton, locale string, data map[string]any) (*models.SingleItem, error)

SetSingletonTranslation replaces a singleton's values in a locale other than the default (see SetItemTranslation). The singleton must have content already.

func UpdateAgent

func UpdateAgent(id uint, updated *models.Agent) error

UpdateAgent updates an existing Agent in the database by its ID.

func UpdateCollection

func UpdateCollection(id uint, updated *models.Collection) error

UpdateCollectionByID updates an existing Collection in the database by its ID.

func UpdateComponent

func UpdateComponent(name string, updated *models.Component) error

UpdateComponent updates an existing component definition by name.

func UpdateItemContent added in v0.4.0

func UpdateItemContent(actor Actor, collection models.Collection, itemID uint, data models.JSONMap, publish *bool) (*models.Item, error)

UpdateItemContent validates data (the item's complete new data) and saves it. publish changes the publication state of a draft-and-publish item (nil leaves it unchanged). It returns ErrItemNotFound when the item is not in the collection, an *ItemValidationError for invalid data, and publishes item:updated (plus item:published / item:unpublished on a state change). A change is recorded as a revision; a save that changes nothing is not, and sends no item:updated event (so agents reacting to each other's writes stop once their content agrees).

func UpdateMedia added in v0.4.0

func UpdateMedia(id uint, info MediaInfo) (*models.Media, error)

UpdateMedia changes a media file's name, alternative text or caption.

func UpdateRole

func UpdateRole(id uint, updates map[string]interface{}) error

UpdateRole updates an existing role by ID.

func UpdateSingleItem

func UpdateSingleItem(actor Actor, SingletonName string, newData map[string]any) (*models.SingleItem, error)

UpdateSingleItem updates the SingleItem for a given single type with new data and records a revision (unless nothing changed). Returns the updated SingleItem or an error if not found or validation fails.

func UpdateUser

func UpdateUser(id uint, updates map[string]interface{}) error

UpdateUser updates the details of an existing user by ID.

func WebhooksFor added in v0.5.0

func WebhooksFor(event, collection string) ([]models.Webhook, error)

WebhooksFor returns the enabled webhooks subscribed to event on collection.

func WithActor added in v0.5.0

func WithActor(ctx context.Context, a Actor) context.Context

WithActor returns a context carrying the actor, for code that writes content on someone's behalf (agent functions).

Types

type Actor added in v0.5.0

type Actor struct {
	Kind       string // models.ActorUser, ActorToken, ActorAgent or ActorSystem
	Name       string // username, token name or agent name
	AgentRunID uint   // the agent run, for agents

	// InRun marks changes made by an agent's functions while it runs. They
	// send no content events, whichever process runs the agent (a worker,
	// or `gohead standalone`), so agents can't trigger each other in loops.
	// Approved proposals are applied by a reviewer's request and do send
	// them (never to the agent that proposed the change).
	InRun bool
	// contains filtered or unexported fields
}

Actor is who makes a content change. It is recorded on each revision.

func ActorFrom added in v0.5.0

func ActorFrom(ctx context.Context) Actor

ActorFrom returns the context's actor, or SystemActor.

type AgentUsage added in v0.5.0

type AgentUsage struct {
	Runs         int     `json:"runs"` // runs that called the model (limited runs excluded)
	InputTokens  int     `json:"inputTokens"`
	OutputTokens int     `json:"outputTokens"`
	CostUSD      float64 `json:"costUsd"`
}

AgentUsage summarizes an agent's runs in a time window.

func AgentUsageBefore added in v0.5.0

func AgentUsageBefore(agentID uint, since time.Time, beforeRun uint, wasQueued bool) (AgentUsage, error)

AgentUsageBefore is AgentUsageSince over the runs created before run beforeRun, which orders runs starting at the same time. With wasQueued (a run recorded when it was requested and started later), runs started since that are not queued count too.

func AgentUsageSince added in v0.5.0

func AgentUsageSince(agentID uint, since time.Time, excludeRun uint) (AgentUsage, error)

AgentUsageSince sums an agent's runs started after since. Runs skipped by a limit do not count as runs, but tokens and cost spent by runs that a limit stopped midway do. excludeRun (or 0) is left out.

func (AgentUsage) Tokens added in v0.5.0

func (u AgentUsage) Tokens() int

Tokens is input plus output tokens.

type DBToolCall

type DBToolCall struct {
	ID           string `json:"id"`
	Type         string `json:"type"`
	FunctionName string `json:"function_name"`
	Arguments    string `json:"arguments"`
}

DBToolCall represents a simplified tool call for database storage

type DuplicateEntryError

type DuplicateEntryError struct {
	Field string
}

Custom error types

func (*DuplicateEntryError) Error

func (e *DuplicateEntryError) Error() string

type FieldChange added in v0.5.0

type FieldChange struct {
	Field  string `json:"field"`
	Change string `json:"change"` // added, removed or changed
	Before any    `json:"before"`
	After  any    `json:"after"`
}

FieldChange is one attribute that differs between two versions.

func DiffData added in v0.5.0

func DiffData(before, after models.JSONMap) []FieldChange

DiffData compares two data maps attribute by attribute, sorted by name.

type GeneralDatabaseError

type GeneralDatabaseError struct {
	Message string
}

func (*GeneralDatabaseError) Error

func (e *GeneralDatabaseError) Error() string

type ItemFilter

type ItemFilter struct {
	Field string
	Op    string
	Value string
}

ItemFilter is one condition on an item attribute (or a built-in column).

type ItemInput added in v0.4.0

type ItemInput struct {
	Data models.JSONMap
	// Publish creates the item as published. It is ignored unless the
	// collection uses draft and publish (other items are always visible).
	Publish bool
}

ItemInput is one item to create.

type ItemQuery

type ItemQuery struct {
	Page     int
	PageSize int
	Filters  []ItemFilter
	Sort     []ItemSort
	// Status filters draft-and-publish collections: "" (all items),
	// models.StatusPublished or models.StatusDraft. Ignored otherwise.
	Status string
	// Locale makes filters and sorts on localized attributes use that
	// locale's values ("" or the default locale: the main data). With
	// Fallback, a missing value falls back to the default locale's.
	Locale   string
	Fallback bool
}

ItemQuery describes a filtered, sorted, paginated item listing.

type ItemSort

type ItemSort struct {
	Field string
	Desc  bool
}

ItemSort orders results by an attribute or a built-in column.

type ItemValidationError

type ItemValidationError struct {
	Index int // position in a batch; 0 for single saves
	Err   error
}

ItemValidationError wraps a validation failure for an item, as opposed to a database error, so callers can answer 400 instead of 500.

func (*ItemValidationError) Error

func (e *ItemValidationError) Error() string

func (*ItemValidationError) Unwrap

func (e *ItemValidationError) Unwrap() error

type LocaleInUseError added in v0.5.0

type LocaleInUseError struct {
	Code    string
	Entries int64
}

LocaleInUseError reports content in a locale that would be lost or mislabelled.

func (*LocaleInUseError) Error added in v0.5.0

func (e *LocaleInUseError) Error() string

type MediaError added in v0.4.0

type MediaError struct {
	Status int // HTTP status to answer with
	Msg    string
}

MediaError is an upload refused for a reason the client can fix.

func (*MediaError) Error added in v0.4.0

func (e *MediaError) Error() string

type MediaInfo added in v0.4.0

type MediaInfo struct {
	Name    *string
	Alt     *string
	Caption *string
}

MediaInfo holds the editable fields of a media file.

type MediaQuery added in v0.4.0

type MediaQuery struct {
	Page, PageSize int
	MimePrefix     string // e.g. "image/" or "application/pdf"
	Search         string // substring of the file name
}

MediaQuery filters the media library.

type NewAPITokenInput added in v0.5.0

type NewAPITokenInput struct {
	Name        string
	Description string
	Role        string
	ExpiresAt   *time.Time
	CreatedBy   string
}

NewAPITokenInput describes a token to create.

type Overview added in v0.5.0

type Overview struct {
	Counts struct {
		Collections int64 `json:"collections"`
		Singletons  int64 `json:"singletons"`
		Components  int64 `json:"components"`
		Items       int64 `json:"items"`
		Media       int64 `json:"media"`
		MediaBytes  int64 `json:"mediaBytes"`
		Users       int64 `json:"users"`
		Agents      int64 `json:"agents"`
		Webhooks    int64 `json:"webhooks"`
		APITokens   int64 `json:"apiTokens"`
	} `json:"counts"`
	// Agent runs of the last 24 hours.
	Runs struct {
		Total        int64   `json:"total"`
		Succeeded    int64   `json:"succeeded"`
		Failed       int64   `json:"failed"`
		Limited      int64   `json:"limited"`
		Running      int64   `json:"running"`
		InputTokens  int64   `json:"inputTokens"`
		OutputTokens int64   `json:"outputTokens"`
		CostUSD      float64 `json:"costUsd"`
	} `json:"runs24h"`
	// Webhook deliveries of the last 24 hours.
	Deliveries struct {
		Total  int64 `json:"total"`
		Failed int64 `json:"failed"`
	} `json:"deliveries24h"`
	RecentItems      []RecentItem             `json:"recentItems"`
	RecentRuns       []agents.AgentRun        `json:"recentRuns"`
	RecentDeliveries []models.WebhookDelivery `json:"recentDeliveries"`
}

Overview summarizes an instance for the admin dashboard.

func GetOverview added in v0.5.0

func GetOverview(recent int) (*Overview, error)

GetOverview counts the content model, content, users and integrations, and lists recent activity.

type ProposalQuery added in v0.6.0

type ProposalQuery struct {
	Status     string // "" or "all": every status
	Collection string // one collection
	// Scope, when not nil, limits each action (create, update, delete) to
	// the collections listed for it: a reviewer's permissions.
	Scope      map[string][]string
	AgentName  string
	AgentRunID uint
	Page       int
	PageSize   int
}

ProposalQuery filters proposals.

type ProposalState added in v0.6.0

type ProposalState struct {
	// Stale: the item changed since the agent proposed the change.
	Stale bool
	// Current holds the item's values now (or the locale's), nil for a
	// creation or a deleted item.
	Current models.JSONMap
	// Proposed holds the values approving would write: for a stale update,
	// the item as it is now with the attributes the agent changed.
	Proposed models.JSONMap
	// Version is the item's latest version, which the change expects.
	Version uint
	// contains filtered or unexported fields
}

ProposalState is a proposal against the item as it is now.

func ProposalNow added in v0.6.0

func ProposalNow(p *models.Proposal) (*ProposalState, error)

ProposalNow compares a pending proposal with its item as it is now.

type QueryFieldError

type QueryFieldError struct{ Msg string }

QueryFieldError reports a filter or sort the collection cannot satisfy.

func (*QueryFieldError) Error

func (e *QueryFieldError) Error() string

type ReadLocale added in v0.5.0

type ReadLocale struct {
	Locale, Default string
	Fallback        bool
	// CanRead, when set, hides related entries of collections it refuses
	// (types the reader's role cannot read).
	CanRead func(collection string) bool
	// CanSeeDrafts, when set, hides related drafts of collections it
	// refuses, even when the request includes drafts.
	CanSeeDrafts func(collection string) bool
}

ReadLocale is the locale related entries are read in. The zero value reads the default locale.

type RecentItem added in v0.5.0

type RecentItem struct {
	ID         uint      `json:"id"`
	Collection string    `json:"collection"`
	Title      string    `json:"title"` // first text value, for display
	UpdatedAt  time.Time `json:"updatedAt"`
}

RecentItem is a recently changed item.

type RestoreResult added in v0.5.0

type RestoreResult struct {
	Revision *models.Revision // the new revision
	// Dropped lists attributes of the old version the type no longer has.
	Dropped []string
	// Undeleted is true when the restore brought back a deleted entry.
	Undeleted bool
	// Unchanged is true when the entry already had that content: no
	// revision was recorded, and Revision is the latest one.
	Unchanged bool
}

RestoreResult describes a restore.

func RestoreItemRevision added in v0.5.0

func RestoreItemRevision(actor Actor, ct models.Collection, itemID, version uint) (*models.Item, *RestoreResult, error)

RestoreItemRevision makes a version of an item its current content, as a new revision. A deleted item is brought back with the publication state the restored version had; otherwise the publication state is left as it is. The data is validated against the current schema.

func RestoreSingletonRevision added in v0.5.0

func RestoreSingletonRevision(actor Actor, st *models.Singleton, version uint) (*models.SingleItem, *RestoreResult, error)

RestoreSingletonRevision makes a version of a singleton's content its current content, as a new revision (re-creating deleted content).

type RevertOutcome added in v0.5.0

type RevertOutcome struct {
	EntityType string `json:"entityType"`
	EntityID   uint   `json:"entityId"`
	TypeName   string `json:"typeName"`
	// Result: reverted (restored the version before the run), deleted
	// (the run created the entry), skipped or failed.
	Result string `json:"result"`
	// Version restored, for "reverted".
	Version uint   `json:"version,omitempty"`
	Reason  string `json:"reason,omitempty"`
}

RevertOutcome is what reverting a run did to one entry.

func RevertAgentRun added in v0.5.0

func RevertAgentRun(actor Actor, runID uint, force bool) ([]RevertOutcome, error)

RevertAgentRun undoes the content changes of an agent run, entry by entry: entries the run created are deleted, the others go back to the version they had before the run. An entry changed by someone else after the run is skipped unless force is set.

type RevisionQuery added in v0.5.0

type RevisionQuery struct {
	EntityType string
	EntityID   uint
	TypeName   string
	Action     string
	ActorKind  string
	ActorName  string
	AgentRunID uint
	Page       int
	PageSize   int
	// Scope, when set, limits the list to these types (for roles that can
	// edit only some of them).
	Scope *RevisionScope
}

RevisionQuery filters a revision list.

type RevisionScope added in v0.5.0

type RevisionScope struct {
	Collections []string // collection names
	Singletons  []uint   // singleton IDs
}

RevisionScope lists the types whose history a role may see.

type RoleInUseError added in v0.5.0

type RoleInUseError struct {
	Users, Tokens int64
}

RoleInUseError is returned when deleting a role that accounts or API tokens still use.

func (*RoleInUseError) Error added in v0.5.0

func (e *RoleInUseError) Error() string

type RoleView added in v0.5.0

type RoleView struct {
	ID          uint   `json:"id"`
	Name        string `json:"name"`
	Description string `json:"description"`
	Builtin     bool   `json:"builtin"`
	// Public: the role of anonymous requests (read permissions only).
	Public      bool             `json:"public,omitempty"`
	Permissions auth.Permissions `json:"permissions"`
}

RoleView is a role with its permissions in API form.

func CreateCustomRole added in v0.5.0

func CreateCustomRole(name, description string, perms auth.Permissions) (*RoleView, error)

CreateCustomRole adds a role.

func GetRoleView added in v0.5.0

func GetRoleView(name string) (*RoleView, error)

GetRoleView returns one role.

func ListRoleViews added in v0.5.0

func ListRoleViews() ([]RoleView, error)

ListRoleViews lists every role: built-in ones, the public role, then custom roles.

func UpdateCustomRole added in v0.5.0

func UpdateCustomRole(name, description string, perms auth.Permissions) (*RoleView, error)

UpdateCustomRole replaces a custom role's description and permissions. Its name cannot change (accounts and tokens refer to it).

type RunQuery added in v0.5.0

type RunQuery struct {
	Page, PageSize int
	Status         string
}

RunQuery filters an agent's runs.

type UploadFile added in v0.4.0

type UploadFile struct {
	Name    string        // client file name
	Size    int64         // bytes
	Content io.ReadSeeker // positioned at the start
	Alt     string
	Caption string
	User    string
}

UploadFile describes one file to upload.

type UploadPolicy added in v0.4.0

type UploadPolicy struct {
	MaxSize      int64    // bytes; 0 means no limit
	AllowedTypes []string // MIME patterns; empty means media.DefaultAllowedTypes
}

UploadPolicy limits what can be uploaded.

Jump to

Keyboard shortcuts

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