@@ -13,35 +13,42 @@ const HEIGHT_EPSILON = 5; // Used to group nodes by height and choose synced
1313module . exports = ( nodes , checkHealthAtStartup = true , checkHealthAtStartupCallback ) => {
1414 const nodesList = nodes ;
1515 let isCheckingNodes = false ;
16+ let startupCallback = checkHealthAtStartupCallback ;
1617
1718 // Note: it may be not synced; and before first health check a node can reply with obsolete data
1819 let [ activeNode ] = nodesList ;
1920
2021 /**
2122 * Updates active nodes. If nodes are already updating, returns Promise of previous call
2223 * @param {boolean } isPlannedUpdate
24+ * @param {boolean } isFirstUpdate
2325 * @return {Promise } Call changeNodes().then to do something when update complete
2426 */
25- async function changeNodes ( isPlannedUpdate = false ) {
27+ async function changeNodes ( isPlannedUpdate = false , isFirstUpdate = false ) {
2628 if ( ! isCheckingNodes ) {
29+ isCheckingNodes = true ;
30+
2731 if ( ! isPlannedUpdate ) {
2832 logger . warn ( '[ADAMANT js-api] Health check: Forcing to update active nodes…' ) ;
2933 }
3034
3135 await checkNodes ( ! isPlannedUpdate ) ;
3236
37+ if ( isFirstUpdate ) {
38+ startupCallback ?. ( ) ;
39+ }
40+
41+ isCheckingNodes = false ;
42+
3343 return true ;
3444 }
3545 }
3646
3747 /**
3848 * Requests every ADAMANT node for its status, makes a list of live nodes, and chooses one active
3949 * @param {boolean } forceChangeActiveNode
40- * @param {function? } checkNodesCallback
4150 */
42- async function checkNodes ( forceChangeActiveNode , checkNodesCallback ) {
43- isCheckingNodes = true ;
44-
51+ async function checkNodes ( forceChangeActiveNode ) {
4552 const liveNodes = [ ] ;
4653
4754 try {
@@ -162,27 +169,33 @@ module.exports = (nodes, checkHealthAtStartup = true, checkHealthAtStartupCallba
162169 } catch ( e ) {
163170 logger . warn ( '[ADAMANT js-api] Health check: Error in checkNodes(), ' + e ) ;
164171 }
172+ }
165173
166- isCheckingNodes = false ;
167- checkNodesCallback ?. ( ) ;
174+ function setStartupCallback ( callback ) {
175+ if ( ! isCheckingNodes ) {
176+ callback ( ) ;
177+ } else {
178+ startupCallback = callback ;
179+ }
168180 }
169181
170182 if ( checkHealthAtStartup ) {
171- changeNodes ( true , checkHealthAtStartupCallback ) ;
183+ changeNodes ( true , true ) ;
172184
173185 setInterval (
174186 ( ) => changeNodes ( true ) ,
175187 CHECK_NODES_INTERVAL ,
176188 ) ;
177189 } else {
178- checkHealthAtStartupCallback ?. ( ) ;
190+ startupCallback ?. ( ) ;
179191 }
180192
181193 return {
182194 /**
183195 * @return {string } Current active node, f. e. http://88.198.156.44:36666
184196 */
185197 node : ( ) => activeNode ,
198+ setStartupCallback,
186199 changeNodes,
187200 } ;
188201} ;
0 commit comments