summaryrefslogtreecommitdiff
path: root/vendor/github.com/authzed/zed/internal/commands/watch.go
blob: 96b3451655c64273172b70ac5d7971e3486130a1 (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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
package commands

import (
	"context"
	"fmt"
	"os"
	"os/signal"
	"strings"
	"syscall"
	"time"

	"github.com/spf13/cobra"

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

	"github.com/authzed/zed/internal/client"
	"github.com/authzed/zed/internal/console"
)

var (
	watchObjectTypes         []string
	watchRevision            string
	watchTimestamps          bool
	watchRelationshipFilters []string
)

func RegisterWatchCmd(rootCmd *cobra.Command) *cobra.Command {
	rootCmd.AddCommand(watchCmd)

	watchCmd.Flags().StringSliceVar(&watchObjectTypes, "object_types", nil, "optional object types to watch updates for")
	watchCmd.Flags().StringVar(&watchRevision, "revision", "", "optional revision at which to start watching")
	watchCmd.Flags().BoolVar(&watchTimestamps, "timestamp", false, "shows timestamp of incoming update events")
	return watchCmd
}

func RegisterWatchRelationshipCmd(parentCmd *cobra.Command) *cobra.Command {
	parentCmd.AddCommand(watchRelationshipsCmd)
	watchRelationshipsCmd.Flags().StringSliceVar(&watchObjectTypes, "object_types", nil, "optional object types to watch updates for")
	watchRelationshipsCmd.Flags().StringVar(&watchRevision, "revision", "", "optional revision at which to start watching")
	watchRelationshipsCmd.Flags().BoolVar(&watchTimestamps, "timestamp", false, "shows timestamp of incoming update events")
	watchRelationshipsCmd.Flags().StringSliceVar(&watchRelationshipFilters, "filter", nil, "optional filter(s) for the watch stream. Example: `optional_resource_type:optional_resource_id_or_prefix#optional_relation@optional_subject_filter`")
	return watchRelationshipsCmd
}

var watchCmd = &cobra.Command{
	Use:        "watch [object_types, ...] [start_cursor]",
	Short:      "Watches the stream of relationship updates from the server",
	Args:       ValidationWrapper(cobra.RangeArgs(0, 2)),
	RunE:       watchCmdFunc,
	Deprecated: "deprecated; please use `zed watch relationships` instead",
}

var watchRelationshipsCmd = &cobra.Command{
	Use:   "watch [object_types, ...] [start_cursor]",
	Short: "Watches the stream of relationship updates from the server",
	Args:  ValidationWrapper(cobra.RangeArgs(0, 2)),
	RunE:  watchCmdFunc,
}

func watchCmdFunc(cmd *cobra.Command, _ []string) error {
	console.Printf("starting watch stream over types %v and revision %v\n", watchObjectTypes, watchRevision)

	cli, err := client.NewClient(cmd)
	if err != nil {
		return err
	}

	relFilters := make([]*v1.RelationshipFilter, 0, len(watchRelationshipFilters))
	for _, filter := range watchRelationshipFilters {
		relFilter, err := parseRelationshipFilter(filter)
		if err != nil {
			return err
		}
		relFilters = append(relFilters, relFilter)
	}

	req := &v1.WatchRequest{
		OptionalObjectTypes:         watchObjectTypes,
		OptionalRelationshipFilters: relFilters,
	}
	if watchRevision != "" {
		req.OptionalStartCursor = &v1.ZedToken{Token: watchRevision}
	}

	ctx, cancel := context.WithCancel(cmd.Context())
	defer cancel()

	signalctx, interruptCancel := signal.NotifyContext(ctx, os.Interrupt, syscall.SIGTERM, syscall.SIGINT)
	defer interruptCancel()

	watchStream, err := cli.Watch(ctx, req)
	if err != nil {
		return err
	}

	for {
		select {
		case <-signalctx.Done():
			console.Errorf("stream interrupted after program termination\n")
			return nil
		case <-ctx.Done():
			console.Errorf("stream canceled after context cancellation\n")
			return nil
		default:
			resp, err := watchStream.Recv()
			if err != nil {
				return err
			}

			for _, update := range resp.Updates {
				if watchTimestamps {
					console.Printf("%v: ", time.Now())
				}

				switch update.Operation {
				case v1.RelationshipUpdate_OPERATION_CREATE:
					console.Printf("CREATED ")

				case v1.RelationshipUpdate_OPERATION_DELETE:
					console.Printf("DELETED ")

				case v1.RelationshipUpdate_OPERATION_TOUCH:
					console.Printf("TOUCHED ")
				}

				subjectRelation := ""
				if update.Relationship.Subject.OptionalRelation != "" {
					subjectRelation = " " + update.Relationship.Subject.OptionalRelation
				}

				console.Printf("%s:%s %s %s:%s%s\n",
					update.Relationship.Resource.ObjectType,
					update.Relationship.Resource.ObjectId,
					update.Relationship.Relation,
					update.Relationship.Subject.Object.ObjectType,
					update.Relationship.Subject.Object.ObjectId,
					subjectRelation,
				)
			}
		}
	}
}

func parseRelationshipFilter(relFilterStr string) (*v1.RelationshipFilter, error) {
	relFilter := &v1.RelationshipFilter{}
	pieces := strings.Split(relFilterStr, "@")
	if len(pieces) > 2 {
		return nil, fmt.Errorf("invalid relationship filter: %s", relFilterStr)
	}

	if len(pieces) == 2 {
		subjectFilter, err := parseSubjectFilter(pieces[1])
		if err != nil {
			return nil, err
		}
		relFilter.OptionalSubjectFilter = subjectFilter
	}

	if len(pieces) > 0 {
		resourcePieces := strings.Split(pieces[0], "#")
		if len(resourcePieces) > 2 {
			return nil, fmt.Errorf("invalid relationship filter: %s", relFilterStr)
		}

		if len(resourcePieces) == 2 {
			relFilter.OptionalRelation = resourcePieces[1]
		}

		resourceTypePieces := strings.Split(resourcePieces[0], ":")
		if len(resourceTypePieces) > 2 {
			return nil, fmt.Errorf("invalid relationship filter: %s", relFilterStr)
		}

		relFilter.ResourceType = resourceTypePieces[0]
		if len(resourceTypePieces) == 2 {
			optionalResourceIDOrPrefix := resourceTypePieces[1]
			if strings.HasSuffix(optionalResourceIDOrPrefix, "%") {
				relFilter.OptionalResourceIdPrefix = strings.TrimSuffix(optionalResourceIDOrPrefix, "%")
			} else {
				relFilter.OptionalResourceId = optionalResourceIDOrPrefix
			}
		}
	}

	return relFilter, nil
}

func parseSubjectFilter(subjectFilterStr string) (*v1.SubjectFilter, error) {
	subjectFilter := &v1.SubjectFilter{}
	pieces := strings.Split(subjectFilterStr, "#")
	if len(pieces) > 2 {
		return nil, fmt.Errorf("invalid subject filter: %s", subjectFilterStr)
	}

	subjectTypePieces := strings.Split(pieces[0], ":")
	if len(subjectTypePieces) > 2 {
		return nil, fmt.Errorf("invalid subject filter: %s", subjectFilterStr)
	}

	subjectFilter.SubjectType = subjectTypePieces[0]
	if len(subjectTypePieces) == 2 {
		subjectFilter.OptionalSubjectId = subjectTypePieces[1]
	}

	if len(pieces) == 2 {
		subjectFilter.OptionalRelation = &v1.SubjectFilter_RelationFilter{
			Relation: pieces[1],
		}
	}

	return subjectFilter, nil
}