package store import ( "context" "crypto/sha256" "database/sql" "encoding/hex" "encoding/json" "errors" "strings" "time" ) type autoPublicationRule struct { Kind, ID, Mode, Scope, Actor string Version int64 } func autoContains(scope, path string) bool { return scope == path || cityPathContains(scope, path) } type AutoPublication struct { Mode string `json:"mode"` Version int64 `json:"version"` Epoch int64 `json:"epoch"` TopologyVersion int64 `json:"topology_version"` CanAutomatic bool `json:"can_automatic"` Active bool `json:"active"` PreviewComplete bool `json:"preview_complete"` Impact LocalityPublication `json:"impact"` } type AutoPublicationChange struct { Mode string `json:"mode"` Version int64 `json:"version"` Epoch int64 `json:"epoch"` TopologyVersion int64 `json:"topology_version"` Confirm bool `json:"confirm"` ImpactToken string `json:"impact_token"` } func autoScope(ctx context.Context, tx *sql.Tx, domain, kind, id string) (string, error) { if kind == "domain" { if id != domain { return "", ErrGovernanceInvalid } return "/", nil } table := "zones" if kind == "spot" { table = "spots" } var scope string err := tx.QueryRowContext(ctx, `SELECT path_prefix FROM `+table+` WHERE domain_uuid=? AND uuid=? AND state!='archived'`, domain, id).Scan(&scope) return scope, err } func autoRules(ctx context.Context, tx *sql.Tx, domain string) ([]autoPublicationRule, error) { rows, err := tx.QueryContext(ctx, `SELECT node_kind,node_uuid,mode,scope_path,actor_uuid,version FROM locality_auto_publication WHERE domain_uuid=? ORDER BY node_kind,node_uuid LIMIT 129`, domain) if err != nil { return nil, err } defer rows.Close() out := []autoPublicationRule{} for rows.Next() { var p autoPublicationRule if err = rows.Scan(&p.Kind, &p.ID, &p.Mode, &p.Scope, &p.Actor, &p.Version); err != nil { return nil, err } out = append(out, p) } if len(out) > 128 { return nil, ErrNavigationBudget } return out, rows.Err() } func requireManualPublication(ctx context.Context, tx *sql.Tx, domain, actor, kind, id string) error { scope, err := autoScope(ctx, tx, domain, kind, id) if err != nil { return err } _, err = tx.ExecContext(ctx, `INSERT INTO locality_auto_publication VALUES(?,?,?,'required',?,?,1) ON CONFLICT(domain_uuid,node_kind,node_uuid) DO UPDATE SET mode='required',scope_path=excluded.scope_path,actor_uuid=excluded.actor_uuid,version=version+1`, domain, kind, id, scope, actor) return err } func (s *Store) AutoPublication(ctx context.Context, domain, actor, kind, id string, change *AutoPublicationChange) (AutoPublication, error) { ctx, cancel := context.WithTimeout(ctx, 3*time.Second) defer cancel() state := AutoPublication{Mode: "inherit"} tx, err := s.DB.BeginTx(ctx, nil) if err != nil { return state, err } defer tx.Rollback() if change != nil { if _, err = tx.ExecContext(ctx, `INSERT INTO city_governance_epochs VALUES(?,0) ON CONFLICT(domain_uuid) DO UPDATE SET version=version`, domain); err != nil { return state, err } } g, err := governanceSnapshot(ctx, tx, domain, actor, kind, id) if err != nil { return state, err } scope, err := autoScope(ctx, tx, domain, kind, id) if err != nil { return state, err } rules, err := autoRules(ctx, tx, domain) if err != nil { return state, err } state.Epoch, state.TopologyVersion = g.Epoch, g.TopologyVersion state.CanAutomatic = (kind == "street" || kind == "spot") && g.DraftEffectivePublic && PublicSemanticPath(scope) blockedScopes := []string{} for _, rule := range rules { if rule.Kind == kind && rule.ID == id { state.Mode, state.Version = rule.Mode, rule.Version state.Active = rule.Mode == "automatic" && rule.Scope == scope if state.Active && rule.Actor != actor { _, e := governanceSnapshot(ctx, tx, domain, rule.Actor, kind, id) if errors.Is(e, sql.ErrNoRows) || errors.Is(e, ErrAccessDenied) { state.Active = false } else if e != nil { return state, e } } } if rule.Mode == "required" && !(rule.Kind == kind && rule.ID == id) { parent, e := autoScope(ctx, tx, domain, rule.Kind, rule.ID) if e != nil && !errors.Is(e, sql.ErrNoRows) { return state, e } if e == nil { blockedScopes = append(blockedScopes, parent) if autoContains(parent, scope) { state.CanAutomatic = false } } } } state.Active = state.Active && state.CanAutomatic if change != nil && (change.Epoch != state.Epoch || change.TopologyVersion != state.TopologyVersion || change.Version != state.Version) { return state, ErrGovernanceConflict } if change == nil || change.Mode != "required" { state.Impact, err = publicationImpact(ctx, tx, domain, actor, kind, id, g) if err != nil { if change == nil && errors.Is(err, ErrPublicationImpact) { state.CanAutomatic = false return state, nil } return state, err } state.PreviewComplete = true visible := []PublicationEntry{} for _, entry := range state.Impact.Entries { blocked := false for _, scope := range blockedScopes { if autoContains(scope, entry.Path) { blocked = true break } } if blocked { state.Impact.Excluded = append(state.Impact.Excluded, entry.Path) } else { visible = append(visible, entry) } } state.Impact.Entries = visible input, _ := json.Marshal(struct { Impact string Rules []autoPublicationRule }{state.Impact.ImpactToken, rules}) hash := sha256.Sum256(input) state.Impact.ImpactToken = hex.EncodeToString(hash[:]) } if change == nil { return state, nil } if change.Mode != "automatic" && change.Mode != "required" && change.Mode != "inherit" { return state, ErrGovernanceInvalid } if change.Mode == "automatic" { if !state.CanAutomatic { return state, ErrGovernanceCeiling } if !change.Confirm || change.ImpactToken == "" || change.ImpactToken != state.Impact.ImpactToken { return state, ErrPublicationImpact } if err = installPublicationGuards(ctx, tx); err != nil { return state, err } } if change.Mode == "inherit" && (!change.Confirm || change.ImpactToken == "" || change.ImpactToken != state.Impact.ImpactToken) { return state, ErrPublicationImpact } before, _ := json.Marshal(state) _, err = tx.ExecContext(ctx, `INSERT INTO locality_auto_publication VALUES(?,?,?,?,?,?,1) ON CONFLICT(domain_uuid,node_kind,node_uuid) DO UPDATE SET mode=excluded.mode,scope_path=excluded.scope_path,actor_uuid=excluded.actor_uuid,version=version+1`, domain, kind, id, change.Mode, scope, actor) if err != nil { return state, err } state.Mode = change.Mode state.Version++ state.Active = change.Mode == "automatic" state.Impact.ImpactToken = "" after, _ := json.Marshal(state) _, err = tx.ExecContext(ctx, `INSERT INTO city_governance_events(domain_uuid,epoch,actor_uuid,node_kind,node_uuid,before_json,after_json,created_at_ms) VALUES(?,?,?,?,?,?,?,?)`, domain, g.Epoch, actor, kind, id, string(before), string(after), time.Now().UnixMilli()) if err != nil { return state, err } return state, tx.Commit() } // Evaluate live heads, audience, publisher authority and literal Path boundaries // in one read transaction. No request mutates approval manifests or source content. func (s *Store) automaticPublicPages(ctx context.Context, domain, onlyPath string) ([]PublishedNavigationPage, error) { tx, err := s.DB.BeginTx(ctx, &sql.TxOptions{ReadOnly: true}) if err != nil { return nil, err } defer tx.Rollback() var live bool if err = tx.QueryRowContext(ctx, `SELECT EXISTS(SELECT 1 FROM domains d JOIN campuses c ON c.uuid=d.campus_uuid JOIN config cfg ON cfg.domain_uuid=d.uuid AND cfg.key='authorization_mode' AND cfg.value='enforcing' WHERE d.uuid=? AND d.enabled=1 AND c.enabled=1)`, domain).Scan(&live); err != nil { return nil, err } if !live { return nil, nil } rules, err := autoRules(ctx, tx, domain) if err != nil { return nil, err } blocked := []string{} for _, rule := range rules { if rule.Mode == "required" { scope, e := autoScope(ctx, tx, domain, rule.Kind, rule.ID) if errors.Is(e, sql.ErrNoRows) { continue } if e != nil { return nil, e } blocked = append(blocked, scope) } } deny := func(p string) bool { for _, scope := range blocked { if autoContains(scope, p) { return true } } return false } if onlyPath != "" && deny(onlyPath) { return nil, nil } entries := map[string]PublicationEntry{} for _, rule := range rules { if rule.Mode != "automatic" || (rule.Kind != "street" && rule.Kind != "spot") { continue } if onlyPath != "" && !autoContains(rule.Scope, onlyPath) { continue } g, e := governanceSnapshot(ctx, tx, domain, rule.Actor, rule.Kind, rule.ID) if errors.Is(e, sql.ErrNoRows) || errors.Is(e, ErrAccessDenied) || errors.Is(e, ErrGovernanceInvalid) { continue } if e != nil { return nil, e } current, e := autoScope(ctx, tx, domain, rule.Kind, rule.ID) if e != nil { return nil, e } if current != rule.Scope || !g.DraftEffectivePublic || deny(current) { continue } p, e := publicationImpactBounded(ctx, tx, domain, rule.Actor, rule.Kind, rule.ID, g, MaxNavigationEntries, onlyPath) if errors.Is(e, ErrAccessDenied) { continue } if e != nil { return nil, e } for _, entry := range p.Entries { if !deny(entry.Path) { entries[entry.Revision] = entry } if len(entries) > MaxNavigationEntries { return nil, ErrNavigationBudget } } } if len(entries) == 0 { return nil, nil } args := []any{} for id := range entries { args = append(args, id) } rows, err := tx.QueryContext(ctx, `SELECT uuid,object_uuid,document_hash,COALESCE(NULLIF(lang,''),'und'),COALESCE(NULLIF(content_type,''),'text/html; charset=utf-8'),COALESCE(filename,''),created_at_ms FROM revisions WHERE uuid IN (`+strings.TrimSuffix(strings.Repeat("?,", len(args)), ",")+`) ORDER BY created_at_ms DESC,uuid`, args...) if err != nil { return nil, err } defer rows.Close() out := []PublishedNavigationPage{} size := 0 for rows.Next() { var p PublishedNavigationPage v := &p.Revision if err = rows.Scan(&v.UUID, &v.ObjectUUID, &v.DocumentHash, &v.Language, &v.ContentType, &v.Filename, &v.CreatedAtMS); err != nil { return nil, err } p.Path = entries[v.UUID].Path size += len(p.Path) + len(v.Filename) + len(v.ContentType) if size > 4<<20 { return nil, ErrNavigationBudget } out = append(out, p) } return out, rows.Err() }