dynamicresource

package
v0.0.0-...-d09923a Latest Latest
Warning

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

Go to latest
Published: Nov 5, 2026 License: LGPL-2.1 Imports: 51 Imported by: 1 module, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package composable is the dynamic-resource engine: schema-driven CRUD, org scoping, permission, computed fields, the built-in REST route table and its param binders, split into the onion layers a feature module already has: a repository, a domain service, an application service and a REST handler, each with a default implementation a module embeds and extends.

The split is what lets a resource expose an action as REST plus service API, or as service API only: a custom action is a method on the module's application service, and a REST route for it is an optional AddRoute call.

Index

Constants

View Source
const (
	ErrRowValidation          = "err_import_validation"
	ErrRowDuplicateExternalId = "err_import_duplicate_external_id"
	ErrRowExternalIdOtherOrg  = "err_import_external_id_in_other_org"
)

Row-level error codes shared by bulk create and import. They are translation keys.

View Source
const (
	// ParamComputeField names the field to compute; the REST engine fills it from the path.
	ParamComputeField = "field"
	// ParamComputeModel is the request body's unsaved model.
	ParamComputeModel = "model"
	// ParamComputeArgs is the request body's caller-supplied extras.
	ParamComputeArgs = "args"
)
View Source
const (
	ImportFormFile    = "file"
	ImportFormMapping = "mapping"
)

Multipart form parts of POST /{resource}/import.

View Source
const (
	ErrImportFileRequired       = "common:err_import_file_required"
	ErrImportFileUnreadable     = "common:err_import_file_unreadable"
	ErrImportTooManyRows        = "common:err_import_too_many_rows"
	ErrImportMappingInvalid     = "common:err_import_mapping_invalid"
	ErrImportMappingUnknown     = "common:err_import_mapping_unknown_field"
	ErrImportMappingDuplicate   = "common:err_import_mapping_duplicate_target"
	ErrImportHeaderNotFound     = "common:err_import_header_not_found"
	ErrImportMandatoryUnmapped  = "common:err_import_mandatory_unmapped"
	ErrImportStorageUnavailable = "common:err_import_storage_unavailable"
)

Request-level error keys: the caller can fix these by changing the request.

View Source
const (
	ErrRowCellInvalid           = "err_import_cell_invalid"
	ErrRowReferenceNotFound     = "err_import_reference_not_found"
	ErrRowReferenceAmbiguous    = "err_import_reference_ambiguous"
	ErrRowReferenceCreateFailed = "err_import_reference_create_failed"
)

Row-level error keys specific to import (the shared ones live in bulk_create.go).

View Source
const (
	FieldM2mAdd    = "add"
	FieldM2mRemove = "remove"
)
View Source
const (
	CrudActionCreate       = CrudAction("create")
	CrudActionUpdate       = CrudAction("update")
	CrudActionDelete       = CrudAction("delete")
	CrudActionSetArchived  = CrudAction("set_archived")
	CrudActionGetById      = CrudAction("get_by_id")
	CrudActionGetByUnique  = CrudAction("get_by_unique")
	CrudActionSearch       = CrudAction("search")
	CrudActionExists       = CrudAction("exists")
	CrudActionGetSchema    = CrudAction("get_schema")
	CrudActionComputeField = CrudAction("compute_field")
	CrudActionBulkCreate   = CrudAction("bulk_create")
	CrudActionImport       = CrudAction("import")
)
View Source
const (
	ActionTypeCreate        = ActionType("Create")
	ActionTypeDelete        = ActionType("Delete")
	ActionTypeRead          = ActionType("Read")
	ActionTypeUpdatePatch   = ActionType("UpdatePatch")
	ActionTypeUpdateReplace = ActionType("UpdateReplace")

	// ActionTypeGeneric is for actions whose semantics are none of the CRUD verbs, such as
	// "exists" or "suspend". It maps to POST so the action may carry a request body.
	ActionTypeGeneric = ActionType("Generic")

	// ActionTypeUpload is a multipart POST. The REST engine does not bind its body: the handler
	// reads the form itself and receives a nil payload.
	ActionTypeUpload = ActionType("Upload")

	// ActionTypeUploadPatch is ActionTypeUpload against an existing record: a multipart PATCH.
	//
	// It exists because a resource whose create accepts a file must be able to accept one on
	// update too, at the same ":id" path its JSON update uses. Serving that through
	// ActionTypeUpdatePatch instead would make the engine attempt a JSON bind of a multipart body,
	// which bindPayload reports as a 400 before the handler ever runs.
	ActionTypeUploadPatch = ActionType("UploadPatch")

	ActionTypeUploadReplace = ActionType("UploadReplace")
)
View Source
const (
	PermissionCreate      = "create"
	PermissionRead        = "read"
	PermissionUpdate      = "update"
	PermissionDelete      = "delete"
	PermissionSetArchived = "set_archived"
)

Permission action codes, matching what the IAM application services assert.

View Source
const (
	FieldSourceSystem = "source_system"
	FieldExternalId   = "external_id"

	SourceSystemManual = "manual"
	SourceSystemImport = "import"
)

Deduplication fields. A schema declaring both gets insert-or-update semantics in bulk create.

View Source
const DefaultImportLanguage = model.DefaultLanguageCode

DefaultImportLanguage fills a mapping that names no language, so a multilingual cell still lands under a real language key.

View Source
const EngineNamePrefix = "dynengine_"

EngineNamePrefix prefixes the dependency container name of every onion.

View Source
const ModuleName = "dynamicresource"

ModuleName is the name feature modules must list in their Deps() to use composable resource onions.

View Source
const RecordIdParam = basemodel.FieldId

RecordIdParam is the path parameter every single-row built-in route carries.

Variables

ModuleSingleton is the exported symbol that will be looked up by the plugin loader

View Source
var RestPathRegex = regexp.MustCompile(`^:?[a-zA-Z0-9_]+(/:?[a-zA-Z0-9_]+)*$`)

RestPathRegex accepts slash-separated segments of [a-zA-Z0-9_], where a segment may be an Echo path param (":name"). Hyphens are deliberately excluded: the word separator is "_".

Functions

func AssertActionPermission

func AssertActionPermission(
	ctx corectx.Context, appSvc CrudApplicationService, params dmodel.DynamicFields, perm ActionPermission,
) (*model.Id, *ft.ClientErrors)

AssertActionPermission is AssertRecordAction without the record check, for a collection action. It returns the org the request is confined to, nil when the resource is not org-scoped.

func AssertCallerInOrg

func AssertCallerInOrg(ctx corectx.Context, orgId model.Id) *ft.ClientErrors

AssertCallerInOrg refuses an org_id the caller may not act inside. It is exported so that a service outside the resource engine that accepts an org_id (org-level settings) answers a non-member with the same error the engine does.

Answering "not found" instead would hide the caller's own mistake behind the same response an empty org produces.

func AssertComputedFunctionsDefined

func AssertComputedFunctionsDefined() error

AssertComputedFunctionsDefined checks every built onion's "function"-kind computed fields against the functions registered on it. Every onion is reported rather than only the first, so one boot surfaces the whole gap.

func AssertRecordAction

func AssertRecordAction(
	ctx corectx.Context, appSvc CrudApplicationService, params dmodel.DynamicFields, perm ActionPermission,
) (*ft.ClientErrors, error)

AssertRecordAction authorizes a custom action addressed at one record by id: it resolves the serving resource's org scope, asserts the permission inside that org, then refuses a record of another org. It is the custom-action counterpart of what the built-in update does.

func BuiltSchemaNames

func BuiltSchemaNames() []string

BuiltSchemaNames lists every schema whose onion has been built so far, sorted. Onions are dig constructors, so one nobody resolved is absent; by OnAppStarted every routed onion is built.

func CreateDefaults

func CreateDefaults(
	ctx corectx.Context, svc CrudDomainService, rows []dmodel.DynamicFields, aliases *defaults.Aliases, orgId model.Id,
) error

CreateDefaults writes a module's `<schema>.json` defaults for one org through svc, resolving aliases against those already created. Every row goes through the domain service's Create, so ids, etags and the resource's own rules are what a REST create would apply.

func CreateOne

func CreateOne(ctx corectx.Context, svc CrudDomainService, row dmodel.DynamicFields) (model.Id, error)

CreateOne creates one record and returns its id; a client error is an error here, because defaults are not user input and a rejected one is a defect.

func DeleteOrgData

func DeleteOrgData(ctx corectx.Context, orgId model.Id, svcs ...CrudDomainService) error

DeleteOrgData deletes everything the org holds in each service's schema, in the order given: children before the parents they reference.

func DeleteOrgDataOf

func DeleteOrgDataOf(ctx corectx.Context, orgId model.Id, schemaNames ...string) error

DeleteOrgDataOf is DeleteOrgData over resources named by schema, children first.

func EngineDependencyName

func EngineDependencyName(schemaName string) string

EngineDependencyName is the container name of the onion serving the given schema.

func Identity

func Identity[TData any](data TData) any

Identity passes the result data through as the response body.

func InRefusableTransaction

func InRefusableTransaction(
	ctx corectx.Context, repo CrudRepository, body func(tranxCtx corectx.Context) (*ft.ClientErrors, error),
) (*ft.ClientErrors, error)

