Last active
September 24, 2020 12:51
-
-
Save kosuke-suzuki/95f951901e71c65e232d5993caa4853e to your computer and use it in GitHub Desktop.
Dummy Service in Python and its wrapper in JavaScript
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import time | |
import pathlib | |
import random | |
time.sleep(random.randrange(1, 10, 1)) | |
file = pathlib.Path('./finish') | |
file.touch() |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const { spawn } = require('child_process'); | |
const fs = require('fs'); | |
const fsPromises = fs.promises; | |
class SomeService { | |
_proc; | |
_callbacks; | |
_intervals; | |
constructor() { | |
this._proc = null; | |
this._callbacks = {}; | |
this._intervals = []; | |
} | |
_monitor() { | |
const interval = setInterval(() => { | |
fsPromises.access('finish') | |
.then(() => { | |
return fsPromises.unlink('finish') | |
.then(() => { | |
this._stopMonitor(); | |
if (this._callbacks.ready != null) { | |
this._callbacks.ready(); | |
this._callbacks.ready = null; | |
} | |
}); | |
}) | |
.catch((err) => { | |
console.log(err); | |
console.log('Proc is not ready yet...'); | |
}); | |
}, 1 * 1000); | |
this._intervals.push(interval); | |
} | |
_stopMonitor() { | |
this._intervals.forEach((interval) => clearInterval(interval)); | |
this._intervals = []; | |
} | |
onReady(callback) { | |
this._callbacks.ready = callback; | |
} | |
start() { | |
this._monitor(); | |
this._proc = spawn('python3', ['dummy_service.py']); | |
} | |
stop() { | |
this._proc.kill(); | |
this._stopMonitor(); | |
} | |
} | |
module.exports = SomeService; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const SomeService = require('./SomeService'); | |
const startService = (timeoutSec) => { | |
const service = new SomeService(); | |
return new Promise((resolve, reject) => { | |
service.onReady(() => { | |
clearTimeout(onTimedout); | |
resolve(service); | |
}); | |
service.start(); | |
const onTimedout = setTimeout(() => { | |
service.stop(); | |
reject(`Proc did not launch within ${timeoutSec} seconds.`); | |
}, timeoutSec * 1000); | |
}); | |
}; | |
startService(5) | |
.then(() => { | |
console.log('Proc launched successfully.'); | |
}, () => { | |
console.log('Attempt to launch proc was timed out.'); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment