summaryrefslogtreecommitdiffstats
path: root/cmd/relay/main.go
blob: 8948ebf2e52f1d1877b5c342dcca33c628f6c2c6 (plain)
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
package main

import (
	"context"
	"flag"
	"log"
	"net"
	"net/http"
	"os"
	"os/signal"
	"syscall"
	"time"

	"connectrpc.com/connect"
	"golang.org/x/net/http2"
	"golang.org/x/net/http2/h2c"
	"google.golang.org/grpc"

	pb "northwest.io/muxstr/api/nostr/v1"
	"northwest.io/muxstr/api/nostr/v1/nostrv1connect"
	"northwest.io/muxstr/internal/auth"
	"northwest.io/muxstr/internal/config"
	connecthandler "northwest.io/muxstr/internal/handler/connect"
	grpchandler "northwest.io/muxstr/internal/handler/grpc"
	wshandler "northwest.io/muxstr/internal/handler/websocket"
	"northwest.io/muxstr/internal/metrics"
	"northwest.io/muxstr/internal/ratelimit"
	"northwest.io/muxstr/internal/storage"
	"northwest.io/muxstr/internal/subscription"
)

func main() {
	configFile := flag.String("config", "", "Path to config file (optional)")
	flag.Parse()

	cfg, err := config.Load(*configFile)
	if err != nil {
		log.Fatalf("failed to load config: %v", err)
	}

	store, err := storage.New(cfg.Database.Path)
	if err != nil {
		log.Fatalf("failed to create storage: %v", err)
	}
	defer store.Close()

	subManager := subscription.NewManager()

	grpcHandler := grpchandler.NewServer(store)
	grpcHandler.SetSubscriptionManager(subManager)

	connectHandler := connecthandler.NewHandler(grpcHandler)

	mux := http.NewServeMux()
	path, handler := nostrv1connect.NewNostrRelayHandler(connectHandler, connect.WithInterceptors())
	mux.Handle(path, handler)

	var unaryInterceptors []grpc.UnaryServerInterceptor
	var streamInterceptors []grpc.StreamServerInterceptor

	var m *metrics.Metrics
	if cfg.Metrics.Enabled {
		m = metrics.New(cfg.Metrics.ToMetrics())
		unaryInterceptors = append(unaryInterceptors, metrics.UnaryServerInterceptor(m))
		streamInterceptors = append(streamInterceptors, metrics.StreamServerInterceptor(m))

		mux.Handle("/metrics", m.PrometheusHandler())
		mux.Handle("/dashboard", m.DashboardHandler())
	}

	if cfg.Auth.Read.Enabled || cfg.Auth.Write.Enabled {
		authOpts := &auth.InterceptorOptions{
			Read:            cfg.Auth.Read,
			Write:           cfg.Auth.Write,
			TimestampWindow: cfg.Auth.TimestampWindow,
			SkipMethods:     cfg.Auth.SkipMethods,
		}
		unaryInterceptors = append(unaryInterceptors, auth.NostrUnaryInterceptor(authOpts))
		streamInterceptors = append(streamInterceptors, auth.NostrStreamInterceptor(authOpts))
	}

	if cfg.RateLimit.Enabled {
		limiter := ratelimit.New(cfg.RateLimit.ToRateLimiter())
		unaryInterceptors = append(unaryInterceptors, ratelimit.UnaryInterceptor(limiter))
		streamInterceptors = append(streamInterceptors, ratelimit.StreamInterceptor(limiter))
	}

	var serverOpts []grpc.ServerOption
	if len(unaryInterceptors) > 0 {
		serverOpts = append(serverOpts, grpc.ChainUnaryInterceptor(unaryInterceptors...))
	}
	if len(streamInterceptors) > 0 {
		serverOpts = append(serverOpts, grpc.ChainStreamInterceptor(streamInterceptors...))
	}

	wsHandler := wshandler.NewHandler(store, subManager)
	if m != nil {
		wsHandler.SetMetrics(m)

		// Update storage stats periodically
		go func() {
			ticker := time.NewTicker(30 * time.Second)
			defer ticker.Stop()

			// Update immediately on start
			if stats, err := store.GetStats(context.Background()); err == nil {
				m.UpdateStorageStats(stats.EventCount, stats.DBSizeBytes)
			}

			for range ticker.C {
				if stats, err := store.GetStats(context.Background()); err == nil {
					m.UpdateStorageStats(stats.EventCount, stats.DBSizeBytes)
				}
			}
		}()
	}

	var grpcDisplay, httpDisplay, wsDisplay string
	if cfg.Server.PublicURL != "" {
		grpcDisplay = cfg.Server.PublicURL + ":443"
		httpDisplay = "https://" + cfg.Server.PublicURL
		wsDisplay = "wss://" + cfg.Server.PublicURL
	} else {
		grpcDisplay = cfg.Server.GrpcAddr
		httpDisplay = "http://" + cfg.Server.HttpAddr
		wsDisplay = "ws://" + cfg.Server.HttpAddr
	}
	wsHandler.SetIndexData(grpcDisplay, httpDisplay, wsDisplay)
	mux.Handle("/", wsHandler)

	grpcLis, err := net.Listen("tcp", cfg.Server.GrpcAddr)
	if err != nil {
		log.Fatalf("failed to listen on gRPC port: %v", err)
	}

	grpcServer := grpc.NewServer(serverOpts...)
	pb.RegisterNostrRelayServer(grpcServer, grpcHandler)

	httpServer := &http.Server{
		Addr:         cfg.Server.HttpAddr,
		Handler:      h2c.NewHandler(mux, &http2.Server{}),
		ReadTimeout:  cfg.Server.ReadTimeout,
		WriteTimeout: cfg.Server.WriteTimeout,
	}

	log.Printf("gRPC server listening on %s", cfg.Server.GrpcAddr)
	log.Printf("HTTP server listening on %s", cfg.Server.HttpAddr)
	log.Printf("  - Connect (gRPC-Web) at %s/nostr.v1.NostrRelay/*", cfg.Server.HttpAddr)
	log.Printf("  - WebSocket (Nostr) at %s/", cfg.Server.HttpAddr)
	if cfg.Metrics.Enabled {
		log.Printf("  - Metrics dashboard at %s/dashboard", cfg.Server.HttpAddr)
		log.Printf("  - Prometheus metrics at %s/metrics", cfg.Server.HttpAddr)
	}
	log.Printf("Database: %s", cfg.Database.Path)
	if cfg.Auth.Read.Enabled || cfg.Auth.Write.Enabled {
		log.Printf("Auth: enabled (read=%v write=%v)", cfg.Auth.Read.Enabled, cfg.Auth.Write.Enabled)
	}
	if cfg.RateLimit.Enabled {
		log.Printf("Rate limiting: enabled")
	}

	sigChan := make(chan os.Signal, 1)
	signal.Notify(sigChan, os.Interrupt, syscall.SIGTERM)

	go func() {
		<-sigChan
		log.Println("Shutting down...")
		grpcServer.GracefulStop()
		httpServer.Shutdown(context.Background())
	}()

	go func() {
		if err := grpcServer.Serve(grpcLis); err != nil {
			log.Fatalf("gRPC server failed: %v", err)
		}
	}()

	if err := httpServer.ListenAndServe(); err != nil && err != http.ErrServerClosed {
		log.Fatalf("WebSocket server failed: %v", err)
	}
}