Files
pages/internal/store/path_snapshot.go
T
Anya Tokugawa c1175d389f Implement Knowledge City platform, organizer and DAV integration
Capture accumulated application, UI, CLI, regression tests and design documentation changes, including task project mapping and default CalDAV list naming.

Keep deployment data, backups, local credentials and build artifacts out of Git. Move the Compose enrollment token to an ignored local environment file.
2026-09-27 14:44:43 +09:00

185 lines
6.3 KiB
Go

package store
import (
"database/sql"
"encoding/json"
"errors"
"strings"
"github.com/google/uuid"
)
var (
ErrPathSnapshotChanged = errors.New("semantic paths changed during authorization; retry the operation")
ErrPathMutationTooLarge = errors.New("too many semantic paths in one operation")
)
// MaxPathMutationPaths bounds both authorization work and a single mutation.
// Larger trees should be submitted as independently authorized smaller subtrees.
const MaxPathMutationPaths = 10000
// PathMutationSnapshot is issued by the store, never decoded from client input.
// Its private bindings are the exact set on which the handler checks grants.
// Checking them again inside the write transaction prevents new descendants,
// removed entries, or replaced Object bindings from escaping those checks.
type PathMutationSnapshot struct {
domainUUID string
root string
recursive bool
bindings []pathRename
}
func (snapshot *PathMutationSnapshot) Root() string { return snapshot.root }
func (snapshot *PathMutationSnapshot) Paths() []string {
paths := make([]string, len(snapshot.bindings))
for i, binding := range snapshot.bindings {
paths[i] = binding.OldPath
}
return paths
}
type pathQueryer interface {
Query(string, ...any) (*sql.Rows, error)
}
func pathMutationTransactionError(err error) error {
var sqliteError interface{ Code() int }
if errors.As(err, &sqliteError) && sqliteError.Code() == 517 { // SQLITE_BUSY_SNAPSHOT
return ErrPathSnapshotChanged
}
return err
}
// Binary half-open ranges are literal and case-sensitive like paths.path.
// '/' followed by any suffix sorts before '0', its next ASCII character.
// Unlike LIKE, neither percent, underscore, backslash nor case changes can
// expand the requested subtree. The range can use the Domain/Path index.
func listMutationPaths(q pathQueryer, domainUUID, root string, recursive bool) ([]pathRename, error) {
prefix := strings.TrimRight(root, "/") + "/"
upper := strings.TrimSuffix(prefix, "/") + "0"
query := `
SELECT path, object_uuid, created_at, COALESCE(is_primary, 0)
FROM paths WHERE domain_uuid = ? AND path = ?`
args := []any{domainUUID, root}
if recursive {
// Separate indexed arms avoid the Domain-wide scan SQLite may choose
// for an OR with a runtime recursive flag. Lexical order is stable and
// puts each parent before its children without a full length sort.
query += ` UNION ALL
SELECT path, object_uuid, created_at, COALESCE(is_primary, 0)
FROM paths WHERE domain_uuid = ?
AND path >= ? COLLATE BINARY AND path < ? COLLATE BINARY AND path != ?`
args = append(args, domainUUID, prefix, upper, root)
}
query += ` ORDER BY path COLLATE BINARY LIMIT ?`
args = append(args, MaxPathMutationPaths+1)
rows, err := q.Query(query, args...)
if err != nil {
return nil, err
}
defer rows.Close()
var bindings []pathRename
for rows.Next() {
var item pathRename
if err := rows.Scan(&item.OldPath, &item.ObjectUUID, &item.CreatedAt, &item.IsPrimary); err != nil {
return nil, err
}
bindings = append(bindings, item)
}
if err := rows.Err(); err != nil {
return nil, err
}
if len(bindings) > MaxPathMutationPaths {
return nil, ErrPathMutationTooLarge
}
return bindings, nil
}
func (s *Store) SnapshotPathsInDomain(domainUUID, root string, recursive bool) (*PathMutationSnapshot, error) {
root = normalizePath(root)
bindings, err := listMutationPaths(s.DB, domainUUID, root, recursive)
if err != nil {
return nil, err
}
if len(bindings) == 0 {
return nil, ErrPathNotFound
}
return &PathMutationSnapshot{domainUUID: domainUUID, root: root, recursive: recursive, bindings: bindings}, nil
}
func (snapshot *PathMutationSnapshot) validate(domainUUID, root string, recursive bool, bindings []pathRename) error {
if snapshot == nil || snapshot.domainUUID != domainUUID || snapshot.root != root || snapshot.recursive != recursive || len(snapshot.bindings) != len(bindings) {
return ErrPathSnapshotChanged
}
for i, binding := range bindings {
if snapshot.bindings[i] != binding {
return ErrPathSnapshotChanged
}
}
return nil
}
// RemovePathsInDomainChecked unlinks the authorized bindings atomically. It
// deliberately retains Objects, Revisions and content-addressed Documents.
// Every scope is revalidated before the first DELETE, including overlapping
// selections. SQLite rejects an upgrade of a stale read snapshot to a write;
// do not retry this transaction without taking and authorizing a new snapshot.
func (s *Store) RemovePathsInDomainChecked(domainUUID string, snapshots []*PathMutationSnapshot) (int, error) {
if err := s.ensureLocalDomain(domainUUID); err != nil {
return 0, err
}
if len(snapshots) == 0 {
return 0, ErrPathNotFound
}
tx, err := s.DB.Begin()
if err != nil {
return 0, err
}
defer tx.Rollback()
bindings := map[string]pathRename{}
for _, snapshot := range snapshots {
if snapshot == nil || snapshot.domainUUID != domainUUID || snapshot.root == "/" {
return 0, ErrPathSnapshotChanged
}
current, err := listMutationPaths(tx, domainUUID, snapshot.root, snapshot.recursive)
if err != nil {
return 0, err
}
if err := snapshot.validate(domainUUID, snapshot.root, snapshot.recursive, current); err != nil {
return 0, err
}
for _, binding := range current {
bindings[binding.OldPath] = binding
}
if len(bindings) > MaxPathMutationPaths {
return 0, ErrPathMutationTooLarge
}
}
for _, binding := range bindings {
if _, err := tx.Exec(`DELETE FROM paths WHERE domain_uuid=? AND path=? AND object_uuid=?`, domainUUID, binding.OldPath, binding.ObjectUUID); err != nil {
return 0, pathMutationTransactionError(err)
}
}
operationID := uuid.NewString()
roots := make([]map[string]any, 0, len(snapshots))
for _, snapshot := range snapshots {
roots = append(roots, map[string]any{"path": snapshot.root, "recursive": snapshot.recursive})
}
payload, err := json.Marshal(map[string]any{"operation_uuid": operationID, "roots": roots, "count": len(bindings)})
if err != nil {
return 0, err
}
if err := s.appendActivityOutboxIfAvailable(tx, ActivityOutboxEvent{
DomainUUID: domainUUID, EventType: "path.unlinked", TargetKind: "path",
Payload: string(payload), IdempotencyKey: "path.unlinked:" + operationID,
}); err != nil {
return 0, err
}
if err := tx.Commit(); err != nil {
return 0, pathMutationTransactionError(err)
}
s.InvalidatePathCaches()
return len(bindings), nil
}