-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathruntime.go
More file actions
236 lines (200 loc) · 6.55 KB
/
runtime.go
File metadata and controls
236 lines (200 loc) · 6.55 KB
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
package runtime
import (
"context"
"errors"
"fmt"
"os"
"time"
"github.com/go-kratos/kratos/v2"
kregistry "github.com/go-kratos/kratos/v2/registry"
"github.com/go-kratos/kratos/v2/transport"
"github.com/goexts/generic/configure"
appv1 "github.com/origadmin/runtime/api/gen/go/config/app/v1"
runtimeconfig "github.com/origadmin/runtime/config"
"github.com/origadmin/runtime/contracts"
"github.com/origadmin/runtime/contracts/component"
"github.com/origadmin/runtime/engine"
"github.com/origadmin/runtime/engine/bootstrap"
enginecontext "github.com/origadmin/runtime/engine/context"
"github.com/origadmin/runtime/helpers/comp"
"github.com/origadmin/runtime/log"
"github.com/origadmin/runtime/registry"
)
// App defines the application's runtime environment powered by engine.
type App struct {
appInfo *appv1.App
result bootstrap.Result
engine component.Container
ctx context.Context
cancel context.CancelFunc
}
// New creates a new App instance.
func New(name, version string, opts ...Option) *App {
return NewWithAppInfo(NewAppInfo(name, version), opts...)
}
// NewWithAppInfo creates a new App instance using a pre-configured App info.
func NewWithAppInfo(info *appv1.App, opts ...Option) *App {
ctx, cancel := context.WithCancel(context.Background())
if info == nil {
info = NewAppInfoBuilder()
}
// Create engine registry at startup with standard resolvers and global registrations
reg := engine.NewContainer(
engine.WithCategoryResolvers(DefaultResolvers),
engine.WithGlobalRegistrations(),
)
app := &App{
appInfo: info,
engine: reg,
ctx: ctx,
cancel: cancel,
}
// Apply options
app = configure.Apply(app, opts)
// Apply framework DEFAULTS last
app.registerDefaultFactories()
return app
}
// WithContainer sets a callback to configure the internal engine container.
func WithContainer(fn func(component.Container)) Option {
return func(a *App) {
fn(a.engine)
}
}
// Register adds a component registration to the engine.
func Register(cat Category, p Provider, opts ...RegisterOption) {
engine.Register(cat, p, opts...)
}
func (r *App) registerDefaultFactories() {
// Logger Default
r.engine.Register(CategoryLogger,
log.DefaultProvider,
engine.WithPriority(component.PriorityFramework))
// Registry components are self-registered by the registry package init()
}
// Load loads configuration into Result.
func (r *App) Load(path string, bootOpts ...bootstrap.Option) error {
res, err := bootstrap.New(path, bootOpts...)
if err != nil {
return fmt.Errorf("bootstrap failed: %w", err)
}
r.result = res
// 1. Foundation: Bootstrap Metadata (Base layer)
if boot := res.Bootstrap(); boot != nil && boot.GetApp() != nil {
UpdateAppInfo(r.appInfo, boot.GetApp())
}
// 2. Override: Business Object (High priority)
if biz := res.Config(); biz != nil {
if p, ok := biz.(contracts.AppConfig); ok && p.GetApp() != nil {
UpdateAppInfo(r.appInfo, p.GetApp())
} else {
// 3. Fallback: Scan from Decoder (if not strong-typed)
if loader := res.Decoder(); loader != nil {
var meta struct {
App *appv1.App `json:"app" yaml:"app"`
}
if err := loader.Scan(&meta); err == nil && meta.App != nil {
UpdateAppInfo(r.appInfo, meta.App)
}
}
}
}
if r.appInfo.GetName() == "" || r.appInfo.GetVersion() == "" {
return errors.New("runtime: application metadata missing after load")
}
// Auto warm-up the engine if business configuration is available
if r.Config() != nil {
if err := r.WarmUp(); err != nil {
return fmt.Errorf("warm-up failed during load: %w", err)
}
}
return nil
}
// WarmUp activates the engine with the loaded configuration.
func (r *App) WarmUp() error {
if r.result == nil || r.result.Config() == nil {
return errors.New("runtime: cannot warm-up without loaded configuration")
}
return r.engine.Load(r.ctx, r.result.Config())
}
// Getters
func (r *App) Decoder() runtimeconfig.KConfig { return r.result.Decoder() }
func (r *App) Config() any { return r.result.Config() }
func (r *App) Logger() log.Logger {
l, err := comp.GetDefault[log.Logger](r.ctx, r.engine.In(CategoryLogger))
if err != nil {
return log.DefaultLogger
}
return l
}
func (r *App) Result() bootstrap.Result { return r.result }
func (r *App) Container() component.Container { return r.engine }
func (r *App) In(cat Category, opts ...InOption) component.Registry {
return r.engine.In(cat, opts...)
}
// Context returns the app context.
func (r *App) Context() context.Context { return r.ctx }
// NewContext creates a new context from the app context.
func NewContext(ctx context.Context) context.Context {
return enginecontext.NewContext(ctx)
}
// NewTrace creates a new context with the given trace ID.
func NewTrace(ctx context.Context, traceID string) context.Context {
return enginecontext.NewTrace(ctx, traceID)
}
func (r *App) Stop() {
if r.cancel != nil {
r.cancel()
}
}
func (r *App) NewApp(servers []transport.Server, options ...kratos.Option) *kratos.App {
info := r.appInfo
md := info.GetMetadata()
if md == nil {
md = make(map[string]string)
}
if info.GetEnv() != "" {
md["env"] = info.GetEnv()
}
opts := []kratos.Option{
kratos.Context(r.ctx),
kratos.Logger(r.Logger()),
kratos.Server(servers...),
kratos.ID(info.GetId()),
kratos.Name(info.GetName()),
kratos.Version(info.GetVersion()),
kratos.Metadata(md),
}
if registrar, _ := r.DefaultRegistrar(); registrar != nil {
opts = append(opts, kratos.Registrar(registrar))
}
opts = append(opts, options...)
return kratos.New(opts...)
}
func (r *App) DefaultRegistrar() (kregistry.Registrar, error) {
// Directly obtain from CategoryRegistrar with standard Kratos interface
return comp.GetDefault[kregistry.Registrar](r.ctx, r.engine.In(CategoryRegistrar))
}
func (r *App) Discoveries() (map[string]registry.KDiscovery, error) {
return registry.GetDiscoveries(r.ctx, r.engine.In(CategoryDiscovery))
}
func (r *App) AppInfo() *appv1.App { return r.appInfo }
func (r *App) ShowAppInfo() {
ai := r.appInfo
if ai == nil {
return
}
ts := time.Now().Format(time.RFC3339)
host, _ := os.Hostname()
pid := os.Getpid()
fmt.Printf("[%s] %s (pid:%d@%s)\n Version: %s\n AppId: %s\n InstanceId: %s\n", ts, ai.Name, pid, host, ai.Version, ai.Id, ai.InstanceId)
}
// --- Wire Providers ---
// ProvideLogger is a Wire provider function that extracts the logger from the App.
func ProvideLogger(rt *App) log.Logger {
return rt.Logger()
}
// ProvideDefaultRegistrar is a Wire provider function that extracts the registrar from the App.
func ProvideDefaultRegistrar(rt *App) (kregistry.Registrar, error) {
return rt.DefaultRegistrar()
}