-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.go
More file actions
273 lines (231 loc) · 8.61 KB
/
app.go
File metadata and controls
273 lines (231 loc) · 8.61 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
package main
import (
"context"
"flag"
"fmt"
"net/http"
"os"
"os/signal"
"syscall"
"time"
"github.com/grove-platform/github-copier/configs"
"github.com/grove-platform/github-copier/services"
)
// version is set at build time via -ldflags:
//
// go build -ldflags "-X main.version=v1.0.0"
//
// When not set (local dev builds), it defaults to "dev".
var version = "dev"
func main() {
// Parse command line flags
var envFile string
var dryRun bool
var validateOnly bool
flag.StringVar(&envFile, "env", "./configs/.env", "Path to environment file")
flag.BoolVar(&dryRun, "dry-run", false, "Enable dry-run mode (no actual changes)")
flag.BoolVar(&validateOnly, "validate", false, "Validate configuration and exit")
showVersion := flag.Bool("version", false, "Print version and exit")
help := flag.Bool("help", false, "Show help")
flag.Parse()
if *showVersion {
fmt.Println(version)
return
}
if *help {
printHelp()
return
}
// Load environment configuration
config, err := configs.LoadEnvironment(envFile)
if err != nil {
fmt.Printf("❌ Error loading environment: %v\n", err)
os.Exit(1)
}
// Load secrets from Secret Manager if not directly provided
ctx := context.Background()
if err := services.LoadWebhookSecret(ctx, config); err != nil {
fmt.Printf("❌ Error loading webhook secret: %v\n", err)
os.Exit(1)
}
if err := services.LoadMongoURI(ctx, config); err != nil {
fmt.Printf("❌ Error loading MongoDB URI: %v\n", err)
os.Exit(1)
}
// Override dry-run from command line
if dryRun {
config.DryRun = true
}
// Initialize services
container, err := services.NewServiceContainer(config)
if err != nil {
fmt.Printf("❌ Failed to initialize services: %v\n", err)
os.Exit(1)
}
defer func() { _ = container.Close(context.Background()) }()
// If validate-only mode, validate config and exit
if validateOnly {
if err := validateConfiguration(container); err != nil {
fmt.Printf("❌ Configuration validation failed: %v\n", err)
os.Exit(1)
}
fmt.Println("✅ Configuration is valid")
return
}
// Initialize Google Cloud logging
services.InitializeLogger(config)
defer services.CloseGoogleLogger()
// Configure GitHub permissions
if err := services.ConfigurePermissions(ctx, config); err != nil {
if config.DryRun {
services.LogWarning("GitHub authentication failed (non-fatal in dry-run mode)", "error", err)
fmt.Printf("⚠️ GitHub auth skipped (dry-run): %v\n", err)
} else {
fmt.Printf("❌ Failed to configure GitHub permissions: %v\n", err)
os.Exit(1)
}
}
// Print startup banner
printBanner(config, container)
// Start web server
if err := startWebServer(config, container); err != nil {
fmt.Printf("❌ Failed to start web server: %v\n", err)
os.Exit(1)
}
}
func printHelp() {
fmt.Println("GitHub Code Example Copier")
fmt.Println()
fmt.Println("Usage:")
fmt.Println(" app [options]")
fmt.Println()
fmt.Println("Options:")
fmt.Println(" -env string Path to environment file (default: ./configs/.env)")
fmt.Println(" -dry-run Enable dry-run mode (no actual changes)")
fmt.Println(" -validate Validate configuration and exit")
fmt.Println(" -help Show this help message")
fmt.Println()
fmt.Println("Examples:")
fmt.Println(" app -env ./configs/.env.test")
fmt.Println(" app -dry-run")
fmt.Println(" app -validate -env ./configs/.env.prod")
}
func printBanner(config *configs.Config, container *services.ServiceContainer) {
fmt.Println("╔════════════════════════════════════════════════════════════════╗")
fmt.Println("║ GitHub Code Example Copier ║")
fmt.Println("╠════════════════════════════════════════════════════════════════╣")
fmt.Printf("║ Version: %-48s║\n", version)
fmt.Printf("║ Port: %-48s║\n", config.Port)
fmt.Printf("║ Webhook Path: %-48s║\n", config.WebserverPath)
fmt.Printf("║ Config File: %-48s║\n", config.EffectiveConfigFile())
fmt.Printf("║ Dry Run: %-48v║\n", config.DryRun)
fmt.Printf("║ Audit Log: %-48v║\n", config.AuditEnabled)
fmt.Printf("║ Metrics: %-48v║\n", config.MetricsEnabled)
fmt.Printf("║ Slack: %-48v║\n", config.SlackEnabled)
fmt.Println("╚════════════════════════════════════════════════════════════════╝")
fmt.Println()
}
func validateConfiguration(container *services.ServiceContainer) error {
ctx := context.Background()
_, err := container.ConfigLoader.LoadConfig(ctx, container.Config)
return err
}
func startWebServer(config *configs.Config, container *services.ServiceContainer) error {
// Create HTTP handler with all routes
mux := http.NewServeMux()
// Webhook endpoint
mux.HandleFunc(config.WebserverPath, func(w http.ResponseWriter, r *http.Request) {
handleWebhook(w, r, config, container)
})
// Liveness probe — lightweight, always 200 if process is running
mux.HandleFunc("/health", services.HealthHandler(container.StartTime, version))
// Readiness probe — checks GitHub auth, MongoDB connectivity
mux.HandleFunc("/ready", services.ReadinessHandler(container))
// Metrics endpoint (if enabled)
if config.MetricsEnabled {
mux.HandleFunc("/metrics", services.MetricsHandler(container.MetricsCollector, container.FileStateService))
}
// Config diagnostic endpoint — shows resolved config with secrets redacted
mux.HandleFunc("/config", services.ConfigDiagnosticHandler(container, version))
// Info endpoint
mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path != "/" {
http.NotFound(w, r)
return
}
w.Header().Set("Content-Type", "text/plain")
_, _ = fmt.Fprintf(w, "GitHub Code Example Copier %s\n", version)
_, _ = fmt.Fprintf(w, "Webhook endpoint: %s\n", config.WebserverPath)
_, _ = fmt.Fprintf(w, "Health check: /health\n")
_, _ = fmt.Fprintf(w, "Readiness check: /ready\n")
_, _ = fmt.Fprintf(w, "Config diagnostic: /config\n")
if config.MetricsEnabled {
_, _ = fmt.Fprintf(w, "Metrics: /metrics\n")
}
})
// Create server
port := ":" + config.Port
server := &http.Server{
Addr: port,
Handler: mux,
ReadTimeout: 30 * time.Second,
WriteTimeout: 30 * time.Second,
IdleTimeout: 120 * time.Second,
}
// Channel to signal server errors
serverErr := make(chan error, 1)
// Start server in goroutine
go func() {
services.LogInfo("Starting web server", "port", port)
if err := server.ListenAndServe(); err != nil && err != http.ErrServerClosed {
serverErr <- fmt.Errorf("server error: %w", err)
}
close(serverErr)
}()
// Wait for interrupt signal
sigChan := make(chan os.Signal, 1)
signal.Notify(sigChan, os.Interrupt, syscall.SIGTERM)
// Block until we receive a signal or server error
select {
case err := <-serverErr:
if err != nil {
return err
}
case sig := <-sigChan:
services.LogInfo("Received signal, initiating graceful shutdown", "signal", sig)
}
// Graceful shutdown with timeout
shutdownCtx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
services.LogInfo("Waiting for in-flight requests to complete")
if err := server.Shutdown(shutdownCtx); err != nil {
services.LogError("Server shutdown error", "error", err)
} else {
services.LogInfo("Server stopped accepting new connections")
}
// Cleanup resources (flush audit logs, close connections)
services.LogInfo("Cleaning up resources")
if err := container.Close(shutdownCtx); err != nil {
services.LogError("Cleanup error", "error", err)
}
services.LogInfo("Shutdown complete")
return nil
}
func handleWebhook(w http.ResponseWriter, r *http.Request, config *configs.Config, container *services.ServiceContainer) {
// Record webhook received
container.MetricsCollector.RecordWebhookReceived()
startTime := time.Now()
// Create context with timeout
baseCtx, rid := services.WithRequestID(r)
timeout := time.Duration(60) * time.Second
ctx, cancel := context.WithTimeout(baseCtx, timeout)
defer cancel()
r = r.WithContext(ctx)
services.LogWebhookOperation(ctx, "receive", "webhook received", nil, map[string]interface{}{
"request_id": rid,
})
// Handle webhook with new pattern matching
services.HandleWebhookWithContainer(w, r, config, container)
// Record processing time
container.MetricsCollector.RecordWebhookProcessed(time.Since(startTime))
}