/
entrypoint.go
72 lines (57 loc) · 1.99 KB
/
entrypoint.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
// 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 servercore
import (
"context"
"time"
"github.com/prometheus/client_golang/prometheus"
"namespacelabs.dev/foundation/std/go/core"
)
var (
serverInitializedInfo = prometheus.NewGaugeVec(prometheus.GaugeOpts{
Namespace: "ns",
Subsystem: "gogrpc",
Name: "server_initialized_info",
}, []string{"package_name", "revision"})
serverInitializedTimestamp = prometheus.NewGaugeVec(prometheus.GaugeOpts{
Namespace: "ns",
Subsystem: "gogrpc",
Name: "server_initialized_timestamp_seconds",
}, []string{"package_name", "revision"})
)
func init() {
prometheus.MustRegister(
serverInitializedInfo,
serverInitializedTimestamp,
)
}
type RunOpts struct {
PackageName string
RegisterInitializers func(*core.DependencyGraph)
WireServices func(context.Context, Server, core.Dependencies) []error
}
func Run(ctx context.Context, opts RunOpts, listenOpts ListenOpts) {
ctx = core.ZLog.WithContext(ctx)
resources, rev := core.PrepareEnv(opts.PackageName)
defer resources.Close(ctx)
ctx = core.WithResources(ctx, resources)
depgraph := core.NewDependencyGraph()
opts.RegisterInitializers(depgraph)
if err := depgraph.RunInitializers(ctx); err != nil {
core.ZLog.Fatal().Err(err).Send()
}
core.InitializationDone()
serverInitializedInfo.WithLabelValues(opts.PackageName, rev).Inc()
serverInitializedTimestamp.WithLabelValues(opts.PackageName, rev).Set(float64(time.Now().Unix()))
if err := Listen(ctx, listenOpts, func(srv Server) {
if errs := opts.WireServices(ctx, srv, depgraph); len(errs) > 0 {
core.ZLog.Fatal().Errs("errors", errs).Msgf("%d services failed to initialize.", len(errs))
}
if err := depgraph.RunPostInitializers(ctx); err != nil {
core.ZLog.Fatal().Err(err).Send()
}
}); err != nil {
core.ZLog.Fatal().Err(err).Msgf("failed to listen.")
}
}