-
Notifications
You must be signed in to change notification settings - Fork 0
/
dryrun.go
419 lines (387 loc) · 12.5 KB
/
dryrun.go
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
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
package dryrun
import (
"context"
"fmt"
"path"
"reflect"
strings "strings"
"github.com/bufbuild/protovalidate-go"
cliutil "github.com/kralicky/codegen/pkg/cliutil"
corev1 "github.com/kralicky/protoconfig/apis/core/v1"
"github.com/kralicky/protoconfig/server"
"github.com/nsf/jsondiff"
"github.com/samber/lo"
cobra "github.com/spf13/cobra"
"github.com/ttacon/chalk"
"google.golang.org/grpc"
codes "google.golang.org/grpc/codes"
status "google.golang.org/grpc/status"
"google.golang.org/protobuf/proto"
"google.golang.org/protobuf/reflect/protoreflect"
"google.golang.org/protobuf/types/known/emptypb"
)
// Creates the 'dry-run' command for a compatible generated service client.
//
// The compiler can resolve all type parameters given the generated
// ClientContextInjector; it should not be necessary to specify them manually.
//
// The ClientContextInjector will be generated for any protobuf file containing
// the file option `option (cli.generator).generate = true;` and a compatible
// service definition.
//
// In a separate file in the same package as the generated code, enable the
// dry-run command as follows, substituting "X" for your service name:
//
// func init() {
// addExtraXCmd(dryrun.BuildCmd("dry-run", XContextInjector),
// BuildXSetDefaultCmd(),
// BuildXSetCmd(),
// BuildXResetDefaultCmd(),
// BuildXResetCmd(),
// )
// }
//
// The use line is the name of the dry-run command. If it is intended to be
// a generated subcommand, it can be multiple words (e.g. "config dry-run").
//
// Once the dry-run command is enabled, it will be available in the CLI
// as a subcommand of the service's top-level command. For example,
// (assuming the service's use line is "config"):
//
// $ <cmd> x config set [--flags ...]
// $ <cmd> x config dry-run set [--flags ...]
// $ <cmd> x config reset [--flags ...]
// $ <cmd> x config dry-run reset [--flags ...]
// etc.
func BuildCmd[
T server.ConfigType[T],
G server.GetRequestType,
S server.SetRequestType[T],
R server.ResetRequestType[T],
D server.DryRunRequestType[T],
DR server.DryRunResponseType[T],
H server.HistoryRequestType,
HR server.HistoryResponseType[T],
I server.ClientContextInjector[C],
C interface {
server.GetClient[T, G]
server.SetClient[T, S]
server.ResetClient[T, R]
server.DryRunClient[T, D, DR]
server.HistoryClient[T, H, HR]
},
](use string, cci I, dryRunnableCmds ...*cobra.Command) *cobra.Command {
var diffFull bool
var diffFormat string
dryRunCmd := &cobra.Command{
Use: use,
PersistentPreRunE: func(cmd *cobra.Command, args []string) error {
if err := cliutil.BasePreRunE(cmd, args); err != nil {
return err
}
// inject the dry-run client into the context
client, ok := cci.ClientFromContext(cmd.Context())
if ok {
cmd.SetContext(cci.ContextWithClient(cmd.Context(), cci.NewClient(NewDryRunClient(client).AsClientConn(cci))))
}
return nil
},
PersistentPostRunE: func(cmd *cobra.Command, args []string) error {
if err := cliutil.BasePostRunE(cmd, args); err != nil {
return err
}
// print the dry-run response
client, ok := cci.ClientFromContext(cmd.Context())
if !ok {
return nil
}
dryRunClient := NewDryRunClient(client).FromClientConn(cci.UnderlyingConn(client))
response := dryRunClient.Response()
if errs := (*protovalidate.ValidationError)(response.GetValidationErrors()); errs != nil {
cmd.Println(chalk.Yellow.Color(errs.Error()))
}
var opts jsondiff.Options
switch diffFormat {
case "console":
opts = jsondiff.DefaultConsoleOptions()
case "json":
opts = jsondiff.DefaultJSONOptions()
case "html":
opts = jsondiff.DefaultHTMLOptions()
default:
return fmt.Errorf("invalid diff format: %s", diffFormat)
}
opts.SkipMatches = !diffFull
str, anyChanges := server.RenderJsonDiff(response.GetCurrent(), response.GetModified(), opts)
if !anyChanges {
cmd.Println("no changes")
} else {
cmd.Println(str)
}
return nil
},
}
dryRunCmd.PersistentFlags().BoolVar(&diffFull, "diff-full", false, "show full diff, including all unchanged fields")
dryRunCmd.PersistentFlags().StringVar(&diffFormat, "diff-format", "console", "diff format (console, json, html)")
// if all commands have multiple words with the same first word, trim the first word
maybeParentCommand := ""
for _, cmd := range dryRunnableCmds {
if words := strings.SplitAfter(cmd.Use, " "); len(words) > 1 {
if maybeParentCommand == "" || maybeParentCommand == words[0] {
maybeParentCommand = words[0]
} else {
maybeParentCommand = ""
break
}
}
}
for _, cmd := range dryRunnableCmds {
cmd.Use = strings.TrimPrefix(cmd.Use, maybeParentCommand)
cmd.Short = fmt.Sprintf("[dry-run] %s", cmd.Short)
dryRunCmd.AddCommand(cmd)
}
return dryRunCmd
}
func NewDryRunClient[
T server.ConfigType[T],
G server.GetRequestType,
S server.SetRequestType[T],
R server.ResetRequestType[T],
D server.DryRunRequestType[T],
DR server.DryRunResponseType[T],
H server.HistoryRequestType,
HR server.HistoryResponseType[T],
C interface {
server.GetClient[T, G]
server.SetClient[T, S]
server.ResetClient[T, R]
server.DryRunClient[T, D, DR]
server.HistoryClient[T, H, HR]
},
](client C) *DryRunClient[T, G, S, R, D, DR, H, HR, C] {
return &DryRunClient[T, G, S, R, D, DR, H, HR, C]{
client: client,
maskedFields: corev1.MaskedFields[T](),
contextKeyable: reflect.TypeFor[D]().Implements(reflect.TypeFor[server.ContextKeyable]()),
}
}
type DryRunClient[
T server.ConfigType[T],
G server.GetRequestType,
S server.SetRequestType[T],
R server.ResetRequestType[T],
D server.DryRunRequestType[T],
DR server.DryRunResponseType[T],
H server.HistoryRequestType,
HR server.HistoryResponseType[T],
C interface {
server.GetClient[T, G]
server.SetClient[T, S]
server.ResetClient[T, R]
server.DryRunClient[T, D, DR]
server.HistoryClient[T, H, HR]
},
] struct {
client C
request D
response DR
maskedFields []protoreflect.FieldDescriptor
contextKeyable bool
}
func (dc *DryRunClient[T, G, S, R, D, DR, H, HR, C]) AsClientConn(cci server.ClientContextInjector[C]) grpc.ClientConnInterface {
return NewDryRunClientShim(dc, cci)
}
func (*DryRunClient[T, G, S, R, D, DR, H, HR, C]) FromClientConn(cc grpc.ClientConnInterface) *DryRunClient[T, G, S, R, D, DR, H, HR, C] {
return cc.(*DryRunClientShim[T, G, S, R, D, DR, H, HR, C]).dr
}
func (dc *DryRunClient[T, G, S, R, D, DR, H, HR, C]) Response() DR {
return dc.response
}
// Reset implements server.GetClient[T, G].
func (dc *DryRunClient[T, G, S, R, D, DR, H, HR, C]) Reset(ctx context.Context, req R, opts ...grpc.CallOption) (*emptypb.Empty, error) {
dc.request = NewDryRunRequest[T, D]().
Active().
Reset().
Revision(req.GetRevision()).
Patch(req.GetPatch()).
Mask(req.GetMask()).
Build()
if dc.contextKeyable {
copyContextKey(dc.request, req)
}
var err error
dc.response, err = dc.client.DryRun(ctx, dc.request, opts...)
if err != nil {
return nil, fmt.Errorf("[dry-run] error: %w", err)
}
return &emptypb.Empty{}, nil
}
// ResetDefault implements server.ResetClient[T, R].
func (dc *DryRunClient[T, G, S, R, D, DR, H, HR, C]) ResetDefault(ctx context.Context, _ *emptypb.Empty, opts ...grpc.CallOption) (*emptypb.Empty, error) {
dc.request = NewDryRunRequest[T, D]().
Default().
Reset().
Build()
var err error
dc.response, err = dc.client.DryRun(ctx, dc.request, opts...)
if err != nil {
return nil, fmt.Errorf("[dry-run] error: %w", err)
}
return &emptypb.Empty{}, nil
}
// Set implements server.SetClient[T, S].
func (dc *DryRunClient[T, G, S, R, D, DR, H, HR, C]) Set(ctx context.Context, in S, opts ...grpc.CallOption) (*emptypb.Empty, error) {
if in.GetSpec().ProtoReflect().IsValid() {
for _, mf := range dc.maskedFields {
in.GetSpec().ProtoReflect().Clear(mf)
}
}
dc.request = NewDryRunRequest[T, D]().
Active().
Set().
Spec(in.GetSpec()).
Build()
if dc.contextKeyable {
copyContextKey(dc.request, in)
}
var err error
dc.response, err = dc.client.DryRun(ctx, dc.request, opts...)
if err != nil {
return nil, fmt.Errorf("[dry-run] error: %w", err)
}
return &emptypb.Empty{}, nil
}
// SetDefault implements server.SetClient[T, S].
func (dc *DryRunClient[T, G, S, R, D, DR, H, HR, C]) SetDefault(ctx context.Context, in S, opts ...grpc.CallOption) (*emptypb.Empty, error) {
if in.GetSpec().ProtoReflect().IsValid() {
for _, mf := range dc.maskedFields {
in.GetSpec().ProtoReflect().Clear(mf)
}
}
dc.request = NewDryRunRequest[T, D]().
Default().
Set().
Spec(in.GetSpec()).
Build()
var err error
dc.response, err = dc.client.DryRun(ctx, dc.request, opts...)
if err != nil {
return nil, fmt.Errorf("[dry-run] error: %w", err)
}
return &emptypb.Empty{}, nil
}
// Get implements server.GetClient[T, G].
func (dc *DryRunClient[T, G, S, R, D, DR, H, HR, C]) Get(ctx context.Context, in G, opts ...grpc.CallOption) (T, error) {
return dc.client.Get(ctx, in, opts...)
}
// GetDefault implements server.GetClient[T, G].
func (dc *DryRunClient[T, G, S, R, D, DR, H, HR, C]) GetDefault(ctx context.Context, in G, opts ...grpc.CallOption) (T, error) {
return dc.client.GetDefault(ctx, in, opts...)
}
// DryRun implements server.DryRunClient[T, D, DR].
func (dc *DryRunClient[T, G, S, R, D, DR, H, HR, C]) DryRun(_ context.Context, _ D, _ ...grpc.CallOption) (DR, error) {
return lo.Empty[DR](), status.Errorf(codes.Unimplemented, "[dry-run] method DryRun not implemented")
}
// History implements server.HistoryClient[T, H, HR].
func (dc *DryRunClient[T, G, S, R, D, DR, H, HR, C]) History(_ context.Context, _ H, _ ...grpc.CallOption) (HR, error) {
return lo.Empty[HR](), status.Errorf(codes.Unimplemented, "[dry-run] method History not implemented")
}
func copyContextKey(dst, src proto.Message) {
dst.ProtoReflect().Set(dst.(server.ContextKeyable).ContextKey(),
src.ProtoReflect().Get(src.(server.ContextKeyable).ContextKey()))
}
type DryRunClientShim[
T server.ConfigType[T],
G server.GetRequestType,
S server.SetRequestType[T],
R server.ResetRequestType[T],
D server.DryRunRequestType[T],
DR server.DryRunResponseType[T],
H server.HistoryRequestType,
HR server.HistoryResponseType[T],
C interface {
server.GetClient[T, G]
server.SetClient[T, S]
server.ResetClient[T, R]
server.DryRunClient[T, D, DR]
server.HistoryClient[T, H, HR]
},
] struct {
cc grpc.ClientConnInterface
dr *DryRunClient[T, G, S, R, D, DR, H, HR, C]
}
func NewDryRunClientShim[
T server.ConfigType[T],
G server.GetRequestType,
S server.SetRequestType[T],
R server.ResetRequestType[T],
D server.DryRunRequestType[T],
DR server.DryRunResponseType[T],
H server.HistoryRequestType,
HR server.HistoryResponseType[T],
C interface {
server.GetClient[T, G]
server.SetClient[T, S]
server.ResetClient[T, R]
server.DryRunClient[T, D, DR]
server.HistoryClient[T, H, HR]
},
](
dr *DryRunClient[T, G, S, R, D, DR, H, HR, C],
cci server.ClientContextInjector[C],
) grpc.ClientConnInterface {
return &DryRunClientShim[T, G, S, R, D, DR, H, HR, C]{
dr: dr,
cc: cci.UnderlyingConn(dr.client),
}
}
// Invoke implements grpc.ClientConnInterface.
func (dc *DryRunClientShim[T, G, S, R, D, DR, H, HR, C]) Invoke(ctx context.Context, method string, args any, reply any, opts ...grpc.CallOption) error {
switch path.Base(method) {
case "GetDefault":
resp, err := dc.dr.GetDefault(ctx, args.(G), opts...)
if err != nil {
return err
}
proto.Merge(reply.(proto.Message), resp)
case "SetDefault":
resp, err := dc.dr.SetDefault(ctx, args.(S), opts...)
if err != nil {
return err
}
proto.Merge(reply.(proto.Message), resp)
case "ResetDefault":
resp, err := dc.dr.ResetDefault(ctx, args.(*emptypb.Empty), opts...)
if err != nil {
return err
}
proto.Merge(reply.(proto.Message), resp)
case "Get":
resp, err := dc.dr.Get(ctx, args.(G), opts...)
if err != nil {
return err
}
proto.Merge(reply.(proto.Message), resp)
case "Set":
resp, err := dc.dr.Set(ctx, args.(S), opts...)
if err != nil {
return err
}
proto.Merge(reply.(proto.Message), resp)
case "Reset":
resp, err := dc.dr.Reset(ctx, args.(R), opts...)
if err != nil {
return err
}
proto.Merge(reply.(proto.Message), resp)
case "DryRun":
return status.Errorf(codes.Unimplemented, "[dry-run] attempted to recursively invoke DryRun")
default:
return dc.cc.Invoke(ctx, method, args, reply, opts...)
}
return nil
}
// NewStream implements grpc.ClientConnInterface.
func (dc *DryRunClientShim[T, G, S, R, D, DR, H, HR, C]) NewStream(ctx context.Context, desc *grpc.StreamDesc, method string, opts ...grpc.CallOption) (grpc.ClientStream, error) {
return dc.cc.NewStream(ctx, desc, method, opts...)
}