Skip to content

Commit f577698

Browse files
Merge pull request #915 from appwrite/feat-await-port-open
Feat: CLI local development port checker
2 parents 2e503d6 + 07bfa4e commit f577698

File tree

1 file changed

+42
-1
lines changed

1 file changed

+42
-1
lines changed

templates/cli/lib/emulation/docker.js.twig

Lines changed: 42 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,10 @@
1+
const net = require('net');
12
const chalk = require('chalk');
23
const childProcess = require('child_process');
34
const { localConfig } = require("../config");
45
const path = require('path');
56
const fs = require('fs');
6-
const { log, success, hint } = require("../parser");
7+
const { log, error, success, hint } = require("../parser");
78
const { openRuntimesVersion, systemTools, Queue } = require("./utils");
89

910
async function dockerStop(id) {
@@ -168,6 +169,13 @@ async function dockerStart(func, variables, port) {
168169
process.stdout.write(chalk.blackBright(data));
169170
});
170171

172+
try {
173+
await waitUntilPortOpen(port);
174+
} catch(err) {
175+
error("Failed to start function with error: " + err.message ? err.message : err.toString());
176+
return;
177+
}
178+
171179
success(`Visit http://localhost:${port}/ to execute your function.`);
172180
}
173181

@@ -186,6 +194,39 @@ async function dockerCleanup(functionId) {
186194
}
187195
}
188196

197+
function waitUntilPortOpen(port, iteration = 0) {
198+
return new Promise((resolve, reject) => {
199+
const client = new net.Socket();
200+
201+
client.once('connect', () => {
202+
client.removeAllListeners('connect');
203+
client.removeAllListeners('error');
204+
client.end();
205+
client.destroy();
206+
client.unref();
207+
208+
resolve();
209+
});
210+
211+
client.once('error', async (err) => {
212+
client.removeAllListeners('connect');
213+
client.removeAllListeners('error');
214+
client.end();
215+
client.destroy();
216+
client.unref();
217+
218+
if(iteration > 100) {
219+
reject(err);
220+
} else {
221+
await new Promise((res) => setTimeout(res, 100));
222+
waitUntilPortOpen(port, iteration + 1).then(resolve).catch(reject);
223+
}
224+
});
225+
226+
client.connect({port, host: '127.0.0.1'}, function() {});
227+
});
228+
}
229+
189230
module.exports = {
190231
dockerPull,
191232
dockerBuild,

0 commit comments

Comments
 (0)