-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcontext.go
More file actions
547 lines (440 loc) · 15.3 KB
/
Copy pathcontext.go
File metadata and controls
547 lines (440 loc) · 15.3 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
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
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
// Copyright 2026 Codnect
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package procyon
import (
"context"
"errors"
"fmt"
"reflect"
"sync"
"time"
"codnect.io/procyon/component"
"codnect.io/procyon/io"
"codnect.io/procyon/runtime"
)
const (
// envContainerKey is the key used to register the runtime environment in the component container.
envContainerKey = "environment"
// lifecycleManagerContainerKey is the key used to register the lifecycle manager in the component container.
lifecycleManagerContainerKey = "procyonLifecycleManager"
)
var (
// bootstrapTypes is a list of types that are considered bootstrap components. These components are used during the
// bootstrapping phase of the application and are not loaded into the main application context. This allows for
// separation of concerns and ensures that certain components are only available during the bootstrapping process.
bootstrapTypes = []reflect.Type{
reflect.TypeFor[runtime.EnvironmentCustomizer](),
reflect.TypeFor[runtime.ContextInitializer](),
}
)
// contextError is a custom error type that wraps errors occurring during context operations (start, stop, refresh).
// It includes the operation being performed and the underlying error, providing more context for debugging and error
// handling.
type contextError struct {
Op string
Err error
}
// Error method returns a string representation of the context error, including the operation and the underlying
// error message.
func (e *contextError) Error() string {
return e.Op + " context: " + e.Err.Error()
}
// Unwrap method allows unwrapping the underlying error, enabling error chaining and compatibility with errors.Is and
// errors.As.
func (e *contextError) Unwrap() error {
return e.Err
}
// Context struct represents the application context of Procyon.
type Context struct {
done chan struct{}
err error
mu sync.RWMutex
refreshed bool
resourceResolver io.ResourceResolver
env runtime.Environment
containerProvider func() component.Container
components []*component.Component
container component.Container
lifecycleManager runtime.LifecycleManager
}
// createContext creates a new application context with the given environment.
// The returned context is not started yet. You need to call Start method to start the context.
func createContext(env runtime.Environment, startupContainer component.Container, resolver io.ResourceResolver) *Context {
if env == nil {
panic("nil environment")
}
if startupContainer == nil {
panic("nil startup container")
}
if resolver == nil {
panic("nil resource resolver")
}
return &Context{
done: make(chan struct{}),
mu: sync.RWMutex{},
resourceResolver: resolver,
env: env,
containerProvider: func() component.Container {
container := component.NewStandardContainer()
container.SetParentContainer(startupContainer)
return container
},
components: component.List(),
}
}
// Deadline method returns the time when work done on behalf of this context should be canceled.
func (c *Context) Deadline() (deadline time.Time, ok bool) {
return time.Time{}, false
}
// Done method returns a channel that's closed when work done on behalf of this context should be canceled.
func (c *Context) Done() <-chan struct{} {
return c.done
}
// Err returns the error that caused the context to terminate. It returns nil if the context is still active.
func (c *Context) Err() error {
c.mu.RLock()
defer c.mu.RUnlock()
return c.err
}
// Value returns the value associated with the given key. Context values are currently not supported and
// this method always returns nil.
func (c *Context) Value(key any) any {
return nil
}
// Start starts the application context. It loads component definitions, registers the context itself
// as a singleton, and initializes singleton components. After this method is called, the context is
// considered running.
func (c *Context) Start(ctx context.Context) error {
c.mu.Lock()
defer c.mu.Unlock()
if err := c.doStart(ctx); err != nil {
return &contextError{Op: "start", Err: err}
}
return nil
}
// doStart starts the lifecycle manager if the context has been refreshed and is not already running.
func (c *Context) doStart(ctx context.Context) error {
if c.err != nil {
return c.err
}
if !c.refreshed {
return errors.New("context not refreshed")
}
if c.lifecycleManager.IsRunning() {
return nil
}
if err := c.startLifecycleManager(ctx); err != nil {
return err
}
return nil
}
// Stop stops the application context by shutting down lifecycle components. If the context is not running,
// it returns nil.
func (c *Context) Stop(ctx context.Context) error {
c.mu.Lock()
defer c.mu.Unlock()
if err := c.doStop(ctx); err != nil {
return &contextError{Op: "stop", Err: err}
}
return nil
}
// doStop stops the lifecycle manager if the context is currently running.
func (c *Context) doStop(ctx context.Context) error {
if c.err != nil {
return c.err
}
if !c.refreshed {
return errors.New("context not refreshed")
}
if !c.lifecycleManager.IsRunning() {
return nil
}
if err := c.stopLifecycleManager(ctx); err != nil {
return err
}
return nil
}
// IsRunning returns true if the application context is currently running, false otherwise.
func (c *Context) IsRunning() bool {
c.mu.RLock()
defer c.mu.RUnlock()
return c.lifecycleManager != nil && c.lifecycleManager.IsRunning()
}
// Refresh initializes the application context by preparing the container, loading component definitions,
// initializing singleton components, and starting lifecycle management.
func (c *Context) Refresh(ctx context.Context) error {
c.mu.Lock()
defer c.mu.Unlock()
if err := c.doRefresh(ctx); err != nil {
return &contextError{Op: "refresh", Err: err}
}
return nil
}
// doRefresh initializes the application context. It prepares the container, loads component definitions, initializes
// singleton components, resolves the lifecycle manager, and starts it.
func (c *Context) doRefresh(ctx context.Context) (err error) {
if c.err != nil {
return c.err
}
if c.refreshed {
return errors.New("context already refreshed")
}
c.refreshed = true
defer func() {
if r := recover(); r != nil {
switch v := r.(type) {
case error:
err = v
default:
err = fmt.Errorf("%v", v)
}
}
if err != nil {
log.Warn("Cancelling application context refresh attempt due to error: {}", err)
err = errors.Join(err, c.cancelRefresh(ctx))
}
}()
c.container = c.containerProvider()
if err = c.prepareContainer(ctx); err != nil {
return err
}
if err = c.invokeContainerCustomizers(ctx); err != nil {
return err
}
if err = c.registerInitProcessors(ctx); err != nil {
return err
}
if err = c.initializeSingletons(ctx); err != nil {
return err
}
if err = c.resolveLifecycleManager(ctx); err != nil {
return err
}
if err = c.container.RegisterSingleton(lifecycleManagerContainerKey, c.lifecycleManager); err != nil {
return err
}
return c.startLifecycleManager(ctx)
}
// prepareContainer registers core infrastructure dependencies and singletons that must be available before
// component definitions are loaded.
func (c *Context) prepareContainer(ctx context.Context) error {
if err := c.container.RegisterDependency(reflect.TypeFor[component.Container](), c.container); err != nil {
return err
}
if err := c.container.RegisterDependency(reflect.TypeFor[runtime.Context](), c); err != nil {
return err
}
if err := c.container.RegisterDependency(reflect.TypeFor[io.ResourceResolver](), c.resourceResolver); err != nil {
return err
}
if err := c.container.RegisterSingleton(envContainerKey, c.env); err != nil {
return err
}
if err := c.loadComponentDefinitions(ctx); err != nil {
return err
}
return nil
}
// invokeContainerCustomizers resolves and invokes all registered ContainerCustomizer components before
// singleton initialization.
func (c *Context) invokeContainerCustomizers(ctx context.Context) error {
customizerType := reflect.TypeFor[component.ContainerCustomizer]()
for _, definition := range c.container.DefinitionsOf(customizerType) {
name := definition.Name()
instance, err := c.container.Resolve(ctx, name)
if err != nil {
return fmt.Errorf("resolve container customizer %q: %w", name, err)
}
customizer := instance.(component.ContainerCustomizer)
if err = customizer.CustomizeContainer(c.container); err != nil {
return fmt.Errorf("customize container %q: %w", name, err)
}
}
return nil
}
// registerInitProcessors resolves and registers all BeforeInitProcessor and AfterInitProcessor components
// with the container before singleton initialization.
func (c *Context) registerInitProcessors(ctx context.Context) error {
if err := c.registerBeforeInitProcessors(ctx); err != nil {
return err
}
if err := c.registerAfterInitProcessors(ctx); err != nil {
return err
}
return nil
}
// registerBeforeInitProcessors resolves and registers all BeforeInitProcessor components with the container.
func (c *Context) registerBeforeInitProcessors(ctx context.Context) error {
processorType := reflect.TypeFor[component.BeforeInitProcessor]()
for _, definition := range c.container.DefinitionsOf(processorType) {
name := definition.Name()
instance, err := c.container.Resolve(ctx, name)
if err != nil {
return fmt.Errorf("resolve before init processor %q: %w", name, err)
}
processor := instance.(component.BeforeInitProcessor)
if err = c.container.UseBeforeInitProcessor(processor); err != nil {
return fmt.Errorf("register before init processor %q: %w", name, err)
}
}
return nil
}
// registerAfterInitProcessors resolves and registers all AfterInitProcessor components with the container.
func (c *Context) registerAfterInitProcessors(ctx context.Context) error {
processorType := reflect.TypeFor[component.AfterInitProcessor]()
for _, definition := range c.container.DefinitionsOf(processorType) {
name := definition.Name()
instance, err := c.container.Resolve(ctx, name)
if err != nil {
return fmt.Errorf("resolve after init processor %q: %w", name, err)
}
processor := instance.(component.AfterInitProcessor)
if err = c.container.UseAfterInitProcessor(processor); err != nil {
return fmt.Errorf("register after init processor %q: %w", name, err)
}
}
return nil
}
// resolveLifecycleManager resolves a LifecycleManager from the container.
// If none is registered, a default implementation is created and used.
func (c *Context) resolveLifecycleManager(ctx context.Context) error {
manager, err := component.ResolveType[runtime.LifecycleManager](ctx, c.container)
if err != nil && !errors.Is(err, component.ErrNotFound) {
return err
}
if manager != nil {
c.lifecycleManager = manager
} else if c.lifecycleManager == nil {
c.lifecycleManager = newDefaultLifecycleManager(c.container)
}
return nil
}
// Close stops the application context, destroys all singleton components, releases resources, and marks
// the context as canceled.
func (c *Context) Close(ctx context.Context) error {
c.mu.Lock()
defer c.mu.Unlock()
if err := c.doClose(ctx); err != nil {
return &contextError{Op: "close", Err: err}
}
return nil
}
// doClose stops lifecycle management, destroys singleton components, and marks the context as canceled.
func (c *Context) doClose(ctx context.Context) error {
if c.err != nil {
return c.err
}
err := c.stopLifecycleManager(ctx)
if c.container != nil {
c.container.DestroySingletons()
c.container = nil
}
c.lifecycleManager = nil
c.err = context.Canceled
close(c.done)
return err
}
// Environment returns the runtime environment associated with this context.
func (c *Context) Environment() runtime.Environment {
c.mu.RLock()
defer c.mu.RUnlock()
return c.env
}
// Container returns the component container associated with this context.
// It panics if the context has not been refreshed yet.
func (c *Context) Container() component.Container {
c.mu.RLock()
defer c.mu.RUnlock()
if c.container == nil {
panic("nil container: context not refreshed")
}
return c.container
}
// ResourceResolver returns the resource resolver used by the application to load resources.
func (c *Context) ResourceResolver() io.ResourceResolver {
return c.resourceResolver
}
// startLifecycleManager starts the lifecycle manager if it exists and is not already running.
func (c *Context) startLifecycleManager(ctx context.Context) error {
if c.lifecycleManager != nil && !c.lifecycleManager.IsRunning() {
if err := c.lifecycleManager.Startup(ctx); err != nil {
return fmt.Errorf("start lifecycle manager: %w", err)
}
}
return nil
}
// stopLifecycleManager stops the lifecycle manager if it exists and is currently running.
func (c *Context) stopLifecycleManager(ctx context.Context) error {
if c.lifecycleManager != nil && c.lifecycleManager.IsRunning() {
if err := c.lifecycleManager.Shutdown(ctx); err != nil {
return fmt.Errorf("stop lifecycle manager: %w", err)
}
}
return nil
}
// loadComponentDefinitions loads component definitions into the container using a ConditionalLoader.
// It retrieves the list of component definitions and loads them into the container, allowing for conditional
// loading based on the context.
func (c *Context) loadComponentDefinitions(ctx context.Context) error {
filtered := make([]*component.Component, 0)
for _, comp := range c.components {
if isBootstrapType(comp.Definition().Type()) {
continue
}
filtered = append(filtered, comp)
}
loader := component.NewConditionalLoader(c.container, filtered)
err := loader.Load(ctx)
if err != nil {
return fmt.Errorf("load component definitions: %w", err)
}
return nil
}
// isBootstrapType reports whether the given type is considered a bootstrap component type.
func isBootstrapType(typ reflect.Type) bool {
for _, bType := range bootstrapTypes {
if typ.ConvertibleTo(bType) {
return true
}
}
return false
}
// initializeSingletons initializes all singleton components defined in the container. It iterates through
// the component definitions, checks for singleton definitions, and resolves them to ensure they are initialized
// and ready for use.
func (c *Context) initializeSingletons(ctx context.Context) error {
for _, definition := range c.container.Definitions() {
if !definition.IsSingleton() {
continue
}
_, err := c.container.Resolve(ctx, definition.Name())
if err != nil {
return fmt.Errorf("initialize singleton %q: %w", definition.Name(), err)
}
}
return nil
}
// cancelRefresh rolls back a failed refresh attempt by stopping lifecycle management, destroying initialized
// singletons, and clearing context state.
func (c *Context) cancelRefresh(ctx context.Context) error {
if err := c.stopLifecycleManager(ctx); err != nil {
return fmt.Errorf("cancel context refresh: %w", err)
}
if c.container != nil {
c.container.DestroySingletons()
c.container = nil
}
c.lifecycleManager = nil
return nil
}