-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathmain.go
More file actions
248 lines (222 loc) · 8.11 KB
/
Copy pathmain.go
File metadata and controls
248 lines (222 loc) · 8.11 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
package main
import (
"context"
"errors"
"log/slog"
"net"
"net/http"
"os"
"time"
"github.com/Marz32onE/instrumentation-go/otel-nats/oteljetstream"
"github.com/hmchangw/chat/history-service/internal/cassrepo"
"github.com/hmchangw/chat/history-service/internal/config"
"github.com/hmchangw/chat/history-service/internal/mongorepo"
"github.com/hmchangw/chat/history-service/internal/publisher"
"github.com/hmchangw/chat/history-service/internal/readcache"
"github.com/hmchangw/chat/history-service/internal/service"
"github.com/hmchangw/chat/pkg/atrest"
"github.com/hmchangw/chat/pkg/cassutil"
"github.com/hmchangw/chat/pkg/emoji"
"github.com/hmchangw/chat/pkg/health"
"github.com/hmchangw/chat/pkg/logctx"
"github.com/hmchangw/chat/pkg/mongoutil"
"github.com/hmchangw/chat/pkg/msgbucket"
"github.com/hmchangw/chat/pkg/natsrouter"
"github.com/hmchangw/chat/pkg/natsutil"
"github.com/hmchangw/chat/pkg/otelutil"
"github.com/hmchangw/chat/pkg/shutdown"
"github.com/hmchangw/chat/pkg/userstore"
)
// checkConfig validates positive-integer config knobs and exits the process on
// the first violation. Kept centralized so future int-bounded settings have one
// place to land.
func checkConfig(cfg *config.Config) {
checks := []struct {
name string
value int
}{
{"MESSAGE_BUCKET_HOURS", cfg.MessageBucketHours},
{"MESSAGE_READ_MAX_BUCKETS", cfg.MessageReadMaxBuckets},
{"MESSAGE_HISTORY_FLOOR_DAYS", cfg.MessageHistoryFloorDays},
{"LARGE_ROOM_THRESHOLD", cfg.LargeRoomThreshold},
{"MAX_PINNED_PER_ROOM", cfg.MaxPinnedPerRoom},
}
for _, c := range checks {
if c.value < 1 {
slog.Error("invalid config", c.name, c.value)
os.Exit(1)
}
}
}
func main() {
logctx.SetupDefault(os.Stdout)
cfg, err := config.Load()
if err != nil {
slog.Error("parse config", "error", err)
os.Exit(1)
}
logctx.Configure(cfg.DebugLog)
checkConfig(&cfg)
slog.Info("message bucket configured",
"hours", cfg.MessageBucketHours,
"maxBuckets", cfg.MessageReadMaxBuckets,
"readBucketConcurrency", cfg.MessageReadBucketConcurrency,
"readEscalateAfter", cfg.MessageReadEscalateAfter,
"historyFloorDays", cfg.MessageHistoryFloorDays,
"largeRoomThreshold", cfg.LargeRoomThreshold,
"maxPinnedPerRoom", cfg.MaxPinnedPerRoom,
"pinEnabled", cfg.PinEnabled,
)
bucketSizer := msgbucket.New(time.Duration(cfg.MessageBucketHours) * time.Hour)
ctx := context.Background()
tracerShutdown, err := otelutil.InitTracer(ctx, "history-service")
if err != nil {
slog.Error("init tracer failed", "error", err)
os.Exit(1)
}
meterShutdown, err := otelutil.InitMeter("history-service")
if err != nil {
slog.Error("init meter failed", "error", err)
os.Exit(1)
}
nc, err := natsutil.Connect(cfg.NATS.URL, cfg.NATS.CredsFile)
if err != nil {
slog.Error("nats connect failed", "error", err)
os.Exit(1)
}
js, err := oteljetstream.New(nc)
if err != nil {
slog.Error("jetstream init failed", "error", err)
os.Exit(1)
}
mongoClient, err := mongoutil.Connect(ctx, cfg.Mongo.URI, cfg.Mongo.Username, cfg.Mongo.Password)
if err != nil {
slog.Error("mongo connect failed", "error", err)
os.Exit(1)
}
cassSession, err := cassutil.Connect(cassutil.Config{
Hosts: cfg.Cassandra.Hosts,
Keyspace: cfg.Cassandra.Keyspace,
Username: cfg.Cassandra.Username,
Password: cfg.Cassandra.Password,
NumConns: cfg.Cassandra.NumConns,
})
if err != nil {
slog.Error("cassandra connect failed", "error", err)
os.Exit(1)
}
var (
cipher atrest.Cipher
vaultWrapper atrest.KeyWrapperCloser
)
if cfg.Atrest.Enabled {
w, err := atrest.NewVaultKeyWrapper(ctx, cfg.Vault)
if err != nil {
slog.Error("failed to construct Vault key wrapper", "addr", cfg.Vault.Address, "error", err)
os.Exit(1)
}
vaultWrapper = w
dekColl := mongoClient.Database(cfg.Mongo.DB).Collection(atrest.CollectionName)
cipher = atrest.NewCipher(w, atrest.NewMongoDEKStore(dekColl), cfg.Atrest)
}
cassRepo := cassrepo.NewRepository(cassSession, bucketSizer, cfg.MessageReadMaxBuckets, cipher,
cassrepo.WithReadConcurrency(cfg.MessageReadBucketConcurrency, cfg.MessageReadEscalateAfter))
db := mongoClient.Database(cfg.Mongo.DB)
subRepo := mongorepo.NewSubscriptionRepo(db)
roomRepo := mongorepo.NewRoomRepo(db)
threadRoomRepo := mongorepo.NewThreadRoomRepo(db)
threadSubRepo := mongorepo.NewThreadSubscriptionRepo(db)
customEmojiRepo := mongorepo.NewCustomEmojiRepo(db)
userStore := userstore.NewMongoStore(db.Collection("users"))
if err := threadRoomRepo.EnsureIndexes(ctx); err != nil {
slog.Error("ensure thread_rooms indexes failed", "error", err)
os.Exit(1)
}
if err := threadSubRepo.EnsureIndexes(ctx); err != nil {
slog.Error("ensure thread_subscriptions indexes failed", "error", err)
os.Exit(1)
}
if err := customEmojiRepo.EnsureIndexes(ctx); err != nil {
slog.Error("ensure custom_emojis indexes failed", "error", err)
os.Exit(1)
}
cachedEmojis, err := emoji.NewCachedLookup(customEmojiRepo, cfg.CustomEmojiCacheSize, cfg.CustomEmojiCacheTTL)
if err != nil {
slog.Error("init custom emoji cache failed", "error", err)
os.Exit(1)
}
slog.Info("custom emoji cache configured",
"size", cfg.CustomEmojiCacheSize,
"ttl", cfg.CustomEmojiCacheTTL,
)
// Front the per-request Mongo reads with process-local LRU+TTL caches.
var subSource service.SubscriptionRepository = subRepo
if cfg.SubCacheSize > 0 && cfg.SubCacheTTL > 0 {
sc, err := readcache.NewSubscriptionCache(subRepo, cfg.SubCacheSize, cfg.SubCacheTTL)
if err != nil {
slog.Error("init subscription cache failed", "error", err)
os.Exit(1)
}
subSource = sc
slog.Info("subscription cache enabled", "size", cfg.SubCacheSize, "ttl", cfg.SubCacheTTL)
}
var roomSource service.RoomRepository = roomRepo
if cfg.RoomCacheSize > 0 && cfg.RoomCacheTTL > 0 {
rc, err := readcache.NewRoomCache(roomRepo, cfg.RoomCacheSize, cfg.RoomCacheTTL)
if err != nil {
slog.Error("init room cache failed", "error", err)
os.Exit(1)
}
roomSource = rc
slog.Info("room cache enabled", "size", cfg.RoomCacheSize, "ttl", cfg.RoomCacheTTL)
}
pub := publisher.New(js)
svc := service.New(cassRepo, subSource, roomSource, pub, threadRoomRepo, threadSubRepo, userStore, cachedEmojis, &cfg)
router := natsrouter.New(nc, "history-service")
router.Use(natsrouter.Recovery())
// RequestID must precede any handler that reads request_id from ctx —
// otherwise Classify's log line records an empty value.
router.Use(natsrouter.RequestID())
router.Use(natsrouter.Logging())
svc.RegisterHandlers(router, cfg.SiteID)
healthStop, err := health.ServeWithPprof(cfg.HealthAddr, 5*time.Second, cfg.PProfEnabled,
natsutil.HealthCheck(nc),
)
if err != nil {
slog.Error("health server failed to start", "error", err)
os.Exit(1)
}
// Bind synchronously so a port conflict fails startup loudly rather than
// running blind — /metrics exposes the cache hit-rate and atrest DEK counters.
metricsServer := otelutil.MetricsServer()
metricsLn, err := net.Listen("tcp", cfg.MetricsAddr)
if err != nil {
slog.Error("metrics listen failed", "addr", cfg.MetricsAddr, "error", err)
os.Exit(1)
}
go func() {
slog.Info("metrics server listening", "addr", cfg.MetricsAddr)
if err := metricsServer.Serve(metricsLn); err != nil && !errors.Is(err, http.ErrServerClosed) {
slog.Error("metrics server failed", "error", err)
}
}()
slog.Info("history-service running", "site", cfg.SiteID)
shutdown.Wait(ctx, 25*time.Second,
func(ctx context.Context) error { return router.Shutdown(ctx) },
// Stop /metrics late so Prometheus can scrape the final drain-window counts,
// then flush the meter provider.
func(ctx context.Context) error { return metricsServer.Shutdown(ctx) },
func(ctx context.Context) error { return nc.Drain() },
func(ctx context.Context) error { return tracerShutdown(ctx) },
func(ctx context.Context) error { return meterShutdown(ctx) },
func(ctx context.Context) error { mongoutil.Disconnect(ctx, mongoClient); return nil },
func(ctx context.Context) error { cassutil.Close(cassSession); return nil },
func(ctx context.Context) error {
if vaultWrapper != nil {
return vaultWrapper.Close()
}
return nil
},
func(ctx context.Context) error { return healthStop(ctx) },
)
}