@@ -22,35 +22,68 @@ class IpnsRepublisher {
22
22
this . _publisher = publisher
23
23
this . _ipfs = ipfs
24
24
this . _repo = ipfs . _repo
25
- this . _timeoutId = null
26
- this . _canceled = false
27
- this . _onCancel = null
25
+ this . _republishHandle = null
28
26
}
29
27
30
28
start ( ) {
31
- const periodically = ( cb ) => {
32
- this . _republishEntries ( this . _ipfs . _peerInfo . id . privKey , this . _ipfs . _options . pass , ( ) => {
33
- if ( this . _canceled ) {
34
- return this . _onCancel ( )
29
+ if ( this . _republishHandle ) {
30
+ const errMsg = 'already running'
31
+
32
+ log . error ( errMsg )
33
+ throw errcode ( new Error ( errMsg ) , 'ERR_REPUBLISH_ALREADY_RUNNING' )
34
+ }
35
+
36
+ // TODO: this handler should be isolated in another module
37
+ const republishHandle = {
38
+ _onCancel : null ,
39
+ _timeoutId : null ,
40
+ runPeriodically : ( fn , period ) => {
41
+ republishHandle . _timeoutId = setTimeout ( ( ) => {
42
+ republishHandle . _timeoutId = null
43
+
44
+ fn ( ( nextPeriod ) => {
45
+ // Was republish cancelled while fn was being called?
46
+ if ( republishHandle . _onCancel ) {
47
+ return republishHandle . _onCancel ( )
48
+ }
49
+ // Schedule next
50
+ republishHandle . runPeriodically ( fn , nextPeriod || period )
51
+ } )
52
+ } , period )
53
+ } ,
54
+ cancel : ( cb ) => {
55
+ // Not currently running a republish, can callback immediately
56
+ if ( republishHandle . _timeoutId ) {
57
+ clearTimeout ( republishHandle . _timeoutId )
58
+ return cb ( )
35
59
}
36
- this . _timeoutId = setTimeout ( ( ) => periodically ( cb ) , defaultBroadcastInterval )
37
- } )
60
+ // Wait for republish to finish then call callback
61
+ republishHandle . _onCancel = cb
62
+ }
38
63
}
39
64
40
- setTimeout ( ( ) => {
41
- periodically ( )
65
+ const { privKey } = this . _ipfs . _peerInfo . id
66
+ const { pass } = this . _ipfs . _options
67
+
68
+ republishHandle . runPeriodically ( ( done ) => {
69
+ this . _republishEntries ( privKey , pass , ( ) => done ( defaultBroadcastInterval ) )
42
70
} , minute )
71
+
72
+ this . _republishHandle = republishHandle
43
73
}
44
74
45
- stop ( cb ) {
46
- this . _canceled = true
47
- if ( this . _timeoutId || ! this . _onCancel ) {
48
- // Not running
49
- clearTimeout ( this . _timeoutId )
50
- return cb ( )
75
+ stop ( callback ) {
76
+ const republishHandle = this . _republishHandle
77
+
78
+ if ( ! republishHandle ) {
79
+ const errMsg = 'not running'
80
+
81
+ log . error ( errMsg )
82
+ return callback ( errcode ( new Error ( errMsg ) , 'ERR_REPUBLISH_NOT_RUNNING' ) )
51
83
}
52
84
53
- this . _onCancel = cb
85
+ this . _republishHandle = null
86
+ republishHandle . cancel ( callback )
54
87
}
55
88
56
89
_republishEntries ( privateKey , pass , callback ) {
@@ -91,6 +124,8 @@ class IpnsRepublisher {
91
124
callback ( null )
92
125
} )
93
126
} )
127
+ } else {
128
+ callback ( null )
94
129
}
95
130
} )
96
131
}
0 commit comments