-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmain.go
More file actions
97 lines (77 loc) · 2.44 KB
/
main.go
File metadata and controls
97 lines (77 loc) · 2.44 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
package main
import (
"context"
"log"
"net/http"
"os"
API "service-a/cmd/api"
"service-a/cmd/api/connection"
DB "service-a/internal/database"
kafkaStructure "service-a/internal/kafka"
"service-a/internal/metrics"
"service-a/internal/outbox"
"service-a/internal/server"
// "time"
)
// Get specific partition based on hostname
func ExtractPartition(serviceHostname string) int {
var partition int = 0;
switch serviceHostname {
case "service-a-1":
partition = 0
case "service-a-2":
partition = 1
case "service-a-3":
partition = 2
}
log.Printf("Extracted partition %d for hostname %s", partition, serviceHostname)
return partition
}
func main() {
log.Println("Starting Summation Service")
// Initialize database connection
db := DB.INIT_DB()
if db == nil {
log.Fatal("Failed to initialize database connection")
}
defer db.Close()
// Initialize outbox repository
repo := outbox.NewRepository(db)
// ------------ Initialize Kafka writer with specific partition based on hostname ------------
serviceHostname, _ := os.Hostname()
var partition int = ExtractPartition(serviceHostname)
log.Printf("Service hostname: %s, assigned to partition: %d", serviceHostname, partition)
writer := kafkaStructure.NewKafkaWriterWithPartition("user-events", partition)
if writer == nil {
log.Fatal("Failed to create Kafka writer")
}
defer writer.Publisher.Close()
// Initialize OutboxPublisher with 3-second check interval
// publisher := outbox.NewOutboxPublisher(repo, writer, 3*time.Second)
// Create context for graceful shutdown
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
// Start the OutboxPublisher in a goroutine
// go publisher.Start(ctx)
// Start the HTTP server for Prometheus metrics
metrics.StartMetricsServer(ctx, 9091)
// -------- Open the GRPC Connection and define the API --------
client, conn, err := connection.GRPC_Connection()
if err != nil {
log.Fatal(err)
}
defer conn.Close()
// ------ API ------
http.HandleFunc("/sum", API.SummationRequest(client))
// Start the gRPC server in a goroutine so it doesn't block
go func() {
if err := server.StartServerWithOutbox(50051, repo); err != nil {
log.Fatalf("Failed to start gRPC server: %v", err)
}
}()
// Start HTTP server for the API
log.Printf("Starting HTTP server on port 8080, hostname: %s", serviceHostname)
if err := http.ListenAndServe(":8080", nil); err != nil {
log.Fatalf("Failed to start HTTP server: %v", err)
}
}