Files
2026-11-15 05:47:14 +09:00

190 lines
8.4 KiB
Go

package store
import (
"context"
"database/sql"
"encoding/json"
"errors"
"strings"
"time"
)
type CityPlanOperation struct {
Action string `json:"action"` // set_path, move_street, move_spot
Kind string `json:"kind,omitempty"`
UUID string `json:"uuid"`
PathPrefix string `json:"path_prefix,omitempty"`
ParentUUID string `json:"parent_uuid,omitempty"`
StreetUUID string `json:"street_uuid,omitempty"`
SortKey int `json:"sort_key,omitempty"`
}
type CityPlan struct {
BaseVersion int64 `json:"base_version"`
RequestID string `json:"request_id,omitempty"`
Operations []CityPlanOperation `json:"operations"`
}
type CityPlanPreview struct {
DomainUUID string `json:"domain_uuid"`
BaseVersion int64 `json:"base_version"`
Before []map[string]any `json:"before"`
After []map[string]any `json:"after"`
Valid bool `json:"valid"`
}
func (s *Store) PreviewCityPlan(domainUUID string, plan CityPlan) (result CityPlanPreview, resultErr error) {
defer func() { resultErr = s.sqlError("city plan preview", resultErr) }()
ctx, cancel := context.WithTimeout(context.Background(), cityReadTimeout)
defer cancel()
tx, err := s.DB.BeginTx(ctx, s.policyReadOptions())
if err != nil {
return CityPlanPreview{}, err
}
defer tx.Rollback()
return s.validateCityPlan(tx, domainUUID, plan)
}
func (s *Store) ApplyCityPlan(domainUUID, actor string, plan CityPlan) (result CityPlanPreview, resultErr error) {
defer func() { resultErr = s.sqlError("city plan apply", resultErr) }()
tx, cancel, err := s.beginPathMutation(domainUUID)
defer cancel()
if err != nil {
return CityPlanPreview{}, err
}
defer tx.Rollback()
preview, err := s.validateCityPlan(tx, domainUUID, plan)
if err != nil {
return preview, err
}
now := time.Now().UnixMilli()
for _, operation := range plan.Operations {
switch operation.Action {
case "set_path":
table := "zones"
if operation.Kind == "spot" {
table = "spots"
}
if _, err := tx.Exec(`UPDATE `+table+` SET path_prefix=`+s.sqlParam(1)+`,version=version+1,updated_at_ms=`+s.sqlParam(2)+` WHERE uuid=`+s.sqlParam(3)+` AND domain_uuid=`+s.sqlParam(4)+` AND state!='archived'`, normalizePath(operation.PathPrefix), now, operation.UUID, domainUUID); err != nil {
return preview, err
}
case "move_street":
if _, err := tx.Exec(`UPDATE zones SET parent_uuid=`+s.sqlParam(1)+`,sort_key=`+s.sqlParam(2)+`,version=version+1,updated_at_ms=`+s.sqlParam(3)+` WHERE uuid=`+s.sqlParam(4)+` AND domain_uuid=`+s.sqlParam(5)+` AND kind='street' AND state!='archived'`, operation.ParentUUID, operation.SortKey, now, operation.UUID, domainUUID); err != nil {
return preview, err
}
case "move_spot":
if _, err := tx.Exec(`UPDATE street_spots SET street_uuid=`+s.sqlParam(1)+`,sort_key=`+s.sqlParam(2)+` WHERE spot_uuid=`+s.sqlParam(3)+``, operation.StreetUUID, operation.SortKey, operation.UUID); err != nil {
return preview, err
}
if _, err := tx.Exec(`UPDATE spots SET version=version+1,updated_at_ms=`+s.sqlParam(1)+` WHERE uuid=`+s.sqlParam(2)+` AND domain_uuid=`+s.sqlParam(3)+``, now, operation.UUID, domainUUID); err != nil {
return preview, err
}
}
}
beforeJSON, _ := json.Marshal(preview.Before)
afterJSON, _ := json.Marshal(preview.After)
if _, err := tx.Exec(`INSERT INTO domain_topology_versions(domain_uuid,version,updated_at_ms) VALUES(`+s.sqlParam(1)+`,2,`+s.sqlParam(2)+`) ON CONFLICT(domain_uuid) DO UPDATE SET version=domain_topology_versions.version+1,updated_at_ms=excluded.updated_at_ms`, domainUUID, now); err != nil {
return preview, err
}
var version int64
if err := tx.QueryRow(`SELECT version FROM domain_topology_versions WHERE domain_uuid=`+s.sqlParam(1)+``, domainUUID).Scan(&version); err != nil {
return preview, err
}
if _, err := tx.Exec(`INSERT INTO topology_events(domain_uuid,topology_version,actor_principal_uuid,operation,target_type,target_uuid,before_json,after_json,request_id,created_at_ms) VALUES(`+s.sqlParam(1)+`,`+s.sqlParam(2)+`,`+s.sqlParam(3)+`,`+s.sqlParam(4)+`,`+s.sqlParam(5)+`,`+s.sqlParam(6)+`,`+s.sqlParam(7)+`,`+s.sqlParam(8)+`,`+s.sqlParam(9)+`,`+s.sqlParam(10)+`)`, domainUUID, version, actor, "city.plan.applied", "plan", plan.RequestID, string(beforeJSON), string(afterJSON), plan.RequestID, now); err != nil {
return preview, err
}
preview.BaseVersion = version
return preview, tx.Commit()
}
func (s *Store) validateCityPlan(tx *sql.Tx, domainUUID string, plan CityPlan) (CityPlanPreview, error) {
preview := CityPlanPreview{DomainUUID: domainUUID, Before: []map[string]any{}, After: []map[string]any{}}
var version int64 = 1
if err := tx.QueryRow(`SELECT version FROM domain_topology_versions WHERE domain_uuid=`+s.sqlParam(1), domainUUID).Scan(&version); err != nil && !errors.Is(err, sql.ErrNoRows) {
return preview, err
}
preview.BaseVersion = version
if plan.BaseVersion != 0 && plan.BaseVersion != version {
return preview, namespaceValidationError("topology version changed; preview the plan again")
}
if len(plan.Operations) == 0 || len(plan.Operations) > 500 {
return preview, namespaceValidationError("a City plan requires 1-500 operations")
}
items, err := s.loadCityBoundaries(tx, domainUUID)
if err != nil {
return preview, err
}
byID := make(map[string]*cityPathBoundary, len(items))
for i := range items {
byID[items[i].id] = &items[i]
}
changed := map[string]bool{}
seen := map[string]bool{}
for index := range plan.Operations {
op := &plan.Operations[index]
op.Action = strings.ToLower(strings.TrimSpace(op.Action))
op.Kind = strings.ToLower(strings.TrimSpace(op.Kind))
item := byID[op.UUID]
if item == nil {
return preview, namespaceValidationError("City plan references an unknown node")
}
key := op.Action + ":" + op.UUID
if seen[key] {
return preview, namespaceValidationError("City plan contains a duplicate operation")
}
seen[key] = true
switch op.Action {
case "set_path":
if op.Kind == "" {
op.Kind = item.kind
}
if op.Kind != item.kind {
return preview, namespaceValidationError("City plan node kind does not match")
}
before := item.path
item.path = normalizePath(op.PathPrefix)
if item.path == "/" && item.kind != "quartier" {
return preview, namespaceValidationError("only a Quartier may bind the Domain root")
}
changed[item.id] = true
preview.Before = append(preview.Before, map[string]any{"action": op.Action, "kind": item.kind, "uuid": item.id, "path_prefix": before})
preview.After = append(preview.After, map[string]any{"action": op.Action, "kind": item.kind, "uuid": item.id, "path_prefix": item.path})
case "move_street":
if item.kind != "street" || byID[op.ParentUUID] == nil || byID[op.ParentUUID].kind != "quartier" {
return preview, namespaceValidationError("move_street requires a Street and destination Quartier")
}
preview.Before = append(preview.Before, map[string]any{"action": op.Action, "uuid": item.id, "parent_uuid": item.parent})
item.parent = op.ParentUUID
preview.After = append(preview.After, map[string]any{"action": op.Action, "uuid": item.id, "parent_uuid": item.parent, "sort_key": op.SortKey})
case "move_spot":
if item.kind != "spot" || byID[op.StreetUUID] == nil || byID[op.StreetUUID].kind != "street" {
return preview, namespaceValidationError("move_spot requires a Spot and destination Street")
}
preview.Before = append(preview.Before, map[string]any{"action": op.Action, "uuid": item.id, "street_uuid": item.parent})
item.parent = op.StreetUUID
preview.After = append(preview.After, map[string]any{"action": op.Action, "uuid": item.id, "street_uuid": item.parent, "sort_key": op.SortKey})
default:
return preview, namespaceValidationError("unsupported City plan operation")
}
}
if err := validateCityBoundaryChanges(items, changed); err != nil {
return preview, err
}
for _, item := range items {
if item.kind == "street" {
parent := byID[item.parent]
if parent == nil || parent.kind != "quartier" || !cityPathContains(parent.path, item.path) {
return preview, namespaceValidationError("Street Path must be a strict descendant of its Quartier Path")
}
}
if item.kind == "spot" {
parent := byID[item.parent]
if parent == nil || parent.kind != "street" || !cityPathContains(parent.path, item.path) {
return preview, namespaceValidationError("Spot Path must be a strict descendant of its Street Path")
}
}
}
preview.Valid = true
return preview, nil
}