-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp_impl.go
More file actions
1555 lines (1271 loc) · 43.4 KB
/
app_impl.go
File metadata and controls
1555 lines (1271 loc) · 43.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
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package forge
import (
"context"
"fmt"
"maps"
"net/http"
nethttppprof "net/http/pprof"
"os"
"os/signal"
"path/filepath"
"runtime"
"strings"
"sync"
"syscall"
"time"
confy "github.com/xraph/confy"
"github.com/xraph/forge/errors"
healthinternal "github.com/xraph/forge/internal/health"
"github.com/xraph/forge/internal/logger"
metricsinternal "github.com/xraph/forge/internal/metrics"
internalrouter "github.com/xraph/forge/internal/router"
"github.com/xraph/forge/internal/shared"
"github.com/xraph/vessel"
"gopkg.in/yaml.v3"
)
// app implements the App interface.
type app struct {
// Configuration
config AppConfig
// Core components
container Container
router Router
configManager ConfigManager
logger Logger
metrics Metrics
healthManager HealthManager
lifecycleManager LifecycleManager
// HTTP server
httpServer *http.Server
// Extensions
extensions []Extension
// Lifecycle
startTime time.Time
mu sync.RWMutex
started bool
starting bool
}
// newApp creates a new app instance.
func newApp(config AppConfig) *app {
// Apply defaults
if config.Name == "" {
config.Name = "forge-app"
}
if config.Version == "" {
config.Version = "1.0.0"
}
if config.Environment == "" {
config.Environment = "development"
}
if config.HTTPAddress == "" {
config.HTTPAddress = ":8080"
}
if config.HTTPTimeout == 0 {
config.HTTPTimeout = 30 * time.Second
}
if config.ShutdownTimeout == 0 {
config.ShutdownTimeout = 30 * time.Second
}
if len(config.ShutdownSignals) == 0 {
config.ShutdownSignals = []os.Signal{os.Interrupt, syscall.SIGTERM}
}
// Create DI container
container := NewContainer()
// Create logger if not provided
logger := config.Logger
if logger == nil {
// Use development logger for dev, production for prod, noop otherwise
switch config.Environment {
case "development":
logger = NewBeautifulLogger("forge")
case "production":
logger = NewProductionLogger()
default:
logger = NewNoopLogger()
}
}
// Create error handler
var errorHandler ErrorHandler
if config.ErrorHandler == nil {
errorHandler = shared.NewDefaultErrorHandler(logger)
}
// Create config manager if not provided (needed for metrics/health initialization)
configManager := config.ConfigManager
// Auto-discover and load config files if ConfigManager not provided and auto-discovery is enabled
if configManager == nil && config.EnableConfigAutoDiscovery {
autoConfig := confy.AutoDiscoveryConfig{
AppName: config.Name,
SearchPaths: config.ConfigSearchPaths,
ConfigNames: config.ConfigBaseNames,
LocalConfigNames: config.ConfigLocalNames,
EnableAppScoping: config.EnableAppScopedConfig,
RequireBase: false,
RequireLocal: false,
MaxDepth: 5,
Logger: logger,
// Environment variable source configuration
EnableEnvSource: config.EnableEnvConfig,
EnvPrefix: config.EnvPrefix,
EnvSeparator: config.EnvSeparator,
EnvOverridesFile: config.EnvOverridesFile,
}
// Try to auto-discover and load configs
if autoManager, result, err := confy.DiscoverAndLoadConfigs(autoConfig); err == nil {
configManager = autoManager
// Log discovery results
if logger != nil {
for _, p := range result.BaseConfigPaths {
logger.Info("auto-discovered base config",
F("path", p),
)
}
for _, p := range result.LocalConfigPaths {
logger.Info("auto-discovered local config",
F("path", p),
)
}
if result.IsMonorepo {
logger.Info("detected monorepo layout",
F("app", config.Name),
F("app_scoped", config.EnableAppScopedConfig),
)
}
}
} else if logger != nil {
// Auto-discovery failed, but that's okay - we'll create a default manager
logger.Debug("config auto-discovery did not find files, using empty config",
F("error", err.Error()),
)
}
}
// Create metrics with full config support
var metrics Metrics
metricsConfig := &config.MetricsConfig
// Apply defaults if metrics config is empty (not explicitly disabled)
if !metricsConfig.Enabled && metricsConfig.Collection.Namespace == "" {
// User didn't provide config, use defaults
defaultMetrics := DefaultMetricsConfig()
metricsConfig = &defaultMetrics
config.MetricsConfig = defaultMetrics // Update config for banner display
}
// Try to load from ConfigManager first
if configManager != nil {
var runtimeConfig shared.MetricsConfig
if err := configManager.Bind("metrics", &runtimeConfig); err == nil {
// Merge: runtime values override defaults, programmatic values override runtime
if runtimeConfig.Enabled {
metricsConfig = mergeMetricsConfig(&runtimeConfig, metricsConfig)
config.MetricsConfig = *metricsConfig // Update config for banner display
}
}
}
if metricsConfig.Enabled {
metrics = metricsinternal.New(metricsConfig, logger)
} else {
metrics = metricsinternal.NewNoOpMetrics()
}
// Initialize config manager if still not provided (after auto-discovery attempt)
if configManager == nil {
configManager = NewDefaultConfigManager(logger, metrics, errorHandler)
if logger != nil {
logger.Debug("using default empty config manager")
}
}
// Load .forge.yaml for app-level configuration (port, build settings, etc.)
// This runs BEFORE server initialization to ensure port is configured
config = loadForgeYAMLConfig(config, logger)
// Create health manager with full config support
var healthManager HealthManager
healthConfig := &config.HealthConfig
// Apply defaults if health config is empty (not explicitly disabled)
if !healthConfig.Enabled && healthConfig.Intervals.Check == 0 {
// User didn't provide config, use defaults
defaultHealth := DefaultHealthConfig()
defaultHealth.Intervals.Check = 30 * time.Second
defaultHealth.Intervals.Report = 60 * time.Second
defaultHealth.Features.AutoDiscovery = true
defaultHealth.Performance.MaxConcurrentChecks = 10
defaultHealth.Performance.DefaultTimeout = 5 * time.Second
defaultHealth.Features.Aggregation = true
defaultHealth.Performance.HistorySize = 100
healthConfig = &defaultHealth
config.HealthConfig = defaultHealth // Update config for banner display
}
// Try to load from ConfigManager first
if configManager != nil {
var runtimeConfig shared.HealthConfig
if err := configManager.Bind("health", &runtimeConfig); err == nil {
if runtimeConfig.Enabled {
healthConfig = mergeHealthConfig(&runtimeConfig, healthConfig)
config.HealthConfig = *healthConfig // Update config for banner display
}
}
}
if healthConfig.Enabled {
// Pass nil container, will be set after container creation in Start()
healthManager = healthinternal.New(healthConfig, logger, metrics, nil)
} else {
healthManager = healthinternal.NewNoOpHealthManager()
}
// Create router with options including observability
routerOpts := config.RouterOptions
if routerOpts == nil {
routerOpts = []RouterOption{}
}
// Add observability options
if config.MetricsConfig.Enabled {
routerOpts = append(routerOpts, WithMetrics(config.MetricsConfig))
}
if config.HealthConfig.Enabled {
routerOpts = append(routerOpts, WithHealth(config.HealthConfig))
}
// Add HTTP address for automatic localhost server in OpenAPI
if config.HTTPAddress != "" {
routerOpts = append(routerOpts, internalrouter.WithHTTPAddress(config.HTTPAddress))
}
// Enable panic recovery to prevent unhandled panics from crashing the server
routerOpts = append(routerOpts, internalrouter.WithRecovery())
router := NewRouter(routerOpts...)
// Register core services with DI - Both key-based (legacy) and type-based (new pattern)
// Key-based registration (backward compatibility)
// Register with both the full keys and simple keys for vessel compatibility
_ = Provide(container, func() (Logger, error) {
return logger, nil
}, vessel.WithAliases(shared.LoggerKey))
_ = Provide(container, func() (ConfigManager, error) {
return configManager, nil
}, vessel.WithAliases(shared.ConfigKey))
_ = Provide(container, func() (Metrics, error) {
return metrics, nil
}, vessel.WithAliases(shared.MetricsKey))
_ = Provide(container, func() (HealthManager, error) {
return healthManager, nil
}, vessel.WithAliases(shared.HealthManagerKey))
_ = Provide(container, func() (Router, error) {
return router, nil
}, vessel.WithAliases(shared.RouterKey))
// Create lifecycle manager
lm := NewLifecycleManager(logger)
a := &app{
config: config,
container: container,
router: router,
configManager: configManager,
logger: logger,
metrics: metrics,
healthManager: healthManager,
lifecycleManager: lm,
extensions: []Extension{}, // Initialize empty, will populate below
startTime: time.Now(),
}
// Register extensions from config
// This ensures RunnableExtension hooks are registered properly
for _, ext := range config.Extensions {
if err := a.RegisterExtension(ext); err != nil {
logger.Error("failed to register extension from config",
F("extension", ext.Name()),
F("error", err),
)
// Continue with other extensions
}
}
// Start the debug server when compiled with -tags forge_debug.
// initDebugServer is a no-op stub in release builds (zero overhead).
initDebugServer(a)
// Setup built-in endpoints
if err := a.setupBuiltinEndpoints(); err != nil {
logger.Error("failed to setup built-in endpoints", F("error", err))
panic(fmt.Sprintf("failed to setup built-in endpoints: %v", err))
}
return a
}
// Container returns the DI container.
func (a *app) Container() Container {
return a.container
}
// Router returns the router.
func (a *app) Router() Router {
return a.router
}
// Config returns the config manager.
func (a *app) Config() ConfigManager {
return a.configManager
}
// Logger returns the logger.
func (a *app) Logger() Logger {
return a.logger
}
// Metrics returns the metrics collector.
func (a *app) Metrics() Metrics {
return a.metrics
}
// HealthManager returns the health manager.
func (a *app) HealthManager() HealthManager {
return a.healthManager
}
// LifecycleManager returns the lifecycle manager.
func (a *app) LifecycleManager() LifecycleManager {
return a.lifecycleManager
}
// GetHTTPAddress returns the configured HTTP address
// This is a helper method for extensions that need to know the server address.
func (a *app) GetHTTPAddress() string {
return a.config.HTTPAddress
}
// RegisterService registers a service with the DI container.
func (a *app) RegisterService(name string, factory Factory, opts ...RegisterOption) error {
return a.container.Register(name, factory, opts...)
}
// RegisterController registers a controller with the router.
func (a *app) RegisterController(controller Controller) error {
return a.router.RegisterController(controller)
}
// RegisterExtension registers an extension with the app.
func (a *app) RegisterExtension(ext Extension) error {
a.mu.Lock()
defer a.mu.Unlock()
// Check for duplicate
for _, existing := range a.extensions {
if existing.Name() == ext.Name() {
return fmt.Errorf("extension %s already registered", ext.Name())
}
}
a.extensions = append(a.extensions, ext)
// Auto-register lifecycle hooks for RunnableExtension implementations
if runnableExt, ok := ext.(RunnableExtension); ok {
a.logger.Debug("registering runnable extension hooks",
F("extension", ext.Name()),
)
// Register Run() hook in PhaseAfterRun
runOpts := DefaultLifecycleHookOptions("run-" + ext.Name())
if err := a.lifecycleManager.RegisterHook(PhaseAfterRun, func(ctx context.Context, app App) error {
return runnableExt.Run(ctx)
}, runOpts); err != nil {
return fmt.Errorf("failed to register run hook for %s: %w", ext.Name(), err)
}
// Register Shutdown() hook in PhaseBeforeStop
shutdownOpts := DefaultLifecycleHookOptions("shutdown-" + ext.Name())
if err := a.lifecycleManager.RegisterHook(PhaseBeforeStop, func(ctx context.Context, app App) error {
return runnableExt.Shutdown(ctx)
}, shutdownOpts); err != nil {
return fmt.Errorf("failed to register shutdown hook for %s: %w", ext.Name(), err)
}
a.logger.Debug("runnable extension hooks registered",
F("extension", ext.Name()),
)
}
return nil
}
// RegisterHook registers a lifecycle hook.
func (a *app) RegisterHook(phase LifecyclePhase, hook LifecycleHook, opts LifecycleHookOptions) error {
return a.lifecycleManager.RegisterHook(phase, hook, opts)
}
// RegisterHookFn is a convenience method to register a hook with default options.
func (a *app) RegisterHookFn(phase LifecyclePhase, name string, hook LifecycleHook) error {
return a.lifecycleManager.RegisterHookFn(phase, name, hook)
}
// Extensions returns all registered extensions.
func (a *app) Extensions() []Extension {
a.mu.RLock()
defer a.mu.RUnlock()
// Return a copy to prevent modification
extensions := make([]Extension, len(a.extensions))
copy(extensions, a.extensions)
return extensions
}
// GetExtension returns an extension by name.
func (a *app) GetExtension(name string) (Extension, error) {
a.mu.RLock()
defer a.mu.RUnlock()
for _, ext := range a.extensions {
if ext.Name() == name {
return ext, nil
}
}
return nil, fmt.Errorf("extension %s not found", name)
}
// Name returns the application name.
func (a *app) Name() string {
return a.config.Name
}
// Version returns the application version.
func (a *app) Version() string {
return a.config.Version
}
// Environment returns the application environment.
func (a *app) Environment() string {
return a.config.Environment
}
// MigrationsDisabled returns true if auto-migrations are disabled via config or .forge.yaml.
func (a *app) MigrationsDisabled() bool {
return a.config.DisableMigrations
}
// StartTime returns the application start time.
func (a *app) StartTime() time.Time {
a.mu.RLock()
defer a.mu.RUnlock()
return a.startTime
}
// Uptime returns the application uptime.
func (a *app) Uptime() time.Duration {
a.mu.RLock()
defer a.mu.RUnlock()
return time.Since(a.startTime)
}
// Start starts the application.
func (a *app) Start(ctx context.Context) error {
a.mu.Lock()
if a.started || a.starting {
a.mu.Unlock()
return errors.New("app already started")
}
a.starting = true
a.mu.Unlock()
a.logger.Info("starting application",
F("name", a.config.Name),
F("version", a.config.Version),
F("environment", a.config.Environment),
F("extensions", len(a.extensions)),
)
// Execute before start hooks
if err := a.lifecycleManager.ExecuteHooks(ctx, PhaseBeforeStart, a); err != nil {
return fmt.Errorf("before start hooks failed: %w", err)
}
// Build extension dependency graph for proper lifecycle ordering
_, extMap, order, err := a.buildExtensionGraph()
if err != nil {
return err
}
// Process each extension's FULL lifecycle in dependency order
// This ensures dependencies are fully ready (Register + Start) before dependents begin
for _, name := range order {
ext, ok := extMap[name]
if !ok {
continue // Dependency might not be registered (optional)
}
// Phase 1: Register extension's services
a.logger.Info("registering extension",
F("extension", ext.Name()),
F("version", ext.Version()),
)
if err := ext.Register(a); err != nil {
return fmt.Errorf("failed to register extension %s: %w", ext.Name(), err)
}
// Phase 2: Start the extension (services auto-start on Resolve)
a.logger.Info("starting extension",
F("extension", ext.Name()),
)
if err := ext.Start(ctx); err != nil {
return fmt.Errorf("failed to start extension %s: %w", ext.Name(), err)
}
a.logger.Info("extension ready",
F("extension", ext.Name()),
)
}
// Execute after register hooks (all extensions now registered and started)
if err := a.lifecycleManager.ExecuteHooks(ctx, PhaseAfterRegister, a); err != nil {
return fmt.Errorf("after register hooks failed: %w", err)
}
// Apply global middleware from extensions
a.logger.Debug("applying extension middlewares")
if err := a.applyExtensionMiddlewares(); err != nil {
return fmt.Errorf("failed to apply extension middlewares: %w", err)
}
a.logger.Debug("extension middlewares applied")
// Start DI container (idempotent - skips already-started services)
a.logger.Debug("finalizing DI container")
if err := a.container.Start(ctx); err != nil {
return fmt.Errorf("failed to start container: %w", err)
}
a.logger.Debug("DI container finalized")
// Start health manager explicitly after container is ready so that
// auto-discovery can see all registered services. The health manager
// is NOT started by container.Start() because it is registered lazily
// (no WithEager), so we must start it here with the container set.
if healthMgr, ok := a.healthManager.(*healthinternal.ManagerImpl); ok {
healthMgr.SetContainer(a.container)
if !healthMgr.IsStarted() {
if err := healthMgr.Start(ctx); err != nil {
return fmt.Errorf("failed to start health manager: %w", err)
}
}
}
// Apply HTTP metrics middleware if enabled
// This must happen after container.Start() which initializes the HTTP collector
a.applyHTTPMetricsMiddleware()
// Reload configs from ConfigManager (hot-reload support)
a.logger.Debug("reloading configs from ConfigManager")
if err := a.reloadConfigsFromManager(); err != nil {
a.logger.Warn("failed to reload configs from ConfigManager", F("error", err))
}
a.logger.Debug("configs reloaded")
// 4. Setup observability endpoints (including extension health checks)
if err := a.setupObservabilityEndpoints(); err != nil {
return fmt.Errorf("failed to setup observability endpoints: %w", err)
}
a.registerExtensionHealthChecks()
// Note: Health manager is already started by container.Start()
// No need to start it again here
a.started = true
a.startTime = time.Now()
// Execute after start hooks
if err := a.lifecycleManager.ExecuteHooks(ctx, PhaseAfterStart, a); err != nil {
return fmt.Errorf("after start hooks failed: %w", err)
}
a.logger.Info("application started successfully")
return nil
}
// Stop stops the application.
func (a *app) Stop(ctx context.Context) error {
a.mu.Lock()
defer a.mu.Unlock()
if !a.started {
return nil
}
a.logger.Info("stopping application")
// Execute before stop hooks
if err := a.lifecycleManager.ExecuteHooks(ctx, PhaseBeforeStop, a); err != nil {
a.logger.Warn("before stop hooks failed", F("error", err))
}
// 1. Stop health manager
if healthMgr, ok := a.healthManager.(*healthinternal.ManagerImpl); ok {
if err := healthMgr.Stop(ctx); err != nil {
a.logger.Error("failed to stop health manager", F("error", err))
}
}
// 2. Stop extensions in reverse order
a.stopExtensions(ctx)
// 3. Stop DI container (stops all services in reverse order)
if err := a.container.Stop(ctx); err != nil {
a.logger.Error("failed to stop container", F("error", err))
}
a.started = false
// Execute after stop hooks
if err := a.lifecycleManager.ExecuteHooks(ctx, PhaseAfterStop, a); err != nil {
a.logger.Warn("after stop hooks failed", F("error", err))
}
a.logger.Info("application stopped")
return nil
}
// Run starts the HTTP server and blocks until a shutdown signal is received.
func (a *app) Run() error {
// Start the application
if err := a.Start(context.Background()); err != nil {
return fmt.Errorf("failed to start app: %w", err)
}
// Create HTTP server.
// WriteTimeout is set to 0 (disabled) because SSE, WebSocket, and gRPC
// streaming handlers need indefinite write durations. A server-wide
// WriteTimeout kills ALL long-lived connections after the deadline,
// making streaming impossible. Regular REST handlers are protected by
// per-route timeouts applied at the router level instead.
a.httpServer = &http.Server{
Addr: a.config.HTTPAddress,
Handler: a.router,
ReadTimeout: a.config.HTTPTimeout,
ReadHeaderTimeout: 10 * time.Second,
WriteTimeout: 0, // disabled — streaming requires indefinite writes
IdleTimeout: a.config.HTTPTimeout * 2,
}
// Print startup banner
a.printStartupBanner()
// Execute before run hooks (before HTTP server starts)
if err := a.lifecycleManager.ExecuteHooks(context.Background(), PhaseBeforeRun, a); err != nil {
return fmt.Errorf("before run hooks failed: %w", err)
}
// Channel for shutdown signal
shutdown := make(chan os.Signal, 1)
signal.Notify(shutdown, a.config.ShutdownSignals...)
// Channel for server errors
errChan := make(chan error, 1)
// Start HTTP server in goroutine
go func() {
if err := a.httpServer.ListenAndServe(); err != nil && err != http.ErrServerClosed {
errChan <- err
}
}()
// Execute after run hooks (after HTTP server starts, non-blocking)
// Run in background to not block main loop
go func() {
if err := a.lifecycleManager.ExecuteHooks(context.Background(), PhaseAfterRun, a); err != nil {
a.logger.Warn("after run hooks failed", F("error", err))
}
}()
// Wait for shutdown signal or error
select {
case err := <-errChan:
return fmt.Errorf("http server error: %w", err)
case sig := <-shutdown:
a.logger.Info("shutdown signal received", F("signal", sig.String()))
}
// Graceful shutdown
return a.gracefulShutdown()
}
// gracefulShutdown performs a graceful shutdown.
func (a *app) gracefulShutdown() error {
ctx, cancel := context.WithTimeout(context.Background(), a.config.ShutdownTimeout)
defer cancel()
a.logger.Info("starting graceful shutdown", F("timeout", a.config.ShutdownTimeout))
// 1. Stop accepting new requests and wait for active requests to complete
if a.httpServer != nil {
if err := a.httpServer.Shutdown(ctx); err != nil {
a.logger.Error("http server shutdown error", F("error", err))
}
}
// 2. Stop the application (which stops all services)
if err := a.Stop(ctx); err != nil {
a.logger.Error("app shutdown error", F("error", err))
}
a.logger.Info("graceful shutdown complete")
return nil
}
// printStartupBanner prints a styled startup banner with app info and endpoints.
func (a *app) printStartupBanner() {
bannerCfg := shared.BannerConfig{
AppName: a.config.Name,
Version: a.config.Version,
Environment: a.config.Environment,
HTTPAddress: a.config.HTTPAddress,
StartTime: a.startTime,
}
// Add OpenAPI paths if enabled
if spec := a.router.OpenAPISpec(); spec != nil {
// Default paths for OpenAPI (standard Forge defaults)
bannerCfg.OpenAPISpec = "/openapi.json"
bannerCfg.OpenAPIUI = "/swagger"
}
// Add AsyncAPI path if enabled
if spec := a.router.AsyncAPISpec(); spec != nil {
// Default path for AsyncAPI UI
bannerCfg.AsyncAPIUI = "/asyncapi"
}
// Add observability endpoints
if a.config.HealthConfig.Enabled {
bannerCfg.HealthPath = "/_/health"
}
if a.config.MetricsConfig.Enabled {
bannerCfg.MetricsPath = "/_/metrics"
}
if a.config.EnablePprof {
prefix := a.config.PprofPrefix
if prefix == "" {
prefix = "/_/debug/pprof"
}
bannerCfg.PprofPath = prefix
}
// Print the banner
shared.PrintStartupBanner(bannerCfg)
}
// setupBuiltinEndpoints sets up built-in endpoints.
func (a *app) setupBuiltinEndpoints() error {
// Info endpoint
if err := a.router.GET("/_/info", a.handleInfo); err != nil {
return fmt.Errorf("failed to register info endpoint: %w", err)
}
return nil
}
// setupObservabilityEndpoints sets up observability endpoints.
func (a *app) setupObservabilityEndpoints() error {
// Setup metrics endpoint if enabled
if a.config.MetricsConfig.Enabled {
if err := a.router.GET("/_/metrics", a.handleMetrics); err != nil {
return fmt.Errorf("failed to register metrics endpoint: %w", err)
}
}
// Setup health endpoints if enabled
if a.config.HealthConfig.Enabled {
if err := a.router.GET("/_/health", a.handleHealth); err != nil {
return fmt.Errorf("failed to register health endpoint: %w", err)
}
if err := a.router.GET("/_/health/live", a.handleHealthLive); err != nil {
return fmt.Errorf("failed to register live health endpoint: %w", err)
}
if err := a.router.GET("/_/health/ready", a.handleHealthReady); err != nil {
return fmt.Errorf("failed to register ready health endpoint: %w", err)
}
}
// Setup pprof profiling endpoints if enabled
if a.config.EnablePprof {
if err := a.setupPprofEndpoints(); err != nil {
return fmt.Errorf("failed to register pprof endpoints: %w", err)
}
}
return nil
}
// setupPprofEndpoints registers net/http/pprof handlers on the router
// and a styled index page for browsing profiles.
func (a *app) setupPprofEndpoints() error {
prefix := a.config.PprofPrefix
if prefix == "" {
prefix = "/_/debug/pprof"
}
prefix = strings.TrimRight(prefix, "/")
// Dispatch table for specific pprof handlers.
specific := map[string]http.HandlerFunc{
"/cmdline": nethttppprof.Cmdline,
"/profile": nethttppprof.Profile,
"/symbol": nethttppprof.Symbol,
"/trace": nethttppprof.Trace,
}
// Single wildcard route handles everything: index page, specific
// handlers, and named profiles (heap, goroutine, etc.).
if err := a.router.Handle(prefix+"/*", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// Strip prefix to get the sub-path (e.g. "/heap", "/profile", "").
sub := strings.TrimPrefix(r.URL.Path, prefix)
// Index page: empty path or just "/".
if sub == "" || sub == "/" {
pprofIndexPage(w, r, prefix)
return
}
// Specific handlers (cmdline, profile, symbol, trace).
if h, ok := specific[sub]; ok {
h.ServeHTTP(w, r)
return
}
// Everything else: named profiles via pprof.Index (heap, goroutine, allocs, etc.).
// pprof.Index expects the profile name at the end of the URL path after "/debug/pprof/".
r.URL.Path = "/debug/pprof" + sub
nethttppprof.Index(w, r)
})); err != nil {
return err
}
a.logger.Info("pprof profiling endpoints enabled",
F("prefix", prefix),
)
return nil
}
// handleInfo handles the /_/info endpoint.
func (a *app) handleInfo(ctx Context) error {
// Get service names from container
services := a.container.Services()
// Get route count
routes := a.router.Routes()
// Get extension info
extensionInfo := make([]ExtensionInfo, 0, len(a.extensions))
for _, ext := range a.extensions {
status := "stopped"
if baseExt, ok := ext.(*BaseExtension); ok {
if baseExt.IsStarted() {
status = "started"
}
} else {
// If not BaseExtension, assume started if we're past app start
if a.started {
status = "started"
}
}
extensionInfo = append(extensionInfo, ExtensionInfo{
Name: ext.Name(),
Version: ext.Version(),
Description: ext.Description(),
Dependencies: ext.Dependencies(),
Status: status,
})
}
info := AppInfo{
Name: a.config.Name,
Version: a.config.Version,
Description: a.config.Description,
Environment: a.config.Environment,
StartTime: a.StartTime(),
Uptime: a.Uptime(),
GoVersion: runtime.Version(),
Services: services,
Routes: len(routes),
Extensions: extensionInfo,
}
return ctx.JSON(200, info)
}
// buildExtensionGraph builds a dependency graph from registered extensions.
// Returns the graph, extension map for lookup, and the topologically sorted order.
func (a *app) buildExtensionGraph() (*vessel.DependencyGraph, map[string]Extension, []string, error) {
graph := vessel.NewDependencyGraph()
extMap := make(map[string]Extension)
for _, ext := range a.extensions {
// Check if extension uses the new DepsSpec() interface first
if specExt, ok := ext.(DependencySpecExtension); ok {
deps := specExt.DepsSpec()
graph.AddNodeWithDeps(ext.Name(), deps)
} else {
// Fall back to legacy Dependencies() []string (treated as eager deps)
deps := ext.Dependencies()
graph.AddNode(ext.Name(), deps)
}
extMap[ext.Name()] = ext
}
order, err := graph.TopologicalSort()
if err != nil {
return nil, nil, nil, fmt.Errorf("circular extension dependency detected: %w", err)
}
return graph, extMap, order, nil
}
// stopExtensions stops all extensions in reverse dependency order.
func (a *app) stopExtensions(ctx context.Context) {
// Build dependency graph to get proper order
_, extMap, order, err := a.buildExtensionGraph()
if err != nil {
// Fallback to reverse add order if graph fails
a.logger.Warn("failed to build extension graph for stop, using reverse add order",
F("error", err),
)
for i := len(a.extensions) - 1; i >= 0; i-- {
ext := a.extensions[i]
a.logger.Info("stopping extension", F("extension", ext.Name()))
if err := ext.Stop(ctx); err != nil {
a.logger.Error("failed to stop extension",
F("extension", ext.Name()),
F("error", err),
)