-
Notifications
You must be signed in to change notification settings - Fork 9
/
genserver.go
350 lines (296 loc) · 8.67 KB
/
genserver.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
// 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 golang
import (
"context"
"fmt"
"path/filepath"
"strings"
"text/template"
"namespacelabs.dev/foundation/internal/fnerrors"
"namespacelabs.dev/foundation/internal/fnfs"
"namespacelabs.dev/foundation/internal/gosupport"
"namespacelabs.dev/foundation/schema"
"namespacelabs.dev/foundation/std/pkggraph"
)
const (
ServerPrepareFilename = "deps.fn.go"
ServerMainFilename = "main.fn.go"
)
func generateServer(ctx context.Context, loader pkggraph.PackageLoader, loc pkggraph.Location, srv *schema.Server, fs fnfs.ReadWriteFS) error {
var opts genTmplOptions
opts.Imports = gosupport.NewGoImports("main")
opts.Imports.Ensure("context")
if err := prepareGenerate(ctx, loader, srv.GetImportedPackages(), &opts); err != nil {
return err
}
if err := generateGoSource(ctx, fs, loc.Rel(ServerPrepareFilename), opts.Imports, serverPrepareTmpl, opts); err != nil {
return err
}
if err := generateGoSource(ctx, fs, loc.Rel(ServerMainFilename), nil, mainTmpl, mainTmplOptions{
PackageName: srv.GetPackageName(),
}); err != nil {
return err
}
return nil
}
func prepareGenerate(ctx context.Context, loader pkggraph.PackageLoader, importList []schema.PackageName, opts *genTmplOptions) error {
allDeps, err := expandInstancedDeps(ctx, loader, importList)
if err != nil {
return err
}
var imports schema.PackageList
imports.AddMultiple(importList...)
// Prepopulate variable names that are used in serverPrepareTmpl.
usedNames := map[string]bool{
"deps": true,
"di": true,
"err": true,
}
// XXX use allocation tree instead.
for _, dep := range allDeps.instances {
var n *nodeWithDeps
var scope string
if dep.Scope != nil {
scope = gosupport.MakeGoPubVar(dep.Scope.Name)
}
for _, node := range opts.Nodes {
if node.PackageName.Equals(dep.Parent.PackageName) &&
node.Scope == scope {
n = node
}
}
if n == nil {
n = &nodeWithDeps{
Name: makeName(filepath.Base(dep.Location.Rel()), usedNames, false), // XXX use package instead?
PackageName: dep.Location.PackageName,
Scope: scope,
}
importURL, err := packageFrom(dep.Location)
if err != nil {
return err
}
n.GoImportURL = importURL
if dep.Parent.GetKind() == schema.Node_SERVICE {
n.VarName = fmt.Sprintf("%sDeps", n.Name)
n.IsService = true
n.Typename = serviceDepsType
opts.Services = append(opts.Services, n)
} else if dep.Scope != nil {
n.Typename = makeProvidesDepsType(dep.Scope)
} else {
n.Typename = extensionDepsType
}
opts.Nodes = append(opts.Nodes, n)
}
n.Provisioned = append(n.Provisioned, dep.Provisioned)
}
for _, init := range allDeps.initializers {
pkg, err := packageFrom(init.Location)
if err != nil {
return err
}
i := goInitializer{
PackageName: schema.PackageName(init.Node.PackageName),
GoImportURL: pkg,
InitializeBefore: init.initializeBefore,
InitializeAfter: init.initializeAfter,
}
for _, node := range opts.Nodes {
if node.PackageName.Equals(init.Node.PackageName) {
i.Deps = &Ref{
GoImportURL: node.GoImportURL,
Typename: node.Typename,
}
break
}
}
opts.Initializers = append(opts.Initializers, i)
}
for _, svc := range allDeps.services {
if len(svc.Node.ExportService) == 0 && len(svc.Node.ExportHttp) == 0 {
continue
}
has := false
for _, existing := range opts.Services {
pkg, err := packageFrom(svc.Location)
if err != nil {
return err
}
if existing.GoImportURL == pkg { // XXX this is not quite right.
has = true
break
}
}
if !has {
var n *nodeWithDeps
for _, node := range opts.Nodes {
if node.PackageName == svc.Location.PackageName {
n = node
}
}
if n == nil {
// Ensure that services with no deps create an empty provider.
n = &nodeWithDeps{
Name: makeName(filepath.Base(svc.Location.Rel()), usedNames, false), // XXX use package instead?
VarName: makeName(filepath.Base(svc.Location.Rel()), usedNames, true),
PackageName: svc.Location.PackageName,
Typename: serviceDepsType,
IsService: true,
}
opts.Nodes = append(opts.Nodes, n)
}
importURL, err := packageFrom(svc.Location)
if err != nil {
return err
}
n.GoImportURL = importURL
opts.Services = append(opts.Services, n)
}
}
// XXX another O(n^2); and this is incorrect when there are multiple nodes
// allocating the same instance types.
for _, n := range opts.Nodes {
n.Refs = make([]Refs, len(n.Provisioned))
for k, p := range n.Provisioned {
switch len(p.Args) {
case 0:
for _, m := range opts.Nodes {
if p.GoPackage == m.GoImportURL {
ref := Ref{
Typename: m.Typename,
GoImportURL: m.GoImportURL,
Scope: m.Scope,
}
if m.Scope == "" {
n.Refs[k].Single = &ref
} else if m.Typename == makeProvidesDepsType(p.Provides) {
n.Refs[k].Scoped = &ref
}
}
}
case 1:
found := false
for _, x := range n.Provisioned {
for _, name := range x.DepVars {
if name.GoName == p.Args[0] {
found = true
x.Dependencies = append(x.Dependencies, p)
n.Provisioned[k] = nil
break
}
}
}
if !found {
return fnerrors.New("didn't find reference: %s", p.Args[0])
}
default:
return fnerrors.New("Instantiate: only support one reference right now, saw %d", len(p.Args))
}
}
}
return nil
}
func makeName(path string, m map[string]bool, withSuffix bool) string {
svcBaseName := gosupport.MakeGoPrivVar(strings.Replace(path, "/", "_", -1))
svcName := svcBaseName
if withSuffix {
svcName += "0"
}
k := 1
for {
if _, ok := m[svcName]; !ok {
m[svcName] = true
return svcName
}
svcName = fmt.Sprintf("%s%d", svcBaseName, k)
k++
}
}
type goPackage struct {
GoImportURL string
}
type goInitializer struct {
PackageName schema.PackageName
GoImportURL string
Deps *Ref
InitializeBefore []string
InitializeAfter []string
}
type Ref struct {
GoImportURL string
Scope string
Typename string
}
type Refs struct {
Single *Ref
Scoped *Ref
}
type nodeWithDeps struct {
goPackage
PackageName schema.PackageName
Name string
VarName string
Typename string
Scope string
IsService bool
Provisioned []*typeProvider
Refs []Refs // Same indexing as `Provisioned`.
}
type genTmplOptions struct {
Imports *gosupport.GoImports
Nodes []*nodeWithDeps
Services []*nodeWithDeps
Initializers []goInitializer
}
type mainTmplOptions struct {
PackageName string
}
var (
serverPrepareTmpl = template.Must(template.New(ServerPrepareFilename).Funcs(funcs).Parse(`{{with $opts := .}}
func RegisterInitializers(di *{{$opts.Imports.Ensure "namespacelabs.dev/foundation/std/go/core"}}DependencyGraph) {
{{- range $k, $init := .Initializers}}
di.AddInitializers({{$opts.Imports.Ensure $init.GoImportURL}}{{longInitializerType $init.PackageName}}...)
{{- end}}
}
func WireServices(ctx context.Context, srv {{$opts.Imports.Ensure "namespacelabs.dev/foundation/std/go/server"}}Server, depgraph {{$opts.Imports.Ensure "namespacelabs.dev/foundation/std/go/core"}}Dependencies) []error {
var errs []error
{{range $k, $v := .Services}}
if err := depgraph.Instantiate(ctx, {{$opts.Imports.Ensure $v.PackageName.String}}{{longProviderType $v.PackageName ""}}, func(ctx context.Context, v interface{}) error {
{{$opts.Imports.Ensure $v.GoImportURL}}WireService(ctx, srv.Scope({{$opts.Imports.Ensure $v.PackageName.String}}{{longPackageType $v.PackageName}}), v.({{makeType $opts.Imports $v.GoImportURL $v.Typename}}))
return nil
}); err != nil{
errs = append(errs, err)
}
{{end}}
return errs
}
{{end}}`))
mainTmpl = template.Must(template.New(ServerMainFilename).Parse(`// This file was automatically generated.
package main
import (
"context"
"flag"
"namespacelabs.dev/foundation/std/go/core"
"namespacelabs.dev/foundation/std/go/server"
)
func main() {
flag.Parse()
resources := core.PrepareEnv("{{.PackageName}}")
defer resources.Close(context.Background())
ctx := core.WithResources(context.Background(), resources)
depgraph := core.NewDependencyGraph()
RegisterInitializers(depgraph)
if err := depgraph.RunInitializers(ctx); err != nil {
core.ZLog.Fatal().Err(err).Send()
}
server.InitializationDone()
server.Listen(ctx, func(srv server.Server) {
if errs := WireServices(ctx, srv, depgraph); len(errs) > 0 {
core.ZLog.Fatal().Errs("errors", errs).Msgf("%d services failed to initialize.", len(errs))
}
})
}
`))
)