Files
oikos/internal/core/ports/entities.go
dtoro 65f415f9db
Some checks failed
ci / build-test (push) Has been cancelled
ci / docker-build (push) Has been cancelled
feat: Phase 3d — ReadModels port, postgres impl, HTTP reads rewire
Problem: entity/relationship/graph/blast-radius reads were embedded
as inline SQL in the httpapi handlers, duplicating the recursive type
tree CTE, the blast_radius function call, and the topology-picking
query across the REST and MCP surfaces with no port abstraction.

Change:
- ports.ReadModels interface: ListEntities, GetEntity, GetEntityBySlug,
  GetEntityRelations, GetBlastRadius, GetGraph (with health),
  ListEntityTypes. Returns EntityWithHealth (domain.Entity + health
  from entity_status join) and domain.Relationship — no gen types
  in the port.
- adapters/postgres/readmodels.go: EntityReader implements ReadModels
  with the existing SQL verbatim (recursive type filter, blast_radius,
  most-connected-first topology, graph edge listing).
- httpapi/entities.go: ListEntities, GetEntity, GetEntityRelations,
  GetBlastRadius, GetGraph rewired to ReadModels. SQL moved to the
  adapter; handlers map domain/ports types to gen wire shapes.
  entityWithHealthToGen, sqlcEntityToGen helpers added.
- Old sqlcEntityToGen (sqlcgen.Entity → gen.Entity) preserved for
  client_lifecycle.go; mutation handlers use domainToGen.

Verification: go build/vet, full test suite (19 pkgs), DB integration
(postgres + mcp — both green). httpapi DB tests have the pre-existing
set of failures (TestAPIEndToEnd entity_types=60/501, TestPhase3*)
verified at ec11956.
2026-08-15 23:58:31 +02:00

150 lines
5.6 KiB
Go

package ports
import (
"time"
"context"
"github.com/dtoro/oikos/internal/core/domain"
"github.com/dtoro/oikos/internal/ontology"
)
// TypeTree is the loaded ontology: entity types, relationship types,
// lifecycle definitions. It is ontology's pure tree behind an interface so
// ports does not alias a concrete struct into the contract.
type TypeTree = *ontology.TypeTree
// EntityFilters bounds entity list/search reads.
type EntityFilters struct {
Type string
State string
Q string
Domain string
Layer string
Cursor string
Limit int
}
// DerivedCheck is one concrete check derived from an entity's type
// monitoring spec, to be written in the same transaction as the entity
// mutation that produced it.
type DerivedCheck struct {
Kind string
Config map[string]any
IntervalS int
}
// Idempotency replays-protects one command: the adapter stores the cached
// response inside the same transaction as the mutation, so a crash between
// the two cannot let a replay re-execute. RenderBody is a pure presenter
// closure that serializes the committed entity into the caller's wire
// shape; the repository never inspects it.
type Idempotency struct {
Actor string
Key string
RequestHash string
RenderBody func(domain.Entity) []byte
}
// IdempotentResponse is a previously cached response for (actor, key).
type IdempotentResponse struct {
RequestHash string
ResponseCode int
ResponseBody []byte
}
// EntityCreateInput is one transaction: the entity, its derived check
// definitions, and the audit/event side-effects of the creation.
type EntityCreateInput struct {
Entity domain.Entity
DerivedChecks []DerivedCheck
Audit []AuditEntry
Event *Event
Idempotency *Idempotency
}
// EntityUpdateInput mutates an entity atomically. ExpectedVersion is the
// optimistic-concurrency check (0 disables it). When RederiveChecks is set,
// the repository re-derives default checks inside the transaction — the
// graph host fallback (a service inherits its container's address) reads
// relationships through the open transaction, so derivation cannot happen
// in the service for updates.
type EntityUpdateInput struct {
Entity domain.Entity
ExpectedVersion int
RederiveChecks bool
Audit []AuditEntry
Event *Event
Idempotency *Idempotency
}
// EntityTransitionInput is a lifecycle state change: the declared-transition
// check and preconditions are validated inside the transaction
// (check-then-act), not against the possibly-stale From.
type EntityTransitionInput struct {
Slug string
From string
To string
Audit []AuditEntry
Event *Event
}
// EntityRepository is the entity aggregate. Command methods are
// transaction-scoped: everything in the input commits or nothing does.
type EntityRepository interface {
Get(ctx context.Context, id domain.UUID) (domain.Entity, error)
BySlug(ctx context.Context, slug string) (domain.Entity, error)
List(ctx context.Context, filters EntityFilters) ([]domain.Entity, string, error)
Search(ctx context.Context, q string, limit int) ([]domain.Entity, error)
Create(ctx context.Context, input EntityCreateInput) (domain.Entity, error)
Update(ctx context.Context, input EntityUpdateInput) (domain.Entity, error)
SetState(ctx context.Context, input EntityTransitionInput) (domain.Entity, error)
// GetIdempotent returns the cached response for (actor, key), or
// domain.ErrNotFound when none exists.
GetIdempotent(ctx context.Context, actor, key string) (IdempotentResponse, error)
}
// RelationshipCreateInput validates endpoints against the ontology in core
// before this is called; the repository persists the edge (+audit/event).
type RelationshipCreateInput struct {
Relationship domain.Relationship
Audit []AuditEntry
Event *Event
}
// RelationshipRepository is the relationship aggregate.
type RelationshipRepository interface {
Create(ctx context.Context, input RelationshipCreateInput) (domain.Relationship, error)
End(ctx context.Context, source, target domain.UUID, relType string) error
ListFor(ctx context.Context, entityID domain.UUID, direction string) ([]domain.Relationship, error)
}
// EntityWithHealth pairs an entity with its probe health (from the
// entity_status join — the read shape graph/report endpoints need).
type EntityWithHealth struct {
Entity domain.Entity
Health string
LastCheckAt *time.Time
}
// ReadModels surfaces query-shaped report reads consumed directly by the
// httpapi/mcpserver adapters (no service hop — invariant-free reads, plan
// §3.4). Methods accrete per phase as report handlers rewire.
type ReadModels interface {
ListEntities(ctx context.Context, filters EntityFilters) ([]EntityWithHealth, string, error)
GetEntity(ctx context.Context, id domain.UUID) (EntityWithHealth, error)
GetEntityBySlug(ctx context.Context, slug string) (EntityWithHealth, error)
GetEntityRelations(ctx context.Context, entityID domain.UUID, direction, relType string) ([]domain.Relationship, error)
GetBlastRadius(ctx context.Context, entityID domain.UUID, depth int) ([]EntityWithHealth, error)
GetGraph(ctx context.Context, depth int, root *domain.UUID, relTypes []string, cap int) (nodes []EntityWithHealth, edges []domain.Relationship, truncated bool, err error)
ListEntityTypes(ctx context.Context) ([]domain.EntityType, error)
}
// OntologyStore loads the type tree; implementations cache. Consumers
// validate entity types, relationship endpoints, and lifecycle transitions
// against it before issuing repository writes.
type OntologyStore interface {
LoadTypeTree(ctx context.Context) (TypeTree, error)
}