-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcontainer_impl.go
More file actions
676 lines (549 loc) · 15.4 KB
/
container_impl.go
File metadata and controls
676 lines (549 loc) · 15.4 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
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
package vessel
import (
"context"
"fmt"
"sync"
"github.com/xraph/go-utils/di"
)
// containerImpl implements Container.
type containerImpl struct {
services map[string]*serviceRegistration
instances map[string]any
graph *DependencyGraph
middleware *middlewareChain
typeRegistry *typeRegistry // Type-based registry for dig-like constructor injection
started bool
mu sync.RWMutex
}
// serviceRegistration holds service registration details.
type serviceRegistration struct {
name string
factory Factory
singleton bool
scoped bool
dependencies []string // Backward compat: just names
deps []di.Dep // New: full dependency specs with modes
groups []string
metadata map[string]string
instance any
started bool
mu sync.RWMutex
}
// newContainerImpl creates a new DI container implementation.
func newContainerImpl() Vessel {
return &containerImpl{
services: make(map[string]*serviceRegistration),
instances: make(map[string]any),
graph: NewDependencyGraph(),
middleware: newMiddlewareChain(),
typeRegistry: newTypeRegistry(),
}
}
// Register adds a service factory to the container.
func (c *containerImpl) Register(name string, factory Factory, opts ...RegisterOption) error {
// Merge options
merged := mergeOptions(opts)
if name == "" {
return fmt.Errorf("service name cannot be empty")
}
if factory == nil {
return ErrInvalidFactory
}
c.mu.Lock()
defer c.mu.Unlock()
if _, exists := c.services[name]; exists {
return ErrServiceAlreadyExists(name)
}
// Get all dependency specs (merges string-based and Dep-based)
allDeps := merged.GetAllDeps()
allDepNames := merged.GetAllDepNames()
// Create registration from merged options
reg := &serviceRegistration{
name: name,
factory: factory,
singleton: merged.Lifecycle == "singleton",
scoped: merged.Lifecycle == "scoped",
dependencies: allDepNames,
deps: allDeps,
groups: merged.Groups,
metadata: merged.Metadata,
}
// Add to services map
c.services[name] = reg
// Add to dependency graph with full Dep specs
if len(allDeps) > 0 {
c.graph.AddNodeWithDeps(name, allDeps)
} else {
c.graph.AddNode(name, nil)
}
return nil
}
// Resolve returns a service by name.
// For singleton services that implement di.Starter, the service is automatically
// started when first resolved.
func (c *containerImpl) Resolve(name string) (any, error) {
ctx := context.Background()
// Call middleware before resolve
if err := c.middleware.beforeResolve(ctx, name); err != nil {
return nil, err
}
// Perform actual resolution
service, err := c.resolveInternal(name)
// Call middleware after resolve
if mwErr := c.middleware.afterResolve(ctx, name, service, err); mwErr != nil {
return nil, mwErr
}
return service, err
}
// resolveInternal performs the actual service resolution without middleware.
func (c *containerImpl) resolveInternal(name string) (any, error) {
c.mu.RLock()
reg, exists := c.services[name]
c.mu.RUnlock()
if !exists {
return nil, ErrServiceNotFound(name)
}
// Singleton: return cached instance
if reg.singleton {
// Fast path: check if already created AND started (read lock)
reg.mu.RLock()
if reg.instance != nil && reg.started {
instance := reg.instance
reg.mu.RUnlock()
return instance, nil
}
// Check if instance exists but not started
existingInstance := reg.instance
reg.mu.RUnlock()
// Slow path: create and/or start instance (write lock)
reg.mu.Lock()
defer reg.mu.Unlock()
// Double-check after acquiring write lock
if reg.instance != nil && reg.started {
return reg.instance, nil
}
// Create instance if needed
if reg.instance == nil {
instance, err := reg.factory(c)
if err != nil {
return nil, NewServiceError(name, "resolve", err)
}
reg.instance = instance
existingInstance = instance
}
// Auto-start if service implements di.Starter and not yet started
if !reg.started {
if starter, ok := existingInstance.(di.Starter); ok {
ctx := context.Background()
// Call middleware before start
if err := c.middleware.beforeStart(ctx, name); err != nil {
return nil, err
}
startErr := starter.Start(ctx)
// Call middleware after start
if mwErr := c.middleware.afterStart(ctx, name, startErr); mwErr != nil {
return nil, mwErr
}
if startErr != nil {
return nil, NewServiceError(name, "auto_start", startErr)
}
}
reg.started = true
}
return reg.instance, nil
}
// Scoped services should be resolved from scope, not container
if reg.scoped {
return nil, fmt.Errorf("scoped service %s must be resolved from a scope", name)
}
// Transient: create new instance each time
instance, err := reg.factory(c)
if err != nil {
return nil, NewServiceError(name, "resolve", err)
}
// Auto-start transient services that implement di.Starter
if starter, ok := instance.(di.Starter); ok {
ctx := context.Background()
// Call middleware before start
if err := c.middleware.beforeStart(ctx, name); err != nil {
return nil, err
}
startErr := starter.Start(ctx)
// Call middleware after start
if mwErr := c.middleware.afterStart(ctx, name, startErr); mwErr != nil {
return nil, mwErr
}
if startErr != nil {
return nil, NewServiceError(name, "auto_start", startErr)
}
}
return instance, nil
}
// Use adds middleware to the container.
// Middleware is called in the order they are added.
func (c *containerImpl) Use(middleware Middleware) {
c.mu.Lock()
defer c.mu.Unlock()
c.middleware.add(middleware)
}
// Has checks if a service is registered.
func (c *containerImpl) Has(name string) bool {
c.mu.RLock()
defer c.mu.RUnlock()
_, exists := c.services[name]
return exists
}
// IsStarted checks if a service has been started.
// Returns false if service doesn't exist or hasn't been started.
func (c *containerImpl) IsStarted(name string) bool {
c.mu.RLock()
reg, exists := c.services[name]
c.mu.RUnlock()
if !exists {
return false
}
reg.mu.RLock()
defer reg.mu.RUnlock()
return reg.started
}
// ResolveReady resolves a service, ensuring it and its dependencies are started first.
// This is useful during extension Register() phase when you need a dependency
// to be fully initialized before use.
func (c *containerImpl) ResolveReady(ctx context.Context, name string) (any, error) {
c.mu.RLock()
reg, exists := c.services[name]
c.mu.RUnlock()
if !exists {
return nil, ErrServiceNotFound(name)
}
// Check if already started
reg.mu.RLock()
started := reg.started
reg.mu.RUnlock()
// If not started, start the service (and its dependencies via startService)
if !started {
if err := c.startService(ctx, name); err != nil {
return nil, NewServiceError(name, "start", err)
}
}
// Now resolve the service
return c.Resolve(name)
}
// Services returns all registered service names.
// Named-registry services are always included (developer explicitly named them).
// Type-registry services are only included if they implement di.HealthChecker,
// which is the minimum contract for a type-registered component to be
// considered a "service" for dashboard and inspection purposes.
func (c *containerImpl) Services() []string {
c.mu.RLock()
defer c.mu.RUnlock()
nameSet := make(map[string]bool)
// Named registry: always include (developer explicitly registered by name)
for name := range c.services {
nameSet[name] = true
}
// Type registry: only health-capable registrations
if c.typeRegistry != nil {
for _, name := range c.typeRegistry.healthCapableNames() {
nameSet[name] = true
}
}
names := make([]string, 0, len(nameSet))
for name := range nameSet {
names = append(names, name)
}
return names
}
// BeginScope creates a new scope for request-scoped services.
func (c *containerImpl) BeginScope() Scope {
return newScope(c)
}
// Start initializes all services in dependency order.
// This method is idempotent - it will skip already-started services and
// won't error if the container is already marked as started.
func (c *containerImpl) Start(ctx context.Context) error {
c.mu.Lock()
// Idempotent: if already started, just return success
if c.started {
c.mu.Unlock()
return nil
}
// Get services in dependency order
order, err := c.graph.TopologicalSort()
if err != nil {
c.mu.Unlock()
return err
}
c.mu.Unlock()
// Start named-registry services in dependency order
for _, name := range order {
if err := c.startService(ctx, name); err != nil {
// Rollback: stop already started services
c.stopServices(ctx, order)
return NewServiceError(name, "start", err)
}
}
// Start type-registry services that implement di.Starter
if c.typeRegistry != nil {
c.typeRegistry.mu.RLock()
for _, reg := range c.typeRegistry.services {
reg.mu.RLock()
instance := reg.instance
started := reg.started
reg.mu.RUnlock()
if instance != nil && !started {
if starter, ok := instance.(di.Starter); ok {
if err := starter.Start(ctx); err != nil {
c.typeRegistry.mu.RUnlock()
return NewServiceError(reg.key.String(), "start", err)
}
reg.mu.Lock()
reg.started = true
reg.mu.Unlock()
}
}
}
c.typeRegistry.mu.RUnlock()
}
c.mu.Lock()
c.started = true
c.mu.Unlock()
return nil
}
// Stop shuts down all services in reverse order.
func (c *containerImpl) Stop(ctx context.Context) error {
c.mu.Lock()
if !c.started {
c.mu.Unlock()
return nil // Not an error, just no-op
}
// Get services in dependency order, then reverse
order, err := c.graph.TopologicalSort()
if err != nil {
c.mu.Unlock()
return err
}
c.mu.Unlock()
// Stop type-registry services first (they were started last)
if c.typeRegistry != nil {
c.typeRegistry.mu.RLock()
for _, reg := range c.typeRegistry.services {
reg.mu.RLock()
instance := reg.instance
started := reg.started
reg.mu.RUnlock()
if instance != nil && started {
if stopper, ok := instance.(di.Stopper); ok {
if err := stopper.Stop(ctx); err != nil {
c.typeRegistry.mu.RUnlock()
return NewServiceError(reg.key.String(), "stop", err)
}
reg.mu.Lock()
reg.started = false
reg.mu.Unlock()
}
}
}
c.typeRegistry.mu.RUnlock()
}
// Stop named-registry services in reverse dependency order
for i := len(order) - 1; i >= 0; i-- {
name := order[i]
if err := c.stopService(ctx, name); err != nil {
return NewServiceError(name, "stop", err)
}
}
c.mu.Lock()
c.started = false
c.mu.Unlock()
return nil
}
// Health checks all services that implement di.HealthChecker.
func (c *containerImpl) Health(ctx context.Context) error {
c.mu.RLock()
// Check named-registry services
for name, reg := range c.services {
// Only check singleton services that have been instantiated
if !reg.singleton || reg.instance == nil {
continue
}
if checker, ok := reg.instance.(di.HealthChecker); ok {
if err := checker.Health(ctx); err != nil {
c.mu.RUnlock()
return NewServiceError(name, "health", err)
}
}
}
c.mu.RUnlock()
// Check type-registry services
if c.typeRegistry != nil {
c.typeRegistry.mu.RLock()
for _, reg := range c.typeRegistry.services {
reg.mu.RLock()
instance := reg.instance
reg.mu.RUnlock()
if instance == nil {
continue
}
if checker, ok := instance.(di.HealthChecker); ok {
serviceName := di.ServiceName(instance)
if err := checker.Health(ctx); err != nil {
c.typeRegistry.mu.RUnlock()
return NewServiceError(serviceName, "health", err)
}
}
}
c.typeRegistry.mu.RUnlock()
}
return nil
}
// Inspect returns diagnostic information about a service.
func (c *containerImpl) Inspect(name string) ServiceInfo {
c.mu.RLock()
defer c.mu.RUnlock()
reg, exists := c.services[name]
if !exists {
// Check type registry for type-based registrations
return c.inspectTypeRegistry(name)
}
reg.mu.RLock()
defer reg.mu.RUnlock()
lifecycle := "transient"
if reg.singleton {
lifecycle = "singleton"
} else if reg.scoped {
lifecycle = "scoped"
}
typeName := "unknown"
if reg.instance != nil {
typeName = fmt.Sprintf("%T", reg.instance)
}
healthy := false
if checker, ok := reg.instance.(di.HealthChecker); ok {
healthy = checker.Health(context.Background()) == nil
}
// Copy metadata and add groups
metadata := make(map[string]string)
for k, v := range reg.metadata {
metadata[k] = v
}
// Store groups in metadata for query purposes
if len(reg.groups) > 0 {
// Store groups as comma-separated string
metadata["__groups"] = joinStrings(reg.groups, ",")
}
return ServiceInfo{
Name: name,
Type: typeName,
Lifecycle: lifecycle,
Dependencies: reg.dependencies,
Deps: reg.deps,
Started: reg.started,
Healthy: healthy,
Metadata: metadata,
}
}
// inspectTypeRegistry returns diagnostic info for a type-registry service.
func (c *containerImpl) inspectTypeRegistry(name string) ServiceInfo {
if c.typeRegistry == nil {
return ServiceInfo{Name: name}
}
c.typeRegistry.mu.RLock()
defer c.typeRegistry.mu.RUnlock()
// Search for the registration matching this name
for key, reg := range c.typeRegistry.services {
serviceName := deriveServiceName(key)
if serviceName != name {
continue
}
reg.mu.RLock()
typeName := key.typ.String()
lifecycle := reg.lifecycle
if lifecycle == "" {
lifecycle = "singleton"
}
healthy := false
if reg.instance != nil {
if checker, ok := reg.instance.(di.HealthChecker); ok {
healthy = checker.Health(context.Background()) == nil
}
}
started := reg.started
reg.mu.RUnlock()
metadata := make(map[string]string)
if len(reg.groups) > 0 {
metadata["__groups"] = joinStrings(reg.groups, ",")
}
return ServiceInfo{
Name: name,
Type: typeName,
Lifecycle: lifecycle,
Started: started,
Healthy: healthy,
Metadata: metadata,
}
}
return ServiceInfo{Name: name}
}
// startService starts a single service.
// This is idempotent - if the service is already started (via auto-start on Resolve),
// it will be skipped.
func (c *containerImpl) startService(ctx context.Context, name string) error {
c.mu.RLock()
reg, exists := c.services[name]
c.mu.RUnlock()
if !exists {
return nil // Service not registered, skip
}
// Check if already started
reg.mu.RLock()
started := reg.started
reg.mu.RUnlock()
if started {
return nil // Already started (via auto-start on Resolve), skip
}
// Resolve the service instance (creates and auto-starts if needed)
_, err := c.Resolve(name)
if err != nil {
return err
}
return nil
}
// stopService stops a single service.
func (c *containerImpl) stopService(ctx context.Context, name string) error {
reg := c.services[name]
reg.mu.RLock()
instance := reg.instance
started := reg.started
reg.mu.RUnlock()
if !started || instance == nil {
return nil
}
// Call Stop if service implements di.Stopper
if stopper, ok := instance.(di.Stopper); ok {
if err := stopper.Stop(ctx); err != nil {
return err
}
reg.mu.Lock()
reg.started = false
reg.mu.Unlock()
}
return nil
}
// stopServices stops multiple services (for rollback).
func (c *containerImpl) stopServices(ctx context.Context, names []string) {
for i := len(names) - 1; i >= 0; i-- {
_ = c.stopService(ctx, names[i])
}
}
// joinStrings is a helper to join strings.
func joinStrings(strs []string, sep string) string {
if len(strs) == 0 {
return ""
}
result := strs[0]
for i := 1; i < len(strs); i++ {
result += sep + strs[i]
}
return result
}