-
Notifications
You must be signed in to change notification settings - Fork 9
/
allocator.go
67 lines (53 loc) · 1.64 KB
/
allocator.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
// 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 eval
import (
"context"
"fmt"
"sync"
"namespacelabs.dev/foundation/internal/fnerrors"
"namespacelabs.dev/foundation/schema"
"namespacelabs.dev/foundation/std/pkggraph"
)
type AllocState struct {
mu sync.Mutex
instances map[string]pkggraph.ValueWithPath
}
type AllocatorFunc func(context.Context, *schema.Node, *schema.Need) (interface{}, error)
func NewAllocState() *AllocState {
return &AllocState{
instances: map[string]pkggraph.ValueWithPath{},
}
}
func (r *AllocState) Alloc(ctx context.Context, server *schema.Server, allocator []AllocatorFunc, n *schema.Node, k int) (pkggraph.ValueWithPath, error) {
// Allow for concurrent computations of the same key.
key := fmt.Sprintf("%s:%s/%d", server.PackageName, n.PackageName, k)
r.mu.Lock()
res, ok := r.instances[key]
r.mu.Unlock()
if ok {
return res, nil
}
if k >= len(n.GetNeed()) {
return pkggraph.ValueWithPath{}, fnerrors.New("k is too large")
}
v, err := r.allocValue(ctx, allocator, n, n.GetNeed()[k])
if err != nil {
return pkggraph.ValueWithPath{}, err
}
vwp := pkggraph.ValueWithPath{Need: n.GetNeed()[k], Value: v}
r.mu.Lock()
r.instances[key] = vwp
r.mu.Unlock()
return vwp, nil
}
func (r *AllocState) allocValue(ctx context.Context, allocator []AllocatorFunc, n *schema.Node, need *schema.Need) (interface{}, error) {
for _, alloc := range allocator {
v, err := alloc(ctx, n, need)
if err != nil || v != nil {
return v, err
}
}
return nil, nil
}