summaryrefslogtreecommitdiff
path: root/vendor/github.com/authzed/spicedb/internal/services/v1/preconditions.go
blob: c34d5d516a103e4a6627ebba410bd8e983764c2f (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
package v1

import (
	"context"
	"fmt"

	v1 "github.com/authzed/authzed-go/proto/authzed/api/v1"

	"github.com/authzed/spicedb/pkg/datastore"
	"github.com/authzed/spicedb/pkg/datastore/options"
	"github.com/authzed/spicedb/pkg/datastore/queryshape"
)

var limitOne uint64 = 1

// checkPreconditions checks whether the preconditions are met in the context of a datastore
// read-write transaction, and returns an error if they are not met.
func checkPreconditions(
	ctx context.Context,
	rwt datastore.ReadWriteTransaction,
	preconditions []*v1.Precondition,
) error {
	for _, precond := range preconditions {
		dsFilter, err := datastore.RelationshipsFilterFromPublicFilter(precond.Filter)
		if err != nil {
			return fmt.Errorf("error converting filter: %w", err)
		}

		iter, err := rwt.QueryRelationships(ctx, dsFilter, options.WithLimit(&limitOne), options.WithQueryShape(queryshape.Varying))
		if err != nil {
			return fmt.Errorf("error reading relationships: %w", err)
		}

		_, ok, err := datastore.FirstRelationshipIn(iter)
		if err != nil {
			return fmt.Errorf("error reading relationships from iterator: %w", err)
		}

		switch precond.Operation {
		case v1.Precondition_OPERATION_MUST_NOT_MATCH:
			if ok {
				return NewPreconditionFailedErr(precond)
			}
		case v1.Precondition_OPERATION_MUST_MATCH:
			if !ok {
				return NewPreconditionFailedErr(precond)
			}
		default:
			return fmt.Errorf("unspecified precondition operation: %s", precond.Operation)
		}
	}

	return nil
}