Documentation
¶
Overview ¶
Package relations implements the entity relations widget for Chronicle. Relations are bi-directional links between entities within a campaign. When a relation is created from entity A to entity B, the reverse relation is automatically created from B to A. This enables graph-like navigation between entities (e.g., "allied with", "parent of"/"child of").
Relations are a Widget in Chronicle's three-tier extension architecture: they provide API endpoints for the frontend relations display component and are mounted on entity profile pages.
Index ¶
- Constants
- Variables
- func RegisterRoutes(e *echo.Echo, h *Handler, campaignSvc campaigns.CampaignService, ...)
- type CampaignRelation
- type CreateRelationRequest
- type EntityGate
- type EntityTypeListerForGraph
- type EntityTypeSummary
- type EntityViewFilter
- type GraphData
- type GraphEdge
- type GraphFilter
- type GraphNode
- type GraphRelation
- type Handler
- func (h *Handler) CreateRelation(c *echo.Context) error
- func (h *Handler) DeleteRelation(c *echo.Context) error
- func (h *Handler) FirstPaint(ctx context.Context, cc *campaigns.CampaignContext, entityID, userID string, ...) (relations []Relation, types any, err error)
- func (h *Handler) GetCommonTypes(c *echo.Context) error
- func (h *Handler) GraphAPI(c *echo.Context) error
- func (h *Handler) GraphPage(c *echo.Context) error
- func (h *Handler) ListRelations(c *echo.Context) error
- func (h *Handler) SetEntityGate(gate EntityGate)
- func (h *Handler) SetEntityTypeLister(lister EntityTypeListerForGraph)
- func (h *Handler) UpdateRelationMetadata(c *echo.Context) error
- type ListingObserver
- type MentionLinkData
- type MentionLinkProvider
- type Relation
- type RelationEventPublisher
- type RelationRepository
- type RelationService
- type RelationTypePair
- type UpdateRelationMetadataRequest
Constants ¶
const ( RelationEventCreated = "created" RelationEventDeleted = "deleted" RelationEventMetadataUpdated = "metadata_updated" )
Relation event types passed to RelationEventPublisher.
Variables ¶
var CommonRelationTypes = []RelationTypePair{
{Forward: "allied with", Reverse: "allied with"},
{Forward: "enemy of", Reverse: "enemy of"},
{Forward: "parent of", Reverse: "child of"},
{Forward: "child of", Reverse: "parent of"},
{Forward: "member of", Reverse: "has member"},
{Forward: "has member", Reverse: "member of"},
{Forward: "located in", Reverse: "contains"},
{Forward: "contains", Reverse: "located in"},
{Forward: "owns", Reverse: "owned by"},
{Forward: "owned by", Reverse: "owns"},
{Forward: "serves", Reverse: "served by"},
{Forward: "served by", Reverse: "serves"},
{Forward: "rules", Reverse: "ruled by"},
{Forward: "ruled by", Reverse: "rules"},
{Forward: "knows", Reverse: "known by"},
{Forward: "sells", Reverse: "sold by"},
{Forward: "sold by", Reverse: "sells"},
}
CommonRelationTypes provides a set of predefined relation type pairs for the frontend UI. Each pair has a forward and reverse label. Symmetric relations use the same label in both directions.
Functions ¶
func RegisterRoutes ¶
func RegisterRoutes(e *echo.Echo, h *Handler, campaignSvc campaigns.CampaignService, authSvc auth.AuthService)
RegisterRoutes sets up all entity relation routes on the given Echo instance. Relation routes are scoped to a campaign and require campaign membership.
Permissions:
- Player (read): list relations for an entity, get common relation types
- Scribe (write): create and delete relations
Types ¶
type CampaignRelation ¶
type CampaignRelation struct {
SourceEntityID string `json:"sourceEntityId"`
SourceEntityName string `json:"sourceEntityName"`
SourceEntityIcon string `json:"sourceEntityIcon"`
SourceEntityColor string `json:"sourceEntityColor"`
SourceEntitySlug string `json:"sourceEntitySlug"`
SourceEntityType string `json:"sourceEntityType"`
TargetEntityID string `json:"targetEntityId"`
TargetEntityName string `json:"targetEntityName"`
TargetEntityIcon string `json:"targetEntityIcon"`
TargetEntityColor string `json:"targetEntityColor"`
TargetEntitySlug string `json:"targetEntitySlug"`
TargetEntityType string `json:"targetEntityType"`
RelationType string `json:"relationType"`
}
CampaignRelation holds a relation row with joined entity details for both source and target entities. Used by the relations graph to build nodes and edges without additional queries.
type CreateRelationRequest ¶
type CreateRelationRequest struct {
TargetEntityID string `json:"targetEntityId"`
RelationType string `json:"relationType"`
ReverseRelationType string `json:"reverseRelationType"`
Metadata json.RawMessage `json:"metadata,omitempty"`
DmOnly bool `json:"dmOnly"`
}
CreateRelationRequest holds the data submitted when creating a new relation. The reverse relation is created automatically by the service layer.
type EntityGate ¶
type EntityGate interface {
EntityViewFilter
// ResolveViewableEntity returns the entity's owning campaign ID and whether
// the viewer (role, userID) may view it. A missing entity returns a
// not-found error.
ResolveViewableEntity(ctx context.Context, entityID string, role int, userID string) (campaignID string, canView bool, err error)
}
EntityGate is the narrow seam the relations handler uses to honor entity visibility + campaign binding on the per-entity relation list. It extends EntityViewFilter with a single-entity resolver for the source-entity gate (mirrors the entity Show page). Implemented by the same adapter.
type EntityTypeListerForGraph ¶
type EntityTypeListerForGraph interface {
// ListEntityTypesForGraph omits the categories the viewer's role may not
// know exist (a DM-only category is not offered to a player).
ListEntityTypesForGraph(ctx context.Context, campaignID string, role int) ([]EntityTypeSummary, error)
}
EntityTypeListerForGraph provides entity type listings for the graph page. Implemented by an adapter wrapping the entity service.
type EntityTypeSummary ¶
type EntityTypeSummary struct {
Slug string `json:"slug"`
Name string `json:"name"`
Color string `json:"color"`
Icon string `json:"icon"`
}
EntityTypeSummary holds minimal entity type info for the graph filter UI.
type EntityViewFilter ¶
type EntityViewFilter interface {
FilterViewableEntityIDs(ctx context.Context, campaignID string, entityIDs []string, role int, userID string) (map[string]bool, error)
}
EntityViewFilter reports which of a set of entity IDs a viewer may see, applying the canonical entity-visibility policy. Implemented by an adapter over the entity service (app wiring). Used by the graph service to drop private entities' nodes/edges from viewers who cannot see them. Defined here to avoid importing the entities package.
type GraphEdge ¶
type GraphEdge struct {
Source string `json:"source"`
Target string `json:"target"`
Type string `json:"type"`
Kind string `json:"kind"` // "relation" (default) or "mention"
}
GraphEdge represents a relation or mention link in the relations graph.
type GraphFilter ¶
type GraphFilter struct {
Types []string // Filter nodes by entity type slugs.
Search string // Filter nodes whose name matches (case-insensitive).
FocusEntityID string // Ego-graph center: show only N hops from this entity.
Hops int // Number of hops from focus entity (default 2).
IncludeMentions bool // Include @mention edges alongside explicit relations.
IncludeOrphans bool // Include entities with zero connections.
}
GraphFilter holds query parameters for filtering the relations graph.
type GraphNode ¶
type GraphNode struct {
ID string `json:"id"`
Name string `json:"name"`
Icon string `json:"icon"`
Color string `json:"color"`
Slug string `json:"slug"`
Type string `json:"type"`
Orphan bool `json:"orphan,omitempty"` // True if entity has no connections.
}
GraphNode represents an entity in the relations graph.
type GraphRelation ¶
type GraphRelation struct {
SourceEntityID string `json:"source_entity_id"`
TargetEntityID string `json:"target_entity_id"`
RelationType string `json:"relation_type"`
DmOnly bool `json:"dm_only"`
SourceEntityName string `json:"source_name"`
SourceEntityIcon string `json:"source_icon"`
SourceEntityColor string `json:"source_color"`
SourceEntitySlug string `json:"source_slug"`
SourceEntityType string `json:"source_type"`
TargetEntityName string `json:"target_name"`
TargetEntityIcon string `json:"target_icon"`
TargetEntityColor string `json:"target_color"`
TargetEntitySlug string `json:"target_slug"`
TargetEntityType string `json:"target_type"`
}
GraphRelation is a flattened relation with both source and target entity details for the relations graph visualization. Only forward relations are included (not reverse duplicates).
type Handler ¶
type Handler struct {
// contains filtered or unexported fields
}
Handler handles HTTP requests for entity relation operations. Handlers are thin: bind request, call service, render response. No business logic lives here.
func NewHandler ¶
func NewHandler(service RelationService) *Handler
NewHandler creates a new relation handler backed by the given service.
func (*Handler) CreateRelation ¶
CreateRelation creates a new bi-directional relation between two entities (POST /campaigns/:id/entities/:eid/relations).
func (*Handler) DeleteRelation ¶
DeleteRelation removes a relation and its reverse direction (DELETE /campaigns/:id/entities/:eid/relations/:rid).
func (*Handler) FirstPaint ¶
func (h *Handler) FirstPaint(ctx context.Context, cc *campaigns.CampaignContext, entityID, userID string, withTypes bool) (relations []Relation, types any, err error)
FirstPaint is what the relations widget would fetch on load, for the entity page to send with the page. The page has already confirmed the viewer may open the entity; everything after that gate is the same code the list endpoint runs. The types are only needed by someone who can add a relation.
func (*Handler) GetCommonTypes ¶
GetCommonTypes returns the predefined relation type pairs for the frontend UI suggestion list (GET /campaigns/:id/relation-types).
func (*Handler) GraphAPI ¶
GraphAPI returns the relations graph data (nodes + edges) for a campaign as JSON. Used by the D3 force-directed graph widget.
Query parameters:
- types: comma-separated entity type slugs to filter by
- search: filter nodes whose name matches (case-insensitive)
- focus: entity ID for local/ego graph (BFS from this node)
- hops: number of hops from focus entity (default 2)
- include_mentions: include @mention edges (default "true")
- include_orphans: include entities with no connections (default "false")
GET /campaigns/:id/relations-graph
func (*Handler) GraphPage ¶
GraphPage renders the standalone relations graph visualization page. GET /campaigns/:id/relations-graph/page
func (*Handler) ListRelations ¶
ListRelations returns all relations for an entity as JSON (GET /campaigns/:id/entities/:eid/relations).
func (*Handler) SetEntityGate ¶
func (h *Handler) SetEntityGate(gate EntityGate)
SetEntityGate injects the entity-visibility gate. Called during app wiring. When set, the public relations list enforces entity privacy + campaign binding on the source entity and filters private relation targets.
func (*Handler) SetEntityTypeLister ¶
func (h *Handler) SetEntityTypeLister(lister EntityTypeListerForGraph)
SetEntityTypeLister injects the entity type lister for the graph page.
type ListingObserver ¶
ListingObserver is told, for each end of a shop listing, that the listing changed. An error from a write inside a transaction rolls it back.
type MentionLinkData ¶
MentionLinkData holds a directional @mention reference for the graph. Defined here to avoid importing the entities package.
type MentionLinkProvider ¶
type MentionLinkProvider interface {
GetMentionLinksForGraph(ctx context.Context, campaignID string, includeDmOnly bool, userID string) ([]MentionLinkData, map[string]GraphNode, error)
}
MentionLinkProvider supplies @mention links for the graph, with the pages at their ends as nodes, keyed by page id. Implemented over the entities service, which leaves out what the viewer may not know of. A link with an end missing from the nodes is not drawn.
type Relation ¶
type Relation struct {
ID int `json:"id"`
CampaignID string `json:"campaignId"`
SourceEntityID string `json:"sourceEntityId"`
TargetEntityID string `json:"targetEntityId"`
RelationType string `json:"relationType"`
ReverseRelationType string `json:"reverseRelationType"`
Metadata json.RawMessage `json:"metadata,omitempty"`
DmOnly bool `json:"dmOnly"`
CreatedAt time.Time `json:"createdAt"`
CreatedBy string `json:"createdBy"`
// Joined fields from the entities table (populated by repository queries).
TargetEntityName string `json:"targetEntityName,omitempty"`
TargetEntityIcon string `json:"targetEntityIcon,omitempty"`
TargetEntityColor string `json:"targetEntityColor,omitempty"`
TargetEntitySlug string `json:"targetEntitySlug,omitempty"`
TargetEntityType string `json:"targetEntityType,omitempty"`
// TargetEntityShopGood marks a target page that exists only to be sold.
TargetEntityShopGood bool `json:"targetEntityShopGood,omitempty"`
}
Relation represents a single directional link between two entities within a campaign. The service layer always creates relations in pairs (forward and reverse) to maintain bi-directional consistency.
type RelationEventPublisher ¶
RelationEventPublisher announces a write to one relation row. Each direction of a pair is its own row and its own event, so a listener keyed on the row's source entity (a Foundry character's inventory) sees every change to that entity's relations. Implemented by a WebSocket adapter in routes.go.
type RelationRepository ¶
type RelationRepository interface {
// Create inserts a new relation row. The relation's ID is set on the
// struct after insert.
Create(ctx context.Context, rel *Relation) error
// FindByID retrieves a single relation by its primary key.
FindByID(ctx context.Context, id int) (*Relation, error)
// ListByEntity returns all relations where the given entity is the source,
// joined with target entity details (name, icon, color, slug, type). The
// campaignID predicate is defense-in-depth against cross-campaign reads (the
// handler is the primary IDOR gate).
ListByEntity(ctx context.Context, campaignID, entityID string) ([]Relation, error)
// Delete removes a relation by ID.
Delete(ctx context.Context, id int) error
// FindReverse finds the reverse relation for a given relation.
// Used when deleting a relation to also remove its reverse.
FindReverse(ctx context.Context, sourceEntityID, targetEntityID, relationType string) (*Relation, error)
// UpdateMetadata updates only the metadata JSON column for a relation.
UpdateMetadata(ctx context.Context, id int, metadata json.RawMessage) error
UpdateMetadataIf(ctx context.Context, id int, expected, metadata json.RawMessage) (bool, error)
// ListByCampaign returns all relations for a campaign with both source and
// target entity details. Used for the relations graph visualization.
ListByCampaign(ctx context.Context, campaignID string) ([]GraphRelation, error)
}
RelationRepository defines the data access contract for entity relations. One repository per aggregate root; all SQL lives here.
func NewRelationRepository ¶
func NewRelationRepository(db *sql.DB) RelationRepository
NewRelationRepository creates a new RelationRepository backed by the given database connection.
type RelationService ¶
type RelationService interface {
// Create validates input and creates a bi-directional relation between
// two entities. Both the forward (A→B) and reverse (B→A) directions are
// created atomically. Returns the forward relation.
Create(ctx context.Context, campaignID, sourceEntityID, targetEntityID, relationType, reverseRelationType, createdBy string, metadata json.RawMessage, dmOnly ...bool) (*Relation, error)
// ListByEntity returns all relations originating from the given entity,
// enriched with target entity display data. campaignID scopes the query
// (defense-in-depth against cross-campaign reads).
ListByEntity(ctx context.Context, campaignID, entityID string) ([]Relation, error)
// Delete removes a relation and its reverse direction. Both directions
// are removed to maintain bi-directional consistency.
Delete(ctx context.Context, id int) error
// GetByID retrieves a single relation by ID.
GetByID(ctx context.Context, id int) (*Relation, error)
// GetCommonTypes returns the predefined relation type pairs for the
// frontend UI suggestion list.
GetCommonTypes() []RelationTypePair
// UpdateMetadata updates the metadata JSON for a relation.
// Used by the shop inventory widget to update price/quantity/stock.
UpdateMetadata(ctx context.Context, id int, metadata json.RawMessage) error
// UpdateMetadataIf updates the metadata only while it still equals
// expected, reporting whether it wrote.
UpdateMetadataIf(ctx context.Context, id int, expected, metadata json.RawMessage) (bool, error)
// GetGraphData returns the relations graph data (nodes + edges) for a
// campaign. Used by the relations graph visualization widget.
// When includeDmOnly is false, dm_only relations are excluded from the graph.
GetGraphData(ctx context.Context, campaignID string, includeDmOnly bool) (*GraphData, error)
// GetFilteredGraphData returns graph data with filtering, mention edges,
// local graph (BFS), and orphan detection support. viewerRole + userID drive
// the per-viewer entity-visibility filter: nodes the viewer cannot see (and
// their edges) are dropped unless includeDmOnly (owner/DM) is set.
GetFilteredGraphData(ctx context.Context, campaignID string, filter GraphFilter, includeDmOnly bool, viewerRole int, userID string) (*GraphData, error)
// SetMentionLinkProvider injects the mention link provider for graph
// visualization. Called during app wiring.
SetMentionLinkProvider(p MentionLinkProvider)
// SetEntityViewFilter injects the entity-visibility filter used to hide
// private-entity nodes from the graph. Called during app wiring.
SetEntityViewFilter(f EntityViewFilter)
// SetEventPublisher injects the publisher that announces relation
// writes to live clients and the sync change feed. Called during app
// wiring; without one, writes are silent.
SetEventPublisher(p RelationEventPublisher)
// SetListingObserver injects the callback told whenever a shop listing
// ("sells" / "sold by") is written or removed, so the page behind a
// shop good can follow who may see it. Called during app wiring.
SetListingObserver(o ListingObserver)
}
RelationService defines the business logic contract for entity relation operations. Handlers call these methods -- they never touch the repository directly.
func NewRelationService ¶
func NewRelationService(repo RelationRepository) RelationService
NewRelationService creates a new RelationService backed by the given repository.
type RelationTypePair ¶
RelationTypePair holds a forward and reverse relation type label. Used by the frontend to suggest relation types and auto-fill the reverse.
type UpdateRelationMetadataRequest ¶
type UpdateRelationMetadataRequest struct {
Metadata json.RawMessage `json:"metadata"`
}
UpdateRelationMetadataRequest holds the data for updating relation metadata. The blob is replaced whole, so a body without the metadata key is refused rather than read as "clear it"; an explicit null still clears.