-
Notifications
You must be signed in to change notification settings - Fork 123
/
compile.go
103 lines (86 loc) · 2.56 KB
/
compile.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
// Copyright 2021-2023 Zenauth Ltd.
// SPDX-License-Identifier: Apache-2.0
package compile
import (
"context"
"errors"
"fmt"
"io/fs"
runtimev1 "github.com/cerbos/cerbos/api/genpb/cerbos/runtime/v1"
internalcompile "github.com/cerbos/cerbos/internal/compile"
"github.com/cerbos/cerbos/internal/observability/logging"
"github.com/cerbos/cerbos/internal/schema"
"github.com/cerbos/cerbos/internal/storage/disk"
"github.com/cerbos/cerbos/internal/storage/index"
"go.uber.org/zap"
)
type Index = index.Index
type Artefact struct {
Error error
PolicySet *runtimev1.RunnablePolicySet
SourceFile string
}
type Errors struct {
*runtimev1.Errors
}
func (e *Errors) Error() string {
switch e.Kind.(type) {
case *runtimev1.Errors_IndexBuildErrors:
return "index build failed"
case *runtimev1.Errors_CompileErrors:
return "compilation failed"
default:
return fmt.Sprintf("unhandled error kind %T", e.Kind)
}
}
func Files(ctx context.Context, fsys fs.FS) (Index, <-chan Artefact, error) {
idx, err := index.Build(ctx, fsys)
if err != nil {
idxErrs := new(index.BuildError)
if errors.As(err, &idxErrs) {
return nil, nil, &Errors{
Errors: &runtimev1.Errors{
Kind: &runtimev1.Errors_IndexBuildErrors{IndexBuildErrors: idxErrs.IndexBuildErrors},
},
}
}
return nil, nil, fmt.Errorf("failed to build index: %w", err)
}
outChan := make(chan Artefact, 1)
go func() {
defer close(outChan)
store := disk.NewFromIndexWithConf(idx, &disk.Conf{})
schemaMgr := schema.NewFromConf(ctx, store, schema.NewConf(schema.EnforcementReject))
logger := logging.FromContext(ctx).Named("compile")
inChan := idx.GetAllCompilationUnits(ctx)
for unit := range inChan {
srcFile := unit.MainSourceFile()
log := logger.With(zap.String("source", srcFile))
log.Debug("Compiling unit")
artefact := Artefact{SourceFile: srcFile}
artefact.PolicySet, artefact.Error = internalcompile.Compile(unit, schemaMgr)
if artefact.Error != nil {
log.Error("Compilation failed", zap.Error(artefact.Error))
compErrs := new(internalcompile.ErrorList)
if errors.As(artefact.Error, &compErrs) {
artefact.Error = &Errors{
Errors: &runtimev1.Errors{
Kind: &runtimev1.Errors_CompileErrors{CompileErrors: compErrs.CompileErrors},
},
}
}
} else {
log.Debug("Compilation succeeded")
}
log.Debug("Sending artefact")
select {
case outChan <- artefact:
log.Debug("Artefact sent")
case <-ctx.Done():
log.Debug("Artefact send cancelled", zap.Error(ctx.Err()))
return
}
}
}()
return idx, outChan, nil
}