-
Notifications
You must be signed in to change notification settings - Fork 9
/
plan.go
362 lines (296 loc) · 8.82 KB
/
plan.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
// Copyright 2022 Namespace Labs Inc; All rights reserved.
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
package execution
import (
"bytes"
"context"
"fmt"
"strconv"
"strings"
"github.com/philopon/go-toposort"
"golang.org/x/exp/maps"
"golang.org/x/exp/slices"
"google.golang.org/protobuf/proto"
"namespacelabs.dev/foundation/framework/rpcerrors/multierr"
"namespacelabs.dev/foundation/internal/console"
"namespacelabs.dev/foundation/internal/fnerrors"
"namespacelabs.dev/foundation/schema"
"namespacelabs.dev/foundation/schema/orchestration"
"namespacelabs.dev/foundation/std/tasks"
)
type HandleResult struct {
Waiter Waiter
Outputs []Output
}
type Output struct {
InstanceID string
Message proto.Message
Instance any
}
// A plan collects a set of invocations which can then be executed as a batch.
type Plan struct {
definitions []*schema.SerializedInvocation
scope schema.PackageList
}
type compiledPlan struct {
definitions []*schema.SerializedInvocation
nodes []*executionNode
}
type executionNode struct {
invocation *schema.SerializedInvocation
message proto.Message
parsed any
computedOrder *schema.ScheduleOrder
dispatch internalFuncs
}
func NewEmptyPlan() *Plan {
return &Plan{}
}
func NewPlan(defs ...*schema.SerializedInvocation) *Plan {
return NewEmptyPlan().Add(defs...)
}
func (g *Plan) Add(defs ...*schema.SerializedInvocation) *Plan {
g.definitions = append(g.definitions, defs...)
for _, def := range defs {
g.scope.AddMultiple(schema.PackageNames(def.Scope...)...)
}
return g
}
func compile(ctx context.Context, srcs []*schema.SerializedInvocation) (*compiledPlan, error) {
g := &compiledPlan{}
var defs []*schema.SerializedInvocation
tocompile := map[string][]*schema.SerializedInvocation{}
for _, src := range srcs {
if compilers[src.Impl.TypeUrl] != nil {
tocompile[src.Impl.TypeUrl] = append(tocompile[src.Impl.TypeUrl], src)
} else {
defs = append(defs, src)
}
}
compileKeys := maps.Keys(tocompile)
slices.Sort(compileKeys)
for _, key := range compileKeys {
compiled, err := compilers[key](ctx, tocompile[key])
if err != nil {
return nil, err
}
defs = append(defs, compiled...)
}
var nodes []*executionNode
for _, src := range defs {
key := src.Impl.GetTypeUrl()
reg, ok := handlers[key]
if !ok {
return nil, fnerrors.InternalError("%v: no handler registered", key)
}
msg, err := reg.unmarshal(src)
if err != nil {
return nil, fnerrors.InternalError("%v: failed to unmarshal: %w", key, err)
}
node := &executionNode{
invocation: src,
dispatch: reg.funcs,
message: msg,
}
if reg.funcs.Parse != nil {
var err error
node.parsed, err = reg.funcs.Parse(ctx, src, msg)
if err != nil {
return nil, fnerrors.InternalError("%s: failed to parse: %w", key, err)
}
}
computedOrder, err := reg.funcs.PlanOrder(ctx, msg, node.parsed)
if err != nil {
return nil, fnerrors.InternalError("%s: failed to compute order: %w", key, err)
}
if computedOrder == nil {
computedOrder = &schema.ScheduleOrder{}
}
computedOrder.SchedCategory = append(computedOrder.SchedCategory, src.Order.GetSchedCategory()...)
computedOrder.SchedAfterCategory = append(computedOrder.SchedAfterCategory, src.Order.GetSchedAfterCategory()...)
node.computedOrder = computedOrder
nodes = append(nodes, node)
}
g.definitions = append(g.definitions, defs...)
g.nodes = append(g.nodes, nodes...)
return g, nil
}
func Serialize(g *Plan) *schema.SerializedProgram {
return &schema.SerializedProgram{Invocation: g.definitions}
}
type recordedOutput struct {
Message proto.Message
Instance any
Used bool
}
func (g *compiledPlan) apply(ctx context.Context, ch chan *orchestration.Event, opts ExecuteOpts) error {
err := tasks.Attachments(ctx).AttachSerializable("definitions.json", "fn.graph", g.definitions)
if err != nil {
fmt.Fprintf(console.Debug(ctx), "failed to serialize graph definition: %v", err)
}
nodes, err := topoSortNodes(ctx, g.nodes)
if err != nil {
return err
}
var errs []error
if ch != nil {
for _, node := range nodes {
if node.dispatch.EmitStart != nil {
node.dispatch.EmitStart(ctx, node.invocation, node.message, node.parsed, ch)
}
}
}
ctx, done := context.WithCancel(ctx)
defer done()
outputs := map[string]*recordedOutput{}
for _, n := range nodes {
typeUrl := n.invocation.Impl.GetTypeUrl()
fmt.Fprintf(console.Debug(ctx), "executing %q (%s)\n", typeUrl, n.invocation.Description)
inputs, err := prepareInputs(outputs, n.invocation)
if err != nil {
if opts.ContinueOnErrors {
errs = append(errs, err)
} else {
return err
}
continue
}
invCtx := injectValues(ctx, InputsInjection.With(inputs))
var running *tasks.RunningAction
if opts.WrapWithActions {
action := tasks.Action("execute.step").Arg("typeUrl", typeUrl)
if n.invocation.Description != "" {
action = action.HumanReadablef(n.invocation.Description)
}
running = action.Start(invCtx)
}
res, err := n.dispatch.Handle(invCtx, n.invocation, n.message, n.parsed, ch)
if running != nil {
_ = running.Done(err)
}
if err != nil {
wrappedErr := fnerrors.InternalError("failed to run %q: %w", typeUrl, err)
if opts.ContinueOnErrors {
errs = append(errs, wrappedErr)
} else {
return wrappedErr
}
} else if res != nil {
for _, output := range res.Outputs {
if _, ok := outputs[output.InstanceID]; ok {
wrappedErr := fnerrors.InternalError("duplicate result key: %q", output.InstanceID)
if opts.ContinueOnErrors {
errs = append(errs, wrappedErr)
} else {
return wrappedErr
}
} else {
outputs[output.InstanceID] = &recordedOutput{
Message: output.Message,
Instance: output.Instance,
}
}
}
if res.Waiter != nil {
if opts.OnWaiter != nil {
opts.OnWaiter(ctx, res.Waiter)
} else {
fmt.Fprintf(console.Debug(ctx), "%s: ignoring waiter\n", typeUrl)
}
}
}
}
var unusedKeys []string
for key, output := range outputs {
if !output.Used {
unusedKeys = append(unusedKeys, key)
}
}
slices.Sort(unusedKeys)
if len(unusedKeys) > 0 {
errs = append(errs, fnerrors.InternalError("unused outputs: %v", unusedKeys))
}
return multierr.New(errs...)
}
func prepareInputs(outputs map[string]*recordedOutput, def *schema.SerializedInvocation) (Inputs, error) {
var missing []string
out := Inputs{}
for _, required := range def.RequiredOutput {
output, ok := outputs[required]
if !ok {
missing = append(missing, required)
} else {
out[required] = Input{
Message: output.Message,
Instance: output.Instance,
}
output.Used = true
}
}
if len(missing) > 0 {
slices.Sort(missing)
return nil, fnerrors.InternalError("required inputs are missing: %v", missing)
}
return out, nil
}
func (g *Plan) Definitions() []*schema.SerializedInvocation {
return g.definitions
}
func topoSortNodes(ctx context.Context, nodes []*executionNode) ([]*executionNode, error) {
graph := toposort.NewGraph(len(nodes))
categories := map[string]struct{}{}
for _, n := range nodes {
for _, cat := range n.computedOrder.GetSchedCategory() {
if _, has := categories[cat]; !has {
graph.AddNode("cat:" + cat)
categories[cat] = struct{}{}
}
}
for _, cat := range n.computedOrder.GetSchedAfterCategory() {
if _, has := categories[cat]; !has {
graph.AddNode("cat:" + cat)
categories[cat] = struct{}{}
}
}
}
// The idea is that a category is only done when all of its individual nodes are.
for k, n := range nodes {
ks := fmt.Sprintf("iid:%d", k)
graph.AddNode(ks)
for _, cat := range n.computedOrder.GetSchedCategory() {
graph.AddEdge(ks, "cat:"+cat)
}
for _, cat := range n.computedOrder.GetSchedAfterCategory() {
graph.AddEdge("cat:"+cat, ks)
}
}
sorted, solved := graph.Toposort()
if !solved {
for k, n := range nodes {
fmt.Fprintf(console.Errors(ctx), " #%d %q --> cats:%v after:%v\n", k, n.invocation.Description,
n.computedOrder.GetSchedCategory(),
n.computedOrder.GetSchedAfterCategory())
}
return nil, fnerrors.InternalError("ops dependencies are not solvable")
}
var debug bytes.Buffer
end := make([]*executionNode, 0, len(nodes))
for _, k := range sorted {
parsed := strings.TrimPrefix(k, "iid:")
if parsed == k {
fmt.Fprintf(&debug, " [%s]\n", k)
continue
}
i, err := strconv.ParseInt(parsed, 10, 64)
if err != nil {
return nil, fnerrors.InternalError("failed to parse serialized index")
}
end = append(end, nodes[i])
fmt.Fprintf(&debug, " #%d %q --> cats:%v after:%v\n", i, nodes[i].invocation.Description,
nodes[i].computedOrder.GetSchedCategory(),
nodes[i].computedOrder.GetSchedAfterCategory())
}
fmt.Fprintf(console.Debug(ctx), "execution sorted:\n%s", debug.Bytes())
return end, nil
}