-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcoordinator.go
More file actions
1443 lines (1241 loc) · 47.3 KB
/
coordinator.go
File metadata and controls
1443 lines (1241 loc) · 47.3 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
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package sync
import (
"context"
"fmt"
"os"
"os/signal"
"path/filepath"
"strings"
"syscall"
"time"
"go.uber.org/zap"
"github.com/fatih/color"
"github.com/sqlrsync/sqlrsync.com/auth"
"github.com/sqlrsync/sqlrsync.com/bridge"
"github.com/sqlrsync/sqlrsync.com/remote"
"github.com/sqlrsync/sqlrsync.com/subscription"
"github.com/sqlrsync/sqlrsync.com/watcher"
)
// Operation represents a sync operation type
type Operation int
const (
OperationPull Operation = iota
OperationPush
OperationPullSubscribe
OperationPushSubscribe
OperationLocalSync
)
// CoordinatorConfig holds sync coordinator configuration
type CoordinatorConfig struct {
ServerURL string
ProvidedAuthKey string // Explicitly provided auth key
ProvidedPullKey string // Explicitly provided pull key
ProvidedPushKey string // Explicitly provided push key
ProvidedReplicaID string // Explicitly provided replica ID
LocalPath string
RemotePath string
ReplicaPath string // For LOCAL TO LOCAL sync
Version string
Operation Operation
SetVisibility int
CommitMessage []byte
DryRun bool
Logger *zap.Logger
Verbose bool
WsID string // Websocket ID for client identification
ClientVersion string // version of the client software
Subscribing bool
WaitIdle string
MaxInterval string
MinInterval string
AutoMerge bool
}
// Coordinator manages sync operations and subscriptions
type Coordinator struct {
config *CoordinatorConfig
logger *zap.Logger
authResolver *auth.Resolver
subManager *subscription.Manager
remoteClient *remote.Client // For PUSH subscription mode
ctx context.Context
cancel context.CancelFunc
sessionStarted bool // Flag to track if we've sent initial SQLRSYNC_CHANGED for this session
lastChangedSent time.Time // Track when we last sent SQLRSYNC_CHANGED
resendTimer *time.Timer // Timer for resending SQLRSYNC_CHANGED 10s before expiration
}
// NewCoordinator creates a new sync coordinator
func NewCoordinator(config *CoordinatorConfig) *Coordinator {
ctx, cancel := context.WithCancel(context.Background())
return &Coordinator{
config: config,
logger: config.Logger,
authResolver: auth.NewResolver(config.Logger),
ctx: ctx,
cancel: cancel,
}
}
// Execute runs the sync operation
func (c *Coordinator) Execute() error {
// Set up signal handling for graceful shutdown
sigChan := make(chan os.Signal, 1)
signal.Notify(sigChan, os.Interrupt, syscall.SIGTERM)
go func() {
<-sigChan
fmt.Println("\nShutting down...")
c.cancel()
// Force exit after 2 seconds if graceful shutdown fails
go func() {
time.Sleep(2 * time.Second)
fmt.Println("Force exiting...")
os.Exit(0)
}()
}()
switch c.config.Operation {
case OperationPull:
return c.executePull(false)
case OperationPush:
return c.executePush()
case OperationPullSubscribe:
return c.executePullSubscribe()
case OperationPushSubscribe:
return c.executePushSubscribe()
case OperationLocalSync:
return c.executeLocalSync()
default:
return fmt.Errorf("unknown operation")
}
}
// displayDryRunInfo displays dry run information for different operations
func (c *Coordinator) displayDryRunInfo(operation string, authResult *auth.ResolveResult, absLocalPath, serverURL, remotePath, localHostname string) {
fmt.Println("SQLRsync Dry Run:")
switch operation {
case "push":
fmt.Printf(" - Mode: %s the LOCAL ORIGIN file up to the REMOTE REPLICA\n", color.YellowString("PUSHing"))
fmt.Printf(" - LOCAL ORIGIN: %s\n", color.GreenString(absLocalPath))
if remotePath == "" {
fmt.Println(" - REMOTE REPLICA: " + color.YellowString("(None - the server will assign a path using this hostname)"))
fmt.Printf(" - Hostname: %s\n", color.GreenString(localHostname))
} else {
fmt.Printf(" - REMOTE REPLICA: %s\n", color.GreenString(remotePath))
}
case "pull":
fmt.Printf(" - Mode: %s the REMOTE ORIGIN file down to LOCAL REPLICA\n", color.YellowString("PULLing"))
fmt.Printf(" - REMOTE ORIGIN: %s\n", color.GreenString(remotePath))
fmt.Printf(" - LOCAL REPLICA: %s\n", color.GreenString(absLocalPath))
case "subscribe":
fmt.Printf(" - Mode: %s to REMOTE ORIGIN to PULL down current and future updates\n", color.YellowString("SUBSCRIBing"))
fmt.Printf(" - REMOTE ORIGIN: %s\n", color.GreenString(remotePath))
fmt.Printf(" - LOCAL REPLICA: %s\n", color.GreenString(absLocalPath))
case "local":
fmt.Printf(" - Mode: %s between two databases\n", color.YellowString("LOCAL ONLY"))
}
if operation != "local" {
fmt.Printf(" - Server: %s\n", color.GreenString(serverURL))
if authResult.AccessKey != "" {
fmt.Printf(" - Access Key: %s\n", color.GreenString(authResult.AccessKey))
} else {
fmt.Printf(" - Access Key: %s\n", color.YellowString("(none)"))
}
if operation == "push" {
switch c.config.SetVisibility {
case 0:
fmt.Println(" - Visibility: " + color.YellowString("PRIVATE") + " (only accessible with access key)")
case 1:
fmt.Println(" - Visibility: " + color.YellowString("UNLISTED") + " (anyone with the link can access)")
case 2:
fmt.Println(" - Visibility: " + color.GreenString("PUBLIC") + " (anyone can access)")
}
}
if c.authResolver.CheckNeedsDashFile(c.config.LocalPath, remotePath) {
fmt.Println(" - A shareable config (the -sqlrsync file) " + color.GreenString("WILL BE") + " created for future PULLs and SUBSCRIBEs")
} else {
fmt.Println(" - A shareable config (the -sqlrsync file) will " + color.RedString("NOT") + " be created")
}
} else {
// For local sync, show the replica path
if c.config.ReplicaPath != "" {
absReplicaPath, _ := filepath.Abs(c.config.ReplicaPath)
fmt.Printf(" - LOCAL ORIGIN: %s\n", color.GreenString(absLocalPath))
fmt.Printf(" - LOCAL REPLICA: %s\n", color.GreenString(absReplicaPath))
}
}
fmt.Println("\nAfter running this command, REPLICA will become a copy of ORIGIN at the moment the command begins.")
}
// resolveAuth resolves authentication for the given operation
func (c *Coordinator) resolveAuth(operation string) (*auth.ResolveResult, error) {
req := &auth.ResolveRequest{
LocalPath: c.config.LocalPath,
RemotePath: c.config.RemotePath,
ServerURL: c.config.ServerURL,
ProvidedPullKey: c.config.ProvidedPullKey,
ProvidedPushKey: c.config.ProvidedPushKey,
ProvidedReplicaID: c.config.ProvidedReplicaID,
Operation: operation,
Logger: c.logger,
}
// Try explicit auth key first
if c.config.ProvidedAuthKey != "" {
return &auth.ResolveResult{
AccessKey: c.config.ProvidedAuthKey,
ReplicaID: c.config.ProvidedReplicaID,
ServerURL: c.config.ServerURL,
RemotePath: c.config.RemotePath,
LocalPath: c.config.LocalPath,
}, nil
}
result, err := c.authResolver.Resolve(req)
if err != nil {
return nil, err
}
// If prompting is needed for push operations
if result.ShouldPrompt || (operation == "push" && result.AccessKey == "") {
key, err := c.authResolver.PromptForKey(c.config.ServerURL, c.config.RemotePath, "PUSH")
if err != nil {
return nil, err
}
result.AccessKey = key
result.ShouldPrompt = false
}
return result, nil
}
// executePullSubscribe runs pull sync with subscription for new versions
func (c *Coordinator) executePullSubscribe() error {
fmt.Println("📡 PULL Subscribe mode enabled - will watch for new versions...")
fmt.Println("📡 Subscribe mode enabled - will watch for new versions...")
fmt.Println(" Press Ctrl+C to stop watching...")
// Resolve authentication for subscription
authResult, err := c.resolveAuth("subscribe")
if err != nil {
return fmt.Errorf("authentication failed: %w", err)
}
// Check for dry run mode
if c.config.DryRun {
absLocalPath, err := filepath.Abs(c.config.LocalPath)
if err != nil {
return fmt.Errorf("failed to get absolute path: %w", err)
}
localHostname, _ := os.Hostname()
serverURL := authResult.ServerURL
if c.config.ServerURL != "" && c.config.ServerURL != "wss://sqlrsync.com" {
serverURL = c.config.ServerURL
}
remotePath := authResult.RemotePath
if c.config.RemotePath != "" {
remotePath = c.config.RemotePath
}
c.displayDryRunInfo("subscribe", authResult, absLocalPath, serverURL, remotePath, localHostname)
return nil
}
// Create subscription manager with reconnection configuration
c.subManager = subscription.NewManager(&subscription.ManagerConfig{
ServerURL: authResult.ServerURL,
ReplicaPath: authResult.RemotePath,
AccessKey: authResult.AccessKey,
ReplicaID: authResult.ReplicaID,
WsID: c.config.WsID,
ClientVersion: c.config.ClientVersion,
Logger: c.logger.Named("subscription"),
MaxReconnectAttempts: 20, // Infinite reconnect attempts
InitialReconnectDelay: 5 * time.Second, // Start with 5 seconds delay
MaxReconnectDelay: 5 * time.Minute, // Cap at 5 minutes
})
c.logger.Info("Starting subscription service", zap.String("server", authResult.ServerURL))
// Connect to subscription service
if err := c.subManager.Connect(); err != nil {
return fmt.Errorf("failed to connect to subscription service2: %w", err)
}
defer c.subManager.Close()
syncCount := 0
for {
syncCount++
fmt.Printf("🔄 Starting sync...\n")
// Perform pull sync
if err := c.executePull(true); err != nil {
c.logger.Error("Sync failed", zap.Error(err), zap.Int("syncCount", syncCount))
return fmt.Errorf("sync #%d failed: %w", syncCount, err)
}
fmt.Printf("✅ Sync completed at %s. Waiting for new version...\n", time.Now().Format(time.RFC3339))
// Wait for new version or shutdown
select {
case <-c.ctx.Done():
fmt.Println("Subscription stopped by user.")
return nil
default:
}
// PULL (read only) Subscribe: Wait for new version notification
for {
if err := c.waitForVersionAndPull(false); err != nil {
// Check if this is a cancellation or reconnection failure (both are terminal)
if strings.Contains(err.Error(), "cancelled") || strings.Contains(err.Error(), "reconnection failed") {
return err
}
// For other errors, continue the loop to try again
continue
}
// Successfully got and processed a new version, break out of version wait loop
break
}
}
}
// executePull performs a single pull sync operation
func (c *Coordinator) executePull(isSubscription bool) error {
// Resolve authentication
authResult, err := c.resolveAuth("pull")
if err != nil {
return fmt.Errorf("authentication failed: %w", err)
}
version := c.config.Version
if version == "" {
version = "latest"
}
// Use resolved values, with config overrides
serverURL := authResult.ServerURL
// Only override if user explicitly provided a different server (not just using the default)
if c.config.ServerURL != "" && c.config.ServerURL != "wss://sqlrsync.com" {
serverURL = c.config.ServerURL
}
remotePath := authResult.RemotePath
if c.config.RemotePath != "" {
remotePath = c.config.RemotePath
}
// Get absolute path and hostname for dry run display
absLocalPath, err := filepath.Abs(c.config.LocalPath)
if err != nil {
return fmt.Errorf("failed to get absolute path: %w", err)
}
localHostname, _ := os.Hostname()
if c.config.DryRun {
c.displayDryRunInfo("pull", authResult, absLocalPath, serverURL, remotePath, localHostname)
return nil
}
if !isSubscription {
fmt.Printf("PULLing down from %s/%s@%s ...\n", serverURL, remotePath, version)
}
// Create remote client for WebSocket transport
remoteClient, err := remote.New(&remote.Config{
ServerURL: serverURL + "/sapi/pull/" + remotePath,
AuthKey: authResult.AccessKey,
ReplicaID: authResult.ReplicaID,
Timeout: 8000,
PingPong: false, // No ping/pong needed for single sync
Logger: c.logger.Named("remote"),
Subscribe: false, // Subscription handled separately
EnableTrafficInspection: c.config.Verbose,
InspectionDepth: 5,
Version: version,
SendConfigCmd: true,
SendKeyRequest: c.authResolver.CheckNeedsDashFile(c.config.LocalPath, remotePath),
WsID: c.config.WsID, // Add websocket ID
ClientVersion: c.config.ClientVersion,
//ProgressCallback: remote.DefaultProgressCallback(remote.FormatSimple),
ProgressCallback: nil,
ProgressConfig: &remote.ProgressConfig{
Enabled: true,
Format: remote.FormatSimple,
UpdateRate: 500 * time.Millisecond,
ShowETA: true,
ShowBytes: true,
ShowPages: true,
PagesPerUpdate: 10,
},
})
if err != nil {
return fmt.Errorf("failed to create remote client: %w", err)
}
defer remoteClient.Close()
// Connect to remote server
if err := remoteClient.Connect(); err != nil {
// I removed the check if the authkey is empty because they
// might have provided the wrong key and let's give them a
// chance to fix that.
if strings.Contains(err.Error(), "key is not authorized") || strings.Contains(err.Error(), "404 Path not found") {
key, err := c.authResolver.PromptForKey(c.config.ServerURL, c.config.RemotePath, "PULL")
if err != nil {
return fmt.Errorf("coordinator failed to get key interactively: %w", err)
}
c.config.ProvidedAuthKey = key
return c.executePull(isSubscription)
} else {
return fmt.Errorf("coordinator failed to connect to server: %w", err)
}
}
// Create local client for SQLite operations
localClient, err := bridge.New(&bridge.BridgeConfig{
DatabasePath: c.config.LocalPath,
DryRun: c.config.DryRun,
Logger: c.logger.Named("local"),
EnableSQLiteRsyncLogging: c.config.Verbose,
})
if err != nil {
return fmt.Errorf("failed to create local client: %w", err)
}
defer localClient.Close()
// Perform the sync
if err := c.performPullSync(localClient, remoteClient); err != nil {
return fmt.Errorf("pull synchronization failed: %w", err)
}
// Check database integrity after pull
localClient.CheckIntegrity()
c.config.Version = remoteClient.GetLatestCommitVersion()
// Save pull result if needed
if remoteClient.GetNewPullKey() != "" && c.authResolver.CheckNeedsDashFile(c.config.LocalPath, remotePath) {
if err := c.authResolver.SavePullResult(
c.config.LocalPath,
serverURL,
remoteClient.GetReplicaPath(),
remoteClient.GetReplicaID(),
remoteClient.GetNewPullKey(),
); err != nil {
c.logger.Warn("Failed to save pull result", zap.Error(err))
} else {
fmt.Println("🔑 Shareable config file created for future pulls")
}
}
if !isSubscription {
c.logger.Info("Pull synchronization completed successfully")
}
return nil
}
// executePush performs a push sync operation
func (c *Coordinator) executePush() error {
// Create local client for SQLite operations
localClient, err := bridge.New(&bridge.BridgeConfig{
DatabasePath: c.config.LocalPath,
DryRun: c.config.DryRun,
Logger: c.logger.Named("local"),
EnableSQLiteRsyncLogging: c.config.Verbose,
})
if err != nil {
return fmt.Errorf("failed to create local client: %w", err)
}
defer localClient.Close()
// Check database integrity before pushing
localClient.CheckIntegrity()
fileInfo, err := os.Stat(c.config.LocalPath)
if err != nil {
return fmt.Errorf("failed to stat local file: %w", err)
}
fileSize := fileInfo.Size()
if fileSize > 100*1024*1024 {
fmt.Printf("⚠️ Warning: The database file is large (%.2f MB) for SQLRsync.com and so the behavior and performance is untested.\n", float64(fileSize)/(1024*1024))
}
// Resolve authentication
authResult, err := c.resolveAuth("push")
if err != nil {
return fmt.Errorf("authentication failed: %w", err)
}
// Use resolved values, with config overrides
serverURL := authResult.ServerURL
// Only override if user explicitly provided a different server (not just using the default)
if c.config.ServerURL != "" && c.config.ServerURL != "wss://sqlrsync.com" {
serverURL = c.config.ServerURL
}
remotePath := authResult.RemotePath
if c.config.RemotePath != "" {
remotePath = c.config.RemotePath
}
// Get absolute path for the local database
absLocalPath, err := filepath.Abs(c.config.LocalPath)
if err != nil {
return fmt.Errorf("failed to get absolute path: %w", err)
}
localHostname, _ := os.Hostname()
if c.config.DryRun {
c.displayDryRunInfo("push", authResult, absLocalPath, serverURL, remotePath, localHostname)
return nil
}
fmt.Printf("PUSHing up to %s/%s ...\n", serverURL, remotePath)
// Create remote client for WebSocket transport
remoteClient, err := remote.New(&remote.Config{
ServerURL: serverURL + "/sapi/push/" + remotePath,
PingPong: true,
Timeout: 15000,
AuthKey: authResult.AccessKey,
Logger: c.logger.Named("remote"),
EnableTrafficInspection: c.config.Verbose,
LocalHostname: localHostname,
LocalAbsolutePath: absLocalPath,
InspectionDepth: 5,
SendKeyRequest: c.authResolver.CheckNeedsDashFile(c.config.LocalPath, remotePath),
SendConfigCmd: true,
SetVisibility: c.config.SetVisibility,
CommitMessage: c.config.CommitMessage,
WsID: c.config.WsID, // Add websocket ID
ClientVersion: c.config.ClientVersion,
ProgressCallback: nil, //remote.DefaultProgressCallback(remote.FormatSimple),
ProgressConfig: &remote.ProgressConfig{
Enabled: true,
Format: remote.FormatSimple,
UpdateRate: 500 * time.Millisecond,
ShowETA: true,
ShowBytes: true,
ShowPages: true,
PagesPerUpdate: 10,
},
})
if err != nil {
return fmt.Errorf("failed to create remote client: %w", err)
}
defer remoteClient.Close()
// Connect to remote server
if err := remoteClient.Connect(); err != nil {
if strings.Contains(err.Error(), "key is not authorized") || strings.Contains(err.Error(), "404 Path not found") {
key, err := subscription.PromptForKey(serverURL, remotePath, "PULL")
if err != nil || key == "" {
return fmt.Errorf("manager failed to get key interactively: %w", err)
}
authResult.AccessKey = key
return c.executePush()
}
return fmt.Errorf("failed to connect to server: %w", err)
}
// Perform the sync
if err := c.performPushSync(localClient, remoteClient); err != nil {
// Check if this was a version conflict and auto-merge is enabled
if remoteClient.HasVersionConflict() && c.config.AutoMerge {
latestVersion := remoteClient.GetLatestVersion()
fmt.Printf("🔄 Auto-merge enabled - attempting to merge with server version %s...\n", latestVersion)
if mergeErr := c.executeAutoMerge(localClient, remoteClient, latestVersion); mergeErr != nil {
return fmt.Errorf("auto-merge failed: %w", mergeErr)
}
// Auto-merge succeeded, retry the push
fmt.Println("✅ Auto-merge successful - retrying PUSH...")
remoteClient.ResetVersionConflict()
if err := c.performPushSync(localClient, remoteClient); err != nil {
return fmt.Errorf("push after auto-merge failed: %w", err)
}
} else {
return fmt.Errorf("push synchronization failed: %w", err)
}
}
c.config.Version = remoteClient.GetLatestCommitVersion()
// Save push result if we got new keys
if remoteClient.GetNewPushKey() != "" {
if err := c.authResolver.SavePushResult(
absLocalPath,
serverURL,
remoteClient.GetReplicaPath(),
remoteClient.GetReplicaID(),
remoteClient.GetNewPushKey(),
); err != nil {
c.logger.Warn("Failed to save push result", zap.Error(err))
} else {
fmt.Println("🔑 A new PUSH access key was stored at ~/.config/sqlrsync/ for ")
fmt.Println(" revokable permission to push updates in the future. Just")
fmt.Println(" use `sqlrsync " + absLocalPath + "` to push again.")
}
}
// Create -sqlrsync file for sharing if needed
if c.authResolver.CheckNeedsDashFile(c.config.LocalPath, remotePath) && remoteClient.GetNewPullKey() != "" {
if err := c.authResolver.SavePullResult(
c.config.LocalPath,
serverURL,
remoteClient.GetReplicaPath(),
remoteClient.GetReplicaID(),
remoteClient.GetNewPullKey(),
); err != nil {
c.logger.Warn("Failed to create shareable config file", zap.Error(err))
} else {
fmt.Println("🔑 A new PULL access key was created: " + c.config.LocalPath + "-sqlrsync")
fmt.Println(" Share this file to allow others to download or subscribe")
fmt.Println(" to this database.")
}
}
c.logger.Info("Push synchronization completed successfully")
return nil
}
// performPullSync executes the pull synchronization
func (c *Coordinator) performPullSync(localClient *bridge.BridgeClient, remoteClient *remote.Client) error {
// Create I/O bridge between remote and local clients
readFunc := func(buffer []byte) (int, error) {
return remoteClient.Read(buffer)
}
writeFunc := func(data []byte) error {
return remoteClient.Write(data)
}
/*
progress := remoteClient.GetProgress()
if progress != nil {
fmt.Printf("Current progress: %.1f%% (%d/%d pages)\n",
progress.PercentComplete, progress.PagesSent, progress.TotalPages)
}*/
// Run the replica sync through the bridge
return localClient.RunPullSync(readFunc, writeFunc)
}
// performPushSync executes the push synchronization
func (c *Coordinator) performPushSync(localClient *bridge.BridgeClient, remoteClient *remote.Client) error {
// Create I/O bridge between local and remote clients
readFunc := func(buffer []byte) (int, error) {
return remoteClient.Read(buffer)
}
writeFunc := func(data []byte) error {
return remoteClient.Write(data)
}
/*
progress := remoteClient.GetProgress()
if progress != nil {
fmt.Printf("Current progress: %.1f%% (%d/%d pages)\n",
progress.PercentComplete, progress.PagesSent, progress.TotalPages)
}*/
// Run the origin sync through the bridge
return localClient.RunPushSync(readFunc, writeFunc)
}
// executeLocalSync performs a direct local-to-local sync operation
func (c *Coordinator) executeLocalSync() error {
// Validate that both database files exist
if _, err := os.Stat(c.config.LocalPath); os.IsNotExist(err) {
return fmt.Errorf("origin database file does not exist: %s", c.config.LocalPath)
}
// For replica, it's okay if it doesn't exist - it will be created
absOriginPath, err := filepath.Abs(c.config.LocalPath)
if err != nil {
return fmt.Errorf("failed to get absolute path for origin: %w", err)
}
absReplicaPath, err := filepath.Abs(c.config.ReplicaPath)
if err != nil {
return fmt.Errorf("failed to get absolute path for replica: %w", err)
}
if c.config.DryRun {
c.displayDryRunInfo("local", nil, absOriginPath, "", "", "")
return nil
}
fmt.Printf("Syncing LOCAL to LOCAL: %s → %s\n", absOriginPath, absReplicaPath)
// Create local client for SQLite operations
localClient, err := bridge.New(&bridge.BridgeConfig{
DatabasePath: absOriginPath,
DryRun: c.config.DryRun,
Logger: c.logger.Named("local"),
EnableSQLiteRsyncLogging: c.config.Verbose,
})
if err != nil {
return fmt.Errorf("failed to create local client: %w", err)
}
defer localClient.Close()
// Perform direct sync
if err := localClient.RunDirectSync(absReplicaPath); err != nil {
return fmt.Errorf("local-to-local synchronization failed: %w", err)
}
c.logger.Info("Local-to-local synchronization completed successfully")
fmt.Println("✅ Local sync completed")
return nil
}
// executePushSubscribe performs an initial push then watches for file changes to auto-push
func (c *Coordinator) executePushSubscribe() error {
fmt.Println("📡 PUSH Subscribe mode enabled - will push on file changes...")
fmt.Println(" Press Ctrl+C to stop watching...")
// Parse duration strings
var waitIdleDuration, maxIntervalDuration, minIntervalDuration time.Duration
var err error
if c.config.WaitIdle == "" {
return fmt.Errorf("--waitIdle is required for PUSH subscription mode")
}
waitIdleDuration, err = ParseDuration(c.config.WaitIdle)
if err != nil {
return fmt.Errorf("invalid --waitIdle: %w", err)
}
if err := ValidateWaitIdle(waitIdleDuration); err != nil {
return fmt.Errorf("invalid --waitIdle: %w", err)
}
if c.config.MaxInterval != "" {
maxIntervalDuration, err = ParseDuration(c.config.MaxInterval)
if err != nil {
return fmt.Errorf("invalid --maxInterval: %w", err)
}
}
if c.config.MinInterval != "" {
minIntervalDuration, err = ParseDuration(c.config.MinInterval)
if err != nil {
return fmt.Errorf("invalid --minInterval: %w", err)
}
} else if c.config.MaxInterval != "" {
// Default minInterval to half of maxInterval
minIntervalDuration = maxIntervalDuration / 2
}
// Perform initial PUSH
fmt.Println("🔄 Performing initial PUSH...")
if err := c.executePush(); err != nil {
return fmt.Errorf("initial PUSH failed: %w", err)
}
lastPushTime := time.Now()
fmt.Println("✅ Initial PUSH complete")
// Check if we should continue with PUSH subscribe based on key type
// The server will tell us via CONFIG what type of key we're using
// Set up persistent remote client connection for sending CHANGED messages
fmt.Println("📡 Establishing persistent connection for change notifications...")
// Resolve authentication (same as in executePush)
authResult, err := c.resolveAuth("push")
if err != nil {
return fmt.Errorf("authentication failed: %w", err)
}
serverURL := authResult.ServerURL
if c.config.ServerURL != "" && c.config.ServerURL != "wss://sqlrsync.com" {
serverURL = c.config.ServerURL
}
remotePath := authResult.RemotePath
if c.config.RemotePath != "" {
remotePath = c.config.RemotePath
}
c.remoteClient, err = remote.New(&remote.Config{
ServerURL: serverURL + "/sapi/push/" + remotePath,
PingPong: true,
Timeout: 60000,
AuthKey: authResult.AccessKey,
ClientVersion: c.config.ClientVersion,
Logger: c.logger.Named("remote-notifications"),
EnableTrafficInspection: c.config.Verbose,
WsID: c.config.WsID, // Add websocket ID
})
if err != nil {
return fmt.Errorf("failed to create remote client: %w", err)
}
defer c.remoteClient.Close()
if err := c.remoteClient.Connect(); err != nil {
if strings.Contains(err.Error(), "key is not authorized") || strings.Contains(err.Error(), "404 Path not found") {
key, err := c.authResolver.PromptForKey(c.config.ServerURL, c.config.RemotePath, "PUSH")
if err != nil {
return fmt.Errorf("coordinator failed to get key interactively: %w", err)
}
c.config.ProvidedAuthKey = key
// We need to SendConfigCmd in the PUSH to get and store keys
return c.executePushSubscribe()
}
return fmt.Errorf("failed to connect to server: %w", err)
}
// Wait briefly for CONFIG message to arrive with key type
time.Sleep(500 * time.Millisecond)
// Check key type - if it's a PULL key, we shouldn't be doing PUSH subscribe
keyType := c.remoteClient.GetKeyType()
if keyType == "PULL" {
fmt.Println("⚠️ Warning: Using a PULL key - ignoring --waitIdle/--maxInterval/--minInterval settings")
fmt.Println(" Switching to PULL subscription mode instead...")
return c.executePullSubscribe()
}
// Create file watcher
fileWatcher, err := watcher.NewWatcher(&watcher.Config{
DatabasePath: c.config.LocalPath,
Logger: c.logger.Named("watcher"),
WriteNotificationFunc: c.sendWriteNotification,
})
if err != nil {
return fmt.Errorf("failed to create file watcher: %w", err)
}
defer fileWatcher.Close()
if err := fileWatcher.Start(); err != nil {
return fmt.Errorf("failed to start file watcher: %w", err)
}
fmt.Printf("👀 Watching %s for changes...\n", c.config.LocalPath)
fmt.Printf(" Wait idle: %v\n", waitIdleDuration)
if maxIntervalDuration > 0 {
fmt.Printf(" Max interval: %v\n", maxIntervalDuration)
}
if minIntervalDuration > 0 {
fmt.Printf(" Min interval: %v\n", minIntervalDuration)
}
// Also set up subscription to listen for remote updates (bidirectional sync)
fmt.Println("📡 Setting up subscription for remote updates...")
c.subManager = subscription.NewManager(&subscription.ManagerConfig{
ServerURL: serverURL,
ReplicaPath: remotePath,
AccessKey: authResult.AccessKey,
ReplicaID: authResult.ReplicaID,
WsID: c.config.WsID,
ClientVersion: c.config.ClientVersion,
Logger: c.logger.Named("subscription"),
MaxReconnectAttempts: 20, // Infinite reconnect attempts
InitialReconnectDelay: 5 * time.Second, // Start with 5 seconds delay
MaxReconnectDelay: 5 * time.Minute, // Cap at 5 minutes
})
// Connect to subscription service for pull notifications
if err := c.subManager.Connect(); err != nil {
c.logger.Warn("Failed to connect to subscription service for pull notifications", zap.Error(err))
fmt.Println("⚠️ Warning: Could not set up pull subscription - will only push changes")
} else {
defer c.subManager.Close()
fmt.Println("✅ Subscribed to remote updates at " + time.Unix(time.Now().Unix(), 0).String() + " - will pull new versions automatically")
// Start goroutine to handle pull notifications
go c.handlePullNotifications()
}
var waitTimer *time.Timer
resetCount := 0
for {
select {
case <-c.ctx.Done():
fmt.Println("Subscription stopped by user.")
return nil
default:
}
// Check for maxInterval timeout even without file changes
if maxIntervalDuration > 0 && time.Since(lastPushTime) >= maxIntervalDuration {
fmt.Printf("⏰ Max interval (%v) reached - pushing...\n", maxIntervalDuration)
if waitTimer != nil {
waitTimer.Stop()
waitTimer = nil
}
if err := c.executePushWithRetry(); err != nil {
c.logger.Error("PUSH failed", zap.Error(err))
} else {
lastPushTime = time.Now()
resetCount = 0
}
continue
}
// Wait for file change with timeout
changeTime, err := fileWatcher.WaitForChange()
if err != nil {
if strings.Contains(err.Error(), "cancelled") {
fmt.Println("Subscription stopped by user.")
return nil
}
return fmt.Errorf("file watcher error: %w", err)
}
timeSinceLastPush := time.Since(lastPushTime)
c.logger.Debug("File change detected",
zap.Time("changeTime", changeTime),
zap.Duration("timeSinceLastPush", timeSinceLastPush))
// Check if we should push immediately due to maxInterval
if maxIntervalDuration > 0 && timeSinceLastPush >= maxIntervalDuration {
fmt.Printf("⏰ Max interval (%v) reached - pushing immediately...\n", maxIntervalDuration)
if waitTimer != nil {
waitTimer.Stop()
waitTimer = nil
}
if err := c.executePushWithRetry(); err != nil {
c.logger.Error("PUSH failed", zap.Error(err))
// Continue watching despite error
} else {
lastPushTime = time.Now()
resetCount = 0
}
continue
}
// Calculate timer duration: MAX(minInterval - timeSinceLastPush, waitIdle)
timerDuration := waitIdleDuration
if minIntervalDuration > 0 {
remainingMinInterval := minIntervalDuration - timeSinceLastPush
if remainingMinInterval > timerDuration {
timerDuration = remainingMinInterval
}
}
c.logger.Debug("Calculated timer duration",
zap.Duration("timerDuration", timerDuration),
zap.Duration("waitIdle", waitIdleDuration),
zap.Duration("minInterval", minIntervalDuration),
zap.Duration("timeSinceLastPush", timeSinceLastPush))
// Reset or start the wait timer
if waitTimer != nil {
waitTimer.Stop()
resetCount++
} else {
resetCount = 0
}
c.logger.Debug("Starting wait timer", zap.Duration("duration", timerDuration))
waitTimer = time.AfterFunc(timerDuration, func() {
fmt.Printf("⏰ Timer expired after %v - pushing changes...\n", timerDuration)
if err := c.executePushWithRetry(); err != nil {
c.logger.Error("PUSH failed", zap.Error(err))
} else {
lastPushTime = time.Now()
resetCount = 0
}
})
}
}
// executePushWithRetry executes a push with exponential backoff on failure
func (c *Coordinator) executePushWithRetry() error {
const maxRetries = 5
delay := 5 * time.Second
var lastErr error
for attempt := 0; attempt < maxRetries; attempt++ {
if attempt > 0 {
c.logger.Info("Retrying PUSH", zap.Int("attempt", attempt+1), zap.Duration("delay", delay))
time.Sleep(delay)
delay *= 2 // Exponential backoff
}
if err := c.executePush(); err != nil {
lastErr = err
c.logger.Warn("PUSH attempt failed", zap.Error(err), zap.Int("attempt", attempt+1))
// Report error to server if it's been more than 5 minutes of failures
if attempt == maxRetries-1 {
c.reportErrorToServer(err)
}
continue
}
// PUSH succeeded - reset session flag for next batch of changes
c.sessionStarted = false
if c.resendTimer != nil {
c.resendTimer.Stop()
c.resendTimer = nil