summaryrefslogtreecommitdiff
path: root/vendor/github.com/authzed/spicedb/pkg/validationfile/blocks/relationships.go
blob: 278c7a8e461c57522c255eb61361e1f44b8250c1 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
package blocks

import (
	"fmt"
	"strings"

	"github.com/ccoveille/go-safecast"
	yamlv3 "gopkg.in/yaml.v3"

	"github.com/authzed/spicedb/pkg/spiceerrors"
	"github.com/authzed/spicedb/pkg/tuple"
)

// ParsedRelationships is the parsed relationships in a validationfile.
type ParsedRelationships struct {
	// RelationshipsString is the found string of newline-separated relationships.
	RelationshipsString string

	// SourcePosition is the position of the schema in the file.
	SourcePosition spiceerrors.SourcePosition

	// Relationships are the fully parsed relationships.
	Relationships []tuple.Relationship
}

// UnmarshalYAML is a custom unmarshaller.
func (pr *ParsedRelationships) UnmarshalYAML(node *yamlv3.Node) error {
	err := node.Decode(&pr.RelationshipsString)
	if err != nil {
		return convertYamlError(err)
	}

	relationshipsString := pr.RelationshipsString
	if relationshipsString == "" {
		return nil
	}

	seenTuples := map[string]bool{}
	lines := strings.Split(relationshipsString, "\n")
	relationships := make([]tuple.Relationship, 0, len(lines))
	for index, line := range lines {
		trimmed := strings.TrimSpace(line)
		if len(trimmed) == 0 || strings.HasPrefix(trimmed, "//") {
			continue
		}

		// +1 for the key, and *2 for newlines in YAML
		errorLine, err := safecast.ToUint64(node.Line + 1 + (index * 2))
		if err != nil {
			return err
		}
		column, err := safecast.ToUint64(node.Column)
		if err != nil {
			return err
		}

		rel, err := tuple.Parse(trimmed)
		if err != nil {
			return spiceerrors.NewWithSourceError(
				fmt.Errorf("error parsing relationship `%s`: %w", trimmed, err),
				trimmed,
				errorLine,
				column,
			)
		}

		_, ok := seenTuples[tuple.StringWithoutCaveatOrExpiration(rel)]
		if ok {
			return spiceerrors.NewWithSourceError(
				fmt.Errorf("found repeated relationship `%s`", trimmed),
				trimmed,
				errorLine,
				column,
			)
		}
		seenTuples[tuple.StringWithoutCaveatOrExpiration(rel)] = true
		relationships = append(relationships, rel)
	}

	pr.Relationships = relationships
	pr.SourcePosition = spiceerrors.SourcePosition{LineNumber: node.Line, ColumnPosition: node.Column}
	return nil
}