Skip to content
File

Blob: config/sync.go

go342 lines
1package config
2 
3import (
4 "context"
5 "crypto/sha256"
6 "math/rand"
7 "net"
8 "net/http"
9 "net/http/httptrace"
10 "sync"
11 "time"
12 
13 "go.miragespace.co/specter/spec/protocol"
14 "go.miragespace.co/specter/spec/rpc"
15 "go.miragespace.co/specter/spec/transport"
16 "go.miragespace.co/specter/util"
17 "go.miragespace.co/specter/util/acceptor"
18 
19 "github.com/twitchtv/twirp"
20 "go.uber.org/zap"
21)
22 
23const (
24 // One protobuf bytes field adds a tag and at most four length bytes.
25 maxSyncBytes = MaxSnapshotBytes + 5
26 maxParallelSyncs = 4
27)
28 
29// Syncer exchanges complete configuration snapshots along the existing Chord
30// peer graph. It neither discovers fleet membership nor assigns key ownership.
31// Each physical server has one Syncer, regardless of its virtual node count.
32type Syncer struct {
33 store *Store
34 transport transport.Transport
35 peers func() []*protocol.Node
36 logger *zap.Logger
37 incoming chan struct{}
38 handling chan struct{}
39 wake chan struct{}
40 receipts map[string]*syncReceipt
41 interval time.Duration
42 timeout time.Duration
43}
44 
45// A physical connection acknowledges only the snapshot sent on it. A failed
46// attempt retains its digest and retry time so unrelated wakeups cannot spin.
47// The serial synchronization rounds own these receipts; none are persisted.
48type syncReceipt struct {
49 digest [sha256.Size]byte
50 physical transport.PhysicalConn
51 retryAt time.Time
52}
53 
54// NewSyncer takes the authenticated Chord transport and a source of peer graph
55// edges. Include the successors of every local virtual node as well as current
56// connections: a connection cache alone is not a membership view. Addresses are
57// deduplicated before dialing so multiple virtual nodes share one exchange.
58func NewSyncer(store *Store, chordTransport transport.Transport, peers func() []*protocol.Node, logger *zap.Logger) *Syncer {
59 if logger == nil {
60 logger = zap.NewNop()
61 }
62 return &Syncer{
63 store: store,
64 transport: chordTransport,
65 peers: peers,
66 logger: logger,
67 incoming: make(chan struct{}, maxParallelSyncs),
68 handling: make(chan struct{}, maxParallelSyncs),
69 wake: make(chan struct{}, 1),
70 receipts: make(map[string]*syncReceipt),
71 interval: 15 * time.Second,
72 timeout: transport.ConnectTimeout,
73 }
74}
75 
76// Bind registers only on the mutually authenticated Chord side of the router.
77// It must be called before the router starts accepting streams. No handler is
78// exposed to the tunnel transport or the unauthenticated local RPC listener.
79func (s *Syncer) Bind(ctx context.Context, router *transport.StreamRouter) {
80 listener := acceptor.NewH2Acceptor(nil)
81 srv := &http.Server{
82 BaseContext: func(net.Listener) context.Context { return ctx },
83 Handler: s.rpcHandler(),
84 MaxHeaderBytes: 1 << 10,
85 ReadHeaderTimeout: s.timeout,
86 ReadTimeout: s.timeout,
87 WriteTimeout: s.timeout,
88 ErrorLog: util.GetStdLogger(s.logger, "config_rpc"),
89 }
90 srv.SetKeepAlivesEnabled(false)
91 go srv.Serve(listener)
92 context.AfterFunc(ctx, func() { srv.Close() })
93 
94 router.HandleChord(protocol.Stream_CONFIG, nil, func(delegate *transport.StreamDelegate) {
95 if ctx.Err() != nil {
96 delegate.Close()
97 return
98 }
99 select {
100 case s.incoming <- struct{}{}:
101 default:
102 delegate.Close()
103 return
104 }
105 streamCtx, cancel := context.WithTimeout(ctx, s.timeout)
106 conn := &syncConn{StreamDelegate: delegate, closed: func() {
107 cancel()
108 <-s.incoming
109 }}
110 // HTTP may reset I/O deadlines. This timer bounds the entire stream,
111 // including time queued for acceptance, request decoding, and replies.
112 context.AfterFunc(streamCtx, func() { conn.Close() })
113 listener.Handle(conn)
114 })
115}
116 
117// syncConn keeps the admission slot until HTTP has finished using the stream.
118type syncConn struct {
119 *transport.StreamDelegate
120 once sync.Once
121 closed func()
122}
123 
124func (c *syncConn) Close() (err error) {
125 c.once.Do(func() {
126 err = c.StreamDelegate.Close()
127 c.closed()
128 })
129 return err
130}
131 
132func (s *Syncer) rpcHandler() http.Handler {
133 handler := protocol.NewConfigServiceServer(s, twirp.WithServerHooks(&twirp.ServerHooks{
134 Error: func(ctx context.Context, err twirp.Error) context.Context {
135 if ctx.Err() == nil {
136 s.logger.Debug("Shared configuration exchange failed", zap.Error(err))
137 }
138 return ctx
139 },
140 }))
141 bounded := util.LimitBody(maxSyncBytes)(handler)
142 return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
143 // Peers use the protobuf client. Excluding the optional JSON encoding
144 // keeps base64 expansion from increasing the response's wire bound.
145 if r.Header.Get("Content-Type") != "application/protobuf" {
146 twirp.WriteError(w, twirp.Malformed.Error("configuration exchange requires application/protobuf"))
147 return
148 }
149 // Closing a timed-out stream cannot interrupt SQLite or a store mutex
150 // wait. Keep decoded request work bounded until its handler returns.
151 select {
152 case s.handling <- struct{}{}:
153 defer func() { <-s.handling }()
154 default:
155 twirp.WriteError(w, twirp.ResourceExhausted.Error("configuration exchanges are busy"))
156 return
157 }
158 bounded.ServeHTTP(w, r)
159 })
160}
161 
162// Wake requests a local state check without waiting for the periodic check.
163// Repeated requests coalesce, and unchanged, acknowledged state stays quiet.
164func (s *Syncer) Wake() {
165 select {
166 case s.wake <- struct{}{}:
167 default:
168 }
169}
170 
171// Run checks local state and peer connections at startup and periodically. The
172// periodic read also observes writes by other processes and uncertain commits.
173// Only pending snapshots are exchanged. Cancellation waits for outgoing work.
174func (s *Syncer) Run(ctx context.Context) {
175 s.receipts = make(map[string]*syncReceipt)
176 ticker := time.NewTicker(s.interval)
177 defer ticker.Stop()
178 for ctx.Err() == nil {
179 s.sync(ctx)
180 select {
181 case <-ctx.Done():
182 return
183 case <-ticker.C:
184 case <-s.wake:
185 }
186 }
187}
188 
189func (s *Syncer) sync(ctx context.Context) {
190 request, err := s.snapshot()
191 if err != nil {
192 if ctx.Err() == nil {
193 s.logger.Debug("Could not read shared configuration for synchronization", zap.Error(err))
194 }
195 return
196 }
197 digest := sha256.Sum256(request.GetData())
198 connected := make(map[string]transport.PhysicalConn)
199 for _, peer := range s.transport.ListConnected() {
200 connected[peer.Identity.GetAddress()] = peer.Physical
201 }
202 seen := map[string]bool{s.transport.Identity().GetAddress(): true, "": true}
203 var addresses []string
204 for _, peer := range s.peers() {
205 address := peer.GetAddress()
206 if seen[address] {
207 continue
208 }
209 seen[address] = true
210 addresses = append(addresses, address)
211 }
212 // Avoid consistently filling the outgoing slots with the same address prefix.
213 rand.Shuffle(len(addresses), func(i, j int) {
214 addresses[i], addresses[j] = addresses[j], addresses[i]
215 })
216 active := make(chan struct{}, maxParallelSyncs)
217 var wg sync.WaitGroup
218 defer wg.Wait()
219 for _, address := range addresses {
220 receipt := s.receipts[address]
221 if receipt == nil {
222 receipt = &syncReceipt{}
223 s.receipts[address] = receipt
224 }
225 if receipt.physical != nil {
226 if receipt.physical != connected[address] {
227 receipt.physical = nil
228 } else {
229 select {
230 case <-receipt.physical.Done():
231 receipt.physical = nil
232 default:
233 }
234 }
235 }
236 if receipt.digest == digest && (receipt.physical != nil || time.Now().Before(receipt.retryAt)) {
237 continue
238 }
239 select {
240 case <-ctx.Done():
241 return
242 case active <- struct{}{}:
243 }
244 wg.Go(func() {
245 defer func() { <-active }()
246 // CONFIG is physical: a virtual node ID is neither required nor
247 // allowed to create an independent configuration replica.
248 peer := &protocol.Node{Address: address}
249 physical, err := s.exchange(ctx, peer, request)
250 // A response may have advanced SQLite, or a writer may have saved
251 // while this request was in flight. Neither acknowledges that newer
252 // state: record only the immutable snapshot sent by this round.
253 receipt.digest = digest
254 receipt.physical = physical
255 receipt.retryAt = time.Now().Add(s.interval)
256 if err != nil && ctx.Err() == nil {
257 s.logger.Debug("Could not synchronize shared configuration", zap.Object("peer", peer), zap.Error(err))
258 }
259 })
260 }
261 for address := range s.receipts {
262 if !seen[address] {
263 delete(s.receipts, address)
264 }
265 }
266}
267 
268func (s *Syncer) exchange(ctx context.Context, peer *protocol.Node, request *protocol.ConfigSnapshot) (transport.PhysicalConn, error) {
269 ctx, cancel := context.WithTimeout(ctx, s.timeout)
270 defer cancel()
271 var physical transport.PhysicalConn
272 var physicalMu sync.Mutex
273 ctx = httptrace.WithClientTrace(ctx, &httptrace.ClientTrace{
274 GotConn: func(info httptrace.GotConnInfo) {
275 var used transport.PhysicalConn
276 if provider, ok := info.Conn.(transport.PhysicalConnProvider); ok {
277 used = provider.PhysicalConn()
278 }
279 physicalMu.Lock()
280 physical = used
281 physicalMu.Unlock()
282 },
283 })
284 // Each exchange owns one HTTP connection and its dial context. QUIC still
285 // reuses the physical peer connection underneath the individual stream.
286 httpTransport := &http.Transport{
287 DialTLSContext: rpc.StreamDialer(ctx, s.transport, protocol.Stream_CONFIG),
288 DisableKeepAlives: true,
289 DisableCompression: true,
290 MaxResponseHeaderBytes: 1 << 10,
291 }
292 defer httpTransport.CloseIdleConnections()
293 client := protocol.NewConfigServiceProtobufClient("https://"+peer.GetAddress(), boundedClient(&http.Client{
294 Transport: httpTransport,
295 }, maxSyncBytes))
296 response, err := client.Exchange(rpc.WithNode(ctx, peer), request)
297 if err != nil {
298 return nil, err
299 }
300 records, err := DecodeSnapshot(response.GetData())
301 if err != nil {
302 return nil, err
303 }
304 if err := s.store.Merge(records); err != nil {
305 return nil, err
306 }
307 s.Wake()
308 physicalMu.Lock()
309 defer physicalMu.Unlock()
310 return physical, nil
311}
312 
313func (s *Syncer) snapshot() (*protocol.ConfigSnapshot, error) {
314 records, err := s.store.Snapshot()
315 if err != nil {
316 return nil, err
317 }
318 data, err := EncodeSnapshot(records)
319 if err != nil {
320 return nil, err
321 }
322 return &protocol.ConfigSnapshot{Data: data}, nil
323}
324 
325// Exchange merges a peer's complete snapshot before returning the observed local
326// snapshot. Namespace-specific payloads stay opaque to both sides of the RPC.
327func (s *Syncer) Exchange(_ context.Context, request *protocol.ConfigSnapshot) (*protocol.ConfigSnapshot, error) {
328 records, err := DecodeSnapshot(request.GetData())
329 if err != nil {
330 return nil, twirp.InvalidArgument.Error(err.Error())
331 }
332 if err := s.store.Merge(records); err != nil {
333 return nil, twirp.InternalErrorWith(err)
334 }
335 s.Wake()
336 response, err := s.snapshot()
337 if err != nil {
338 return nil, twirp.InternalErrorWith(err)
339 }
340 return response, nil
341}