Add D&D item event artifact contract
This commit is contained in:
@@ -0,0 +1,45 @@
|
||||
{
|
||||
"$schema": "https://json-schema.org/draft/2020-12/schema",
|
||||
"$id": "notarius.dnd.item_events",
|
||||
"type": "object",
|
||||
"additionalProperties": false,
|
||||
"required": ["events"],
|
||||
"properties": {
|
||||
"events": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
"type": "object",
|
||||
"additionalProperties": false,
|
||||
"required": ["name", "kind", "source_refs"],
|
||||
"properties": {
|
||||
"name": {"type": "string", "minLength": 1},
|
||||
"kind": {"type": "string", "enum": ["discovered", "acquired", "lost", "consumed", "transferred"]},
|
||||
"quantity": {"type": "integer", "minimum": 1},
|
||||
"from": {"type": "string", "minLength": 1},
|
||||
"to": {"type": "string", "minLength": 1},
|
||||
"source_refs": {
|
||||
"type": "array",
|
||||
"minItems": 1,
|
||||
"items": {
|
||||
"type": "object",
|
||||
"additionalProperties": false,
|
||||
"required": ["source_id", "start_unit_id", "end_unit_id"],
|
||||
"properties": {
|
||||
"source_id": {"type": "string", "minLength": 1},
|
||||
"start_unit_id": {"type": "integer", "minimum": 1},
|
||||
"end_unit_id": {"type": "integer", "minimum": 1}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"allOf": [
|
||||
{"if": {"properties": {"kind": {"const": "discovered"}}, "required": ["kind"]}, "then": {"not": {"anyOf": [{"required": ["from"]}, {"required": ["to"]}]}}},
|
||||
{"if": {"properties": {"kind": {"const": "acquired"}}, "required": ["kind"]}, "then": {"required": ["to"], "not": {"required": ["from"]}}},
|
||||
{"if": {"properties": {"kind": {"const": "lost"}}, "required": ["kind"]}, "then": {"required": ["from"], "not": {"required": ["to"]}}},
|
||||
{"if": {"properties": {"kind": {"const": "consumed"}}, "required": ["kind"]}, "then": {"required": ["from"], "not": {"required": ["to"]}}},
|
||||
{"if": {"properties": {"kind": {"const": "transferred"}}, "required": ["kind"]}, "then": {"required": ["from", "to"]}}
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
146
internal/modules/dnd/codec/itemevents/codec.go
Normal file
146
internal/modules/dnd/codec/itemevents/codec.go
Normal file
@@ -0,0 +1,146 @@
|
||||
// Package itemevents encodes durable D&D item-event artifacts.
|
||||
package itemevents
|
||||
|
||||
import (
|
||||
"embed"
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"gitea.maximumdirect.net/eric/notarius/internal/core/source"
|
||||
"gitea.maximumdirect.net/eric/notarius/internal/framework/contracts"
|
||||
"gitea.maximumdirect.net/eric/notarius/internal/modules/dnd"
|
||||
"gitea.maximumdirect.net/eric/notarius/internal/modules/dnd/codec/candidatejson"
|
||||
"gitea.maximumdirect.net/eric/notarius/internal/modules/dnd/itemevents"
|
||||
)
|
||||
|
||||
const (
|
||||
SchemaID = "notarius.dnd.item_events"
|
||||
SchemaName = "notarius_dnd_item_events_v1"
|
||||
SchemaVersion = "v1"
|
||||
MediaType = "application/json"
|
||||
)
|
||||
|
||||
//go:embed assets/schemas/dnd_item_events.v1.json
|
||||
var schemaAssets embed.FS
|
||||
|
||||
var _ contracts.ArtifactCodec[dnd.ItemEventList] = (*Codec)(nil)
|
||||
|
||||
type Codec struct{}
|
||||
|
||||
func New() *Codec { return &Codec{} }
|
||||
|
||||
func (c *Codec) Kind() contracts.ArtifactKind { return dnd.ItemEventListKind }
|
||||
|
||||
func (c *Codec) Schema() contracts.ArtifactSchema {
|
||||
raw, err := schemaAssets.ReadFile("assets/schemas/dnd_item_events.v1.json")
|
||||
if err != nil {
|
||||
return contracts.ArtifactSchema{}
|
||||
}
|
||||
return contracts.ArtifactSchema{
|
||||
ID: SchemaID,
|
||||
Name: SchemaName,
|
||||
Version: SchemaVersion,
|
||||
JSONSchema: append([]byte(nil), raw...),
|
||||
}
|
||||
}
|
||||
|
||||
func (c *Codec) MediaType() string { return MediaType }
|
||||
|
||||
func (c *Codec) Metadata(value dnd.ItemEventList) map[string]any {
|
||||
return map[string]any{"event_count": len(value.Events)}
|
||||
}
|
||||
|
||||
func (c *Codec) Encode(value dnd.ItemEventList) ([]byte, error) {
|
||||
if err := validate(value); err != nil {
|
||||
return nil, fmt.Errorf("encode dnd item event list: %w", err)
|
||||
}
|
||||
return c.EncodeCandidate(value)
|
||||
}
|
||||
|
||||
// EncodeCandidate provides the durable representation before semantic
|
||||
// validators have approved a value.
|
||||
func (c *Codec) EncodeCandidate(value dnd.ItemEventList) ([]byte, error) {
|
||||
return candidatejson.EncodeCandidate("dnd item event list", cloneList(value))
|
||||
}
|
||||
|
||||
func (c *Codec) Decode(content []byte) (dnd.ItemEventList, error) {
|
||||
value, err := c.DecodeCandidate(content)
|
||||
if err != nil {
|
||||
return dnd.ItemEventList{}, err
|
||||
}
|
||||
if err := validate(value); err != nil {
|
||||
return dnd.ItemEventList{}, fmt.Errorf("decode dnd item event list: %w", err)
|
||||
}
|
||||
return value, nil
|
||||
}
|
||||
|
||||
// DecodeCandidate reads one strict durable JSON value before semantic
|
||||
// validators have approved it.
|
||||
func (c *Codec) DecodeCandidate(content []byte) (dnd.ItemEventList, error) {
|
||||
value, err := candidatejson.DecodeCandidate[dnd.ItemEventList]("dnd item event list", content)
|
||||
if err != nil {
|
||||
return dnd.ItemEventList{}, err
|
||||
}
|
||||
return cloneList(value), nil
|
||||
}
|
||||
|
||||
func validate(value dnd.ItemEventList) error {
|
||||
if value.Events == nil {
|
||||
return fmt.Errorf("events must be present")
|
||||
}
|
||||
for index, event := range value.Events {
|
||||
prefix := fmt.Sprintf("events[%d]", index)
|
||||
if strings.TrimSpace(event.Name) == "" {
|
||||
return fmt.Errorf("%s.name must not be empty", prefix)
|
||||
}
|
||||
if !itemevents.SupportedKind(event.Kind) {
|
||||
return fmt.Errorf("%s.kind must be supported", prefix)
|
||||
}
|
||||
if event.From != "" && strings.TrimSpace(event.From) == "" {
|
||||
return fmt.Errorf("%s.from must not be empty when present", prefix)
|
||||
}
|
||||
if event.To != "" && strings.TrimSpace(event.To) == "" {
|
||||
return fmt.Errorf("%s.to must not be empty when present", prefix)
|
||||
}
|
||||
if !itemevents.ValidHolderCombination(event.Kind, event.From, event.To) {
|
||||
return fmt.Errorf("%s holders are incompatible with %q", prefix, event.Kind)
|
||||
}
|
||||
if event.Quantity != nil && *event.Quantity < 1 {
|
||||
return fmt.Errorf("%s.quantity must be positive when present", prefix)
|
||||
}
|
||||
if len(event.SourceRefs) == 0 {
|
||||
return fmt.Errorf("%s.source_refs must contain at least one reference", prefix)
|
||||
}
|
||||
for refIndex, ref := range event.SourceRefs {
|
||||
refPrefix := fmt.Sprintf("%s.source_refs[%d]", prefix, refIndex)
|
||||
if strings.TrimSpace(ref.SourceID) == "" {
|
||||
return fmt.Errorf("%s.source_id must not be empty", refPrefix)
|
||||
}
|
||||
if ref.StartUnitID <= 0 {
|
||||
return fmt.Errorf("%s.start_unit_id must be positive", refPrefix)
|
||||
}
|
||||
if ref.EndUnitID <= 0 {
|
||||
return fmt.Errorf("%s.end_unit_id must be positive", refPrefix)
|
||||
}
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func cloneList(value dnd.ItemEventList) dnd.ItemEventList {
|
||||
if value.Events == nil {
|
||||
return dnd.ItemEventList{}
|
||||
}
|
||||
cloned := dnd.ItemEventList{Events: make([]dnd.ItemEvent, len(value.Events))}
|
||||
for index, event := range value.Events {
|
||||
cloned.Events[index] = event
|
||||
if event.Quantity != nil {
|
||||
quantity := *event.Quantity
|
||||
cloned.Events[index].Quantity = &quantity
|
||||
}
|
||||
if event.SourceRefs != nil {
|
||||
cloned.Events[index].SourceRefs = append([]source.SourceRef(nil), event.SourceRefs...)
|
||||
}
|
||||
}
|
||||
return cloned
|
||||
}
|
||||
146
internal/modules/dnd/codec/itemevents/codec_test.go
Normal file
146
internal/modules/dnd/codec/itemevents/codec_test.go
Normal file
@@ -0,0 +1,146 @@
|
||||
package itemevents
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"reflect"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"gitea.maximumdirect.net/eric/notarius/internal/core/source"
|
||||
"gitea.maximumdirect.net/eric/notarius/internal/framework/contracts"
|
||||
"gitea.maximumdirect.net/eric/notarius/internal/framework/pipeline"
|
||||
"gitea.maximumdirect.net/eric/notarius/internal/modules/dnd"
|
||||
)
|
||||
|
||||
func validList() dnd.ItemEventList {
|
||||
quantity := 12
|
||||
return dnd.ItemEventList{Events: []dnd.ItemEvent{
|
||||
{Name: "Hidden Cache", Kind: dnd.ItemEventKindDiscovered, SourceRefs: refs(1, 1)},
|
||||
{Name: "Gold Pieces", Kind: dnd.ItemEventKindAcquired, Quantity: &quantity, To: "party", SourceRefs: refs(2, 2)},
|
||||
{Name: "Torch", Kind: dnd.ItemEventKindLost, From: "party", SourceRefs: refs(3, 3)},
|
||||
{Name: "Healing Potion", Kind: dnd.ItemEventKindConsumed, From: "party", SourceRefs: refs(4, 4)},
|
||||
{Name: "Moonblade", Kind: dnd.ItemEventKindTransferred, From: "Aria", To: "Borin", SourceRefs: refs(5, 5)},
|
||||
}}
|
||||
}
|
||||
|
||||
func refs(start, end int) []source.SourceRef {
|
||||
return []source.SourceRef{{SourceID: "session", StartUnitID: start, EndUnitID: end}}
|
||||
}
|
||||
|
||||
func TestCodecRoundTripAndIdentities(t *testing.T) {
|
||||
codec := New()
|
||||
value := validList()
|
||||
content, err := codec.Encode(value)
|
||||
if err != nil {
|
||||
t.Fatalf("Encode() error = %v", err)
|
||||
}
|
||||
decoded, err := codec.Decode(content)
|
||||
if err != nil || !reflect.DeepEqual(decoded, value) {
|
||||
t.Fatalf("Decode() = %#v, %v; want %#v", decoded, err, value)
|
||||
}
|
||||
|
||||
schema := codec.Schema()
|
||||
if codec.Kind() != dnd.ItemEventListKind || codec.MediaType() != MediaType || schema.ID != SchemaID || schema.Name != SchemaName || schema.Version != SchemaVersion || !json.Valid(schema.JSONSchema) {
|
||||
t.Fatalf("codec identity/schema = %q/%q %#v", codec.Kind(), codec.MediaType(), schema)
|
||||
}
|
||||
registry := pipeline.NewArtifactCodecRegistry()
|
||||
if err := pipeline.RegisterArtifactCodec(registry, codec); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
spec, ok := registry.Spec(dnd.ItemEventListKind)
|
||||
if !ok || spec.SchemaDigest != contracts.DigestArtifactSchema(schema) {
|
||||
t.Fatalf("registered spec = %#v, %t", spec, ok)
|
||||
}
|
||||
if _, err := registry.Encode(dnd.ItemEventListKind, dnd.NPCList{}); err == nil {
|
||||
t.Fatal("Encode() error = nil, want exact type rejection")
|
||||
} else {
|
||||
var typeErr *pipeline.ArtifactCodecTypeError
|
||||
if !errors.As(err, &typeErr) {
|
||||
t.Fatalf("Encode() error = %T, want ArtifactCodecTypeError", err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestCodecSupportsEmptyListAndPreservesInvalidCandidates(t *testing.T) {
|
||||
codec := New()
|
||||
empty := dnd.ItemEventList{Events: []dnd.ItemEvent{}}
|
||||
if content, err := codec.Encode(empty); err != nil || string(content) != `{"events":[]}` {
|
||||
t.Fatalf("Encode() = %s, %v", content, err)
|
||||
}
|
||||
zero := 0
|
||||
candidate := dnd.ItemEventList{Events: []dnd.ItemEvent{{
|
||||
Name: " ", Kind: dnd.ItemEventKindTransferred, Quantity: &zero, From: "party", To: "Party",
|
||||
SourceRefs: []source.SourceRef{{SourceID: "", StartUnitID: 0, EndUnitID: -1}},
|
||||
}}}
|
||||
content, err := codec.EncodeCandidate(candidate)
|
||||
if err != nil || !json.Valid(content) {
|
||||
t.Fatalf("EncodeCandidate() = %s, %v", content, err)
|
||||
}
|
||||
decoded, err := codec.DecodeCandidate(content)
|
||||
if err != nil || !reflect.DeepEqual(decoded, candidate) {
|
||||
t.Fatalf("DecodeCandidate() = %#v, %v; want %#v", decoded, err, candidate)
|
||||
}
|
||||
if _, err := codec.Decode(content); err == nil {
|
||||
t.Fatal("Decode() error = nil, want semantic candidate rejection")
|
||||
}
|
||||
}
|
||||
|
||||
func TestCodecRejectsStrictJSONAndApprovedBoundaries(t *testing.T) {
|
||||
validJSON := `{"events":[{"name":"Ring","kind":"acquired","to":"party","source_refs":[{"source_id":"session","start_unit_id":1,"end_unit_id":1}]}]}`
|
||||
tests := []struct {
|
||||
name, raw, want string
|
||||
}{
|
||||
{"malformed", `{`, "decode dnd item event list"},
|
||||
{"unknown top level", `{"events":[],"unexpected":true}`, "unknown field"},
|
||||
{"unknown event field", strings.Replace(validJSON, `"to":"party"`, `"to":"party","unexpected":true`, 1), "unknown field"},
|
||||
{"unknown reference field", strings.Replace(validJSON, `"end_unit_id":1`, `"end_unit_id":1,"unexpected":true`, 1), "unknown field"},
|
||||
{"trailing", `{"events":[]} {}`, "multiple JSON values"},
|
||||
{"missing list", `{}`, "events must be present"},
|
||||
{"zero quantity", strings.Replace(validJSON, `"to":"party"`, `"quantity":0,"to":"party"`, 1), "quantity must be positive"},
|
||||
{"negative quantity", strings.Replace(validJSON, `"to":"party"`, `"quantity":-1,"to":"party"`, 1), "quantity must be positive"},
|
||||
{"party transfer", strings.Replace(validJSON, `"kind":"acquired","to":"party"`, `"kind":"transferred","from":"party","to":"Borin"`, 1), "holders are incompatible"},
|
||||
{"self transfer", strings.Replace(validJSON, `"kind":"acquired","to":"party"`, `"kind":"transferred","from":"Aria","to":"aria"`, 1), "holders are incompatible"},
|
||||
{"missing source refs", strings.Replace(validJSON, `,"source_refs":[{"source_id":"session","start_unit_id":1,"end_unit_id":1}]`, "", 1), "source_refs must contain"},
|
||||
}
|
||||
for _, test := range tests {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
if _, err := New().Decode([]byte(test.raw)); err == nil || !strings.Contains(err.Error(), test.want) {
|
||||
t.Fatalf("Decode() error = %v, want %q", err, test.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestCodecDeepCopiesBoundaryValuesAndMetadata(t *testing.T) {
|
||||
codec := New()
|
||||
value := validList()
|
||||
content, err := codec.EncodeCandidate(value)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
decoded, err := codec.DecodeCandidate(content)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if decoded.Events[1].Quantity == value.Events[1].Quantity || &decoded.Events[1].SourceRefs[0] == &value.Events[1].SourceRefs[0] {
|
||||
t.Fatal("DecodeCandidate() retained caller-owned event fields")
|
||||
}
|
||||
*decoded.Events[1].Quantity = 99
|
||||
decoded.Events[1].SourceRefs[0].SourceID = "changed"
|
||||
if *value.Events[1].Quantity != 12 || value.Events[1].SourceRefs[0].SourceID != "session" {
|
||||
t.Fatal("decoded item event aliases input")
|
||||
}
|
||||
|
||||
first := codec.Schema()
|
||||
first.JSONSchema[0] = '['
|
||||
if second := codec.Schema(); !json.Valid(second.JSONSchema) || second.JSONSchema[0] == '[' {
|
||||
t.Fatal("Schema() returned shared bytes")
|
||||
}
|
||||
metadata := codec.Metadata(value)
|
||||
metadata["payload"] = bytes.Repeat([]byte("x"), 10)
|
||||
if next := codec.Metadata(value); len(next) != 1 || next["event_count"] != len(value.Events) {
|
||||
t.Fatalf("Metadata() = %#v", next)
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user