mirror of
https://github.com/tdurieux/anonymous_github.git
synced 2026-12-02 17:13:33 +01:00
Complete queue diagnostics and validate current-main Go parity
This commit is contained in:
1 parent
116cbbaf66
commit
e85f7df752
16 files changed
+505
-20
No files matched your search
@@ -22,6 +22,7 @@ func TestVectorCollector(t *testing.T) {
|
||||
logger.Info("request", "requestId", "aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa", "route", "/api/repo/:id/file/:path", "status", 200, "ms", 42, "stages", map[string]float64{"upstream": 12})
|
||||
logger.With("service", "worker", "jobId", "bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb").Error("job failed", "queue", "download", "code", "quota_exceeded", "attempt", 2, "error", "secret-repository")
|
||||
logger.Info("process heartbeat", "rss", 123456, "memoryRatio", 0.25, "uptime", 30)
|
||||
logger.Info("queue heartbeat", "queue", "download", "waiting", 3, "active", 2, "delayed", 1, "failed", 4, "oldestWaitingMs", 60000)
|
||||
dir := t.TempDir()
|
||||
program, err := os.ReadFile("testdata/collector.vrl")
|
||||
if err != nil {
|
||||
@@ -46,7 +47,7 @@ func TestVectorCollector(t *testing.T) {
|
||||
t.Fatalf("%v: %s", err, output)
|
||||
}
|
||||
decoder := json.NewDecoder(bytes.NewReader(output))
|
||||
for i, event := range []string{"request_completed", "job_failed", "process_heartbeat"} {
|
||||
for i, event := range []string{"request_completed", "job_failed", "process_heartbeat", "queue_heartbeat"} {
|
||||
var row map[string]any
|
||||
var encoded string
|
||||
if err = decoder.Decode(&encoded); err == nil {
|
||||
@@ -64,6 +65,9 @@ func TestVectorCollector(t *testing.T) {
|
||||
if i == 1 && (row["service"] != "worker" || row["errorCode"] != "quota_exceeded" || row["severity"] != "error" || row["jobId"] == nil) {
|
||||
t.Fatal(row)
|
||||
}
|
||||
if i == 3 && (row["queue"] != "download" || row["waiting"] != float64(3) || row["oldestWaitingMs"] != float64(60000)) {
|
||||
t.Fatal(row)
|
||||
}
|
||||
if i == 2 && row["memoryRatio"] != 0.25 {
|
||||
t.Fatal(row)
|
||||
}
|
||||
|
||||
@@ -687,6 +687,7 @@
|
||||
"stage_cache_fill_ms",
|
||||
"stage_worker_wait_ms",
|
||||
"stage_anonymize_ms",
|
||||
"stage_streamer_headers_ms"
|
||||
"stage_streamer_headers_ms",
|
||||
"listenPort"
|
||||
]
|
||||
}
|
||||
@@ -29,6 +29,7 @@ type Config struct {
|
||||
AppID, AppClientID, AppClientSecret, AppCallback, AppSlug, AppPrivateKey, AppWebhookSecret string
|
||||
AppEnabled, AppNewConnections, OAuthEnabled, Download, SecureCookies bool
|
||||
CacheMonitoring bool
|
||||
DisableRedisLogMirror bool
|
||||
TrustedHops int
|
||||
RateLimit, Workers int
|
||||
Cipher *security.Cipher
|
||||
@@ -56,7 +57,7 @@ func envInt(key string, fallback int) int {
|
||||
return v
|
||||
}
|
||||
func LoadConfig() (Config, error) {
|
||||
c := Config{EmailAPIKey: os.Getenv("RESEND_API_KEY"), EmailFrom: os.Getenv("EMAIL_FROM"), CacheMonitoring: envBool("CACHE_MONITORING_ENABLED", true), Storage: env("STORAGE", "filesystem"), S3Bucket: os.Getenv("S3_BUCKET"), S3Region: os.Getenv("S3_REGION"), S3Endpoint: os.Getenv("S3_ENDPOINT"), S3ID: os.Getenv("S3_CLIENT_ID"), S3Secret: os.Getenv("S3_CLIENT_SECRET"), Address: ":" + env("PORT", "5000"), MongoURI: os.Getenv("MONGODB_URI"), Database: env("MONGODB_DATABASE", "production"), RedisAddress: net.JoinHostPort(env("REDIS_HOSTNAME", "redis"), env("REDIS_PORT", "6379")), SessionSecret: os.Getenv("SESSION_SECRET"), Root: env("FOLDER", "repositories"), PublicDir: env("PUBLIC_DIR", "public"), Hostname: env("APP_HOSTNAME", "localhost:5000"), Mask: env("ANONYMIZATION_MASK", "XXXX"), ClientID: os.Getenv("CLIENT_ID"), ClientSecret: os.Getenv("CLIENT_SECRET"), Callback: env("AUTH_CALLBACK", "http://localhost:5000/github/auth"), AppID: os.Getenv("GITHUB_APP_ID"), AppClientID: os.Getenv("GITHUB_APP_CLIENT_ID"), AppClientSecret: os.Getenv("GITHUB_APP_CLIENT_SECRET"), AppCallback: env("GITHUB_APP_CALLBACK", "http://localhost:5000/github/app/callback"), AppSlug: os.Getenv("GITHUB_APP_SLUG"), AppPrivateKey: os.Getenv("GITHUB_APP_PRIVATE_KEY"), AppWebhookSecret: os.Getenv("GITHUB_APP_WEBHOOK_SECRET"), AppEnabled: envBool("GITHUB_APP_ENABLED", false), AppNewConnections: envBool("GITHUB_APP_NEW_CONNECTIONS", true), OAuthEnabled: envBool("GITHUB_OAUTH_ENABLED", true), Download: envBool("ENABLE_DOWNLOAD", true), SecureCookies: envBool("COOKIE_SECURE", os.Getenv("NODE_ENV") == "production"), RateLimit: envInt("RATE_LIMIT", 1000), Workers: envInt("ANONYMIZATION_WORKERS", 1)}
|
||||
c := Config{DisableRedisLogMirror: os.Getenv("LOG_REDIS_MIRROR") == "off", EmailAPIKey: os.Getenv("RESEND_API_KEY"), EmailFrom: os.Getenv("EMAIL_FROM"), CacheMonitoring: envBool("CACHE_MONITORING_ENABLED", true), Storage: env("STORAGE", "filesystem"), S3Bucket: os.Getenv("S3_BUCKET"), S3Region: os.Getenv("S3_REGION"), S3Endpoint: os.Getenv("S3_ENDPOINT"), S3ID: os.Getenv("S3_CLIENT_ID"), S3Secret: os.Getenv("S3_CLIENT_SECRET"), Address: ":" + env("PORT", "5000"), MongoURI: os.Getenv("MONGODB_URI"), Database: env("MONGODB_DATABASE", "production"), RedisAddress: net.JoinHostPort(env("REDIS_HOSTNAME", "redis"), env("REDIS_PORT", "6379")), SessionSecret: os.Getenv("SESSION_SECRET"), Root: env("FOLDER", "repositories"), PublicDir: env("PUBLIC_DIR", "public"), Hostname: env("APP_HOSTNAME", "localhost:5000"), Mask: env("ANONYMIZATION_MASK", "XXXX"), ClientID: os.Getenv("CLIENT_ID"), ClientSecret: os.Getenv("CLIENT_SECRET"), Callback: env("AUTH_CALLBACK", "http://localhost:5000/github/auth"), AppID: os.Getenv("GITHUB_APP_ID"), AppClientID: os.Getenv("GITHUB_APP_CLIENT_ID"), AppClientSecret: os.Getenv("GITHUB_APP_CLIENT_SECRET"), AppCallback: env("GITHUB_APP_CALLBACK", "http://localhost:5000/github/app/callback"), AppSlug: os.Getenv("GITHUB_APP_SLUG"), AppPrivateKey: os.Getenv("GITHUB_APP_PRIVATE_KEY"), AppWebhookSecret: os.Getenv("GITHUB_APP_WEBHOOK_SECRET"), AppEnabled: envBool("GITHUB_APP_ENABLED", false), AppNewConnections: envBool("GITHUB_APP_NEW_CONNECTIONS", true), OAuthEnabled: envBool("GITHUB_OAUTH_ENABLED", true), Download: envBool("ENABLE_DOWNLOAD", true), SecureCookies: envBool("COOKIE_SECURE", os.Getenv("NODE_ENV") == "production"), RateLimit: envInt("RATE_LIMIT", 1000), Workers: envInt("ANONYMIZATION_WORKERS", 1)}
|
||||
if raw, ok := os.LookupEnv("REVIEW_SERVICE_KEYS"); ok {
|
||||
c.ReviewKeys = &raw
|
||||
}
|
||||
|
||||
@@ -85,6 +85,9 @@ func (s *Server) enqueueError(level, module, message, code string, status int, d
|
||||
if module != "requests" {
|
||||
slog.Log(context.Background(), severity, message, "module", module, "code", code, "httpStatus", status, "requestId", str(detail["requestId"]))
|
||||
}
|
||||
if s.Config.DisableRedisLogMirror {
|
||||
return
|
||||
}
|
||||
at := time.Now().UTC()
|
||||
bucket := errorBucket(status, level)
|
||||
data, err := json.Marshal(M{"ts": at, "module": module, "level": level, "message": message, "raw": []any{message, detail}})
|
||||
|
||||
@@ -139,6 +139,19 @@ func runErrorLogIntegration(t *testing.T, base *Server) {
|
||||
if ttl := client.TTL(ctx, hourly).Val(); ttl < 47*time.Hour || ttl > 48*time.Hour {
|
||||
t.Fatal(ttl)
|
||||
}
|
||||
// Disabling collection must retain previously recorded history and stop
|
||||
// both new entries and counters, while structured output remains independent.
|
||||
s.Config.DisableRedisLogMirror = true
|
||||
s.recordError(ctx, fail("upstream_error", 502))
|
||||
report, err = s.adminErrors(query("GET", "/api/admin/errors"))
|
||||
if err != nil || number(obj(report)["total"]) != 3 {
|
||||
t.Fatal("mirror opt-out erased or appended history", report, err)
|
||||
}
|
||||
stats, err = s.errorStats(query("GET", "/api/admin/errors/stats"))
|
||||
if err != nil || number(obj(stats)["last24h"]) != 5 {
|
||||
t.Fatal("disabled mirror changed counters", stats, err)
|
||||
}
|
||||
s.Config.DisableRedisLogMirror = false
|
||||
// Malformed legacy entries retain the TypeScript fallback shape.
|
||||
client.LPush(ctx, "admin:errors", "malformed legacy entry")
|
||||
report, err = s.adminErrors(query("GET", "/api/admin/errors?limit=1"))
|
||||
|
||||
@@ -131,6 +131,7 @@ func TestBackendIntegration(t *testing.T) {
|
||||
}
|
||||
t.Run("owner notification lifecycle", func(t *testing.T) { runOwnerAlertsIntegration(t, server) })
|
||||
t.Run("email delivery history", func(t *testing.T) { runEmailHistoryIntegration(t, server) })
|
||||
t.Run("queue heartbeat logging", func(t *testing.T) { runQueueHeartbeatIntegration(t, server) })
|
||||
t.Run("job structured logging", func(t *testing.T) { runJobLoggingIntegration(t, server) })
|
||||
t.Run("hosting quota jobs", func(t *testing.T) { runQuotaJobIntegration(t, server) })
|
||||
t.Run("billing lifecycle", func(t *testing.T) { runBillingIntegration(t, server) })
|
||||
|
||||
@@ -55,6 +55,7 @@ func (s *Server) RunJobs(ctx context.Context) {
|
||||
s.removalRecoveryPending.Store(true)
|
||||
s.recoverImportedRemovalJobs(ctx)
|
||||
var workers sync.WaitGroup
|
||||
workers.Go(func() { s.runQueueHeartbeats(ctx) })
|
||||
if s.Config.Billing.Enabled {
|
||||
workers.Go(func() { s.runBillingMaintenance(ctx) })
|
||||
}
|
||||
|
||||
@@ -32,6 +32,7 @@ func TestResourceStatusErrors(t *testing.T) {
|
||||
http int
|
||||
}{
|
||||
{"repo", "queue", "rate_limited:1790000000000", "rate_limited", 425},
|
||||
{"repo", "error", "", "repository_not_accessible", 500},
|
||||
{"repo", "error", "repository_access_revoked", "repository_access_revoked", 500},
|
||||
{"repo", "error", "repo_not_found", "repo_not_found", 404},
|
||||
{"repo", "error", "branch_not_found", "branch_not_found", 404},
|
||||
|
||||
@@ -0,0 +1,81 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"context"
|
||||
"log/slog"
|
||||
"time"
|
||||
)
|
||||
|
||||
// Sample independently of maintenance; a slow maintenance pass must not look
|
||||
// like a dead queue. Each sample is bounded and samples cannot overlap.
|
||||
func (s *Server) runQueueHeartbeats(ctx context.Context) {
|
||||
ticker := time.NewTicker(30 * time.Second)
|
||||
defer ticker.Stop()
|
||||
for {
|
||||
s.logQueueHeartbeat(ctx, time.Now())
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return
|
||||
case <-ticker.C:
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Server) logQueueHeartbeat(ctx context.Context, now time.Time) {
|
||||
rows, err := s.queueHeartbeat(ctx, now)
|
||||
if err != nil {
|
||||
return
|
||||
} // Missing heartbeats report an unavailable queue store.
|
||||
for _, row := range rows {
|
||||
slog.InfoContext(ctx, "queue heartbeat", "module", "queue", "queue", row["queue"], "waiting", row["waiting"], "active", row["active"], "delayed", row["delayed"], "failed", row["failed"], "oldestWaitingMs", row["oldestWaitingMs"])
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Server) queueHeartbeat(ctx context.Context, now time.Time) ([]M, error) {
|
||||
ctx, cancel := context.WithTimeout(ctx, 3*time.Second)
|
||||
defer cancel()
|
||||
// Go represents timed retries as waiting with a future availableAt. Report
|
||||
// those as delayed, matching the Node queue dashboard and alert semantics.
|
||||
state := M{"$cond": []any{M{"$and": []any{M{"$eq": []any{"$state", "waiting"}}, M{"$gt": []any{"$availableAt", now}}}}, "delayed", "$state"}}
|
||||
cursor, err := s.Store.DB.Collection("gojobs").Aggregate(ctx, []M{
|
||||
{"$match": M{"state": M{"$in": []string{"waiting", "active", "delayed", "failed"}}, "action": M{"$in": []string{"prepare", "cache", "remove", "expire"}}}},
|
||||
{"$group": M{"_id": M{"action": "$action", "state": state}, "count": M{"$sum": 1}, "oldest": M{"$min": "$createdAt"}}},
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer cursor.Close(ctx)
|
||||
groups := []M{}
|
||||
if err = cursor.All(ctx, &groups); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
rows := []M{}
|
||||
byName := map[string]M{}
|
||||
for _, queue := range workerQueues {
|
||||
row := M{"queue": queue.name, "waiting": int64(0), "active": int64(0), "delayed": int64(0), "failed": int64(0), "oldestWaitingMs": int64(0)}
|
||||
rows = append(rows, row)
|
||||
byName[queue.name] = row
|
||||
}
|
||||
for _, group := range groups {
|
||||
id := obj(group["_id"])
|
||||
queue := "download"
|
||||
switch str(id["action"]) {
|
||||
case "cache":
|
||||
queue = "cache"
|
||||
case "remove", "expire":
|
||||
queue = "remove"
|
||||
}
|
||||
row := byName[queue]
|
||||
state := str(id["state"])
|
||||
row[state] = number(row[state]) + number(group["count"])
|
||||
if state == "waiting" {
|
||||
if oldest, ok := storedDate(group["oldest"]); ok {
|
||||
age := now.Sub(oldest).Milliseconds()
|
||||
if age > number(row["oldestWaitingMs"]) {
|
||||
row["oldestWaitingMs"] = age
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return rows, nil
|
||||
}
|
||||
@@ -0,0 +1,91 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"log/slog"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/tdurieux/anonymous_github/backend/internal/logging"
|
||||
"go.mongodb.org/mongo-driver/v2/bson"
|
||||
)
|
||||
|
||||
func runQueueHeartbeatIntegration(t *testing.T, base *Server) {
|
||||
ctx := t.Context()
|
||||
db := base.Store.DB.Client().Database("queue_heartbeat_test_" + bson.NewObjectID().Hex())
|
||||
defer db.Drop(ctx)
|
||||
s := &Server{Store: &Store{DB: db, Redis: base.Store.Redis}}
|
||||
now := time.Now().Truncate(time.Millisecond)
|
||||
rows := []any{
|
||||
M{"action": "prepare", "state": "waiting", "createdAt": now.Add(-time.Minute), "availableAt": now, "resourceId": "private-repository"},
|
||||
M{"action": "prepare", "state": "waiting", "createdAt": now.Add(-time.Hour), "availableAt": now.Add(time.Minute)},
|
||||
M{"action": "prepare", "state": "active"}, M{"action": "prepare", "state": "failed"}, M{"action": "prepare", "state": "completed"},
|
||||
M{"action": "remove", "state": "waiting", "createdAt": now.Add(-time.Second)},
|
||||
M{"action": "expire", "state": "waiting", "createdAt": now.Add(-2 * time.Second)},
|
||||
M{"action": "cache", "state": "delayed"}, M{"action": "unknown", "state": "waiting"},
|
||||
}
|
||||
if _, err := db.Collection("gojobs").InsertMany(ctx, rows); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
previous := slog.Default()
|
||||
defer slog.SetDefault(previous)
|
||||
var output bytes.Buffer
|
||||
slog.SetDefault(slog.New(logging.New(&output, slog.LevelInfo, "")))
|
||||
s.logQueueHeartbeat(ctx, now)
|
||||
lines := strings.Split(strings.TrimSpace(output.String()), "\n")
|
||||
if len(lines) != 3 {
|
||||
t.Fatal(output.String())
|
||||
}
|
||||
counts := map[string]M{}
|
||||
for _, line := range lines {
|
||||
row := M{}
|
||||
if err := json.Unmarshal([]byte(line), &row); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
counts[str(row["queue"])] = row
|
||||
if row["event"] != "queue_heartbeat" {
|
||||
t.Fatal(row)
|
||||
}
|
||||
}
|
||||
download := counts["download"]
|
||||
for _, key := range []string{"waiting", "active", "delayed", "failed"} {
|
||||
if number(download[key]) != 1 {
|
||||
t.Fatal(download)
|
||||
}
|
||||
}
|
||||
if number(download["oldestWaitingMs"]) != 60000 || number(counts["remove"]["oldestWaitingMs"]) != 2000 || number(counts["remove"]["waiting"]) != 2 || number(counts["cache"]["delayed"]) != 1 {
|
||||
t.Fatal(counts)
|
||||
}
|
||||
if strings.Contains(output.String(), "private") {
|
||||
t.Fatal(output.String())
|
||||
}
|
||||
output.Reset()
|
||||
cancelled, cancel := context.WithCancel(ctx)
|
||||
cancel()
|
||||
s.logQueueHeartbeat(cancelled, now)
|
||||
if output.Len() != 0 {
|
||||
t.Fatal("database failure emitted a healthy heartbeat", output.String())
|
||||
}
|
||||
if _, err := db.Collection("gojobs").DeleteMany(ctx, M{}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
s.logQueueHeartbeat(ctx, now)
|
||||
lines = strings.Split(strings.TrimSpace(output.String()), "\n")
|
||||
if len(lines) != 3 {
|
||||
t.Fatal("empty queues must still report heartbeats", output.String())
|
||||
}
|
||||
for _, line := range lines {
|
||||
row := M{}
|
||||
if err := json.Unmarshal([]byte(line), &row); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, key := range []string{"waiting", "active", "delayed", "failed", "oldestWaitingMs"} {
|
||||
if number(row[key]) != 0 {
|
||||
t.Fatal(row)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -90,7 +90,7 @@ func (s *Server) checkResource(ctx context.Context, kind string, r M) error {
|
||||
}
|
||||
}
|
||||
if kind == "repo" {
|
||||
return fail(code, repositoryFailureStatus(code))
|
||||
return fail(code, repositoryFailureStatus(str(r["statusMessage"])))
|
||||
}
|
||||
return fail(code, 500)
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user