@@ -38,6 +38,7 @@ type Server struct {
38
38
masterAddr string
39
39
messageChan chan client.Message
40
40
masterClient * client.Client
41
+ replicationID string
41
42
disconnectChan chan * client.Client
42
43
}
43
44
@@ -50,6 +51,10 @@ func NewServer(cfg *config.Config) *Server {
50
51
parts := strings .Split (replicaOf , " " )
51
52
masterAddr = fmt .Sprintf ("%s:%s" , parts [0 ], parts [1 ])
52
53
}
54
+ var replicationID string
55
+ if isMaster {
56
+ replicationID = utils .GenerateRandomAlphanumeric (40 )
57
+ }
53
58
s := & Server {
54
59
mu : sync.Mutex {},
55
60
cfg : cfg ,
@@ -61,6 +66,7 @@ func NewServer(cfg *config.Config) *Server {
61
66
masterAddr : masterAddr ,
62
67
messageChan : make (chan client.Message ),
63
68
masterClient : nil ,
69
+ replicationID : replicationID ,
64
70
disconnectChan : make (chan * client.Client ),
65
71
}
66
72
s .cFactory = command .NewCommandFactory (store , cfg , s )
@@ -160,6 +166,10 @@ func (s *Server) startReplication(ctx context.Context) (err error) {
160
166
return fmt .Errorf ("failed to send REPLCONF to master: %v" , err )
161
167
}
162
168
169
+ if err := s .sendPsyncToMaster (ctx ); err != nil {
170
+ return fmt .Errorf ("failed to send PSYNC to master: %v" , err )
171
+ }
172
+
163
173
return nil
164
174
}
165
175
@@ -222,6 +232,21 @@ func (s *Server) sendReplconfToMaster(ctx context.Context) error {
222
232
return nil
223
233
}
224
234
235
+ func (s * Server ) sendPsyncToMaster (ctx context.Context ) error {
236
+ psyncCmd := resp .CreatePsyncCommand ("?" , "-1" )
237
+ response , err := s .sendAndReceive (psyncCmd )
238
+ if err != nil {
239
+ return fmt .Errorf ("failed to send PSYNC to master: %v" , err )
240
+ }
241
+
242
+ if response .Type != resp .SimpleString || ! strings .HasPrefix (response .String (), "FULLRESYNC" ) {
243
+ return fmt .Errorf ("unexpected response from master for PSYNC: %v" , response )
244
+ }
245
+
246
+ logger .Info (ctx , "Successfully sent PSYNC to master and received FULLRESYNC" )
247
+ return nil
248
+ }
249
+
225
250
func (s * Server ) loop (ctx context.Context ) {
226
251
for {
227
252
select {
@@ -342,3 +367,9 @@ func (s *Server) Close(_ context.Context) error {
342
367
}
343
368
return nil
344
369
}
370
+
371
+ func (s * Server ) GetReplicationID () string {
372
+ s .mu .Lock ()
373
+ defer s .mu .Unlock ()
374
+ return s .replicationID
375
+ }
0 commit comments