<s> from collections import defaultdict <EOL> from . state import State <EOL> from . . messages . append_entries import AppendEntriesMessage <EOL> class Leader ( State ) : <EOL> def __init__ ( self ) : <EOL> self . _nextIndexes = defaultdict ( int ) <EOL> self . _matchIndex = defaultdict ( int ) <EOL> def set_sever ( self , server ) : <EOL> self . _sever = server <EOL> self . _send_heart_beat ( ) <EOL> for n in self . _server . _neighbors : <EOL> self . _nextIndexes [ n . _name ] = self . _server . _lastLogIndex + <NUM_LIT:1> <EOL> self . _matchIndex [ n . _name ] = <NUM_LIT:0> <EOL> def on_response_received ( self , message ) : <EOL> if ( not message . data [ "<STR_LIT>" ] ) : <EOL> self . _nextIndexes [ message . sender ] -= <NUM_LIT:1> <EOL> previousIndex = max ( <NUM_LIT:0> , self . _nextIndexes [ message . sender ] - <NUM_LIT:1> ) <EOL> previous = self . _server . _log [ previousIndex ] <EOL> current = self . _server . _log [ self . _nextIndexes [ message . sender ] ] <EOL> appendEntry = AppendEntriesMessage ( <EOL> self . _server . _name , <EOL> message . sender , <EOL> self . _server . _currentTerm , <EOL> { <EOL> "<STR_LIT>" : self . _server . _name , <EOL> "<STR_LIT>" : previousIndex , <EOL> "<STR_LIT>" : previous [ "<STR_LIT>" ] , <EOL> "<STR_LIT>" : [ current ] , <EOL> "<STR_LIT>" : self . _server . _commitIndex , <EOL> } ) <EOL> self . _send_response_message ( appendEntry ) <EOL> else : <EOL> self . _nextIndexes [ message . sender ] += <NUM_LIT:1> <EOL> if ( self . _nextIndexes [ message . sender ] > self . _server . _lastLogIndex ) : <EOL> self . _nextIndexes [ message . sender ] = self . _server . _lastLogIndex <EOL> return self , None <EOL> def _send_heart_beat ( self ) : <EOL> message = AppendEntriesMessage ( <EOL> self . _server . _name , <EOL> None , <EOL> self . _server . _currentTerm , <EOL> { <EOL> "<STR_LIT>" : self . _server . _name , <EOL> "<STR_LIT>" : self . _server . _lastLogIndex , <EOL> "<STR_LIT>" : self . _server . _lastLogTerm , <EOL> "<STR_LIT>" : [ ] , <EOL> "<STR_LIT>" : self . _server . _commitIndex , <EOL> } ) <EOL> self . _server . send_message ( message ) </s>