InRefusableTransaction is InTransaction for a body that may refuse the request with client errors after it has already written something. The refusal is carried out as a ClientErrorSignal so the transaction rolls back, then handed back as client errors.

When ctx carries the caller's transaction, rolling it back is the caller's decision: the refusal is still reported, and the caller sees the client errors before it commits.

func InTransaction

func InTransaction(
	ctx corectx.Context, repo CrudRepository, body func(tranxCtx corectx.Context) error,
) error

InTransaction joins the transaction ctx already carries - a bulk create, an import, or a caller that opened one - since the database client refuses a nested one, and otherwise opens its own through WithTransaction.

func IsAuditedSchema

func IsAuditedSchema(schemaName string) bool

IsAuditedSchema reports whether the resource records its mutations. A custom mutation that calls the port itself checks it too.

func MutateResponse

func MutateResponse(mutation dyn.MutateResultData) any

MutateResponse shapes a mutation result the way the built-in update and delete answer.

func NewLazyStorageConsumer

func NewLazyStorageConsumer() storage.StorageConsumer

NewLazyStorageConsumer is also what a domain service uses when it calls the port itself, such as to duplicate a file, for the same init-order reason.

func NewResourceAccess

func NewResourceAccess() resourceaccess.ResourceAccess

NewResourceAccess implements the core/resourceaccess port from the engine registry: the record is read through the target's own application GetById, as the caller, so the answer is exactly what opening the record would have been.

func ParamBool

func ParamBool(params dmodel.DynamicFields, field string) (bool, bool)

ParamBool reads a bool or *bool param. The second value reports whether one was present.

func ParamId

func ParamId(params dmodel.DynamicFields) model.Id

ParamId reads the record id out of a command or query. Empty when absent.

func ParamOrgId

func ParamOrgId(params dmodel.DynamicFields) *model.Id

ParamOrgId reads the org the caller named, or nil when the params carry none.

func ParamString

func ParamString(params dmodel.DynamicFields, field string) string

ParamString reads a string-typed param. model.Id and model.Etag are string types, so the string case covers them too. Anything else answers empty.

func RecordAudit

func RecordAudit(
	ctx corectx.Context, schema *dmodel.ModelSchema, action string, before, after dmodel.DynamicFields,
) error

RecordAudit is for a custom write that goes neither through the default domain service nor through Repository().Insert/Update/DeleteOne, such as a corecrud.UpdateRegardless caller. Call it inside the write's transaction with the row before and the fields written: a nil before is a create, a nil after a delete. Any other action is an update, recorded only when a field flagged audit.MetadataTrackHistory changed, with only the tracked fields.

func SchemaSupportsDedup

func SchemaSupportsDedup(schema *dmodel.ModelSchema) bool

SchemaSupportsDedup reports whether a schema carries the two deduplication fields, which is what switches bulk create from "insert every row" to "insert or update by external key".

func SearchRepositoryRows

func SearchRepositoryRows(
	ctx corectx.Context, repo CrudRepository, schemaName string, keyColumn string, keys []any, fields []string,
) ([]dmodel.DynamicFields, error)

SearchRepositoryRows runs the IN-keyed projection read a computed field needs against one repository.

func SearchResponse

func SearchResponse(paged dyn.PagedResultData[dmodel.DynamicFields]) any

SearchResponse shapes a search result the way the built-in search answers, for a custom sub-collection read such as ":id/roles".

func ServeAction

func ServeAction[TData any](
	echoCtx *echo.Context,
	action string,
	payload map[string]any,
	call func(ctx corectx.Context, params dmodel.DynamicFields) (*dyn.OpResult[TData], error),
	shape func(data TData) any,
) (err error)

ServeAction is the body of a custom route's handler: it hands the bound payload to an application-service method and answers the way the built-in handlers do. A client error answers 400, a result without data answers 400 with a not-found payload, and a Go error bubbles up as 500.

func (this *WarehouseRest) Suspend(echoCtx *echo.Context, payload map[string]any) error {
	return dynamicresource.ServeAction(echoCtx, "suspend warehouse", payload, this.warehouseSvc.Suspend, dynamicresource.MutateResponse)
}

func StartActionSpan

func StartActionSpan(ctx corectx.Context, schemaName string, action string) func(err error)

StartActionSpan opens an application action's span as the current span of ctx, in place, so the domain service and repository below record under it, and returns the func that ends it. Ending makes the previous span current again while keeping every value the action set on ctx meanwhile (acting org, request action), which a derived clone would have hidden from the caller.

func UpdateOne

func UpdateOne(ctx corectx.Context, svc CrudDomainService, id model.Id, fields dmodel.DynamicFields) error

UpdateOne sets fields on the record with this id, reading its current etag first. For wiring an edge between defaults after both ends exist.

func WithTransaction

func WithTransaction(
	ctx corectx.Context, repo CrudRepository, body func(tranxCtx corectx.Context) error,
) error

WithTransaction runs body inside one database transaction opened on repo, committing when body returns nil and rolling back otherwise. The body receives a cloned request context that carries the transaction, so every repository call made through it joins the same unit.

Types

type ActionPermission

type ActionPermission struct {
	ActionCode string

	// ResourceCode is empty for the serving resource itself.
	ResourceCode string

	// Scope applies only with ResourceCode. Nil means requestguard.ResourceScopeOrg.
	Scope *requestguard.ResourceScope
}

ActionPermission names the permission a custom action asserts. It is the resource's own unless ResourceCode names another one: assigning roles to a group asserts manage_role_assignments on iam_group even when the route is served by iam_role.

type ActionType

type ActionType string

ActionType classifies a route for the REST engine, which maps it to an HTTP method and decides how the request payload is bound.

func (ActionType) HasRequestBody

func (this ActionType) HasRequestBody() bool

HasRequestBody reports whether the REST engine reads a JSON body for this type. Upload is a multipart form, which the handler consumes itself.

func (ActionType) HttpMethod

func (this ActionType) HttpMethod() string

HttpMethod returns an empty string for an invalid type; callers validate before registering.

func (ActionType) IsUpload

func (this ActionType) IsUpload() bool

IsUpload reports whether the engine leaves this action's body to the handler. Every multipart type does; every other type is bound before the handler is called.

func (ActionType) IsValid

func (this ActionType) IsValid() bool

func (ActionType) String

func (this ActionType) String() string

type AfterValidationFn

type AfterValidationFn = corecrud.AfterValidationSuccessFn[*DynamicEntity]

AfterValidationFn runs after successful schema validation.

type AuditRecorder

type AuditRecorder interface {
	audit.AuditSink
	Enabled() bool
}

AuditRecorder is the audit port as the engine holds it: audit.LazyAuditSink in production, a fake in tests. Enabled is false in a binary without the auditlog module, and the engine then skips the before-row reads and the transactions it would only need for the entry.

type BeforeValidationFn

type BeforeValidationFn = corecrud.BeforeValidationFn[*DynamicEntity]

BeforeValidationFn may sanitize or enrich the model before schema validation.

func ChainBeforeValidation

func ChainBeforeValidation(fns ...BeforeValidationFn) BeforeValidationFn

ChainBeforeValidation runs the given hooks in order, each on the model the previous one returned, and stops at the first error or reported violation. Nil hooks are skipped; a chain of nothing is nil, which corecrud treats as "no hook".

type BuildParam

type BuildParam struct {
	dig.In

	Client        orm.DbClient
	ConfigSvc     config.ConfigService
	QueryBuilder  orm.QueryBuilder
	Logger        logging.LoggerService
	NewBaseRepoFn dyn.NewBaseDynamicRepositoryFn

	// Storage holds the transient file of an import. Optional so a binary without object storage
	// still builds every onion; import then answers a configuration error instead.
	Storage filestorage.FileStorageAdapter `optional:"true"`
}

BuildParam carries the core services every repository needs. A module's registration closure declares it as a constructor argument, so the container fills it:

deps.RegisterNamed(dynamicresource.EngineDependencyName(schema), func(param dynamicresource.BuildParam) dynamicresource.DynamicResourceEngineOnion {
	return dynamicresource.MustBuild(&dynamicresource.DynamicResourceEngineOnionImpl{SchemaName: schema, ...}, param)
})

type BulkCreateCommand

type BulkCreateCommand = dmodel.DynamicFields

BulkCreateCommand is the wire form of POST /{resource}/bulk: {org_id?, items: [{...}, ...]}.

type BulkCreateResult

type BulkCreateResult = dyn.OpResult[BulkCreateResultData]

func RunBulkCreate

func RunBulkCreate(
	ctx corectx.Context, domSvc CrudDomainService, rows []BulkRow, rejected []RowError,
) (*BulkCreateResult, error)

RunBulkCreate writes rows through domSvc inside one transaction and reports the outcome.

domSvc must be the outermost domain service of the resource (the module's own, when it has one) so that its Create/Update overrides and hooks run for every row exactly as they would for a single call. A row the schema or a hook rejects is reported in the result and skipped; a Go error - including a database refusal such as the unique-key last defence - aborts and rolls back every row.

rejected are rows the caller already refused (import conversion, unresolved references); they count toward TotalRows and are echoed in the errors list.

type BulkCreateResultData

type BulkCreateResultData struct {
	AffectedCount int                 `json:"affected_count"`
	CreatedCount  int                 `json:"created_count"`
	UpdatedCount  int                 `json:"updated_count"`
	AffectedAt    model.ModelDateTime `json:"affected_at"`
	TotalRows     int                 `json:"total_rows"`
	ErrorCount    int                 `json:"error_count"`
	Errors        []RowError          `json:"errors"`
}

BulkCreateResultData answers bulk_create and import alike: what was written, and which rows were skipped and why. Skipped rows are data, not client errors, because the caller cannot fix them by changing the request - only by changing the file.

type BulkRow

type BulkRow struct {
	Number int
	Fields dmodel.DynamicFields
}

BulkRow is one record to write, tagged with its 1-based position so a rejection can be pointed back at the caller's list or spreadsheet.

type ClientErrorSignal

type ClientErrorSignal struct {
	Errors ft.ClientErrors
}

ClientErrorSignal carries a rule violation out through a transaction body, so a rejected operation rolls back rather than committing half of itself. It is an error only in the plumbing sense: the caller unwraps it back into client errors, which answer 400 rather than 500.

func AsClientErrorSignal

func AsClientErrorSignal(err error) (ClientErrorSignal, bool)

func (ClientErrorSignal) Error

func (this ClientErrorSignal) Error() string

type ColumnMapping

type ColumnMapping struct {
	Source string `json:"source"`
	Target string `json:"target"`
}

ColumnMapping pairs a file header with a target field name. The referenced schema of an edge field is derived from the schema relations, never sent by the client.

type ComputeFieldCommand

type ComputeFieldCommand = dmodel.DynamicFields

Commands and queries are the field map itself. A resource declares its own aliases over these (type CreateUomCommand = dynamicresource.CreateCommand) so that its service signatures read as a hand-written module while the wire type stays the schema-agnostic map the binders, the org scoping helpers and the crud helpers already speak.

type ComputeFieldResult

type ComputeFieldResult = dyn.OpResult[ComputeFieldResultData]

type ComputeFieldResultData

type ComputeFieldResultData struct {
	DataType string `json:"data_type"`
	IsArray  bool   `json:"is_array"`
	Value    any    `json:"value"`
}

ComputeFieldResultData is the answer of a meta/compute call: the evaluated value with the declared type of the field, so a client can render it without knowing the function.

type ComputeFnRequest

type ComputeFnRequest struct {
	// SchemaName and FieldName identify what is being computed, so one function can serve several
	// fields or several schemas.
	SchemaName string
	FieldName  string

	// Models are the rows to compute over: a page of rows on a read, exactly one on a
	// meta/compute call, where it is the unsaved model the client posted.
	Models []dmodel.DynamicFields

	// Args carries the caller-supplied extras of a meta/compute call. Nil on a read.
	Args map[string]any
}

ComputeFnRequest is what a computed-field function is given.

type ComputedFieldFn

type ComputedFieldFn func(ctx corectx.Context, req ComputeFnRequest) ([]any, error)

ComputedFieldFn produces the value of a "function"-kind computed field.

It receives the whole page at once rather than one row at a time: a search returns up to a page of rows, and a per-row signature would turn any lookup the function performs into an N+1. It must return exactly one value per row in Models, in the same order; a length mismatch is an error, never a partial fill.

The function may resolve services from the dependency container. Resolve them once, when the module registers the function, and close over them.

type CreateCommand

type CreateCommand = dmodel.DynamicFields

Commands and queries are the field map itself. A resource declares its own aliases over these (type CreateUomCommand = dynamicresource.CreateCommand) so that its service signatures read as a hand-written module while the wire type stays the schema-agnostic map the binders, the org scoping helpers and the crud helpers already speak.

type CreateOptions

type CreateOptions struct {
	BeforeValidation       BeforeValidationFn
	AfterValidationSuccess AfterValidationFn
	ValidateExtra          ValidateExtraFn
}

CreateOptions are what a derived domain service passes when it calls the embedded default's Create: the override hands the hooks over on each call.

type CreateResult

type CreateResult = dyn.OpResult[dmodel.DynamicFields]

type CrudAction

type CrudAction string

CrudAction names one built-in action. The values double as action labels in error messages and as the allow-list vocabulary of NewDomainServiceParam.CrudActions.

func AllCrudActions

func AllCrudActions() []CrudAction

AllCrudActions lists every built-in action.

func ReadCrudActions

func ReadCrudActions() []CrudAction

func (CrudAction) String

func (this CrudAction) String() string

type CrudApplicationService

type CrudApplicationService interface {
	Create(ctx corectx.Context, cmd CreateCommand) (*CreateResult, error)
	Update(ctx corectx.Context, cmd UpdateCommand) (*MutateResult, error)
	Delete(ctx corectx.Context, cmd DeleteCommand) (*MutateResult, error)
	SetArchived(ctx corectx.Context, cmd SetArchivedCommand) (*MutateResult, error)
	GetById(ctx corectx.Context, query GetByIdQuery) (*GetOneResult, error)
	GetOne(ctx corectx.Context, query GetOneQuery) (*GetOneResult, error)
	Search(ctx corectx.Context, query SearchQuery) (*SearchResult, error)
	Exists(ctx corectx.Context, query ExistsQuery) (*ExistsResult, error)
	GetSchema(ctx corectx.Context, query GetSchemaQuery) (*GetSchemaResult, error)
	ComputeField(ctx corectx.Context, cmd ComputeFieldCommand) (*ComputeFieldResult, error)

	// CreateBulk writes {items: [...]} under one permission check and one transaction; a row
	// the schema rejects is reported in the result rather than failing the call.
	CreateBulk(ctx corectx.Context, cmd BulkCreateCommand) (*BulkCreateResult, error)

	// Import parses an uploaded xlsx/csv through a column mapping and writes it like CreateBulk.
	Import(ctx corectx.Context, cmd ImportCommand) (*BulkCreateResult, error)

	DomainService() CrudDomainService
	Schema() *dmodel.ModelSchema

	// ResourceCode is the permission resource code, which is the schema name.
	ResourceCode() string

	// The authorization machinery, reusable by a derived service's custom actions.
	AssertAction(ctx corectx.Context, actionCode string, params dmodel.DynamicFields) (*model.Id, *ft.ClientErrors)
	AssertPermission(ctx corectx.Context, actionCode string, orgId *model.Id) *ft.ClientErrors
	ResolveOrgScope(ctx corectx.Context, params dmodel.DynamicFields) (*model.Id, *ft.ClientErrors)
	// IsOrgBound reports a tenant catalogue answered per org (see NewAppServiceParam.IsOrgBound).
	IsOrgBound() bool
	ConstrainSearchToOrg(params dmodel.DynamicFields, orgId model.Id) error
	AssertRecordInOrg(ctx corectx.Context, params dmodel.DynamicFields, orgId model.Id) (*ft.ClientErrors, error)
	FetchByKeys(ctx corectx.Context, keys dmodel.DynamicFields, vErrs *ft.ClientErrors) (dmodel.DynamicFields, error)

	// Field-level authorization (see app_fieldauth.go), for a custom action that writes or returns
	// a field map of this resource.
	AssertFieldAction(ctx corectx.Context, actionCode string, params dmodel.DynamicFields) (*model.Id, *ft.ClientErrors)
	AssertFields(ctx corectx.Context, actionCode string, orgId *model.Id, fields dmodel.DynamicFields) *ft.ClientErrors
	AssertFieldNames(ctx corectx.Context, actionCode string, orgId *model.Id, names []string) *ft.ClientErrors
	NarrowReadFields(
		ctx corectx.Context, orgId *model.Id, desiredFields []string, records ...dmodel.DynamicFields,
	) []string
	AssertGraphReadable(ctx corectx.Context, orgId *model.Id, rawGraph any) (*ft.ClientErrors, error)
}

CrudApplicationService is the layer that authorizes. Every built-in method resolves the org scope, asserts the permission and only then delegates to the domain service, which is what a hand-written {entity}_appservice.go does.

A module extends it by embedding the default implementation into its own {Resource}ApplicationServiceImpl. A custom action is a method on that struct which calls AssertAction (and AssertRecordInOrg for a single-row action) before delegating. Whether the action also gets a REST route is decided in the transport layer with RestEngine.AddRoute; a method without a route is the resource's service-only API.

func NewDefaultApplicationService

func NewDefaultApplicationService(param NewAppServiceParam) CrudApplicationService

type CrudDomainService

type CrudDomainService interface {
	Create(ctx corectx.Context, cmd CreateCommand, options ...CreateOptions) (*CreateResult, error)
	// Update refuses a managed record (non-null managed_by_type): its manager changes it.
	Update(ctx corectx.Context, cmd UpdateCommand, options ...UpdateOptions) (*MutateResult, error)
	// UpdateManaged is the manager's update: the same path as Update, but it accepts only a
	// managed record. It has no REST route; the managing module calls it.
	UpdateManaged(ctx corectx.Context, cmd UpdateCommand, options ...UpdateOptions) (*MutateResult, error)
	// Delete refuses a managed record (non-null managed_by_type): its manager removes it.
	Delete(ctx corectx.Context, cmd DeleteCommand, options ...DeleteOptions) (*MutateResult, error)
	// DeleteManaged is the manager's delete: the same path as Delete, but it accepts only a
	// managed record. It has no REST route; the managing module calls it.
	DeleteManaged(ctx corectx.Context, cmd DeleteCommand, options ...DeleteOptions) (*MutateResult, error)
	SetArchived(ctx corectx.Context, cmd SetArchivedCommand) (*MutateResult, error)
	// DeleteByOrg removes every record of the org, for org cleanup. It runs no delete rule:
	// the whole org is going, so there is nothing left for a rule to protect.
	DeleteByOrg(ctx corectx.Context, orgId model.Id) (int, error)

	// GetById fetches one record by primary key. The query carries "id" and optional "fields".
	GetById(ctx corectx.Context, query GetByIdQuery) (*GetOneResult, error)

	// GetOne fetches one record by any unique key carried in the query. It has no REST route.
	GetOne(ctx corectx.Context, query GetOneQuery) (*GetOneResult, error)

	Search(ctx corectx.Context, query SearchQuery, options ...corecrud.ServiceSearchOptions) (*SearchResult, error)
	Exists(ctx corectx.Context, query ExistsQuery) (*ExistsResult, error)

	// ComputeField evaluates one "function"-kind computed field against the unsaved model the
	// command carries under "model", with optional "args".
	ComputeField(ctx corectx.Context, cmd ComputeFieldCommand) (*ComputeFieldResult, error)

	Schema() *dmodel.ModelSchema
	Repository() CrudRepository
}

CrudDomainService holds the business processing of a resource. It performs validation and orchestration, and invokes the repository when it needs to touch the database. It performs no permission check: that belongs to the application service, which sits above it.

A module extends it by embedding the default implementation into its own {Resource}DomainServiceImpl. An override of Create/Update/Delete adds its rules by passing options to the embedded default, so the rules run inside the crud helper and fire on a direct service call as well as on a REST call.

func NewDefaultDomainService

func NewDefaultDomainService(param NewDomainServiceParam) CrudDomainService

func ResolveDomainServices

func ResolveDomainServices(schemaNames ...string) ([]CrudDomainService, error)

ResolveDomainServices is ResolveEngines narrowed to each onion's domain service.

func WithComputedFields

func WithComputedFields(
	base CrudDomainService, sourceSearch SourceSearchFn, invokeFunction FunctionInvokeFn,
	defaultSearchFields []string,
) CrudDomainService

WithComputedFields decorates a domain service so declared computed fields evaluate on every read and reject every write. Wrapping is unconditional and costs nothing for a schema without computed fields: the eval planner returns nil and every call passes straight through.

The onion wraps the default before handing it to NewDomainServiceFn, so a module's derived service embeds the wrapped one and its overrides keep layering on top.

defaultSearchFields must be the same list the wrapped service falls back to when a search names no fields, otherwise a defaulted listing evaluates the wrong set of computed fields and reads operands the projection never selected.

type CrudRepository

type CrudRepository interface {
	// Embedding this interface lets the repository be passed directly to the generic helpers
	// of modules/core/dynamicmodel/crud, which expect a dyn.DynamicModelRepository.
	dyn.DynamicModelRepository

	BeginTransaction(ctx corectx.Context) (database.DbTransaction, error)

	Insert(ctx corectx.Context, data dmodel.DynamicFields) (*dyn.OpResult[int], error)
	Update(ctx corectx.Context, data dmodel.DynamicFields) (*MutateResult, error)
	DeleteOne(ctx corectx.Context, keys dmodel.DynamicFields) (*MutateResult, error)
	// DeleteByOrg deletes every row the org holds in this schema; it serves org cleanup only.
	DeleteByOrg(ctx corectx.Context, orgId model.Id) (int, error)

	// FindByKeys fetches the single record identified by the given primary or unique keys.
	FindByKeys(ctx corectx.Context, keys dmodel.DynamicFields) (*dyn.OpResult[dmodel.DynamicFields], error)
	// KeyExist tells whether a record matching every given key exists, reading no column; use it
	// instead of FindByKeys when the row itself is not needed.
	KeyExist(ctx corectx.Context, keys dmodel.DynamicFields) (*dyn.OpResult[bool], error)

	GetOne(ctx corectx.Context, param dyn.RepoGetOneParam) (*dyn.OpResult[dmodel.DynamicFields], error)
	Search(ctx corectx.Context, param dyn.RepoSearchParam) (*SearchResult, error)
	Exists(ctx corectx.Context, keys []dmodel.DynamicFields) (*dyn.OpResult[dyn.RepoExistsResult], error)

	Schema() *dmodel.ModelSchema
}

CrudRepository reads and writes the resource records through the SQL query builder.

A module extends it by embedding the default implementation into its own {Resource}RepositoryImpl and handing that struct to DynamicResourceEngineOnionImpl.NewRepositoryFn.

func LookupSourceRepository

func LookupSourceRepository(schemaName string) (CrudRepository, bool)

LookupSourceRepository returns the repository of a schema served by a composable onion.

func NewDefaultCrudRepository

func NewDefaultCrudRepository(param NewRepositoryParam) CrudRepository

type CrudRestBase

type CrudRestBase struct {
	httpserver.RestBase
	// contains filtered or unexported fields
}

CrudRestBase serves the built-in actions of one resource over HTTP. Every handler binds the request, calls the application service (which authorizes) and shapes the response the way the hand-written REST handlers in modules/core/httpserver do.

type UomRest struct{ dynamicresource.CrudRestBase }

func NewUomRest(param struct {
	dig.In
	Engine dynamicresource.DynamicResourceEngineOnion `name:"dynengine_essential_uom"`
}) *UomRest {
	rest := &UomRest{}
	rest.SetApplicationService(param.Engine.ApplicationService())
	return rest
}

func (*CrudRestBase) ApplicationService

func (this *CrudRestBase) ApplicationService() CrudApplicationService

func (*CrudRestBase) ComputeField

func (this *CrudRestBase) ComputeField(echoCtx *echo.Context) error

ComputeField serves POST {resource}/meta/compute/:field with a body of {model, args}.

func (*CrudRestBase) Create

func (this *CrudRestBase) Create(echoCtx *echo.Context) error

func (*CrudRestBase) CreateBulk

func (this *CrudRestBase) CreateBulk(echoCtx *echo.Context) error

CreateBulk serves POST {resource}/bulk with a body of {org_id?, items: [...]}. The body is bound raw: "items" is not a schema field, and each item is filtered by the create path.

func (*CrudRestBase) Delete

func (this *CrudRestBase) Delete(echoCtx *echo.Context) error

func (*CrudRestBase) Exists

func (this *CrudRestBase) Exists(echoCtx *echo.Context) error

func (*CrudRestBase) GetById

func (this *CrudRestBase) GetById(echoCtx *echo.Context) error

func (*CrudRestBase) GetSchema

func (this *CrudRestBase) GetSchema(echoCtx *echo.Context) error

func (*CrudRestBase) Import

func (this *CrudRestBase) Import(echoCtx *echo.Context) (err error)

Import serves POST {resource}/import: a multipart form with exactly two parts, "file" and "mapping" (a JSON document). org_id travels in the query string, as on every read route.

func (*CrudRestBase) Search

func (this *CrudRestBase) Search(echoCtx *echo.Context) error

Search answers 200 with an empty item list for a filter matching nothing, or a page past the end: HasData=false is a successful result there, not a missing record.

func (*CrudRestBase) SetApplicationService

func (this *CrudRestBase) SetApplicationService(svc CrudApplicationService)

func (*CrudRestBase) SetArchived

func (this *CrudRestBase) SetArchived(echoCtx *echo.Context) error

func (*CrudRestBase) Update

func (this *CrudRestBase) Update(echoCtx *echo.Context) error

type CrudRestHandlers

type CrudRestHandlers interface {
	Create(echoCtx *echo.Context) error
	Update(echoCtx *echo.Context) error
	Delete(echoCtx *echo.Context) error
	SetArchived(echoCtx *echo.Context) error
	GetById(echoCtx *echo.Context) error
	Search(echoCtx *echo.Context) error
	Exists(echoCtx *echo.Context) error
	GetSchema(echoCtx *echo.Context) error
	ComputeField(echoCtx *echo.Context) error
	CreateBulk(echoCtx *echo.Context) error
	Import(echoCtx *echo.Context) error

	ApplicationService() CrudApplicationService
}

CrudRestHandlers is what RestEngine.AddCrudRoutes binds. CrudRestBase implements it; a module's {Resource}Rest embeds CrudRestBase and adds its own handlers for AddRoute.

type DefaultApplicationServiceImpl

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

func (*DefaultApplicationServiceImpl) AssertAction

func (this *DefaultApplicationServiceImpl) AssertAction(
	ctx corectx.Context, actionCode string, params dmodel.DynamicFields,
) (*model.Id, *ft.ClientErrors)

AssertAction is the one call a built-in or custom action makes before touching data: it resolves the org the request is confined to, then asserts the caller holds actionCode on this resource inside that org. A nil org means the action is not org-scoped.

func (*DefaultApplicationServiceImpl) AssertFieldAction

func (this *DefaultApplicationServiceImpl) AssertFieldAction(
	ctx corectx.Context, actionCode string, params dmodel.DynamicFields,
) (*model.Id, *ft.ClientErrors)

AssertFieldAction is AssertAction for an action whose reach can be narrowed per field (create, read, update): the caller passes with a grant on the whole resource or on at least one of its fields. Pair it with AssertFields on what is written, or NarrowReadFields on what is returned - on its own it lets a holder of one field grant through.

func (*DefaultApplicationServiceImpl) AssertFieldNames

func (this *DefaultApplicationServiceImpl) AssertFieldNames(
	ctx corectx.Context, actionCode string, orgId *model.Id, names []string,
) *ft.ClientErrors

AssertFieldNames is AssertFields over field names, for a payload that is not a field map.

func (*DefaultApplicationServiceImpl) AssertFields

func (this *DefaultApplicationServiceImpl) AssertFields(
	ctx corectx.Context, actionCode string, orgId *model.Id, fields dmodel.DynamicFields,
) *ft.ClientErrors

AssertFields authorizes actionCode on every schema field fields carries. Keys naming no schema field (paging, "fields", a virtual param) and the addressing keys (see isAddressingField) are not data the caller writes or reads, so they need no field grant.

func (*DefaultApplicationServiceImpl) AssertGraphReadable

func (this *DefaultApplicationServiceImpl) AssertGraphReadable(
	ctx corectx.Context, orgId *model.Id, rawGraph any,
) (*ft.ClientErrors, error)

AssertGraphReadable refuses a search whose graph filters or sorts on a field the caller may not read: the rows it returns would disclose the field's value even with the column masked.

func (*DefaultApplicationServiceImpl) AssertPermission

func (this *DefaultApplicationServiceImpl) AssertPermission(
	ctx corectx.Context, actionCode string, orgId *model.Id,
) *ft.ClientErrors

AssertPermission checks the caller's entitlement for actionCode on this resource.

orgId names the org the record belongs to, and is nil for an action that is not org-scoped. Passing it through InOrg is what lets an org-scoped grant match: a Perm with no OrgId can only ever match an exact or domain grant. An empty actionCode skips the check.

func (*DefaultApplicationServiceImpl) AssertRecordInOrg

func (this *DefaultApplicationServiceImpl) AssertRecordInOrg(
	ctx corectx.Context, params dmodel.DynamicFields, orgId model.Id,
) (*ft.ClientErrors, error)

AssertRecordInOrg refuses a single-row action whose target row belongs to another org.

The crud commands behind get_by_id, update, delete and set_archived take an id and nothing else, so without this check a caller holding a grant in their own org could read or mutate any row whose id they knew, simply by naming their own org. A row in another org answers "not found" rather than "forbidden": the caller is not entitled to learn that the id exists. Params without an id are left to the action's own validation.

func (*DefaultApplicationServiceImpl) ComputeField

func (this *DefaultApplicationServiceImpl) ComputeField(
	ctx corectx.Context, cmd ComputeFieldCommand,
) (out *ComputeFieldResult, outErr error)

ComputeField evaluates a function-kind computed field over an unsaved model. The model travels in the command and there is no stored row to confine to an org, so only the permission is checked: computing a derived value discloses no more than reading the record would.

func (*DefaultApplicationServiceImpl) ConstrainSearchToOrg

func (this *DefaultApplicationServiceImpl) ConstrainSearchToOrg(
	params dmodel.DynamicFields, orgId model.Id,
) error

ConstrainSearchToOrg ANDs an org_id equality onto whatever graph the caller sent, so the org the caller named decides which rows a search can reach, not just which rows it asks for.

The caller's graph arrives as a decoded map, so it is re-marshalled through SearchGraph rather than manipulated in place: SearchGraph owns the graph's JSON shape.

func (*DefaultApplicationServiceImpl) Create

func (this *DefaultApplicationServiceImpl) Create(
	ctx corectx.Context, cmd CreateCommand,
) (out *CreateResult, outErr error)

Create defers a missing org_id to schema validation rather than reporting it here.

org_id is a declared required-for-create field on an org-scoped resource, so a create that omits it is a missing required field like any other, and must answer the same err_missing_required_field the rest of the payload would. Reporting err_org_id_required first would make one required field explain itself differently from its neighbours. An org_id that IS present still resolves here, so a caller naming an org they do not belong to is refused before the record is written.

func (*DefaultApplicationServiceImpl) CreateBulk

func (this *DefaultApplicationServiceImpl) CreateBulk(
	ctx corectx.Context, cmd BulkCreateCommand,
) (out *BulkCreateResult, outErr error)

CreateBulk writes many records under one permission check and one transaction. It lives on the application service rather than the domain service on purpose: the loop must call the OUTERMOST domain service so a module's Create/Update overrides run per row, and only the application layer holds that reference.

func (*DefaultApplicationServiceImpl) Delete

func (this *DefaultApplicationServiceImpl) Delete(
	ctx corectx.Context, cmd DeleteCommand,
) (out *MutateResult, outErr error)

func (*DefaultApplicationServiceImpl) DomainService

func (this *DefaultApplicationServiceImpl) DomainService() CrudDomainService

func (*DefaultApplicationServiceImpl) Exists

func (this *DefaultApplicationServiceImpl) Exists(
	ctx corectx.Context, query ExistsQuery,
) (out *ExistsResult, outErr error)

func (*DefaultApplicationServiceImpl) FetchByKeys

FetchByKeys loads the record a custom action wants to act on. A missing record is a client error reported through vErrs with a nil map, not a Go error.

A key of the wrong shape can never match a row, and reporting it as "not found" hides the caller's actual mistake, so each key is first checked against its declared data type.

func (*DefaultApplicationServiceImpl) GetById

func (this *DefaultApplicationServiceImpl) GetById(
	ctx corectx.Context, query GetByIdQuery,
) (out *GetOneResult, outErr error)

func (*DefaultApplicationServiceImpl) GetOne

func (this *DefaultApplicationServiceImpl) GetOne(
	ctx corectx.Context, query GetOneQuery,
) (out *GetOneResult, outErr error)

GetOne is org-confined through the normalized org_id itself: the domain service turns every column-named param, org_id included, into an equality condition.

func (*DefaultApplicationServiceImpl) GetSchema

func (this *DefaultApplicationServiceImpl) GetSchema(
	ctx corectx.Context, _ GetSchemaQuery,
) (out *GetSchemaResult, outErr error)

GetSchema serves the resource schema in the simplified shape the clients cache. It asserts no permission - the authenticated route is the only gate: the schema is metadata, identical for every caller (ToSimplized takes no caller input), which is what lets the Web BFF cache it across callers. A client needs it to render a locked field or edge it may not read, and an org-bound resource is flagged `is_org_bound` so any client sends org_id without knowing the resource.

func (*DefaultApplicationServiceImpl) Import

func (this *DefaultApplicationServiceImpl) Import(
	ctx corectx.Context, cmd ImportCommand,
) (out *BulkCreateResult, outErr error)

Import is POST {resource}/import: after the same permission check as create, the file is bounded by the configured limits, parked in object storage under a random name, parsed from there and written through bulk create. The object is removed whatever the outcome.

The order is deliberate - nothing touches storage before the permission check - for the reason coremart's vending-machine upload states: a stored file is a side effect a refused caller must not be able to cause.

func (*DefaultApplicationServiceImpl) IsOrgBound

func (this *DefaultApplicationServiceImpl) IsOrgBound() bool

IsOrgBound reports a tenant catalogue answered per org; its REST binders accept org_id although the schema declares no such field.

func (*DefaultApplicationServiceImpl) NarrowReadFields

func (this *DefaultApplicationServiceImpl) NarrowReadFields(
	ctx corectx.Context, orgId *model.Id, desiredFields []string, records ...dmodel.DynamicFields,
) []string

NarrowReadFields blanks, in place, every field of records the caller may not read, and returns the blanked names for the response's masked_fields. Following the masked-field contract of dyn.PagedResultData, a blanked field stays present as null, so a client can tell "locked" from "absent". desiredFields widens the masked list to fields asked for but missing from every record.

func (*DefaultApplicationServiceImpl) ResolveOrgScope

func (this *DefaultApplicationServiceImpl) ResolveOrgScope(
	ctx corectx.Context, params dmodel.DynamicFields,
) (*model.Id, *ft.ClientErrors)

ResolveOrgScope enforces the resource's org scoping and returns the org the request is confined to. A nil org means the resource is not org-scoped, and nothing downstream filters by org. The authoritative org_id is normalized back into params so that every downstream consumer - the search graph, the single-row key set, the create payload - reads one value. Whichever org is resolved also becomes the request's acting org (`${ctx.org_id}`).

An org-bound resource (no org_id column) resolves the org the same way, records it as the acting org, drops it from params (no column takes it) and returns nil: nothing filters by it.

func (*DefaultApplicationServiceImpl) ResourceCode

func (this *DefaultApplicationServiceImpl) ResourceCode() string

func (*DefaultApplicationServiceImpl) Schema

func (*DefaultApplicationServiceImpl) Search

func (this *DefaultApplicationServiceImpl) Search(
	ctx corectx.Context, query SearchQuery,
) (out *SearchResult, outErr error)

func (*DefaultApplicationServiceImpl) SetArchived

func (this *DefaultApplicationServiceImpl) SetArchived(
	ctx corectx.Context, cmd SetArchivedCommand,
) (out *MutateResult, outErr error)

func (*DefaultApplicationServiceImpl) Update

func (this *DefaultApplicationServiceImpl) Update(
	ctx corectx.Context, cmd UpdateCommand,
) (out *MutateResult, outErr error)

type DefaultCrudRepositoryImpl

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

DefaultCrudRepositoryImpl is the schema-agnostic counterpart of the hand-written repositories such as iam's UserDynamicRepository: it delegates to the same baserepo helpers, but speaks DynamicFields instead of a typed domain model.

func (*DefaultCrudRepositoryImpl) BeginTransaction

func (this *DefaultCrudRepositoryImpl) BeginTransaction(ctx corectx.Context) (database.DbTransaction, error)

func (*DefaultCrudRepositoryImpl) DeleteByOrg

func (this *DefaultCrudRepositoryImpl) DeleteByOrg(ctx corectx.Context, orgId model.Id) (int, error)

func (*DefaultCrudRepositoryImpl) DeleteOne

func (*DefaultCrudRepositoryImpl) Exists

func (*DefaultCrudRepositoryImpl) FindByKeys

FindByKeys reads every column of the schema.

func (*DefaultCrudRepositoryImpl) GetBaseRepo

func (*DefaultCrudRepositoryImpl) GetOne

func (*DefaultCrudRepositoryImpl) Insert

func (*DefaultCrudRepositoryImpl) KeyExist

func (*DefaultCrudRepositoryImpl) Schema

func (*DefaultCrudRepositoryImpl) Search

func (*DefaultCrudRepositoryImpl) Update

type DefaultDomainServiceImpl

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

DefaultDomainServiceImpl is the schema-agnostic domain service: what a feature module writes by hand in {entity}_domservice.go, minus anything resource-specific.

func (*DefaultDomainServiceImpl) ComputeField

func (*DefaultDomainServiceImpl) Create

func (this *DefaultDomainServiceImpl) Create(
	ctx corectx.Context, cmd CreateCommand, options ...CreateOptions,
) (*CreateResult, error)

func (*DefaultDomainServiceImpl) Delete

func (this *DefaultDomainServiceImpl) Delete(
	ctx corectx.Context, cmd DeleteCommand, options ...DeleteOptions,
) (*MutateResult, error)

func (*DefaultDomainServiceImpl) DeleteByOrg

func (this *DefaultDomainServiceImpl) DeleteByOrg(ctx corectx.Context, orgId model.Id) (int, error)

DeleteByOrg is not audited: it is the org's teardown, and the org's entries go with it.

func (*DefaultDomainServiceImpl) DeleteManaged

func (this *DefaultDomainServiceImpl) DeleteManaged(
	ctx corectx.Context, cmd DeleteCommand, options ...DeleteOptions,
) (*MutateResult, error)

func (*DefaultDomainServiceImpl) Exists

func (this *DefaultDomainServiceImpl) Exists(
	ctx corectx.Context, params ExistsQuery,
) (*ExistsResult, error)

func (*DefaultDomainServiceImpl) GetById

func (this *DefaultDomainServiceImpl) GetById(
	ctx corectx.Context, params GetByIdQuery,
) (*GetOneResult, error)

func (*DefaultDomainServiceImpl) GetOne

func (this *DefaultDomainServiceImpl) GetOne(
	ctx corectx.Context, params GetOneQuery,
) (*GetOneResult, error)

GetOne fetches one record by any unique key present in the query. Every param that names a schema column is used as an equality condition, so callers must pass only key fields.

func (*DefaultDomainServiceImpl) Repository

func (this *DefaultDomainServiceImpl) Repository() CrudRepository

func (*DefaultDomainServiceImpl) Schema

func (*DefaultDomainServiceImpl) Search

func (*DefaultDomainServiceImpl) SetArchived

func (this *DefaultDomainServiceImpl) SetArchived(
	ctx corectx.Context, cmd SetArchivedCommand,
) (*MutateResult, error)

func (*DefaultDomainServiceImpl) Update

func (this *DefaultDomainServiceImpl) Update(
	ctx corectx.Context, cmd UpdateCommand, options ...UpdateOptions,
) (*MutateResult, error)

func (*DefaultDomainServiceImpl) UpdateManaged

func (this *DefaultDomainServiceImpl) UpdateManaged(
	ctx corectx.Context, cmd UpdateCommand, options ...UpdateOptions,
) (*MutateResult, error)

type DeleteCommand

type DeleteCommand = dmodel.DynamicFields

Commands and queries are the field map itself. A resource declares its own aliases over these (type CreateUomCommand = dynamicresource.CreateCommand) so that its service signatures read as a hand-written module while the wire type stays the schema-agnostic map the binders, the org scoping helpers and the crud helpers already speak.

type DeleteOptions

type DeleteOptions struct {
	// ValidateExtra receives the stored record as foundModel: the default service fetches it
	// before running the hook, because a delete guard's whole job is to inspect the row.
	ValidateExtra ValidateExtraFn
}

type DynamicEntity

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

DynamicEntity is the schema-agnostic domain model of the composable engine. It carries nothing but the field map, which makes it usable as the TDomain type argument of the generic helpers in modules/core/dynamicmodel/crud and .../baserepo, no matter which schema the enclosing onion serves.

func NewDynamicEntity

func NewDynamicEntity() *DynamicEntity

func NewDynamicEntityFrom

func NewDynamicEntityFrom(fields dmodel.DynamicFields) *DynamicEntity

func (*DynamicEntity) GetFieldData

func (this *DynamicEntity) GetFieldData() dmodel.DynamicFields

GetFieldData implements dmodel.DynamicModelGetter.

func (*DynamicEntity) SetFieldData

func (this *DynamicEntity) SetFieldData(data dmodel.DynamicFields)

SetFieldData implements dmodel.DynamicModelSetter.

type DynamicResourceEngineOnion

type DynamicResourceEngineOnion interface {
	ResourceName() string
	Schema() *dmodel.ModelSchema
	Repository() CrudRepository
	DomainService() CrudDomainService
	ApplicationService() CrudApplicationService

	ComputedFieldFunction(name string) (ComputedFieldFn, bool)
	AssertComputedFunctionsDefined() error
}

DynamicResourceEngineOnion is one resource's stack of layers, built once and registered in the dependency container as "dynengine_{schema}". A REST handler injects it by that name to reach the application service; a module publishes the typed layers from it for other consumers.

func LookupSourceOnion

func LookupSourceOnion(schemaName string) (DynamicResourceEngineOnion, bool)

LookupSourceOnion returns the whole onion of a schema served by a composable engine, for a caller that needs the domain service of a sibling resource (import resolves and, on request, creates referenced records through it so their own rules run).

func MustBuild

MustBuild is Build for a dig constructor, where a wiring mistake should stop the boot.

func ResolveEngines

func ResolveEngines(schemaNames ...string) ([]DynamicResourceEngineOnion, error)

ResolveEngines returns the onions registered under dynengine_{schema} for each schema name, in order. It is for code that works over a list of resources rather than naming each typed layer, such as an org cleanup; a resource that needs its own rules is injected by type instead.

dig resolves a named value only through a struct tag, so the parameter struct is built at run time with one tagged field per schema.

type DynamicResourceEngineOnionImpl

type DynamicResourceEngineOnionImpl struct {
	SchemaName string

	// The factories receive the default layer and return the module's own, which embeds it.
	// The domain default handed over is already wrapped with computed-field evaluation.
	NewRepositoryFn    func(base CrudRepository) CrudRepository
	NewDomainServiceFn func(base CrudDomainService) CrudDomainService
	NewAppServiceFn    func(base CrudApplicationService) CrudApplicationService

	// CrudActions selects which built-in actions this resource supports. Nil means all.
	CrudActions []CrudAction

	// DefaultSearchFields is the field list a search returns when it names none. Empty means the
	// schema's own default_search_fields, then every column.
	DefaultSearchFields []string

	// PermissionScope applies to every permission check. Nil means requestguard.ResourceScopeOrg.
	PermissionScope *requestguard.ResourceScope

	// IsOrgScoped is nil-means-true; false withdraws org scoping for a resource whose org_id is
	// optional and NULL means "global".
	IsOrgScoped *bool

	// IsOrgBound makes a tenant-wide catalogue (no org_id column) answer per organization: every
	// action requires an org_id the caller belongs to, and that org becomes the `${ctx.org_id}` its
	// computed fields read (an activation flag), while rows are never filtered by org.
	IsOrgBound bool

	// RejectArchivedOnCreate refuses is_archived in a create body for a schema that has the
	// field, ahead of any rule a derived service adds.
	RejectArchivedOnCreate bool

	// ComputedFunctions implements the schema's "function"-kind computed fields, by name.
	ComputedFunctions map[string]ComputedFieldFn

	// IsAudited is nil-means-true: every mutation of the resource is recorded through the
	// core/audit port. false opts a resource out, which only the audit log itself should need.
	IsAudited *bool

	// AuditReads is nil-means-false: GetById and Search are recorded too, for a resource whose
	// reads are themselves sensitive.
	AuditReads *bool
	// contains filtered or unexported fields
}

DynamicResourceEngineOnionImpl declares a resource. Only SchemaName is required; every other field customizes one layer or one rule, and the zero value reproduces the default behaviour.

func (*DynamicResourceEngineOnionImpl) ApplicationService

func (this *DynamicResourceEngineOnionImpl) ApplicationService() CrudApplicationService

func (*DynamicResourceEngineOnionImpl) AssertComputedFunctionsDefined

func (this *DynamicResourceEngineOnionImpl) AssertComputedFunctionsDefined() error

func (*DynamicResourceEngineOnionImpl) Build

Build wires the three layers in order, handing each default to the module's factory, and indexes the result so computed fields of other resources can read this one.

func (*DynamicResourceEngineOnionImpl) ComputedFieldFunction

func (this *DynamicResourceEngineOnionImpl) ComputedFieldFunction(name string) (ComputedFieldFn, bool)

func (*DynamicResourceEngineOnionImpl) DomainService

func (this *DynamicResourceEngineOnionImpl) DomainService() CrudDomainService

func (*DynamicResourceEngineOnionImpl) Repository

func (*DynamicResourceEngineOnionImpl) ResourceName

func (this *DynamicResourceEngineOnionImpl) ResourceName() string

func (*DynamicResourceEngineOnionImpl) Schema

type DynamicResourceModule

type DynamicResourceModule struct {
}

func (*DynamicResourceModule) Category

func (*DynamicResourceModule) Deps

func (*DynamicResourceModule) Deps() []string

Deps implements InCodeModule.

func (*DynamicResourceModule) HasUi

func (*DynamicResourceModule) HasUi() bool

func (*DynamicResourceModule) Init

func (*DynamicResourceModule) Init() error

Init implements InCodeModule. The engine registry answers core/resourceaccess itself: every engine resource is reachable from it, so there is no feature module to bind the port to.

func (*DynamicResourceModule) IsInternal

func (*DynamicResourceModule) IsInternal() bool

IsInternal implements InCodeModule.

func (*DynamicResourceModule) LabelKey

func (*DynamicResourceModule) LabelKey() string

LabelKey implements InCodeModule.

func (*DynamicResourceModule) ModelPrefixes

func (*DynamicResourceModule) ModelPrefixes() []string

ModelPrefixes implements DynamicModule.

func (*DynamicResourceModule) Name

func (*DynamicResourceModule) Name() string

Name implements InCodeModule.

func (*DynamicResourceModule) OnAppStarted

func (*DynamicResourceModule) OnAppStarted() error

OnAppStarted implements InCodeModuleAppStarted.

It matches every "function"-kind computed field against the functions its onion registered. The check has to run here rather than at onion construction: a feature module builds its onions and registers their functions inside its own Init(), which is long after this module's. By the time any OnAppStarted runs, every module's Init() has completed — so a missing function fails the boot with a precise message instead of surfacing as a broken read later.

func (*DynamicResourceModule) Version

func (*DynamicResourceModule) Version() semver.SemVer

Version implements InCodeModule.

type ExistsQuery

type ExistsQuery = dmodel.DynamicFields

Commands and queries are the field map itself. A resource declares its own aliases over these (type CreateUomCommand = dynamicresource.CreateCommand) so that its service signatures read as a hand-written module while the wire type stays the schema-agnostic map the binders, the org scoping helpers and the crud helpers already speak.

type ExistsResult

type ExistsResult = dyn.OpResult[dyn.ExistsResultData]

type FunctionInvokeFn

type FunctionInvokeFn func(
	ctx corectx.Context, schemaName string, functionName string, fieldName string,
	rows []dmodel.DynamicFields,
) ([]any, error)

FunctionInvokeFn runs a registered computed-field function over a page of rows.

type GetByIdQuery

type GetByIdQuery = dmodel.DynamicFields

Commands and queries are the field map itself. A resource declares its own aliases over these (type CreateUomCommand = dynamicresource.CreateCommand) so that its service signatures read as a hand-written module while the wire type stays the schema-agnostic map the binders, the org scoping helpers and the crud helpers already speak.

type GetOneQuery

type GetOneQuery = dmodel.DynamicFields

Commands and queries are the field map itself. A resource declares its own aliases over these (type CreateUomCommand = dynamicresource.CreateCommand) so that its service signatures read as a hand-written module while the wire type stays the schema-agnostic map the binders, the org scoping helpers and the crud helpers already speak.

type GetSchemaQuery

type GetSchemaQuery = dmodel.DynamicFields

Commands and queries are the field map itself. A resource declares its own aliases over these (type CreateUomCommand = dynamicresource.CreateCommand) so that its service signatures read as a hand-written module while the wire type stays the schema-agnostic map the binders, the org scoping helpers and the crud helpers already speak.

type GetSchemaResult

type GetSchemaResult = dyn.OpResult[any]

type HandlerFn

type HandlerFn func(echoCtx *echo.Context, payload map[string]any) error

HandlerFn is the shape of a custom route's handler. payload is the request bound the way echo.Bind does (path, query on GET/DELETE, JSON body) plus the resolved org_id; it is nil for ActionTypeUpload, whose multipart form the handler reads itself.

type ImportCommand

type ImportCommand struct {
	Params     dmodel.DynamicFields
	FileHeader *multipart.FileHeader
	Mapping    ImportMapping
}

ImportCommand is what the REST handler hands to the application service. Params carries org_id (and anything else the query string named) so the org resolves exactly as on create.

type ImportLimits

type ImportLimits struct {
	MaxFileSizeBytes  int64
	AllowedExtensions []string
	MaxRows           int
}

ImportLimits is what the Configuration Service allows one import request to carry.

func (ImportLimits) IsAllowed

func (this ImportLimits) IsAllowed(ext string) bool

IsAllowed reports whether a filename extension (with or without the dot) is importable.

type ImportMapping

type ImportMapping struct {
	LanguageCode            string          `json:"language_code"`
	CreateMissingReferences bool            `json:"create_missing_references"`
	Columns                 []ColumnMapping `json:"columns"`
}

ImportMapping is the JSON carried by the "mapping" form part: which file column feeds which schema field, in which language a free-text cell is written, and whether a reference cell naming no stored record may create one.

type M2mChange

type M2mChange struct {
	SrcId   model.Id
	Added   []model.Id
	Removed []model.Id
}

M2mChange is what one manage call asked to link and unlink, handed to the hooks.

func ParseM2mChange

func ParseM2mChange(cmd ManageM2mCommand) (*M2mChange, *ft.ClientErrors)

ParseM2mChange reads the id and the add/remove id lists of a manage command. A list that is not an array of strings is the caller's mistake and answers a malformed-request error.

func (M2mChange) AllPeerIds

func (this M2mChange) AllPeerIds() []model.Id

AllPeerIds lists the added and the removed ids together, for a hook that refreshes every peer the call touched.

type ManageM2mCommand

type ManageM2mCommand = dmodel.DynamicFields

ManageM2mCommand carries "id" (the source record, from the path), "add" and "remove".

type ManageM2mParam

type ManageM2mParam struct {
	// Action labels the operation in error messages ("manage group users").
	Action string

	// DestSchemaName is the peer schema; the source schema must declare a many-to-many relation
	// to it.
	DestSchemaName string

	// JunctionIdField names the junction table's own id column, filled with a fresh id on every
	// inserted row. Empty for a junction keyed by the pair alone.
	JunctionIdField string

	// Validate runs before anything is written, inside the transaction. A violation appended to
	// vErrs refuses the call.
	Validate func(ctx corectx.Context, change M2mChange, vErrs *ft.ClientErrors) error

	// AfterChange runs after the junction rows changed, inside the same transaction, so a
	// permission rebuild stands or falls with the link. It does not run when the
	// call changed nothing. A returned error rolls the whole call back.
	AfterChange func(tranxCtx corectx.Context, change M2mChange) error
}

ManageM2mParam declares one many-to-many action of a resource.

type MutateResult

type MutateResult = dyn.OpResult[dyn.MutateResultData]

func ManageM2m

func ManageM2m(
	ctx corectx.Context, repo CrudRepository, cmd ManageM2mCommand, param ManageM2mParam,
) (*MutateResult, error)

ManageM2m links and unlinks the peers named in cmd, in one transaction with the hooks.

A call that changes nothing answers a result without data, which the REST layer reports as not-found exactly like the hand-written manage routes it replaces.

type NewAppServiceParam

type NewAppServiceParam struct {
	DomainService CrudDomainService

	// PermissionScope applies to every permission check. Nil means requestguard.ResourceScopeOrg.
	PermissionScope *requestguard.ResourceScope

	// IsOrgScoped confines every action to one organization: the caller must supply org_id, the
	// value must name an org the caller belongs to, and the action only ever sees records of
	// that org. Nil means true, because the unsafe direction is the silent one. It has no effect
	// on a resource whose schema declares no org_id field.
	IsOrgScoped *bool

	// IsOrgBound requires and checks org_id on a schema without an org_id column, recording it as
	// the request's acting org (`dyn.WithActingOrg`) without filtering rows. See the onion's field.
	IsOrgBound bool

	// CrudActions is the allow-list. Empty means every action is supported.
	CrudActions []CrudAction

	// Import support. Storage may be nil (see BuildParam.Storage); Logger may be nil in tests.
	Storage      filestorage.FileStorageAdapter
	ImportLimits ImportLimits
	Logger       logging.LoggerService

	// AuditSink records GetById and Search. Nil unless the resource opted in (AuditReads).
	AuditSink AuditRecorder
}

NewAppServiceParam carries what a default application service needs to work.

type NewDomainServiceParam

type NewDomainServiceParam struct {
	Schema     *dmodel.ModelSchema
	Repository CrudRepository

	// DefaultFields is returned by a search that specifies neither fields nor a resolvable view.
	// When empty, every column of the schema is returned.
	DefaultFields []string

	// CrudActions is the allow-list. Empty means every action is supported.
	CrudActions []CrudAction

	// ComputedFunction resolves the Go implementation of a "function"-kind computed field. Nil
	// when the resource registers none.
	ComputedFunction func(name string) (ComputedFieldFn, bool)

	// StorageConsumer drives the lifecycle of the schema's file fields (metadata.file_field).
	// Nil when the binary has no storage module; file fields are then stored unchecked.
	StorageConsumer storage.StorageConsumer

	// AuditSink records every create, update, delete and set_archived in the write's transaction.
	// Nil for a resource that opted out (IsAudited false).
	AuditSink AuditRecorder
}

NewDomainServiceParam carries what a default domain service needs to work.

type NewRepositoryParam

type NewRepositoryParam struct {
	Client        orm.DbClient
	ConfigSvc     config.ConfigService
	QueryBuilder  orm.QueryBuilder
	Logger        logging.LoggerService
	NewBaseRepoFn dyn.NewBaseDynamicRepositoryFn
	Schema        *dmodel.ModelSchema

	// AuditSink records the direct Insert, Update and DeleteOne a custom domain method makes.
	// Nil for a resource that opted out (IsAudited false).
	AuditSink AuditRecorder
}

NewRepositoryParam carries the core services a repository needs. The onion fills it from BuildParam for the schema it serves.

type OrgDataCleanup

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

OrgDataCleanup is the org lifecycle of a module that writes no defaults: InitOrg does nothing and CleanUpOrg deletes the org's rows of each schema, in the order given (children first), in one transaction. A module embeds it in its own OrgLifecycleAppServiceImpl.

func NewOrgDataCleanup

func NewOrgDataCleanup(schemaNames ...string) OrgDataCleanup

func (OrgDataCleanup) CleanUpOrg

func (this OrgDataCleanup) CleanUpOrg(ctx corectx.Context, orgId model.Id) error

func (OrgDataCleanup) InitOrg

func (this OrgDataCleanup) InitOrg(corectx.Context, model.Id) error

type RestEngine

type RestEngine interface {
	// AddCrudRoutes adds the built-in route table, or only the named actions when given.
	// GetByUnique has no route: it is the service-only read by unique key.
	AddCrudRoutes(only ...CrudAction) RestEngine

	AddRoute(def RouteDefinition) RestEngine

	// RegisterRoutes adds every route under "/{schema}" of the group. The optional middlewares
	// replace UserSmokeAuthz on authorized routes, which is what a test passes to avoid the
	// container; a public route keeps PublicUnauthorized regardless.
	RegisterRoutes(group *echo.Group, authorizedMiddlewares ...echo.MiddlewareFunc) error
}

RestEngine registers the routes of one resource onto an echo group, in an order that keeps a literal path such as "meta/schema" ahead of the ":id" pattern that would swallow it.

func NewRestEngine

func NewRestEngine(schemaName string, handlers CrudRestHandlers) RestEngine

type RestEngineImpl

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

func (*RestEngineImpl) AddCrudRoutes

func (this *RestEngineImpl) AddCrudRoutes(only ...CrudAction) RestEngine

func (*RestEngineImpl) AddRoute

func (this *RestEngineImpl) AddRoute(def RouteDefinition) RestEngine

func (*RestEngineImpl) RegisterRoutes

func (this *RestEngineImpl) RegisterRoutes(group *echo.Group, authorizedMiddlewares ...echo.MiddlewareFunc) error

RegisterRoutes registers by decreasing specificity: paths with fewer path params first, then deeper paths, then alphabetically. Echo matches in registration order, so that places "meta/schema" and "exists" ahead of ":id", and ":id/archived" ahead of ":id".

type RouteDefinition

type RouteDefinition struct {
	// Path is relative to the resource base and may carry Echo path params (":id"). An empty
	// string is the resource base itself. Segments are [a-zA-Z0-9_]; hyphens are rejected.
	Path string

	// ActionType decides the HTTP method and how the payload is bound.
	ActionType ActionType

	HandlerFn HandlerFn

	// IsAuthorized adds the UserSmokeAuthz middleware, which verifies the caller's token and then
	// asserts that some layer actually performed a permission check. Nil means true. A public
	// endpoint (false) gets PublicUnauthorized instead; it must never reach an AssertAction.
	IsAuthorized *bool

	// Middlewares are appended after the authorization middleware.
	Middlewares []echo.MiddlewareFunc
}

RouteDefinition declares one custom route of a resource.

type RowError

type RowError struct {
	Row    int            `json:"row"`
	Field  string         `json:"field,omitempty"`
	Code   string         `json:"code"`
	Params map[string]any `json:"params,omitempty"`
}

RowError locates one rejected row. Row is 1-based over the data rows, the header excluded, so it matches what the user sees in a spreadsheet minus the header line.

type SearchQuery

type SearchQuery = dmodel.DynamicFields

Commands and queries are the field map itself. A resource declares its own aliases over these (type CreateUomCommand = dynamicresource.CreateCommand) so that its service signatures read as a hand-written module while the wire type stays the schema-agnostic map the binders, the org scoping helpers and the crud helpers already speak.

type SearchResult

func SearchLinked

func SearchLinked(
	ctx corectx.Context, peer CrudDomainService, query SearchQuery, peerEdge string, srcId model.Id,
	defaultFields []string,
) (*SearchResult, error)

SearchLinked lists the peers linked to one record through a many-to-many edge the peer declares: a search of the peer resource with "<peerEdge> linked <srcId>" ANDed onto the caller's graph. defaultFields applies when the query names none.

type SetArchivedCommand

type SetArchivedCommand = dmodel.DynamicFields

Commands and queries are the field map itself. A resource declares its own aliases over these (type CreateUomCommand = dynamicresource.CreateCommand) so that its service signatures read as a hand-written module while the wire type stays the schema-agnostic map the binders, the org scoping helpers and the crud helpers already speak.

type SourceSearchFn

type SourceSearchFn func(
	ctx corectx.Context, schemaName string, keyColumn string, keys []any, fields []string,
) ([]dmodel.DynamicFields, error)

SourceSearchFn fetches rows of another resource for a batched related-field read.

type UpdateCommand

type UpdateCommand = dmodel.DynamicFields

Commands and queries are the field map itself. A resource declares its own aliases over these (type CreateUomCommand = dynamicresource.CreateCommand) so that its service signatures read as a hand-written module while the wire type stays the schema-agnostic map the binders, the org scoping helpers and the crud helpers already speak.

type UpdateOptions

type UpdateOptions struct {
	BeforeValidation       BeforeValidationFn
	AfterValidationSuccess AfterValidationFn
	ValidateExtra          ValidateExtraFn
}

type ValidateExtraFn

type ValidateExtraFn = corecrud.UpdateValidateExtraFn[*DynamicEntity]

ValidateExtraFn performs validation the schema cannot express.

It is the corecrud *update* hook shape, the wider of the two, so one type serves create, update and delete. On update and delete, foundModel is the stored record. On create there is no stored record and foundModel is nil, so a hook that reads it must nil-check first.

func ChainValidateExtra

func ChainValidateExtra(fns ...ValidateExtraFn) ValidateExtraFn

ChainValidateExtra runs the given hooks in order and stops at the first one that reports a violation, so a guard placed first keeps a later rule from running against input it already refused. Nil hooks are skipped; a chain of nothing is nil, which corecrud treats as "no hook".

func KeepId

func KeepId(id string) ValidateExtraFn

KeepId restores an id the caller generated before Create, because schema validation regenerates an auto-generated primary key. Only for an internal caller that must stamp the id on other records first (a managing record's managed_by_id, a slot's location); a REST create never uses it.

func RejectArchivedOnCreate

func RejectArchivedOnCreate(schema *dmodel.ModelSchema, cmd CreateCommand) ValidateExtraFn

RejectArchivedOnCreate refuses a create that carries is_archived, which is set through the /archived action and never as a create field. The schema validator drops it silently, answering 201 with a record whose visibility is not what the caller asked for, so it is reported instead. Nil for a schema without an is_archived field.

cmd is the command as the client sent it. The check cannot be made against the entity the hook receives: corecrud calls InjectServiceFields before ValidateExtra, which applies the schema's own default for is_archived, so by then the field is present on every create and the guard would refuse them all.

Jump to

Keyboard shortcuts

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