Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

refactor(devtools): use same port for ws and http #5939

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
7 changes: 7 additions & 0 deletions .changeset/chatty-beds-smoke.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
---
"@refinedev/cli": patch
---

fix(cli): prevent exit on devtools error

Updated the `dev` command's devtools runner logic to prevent the process from exiting when devtools server fails to start. Previously, the process would exit if devtools server failed to start regardless of the development server's status.
8 changes: 8 additions & 0 deletions .changeset/stupid-rules-pull.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
---
"@refinedev/devtools-server": patch
"@refinedev/devtools-shared": patch
---

refactor: use same port for ws and http servers

This PR merges WebSocket and Http server ports into one (5001) to simplify the configuration and avoid port conflicts. Previously the WebSocket server was running on port 5002 and the Http server on port 5001. Now both servers are running on port 5001.
7 changes: 7 additions & 0 deletions .changeset/tender-hats-lick.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
---
"@refinedev/devtools-server": patch
---

chore(devtools-server): customizable exit function

This change allows you to customize the exit function of the devtools server when using it via API.
2 changes: 1 addition & 1 deletion documentation/docs/guides-concepts/development/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -277,7 +277,7 @@ As an alternative, you can also install the `@refinedev/devtools-server` package

**Required Ports**

Devtools server will run on port `5001` and also run a WebSocket server on port `5002`. Make sure these ports are available on your machine. Both of these ports are required for devtools to work properly and maintain a connection between your app and the devtools interface.
Devtools server will run on port `5001`. Devtools will serve HTTP and WebSocket connections on this port. Make sure the port is available on your machine.

## Using Inferencer

Expand Down
12 changes: 10 additions & 2 deletions packages/cli/src/commands/devtools/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -164,7 +164,9 @@ const devtoolsInstaller = async () => {
}
};

export const devtoolsRunner = async () => {
export const devtoolsRunner = async ({
exitOnError = true,
}: { exitOnError?: boolean } = {}) => {
const corePackage = await getRefineCorePackage();

if (corePackage) {
Expand All @@ -184,7 +186,13 @@ export const devtoolsRunner = async () => {
}
}

server();
server({
onError: () => {
if (exitOnError) {
process.exit(1);
}
},
}).catch((e) => {});
};

const getRefineCorePackage = async () => {
Expand Down
2 changes: 1 addition & 1 deletion packages/cli/src/commands/runner/dev/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ const action = async (
const devtools = params.devtools === "false" ? false : devtoolsDefault;

if (devtools) {
devtoolsRunner();
devtoolsRunner({ exitOnError: false });
}

runScript(binPath, command);
Expand Down
2 changes: 1 addition & 1 deletion packages/devtools-server/src/cli.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
#!/usr/bin/env node
import { server } from "./index";

server();
server().catch(() => 0);
3 changes: 0 additions & 3 deletions packages/devtools-server/src/constants.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,4 @@
export const DEFAULT_WS_PORT = 5002;
export const DEFAULT_SERVER_PORT = 5001;

export const WS_PORT = DEFAULT_WS_PORT;
export const SERVER_PORT = DEFAULT_SERVER_PORT;

export const REFINE_API_URL = __DEVELOPMENT__
Expand Down
199 changes: 107 additions & 92 deletions packages/devtools-server/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,5 @@
import express from "express";

import { cyanBright, bold } from "chalk";

import { DevtoolsEvent, receive, send } from "@refinedev/devtools-shared";

import { serveClient } from "./serve-client";
Expand All @@ -10,128 +8,145 @@ import { reloadOnChange } from "./reload-on-change";
import { setupServer } from "./setup-server";
import { Activity, createDb } from "./create-db";
import { serveApi } from "./serve-api";
import { SERVER_PORT } from "./constants";
import { serveProxy } from "./serve-proxy";
import { serveOpenInEditor } from "./serve-open-in-editor";

type Options = {
projectPath?: string;
onError?: () => void;
};

export const server = async ({ projectPath = process.cwd() }: Options = {}) => {
const app = express();
const ws = serveWs();

const db = createDb();
export const server = async ({
projectPath = process.cwd(),
onError = () => {
process.exit(1);
},
}: Options = {}) => {
return new Promise((_, reject) => {
const app = express();
const server = setupServer(app, () => {
reject();
onError();
});
const ws = serveWs(server, () => {
reject();
onError();
});

ws.on("connection", (client) => {
// Initialize development client
receive(client as any, DevtoolsEvent.DEVTOOLS_INIT, (data) => {
if (db.connectedApp) {
// send client the devtools client url if already connected
send(client as any, DevtoolsEvent.DEVTOOLS_ALREADY_CONNECTED, {
url: db.connectedApp,
});
} else {
db.connectedApp = data.url;
db.clientWs = client;
const db = createDb();

ws.clients.forEach((c) => {
send(c as any, DevtoolsEvent.DEVTOOLS_CONNECTED_APP, {
ws.on("connection", (client) => {
// Initialize development client
receive(client as any, DevtoolsEvent.DEVTOOLS_INIT, (data) => {
if (db.connectedApp) {
// send client the devtools client url if already connected
send(client as any, DevtoolsEvent.DEVTOOLS_ALREADY_CONNECTED, {
url: db.connectedApp,
});
});
}
});
} else {
db.connectedApp = data.url;
db.clientWs = client;

receive(client as any, DevtoolsEvent.ACTIVITY, (data) => {
// match by identifier, if identifier is same, update data instead of pushing
const index = db.activities.findIndex(
(activity) => activity.identifier === data.identifier,
);
ws.clients.forEach((c) => {
send(c as any, DevtoolsEvent.DEVTOOLS_CONNECTED_APP, {
url: db.connectedApp,
});
});
}
});

const record: Activity = {
...data,
createdAt: Date.now(),
updatedAt: Date.now(),
};
receive(client as any, DevtoolsEvent.ACTIVITY, (data) => {
// match by identifier, if identifier is same, update data instead of pushing
const index = db.activities.findIndex(
(activity) => activity.identifier === data.identifier,
);

if (index > -1) {
record.createdAt = db.activities[index].createdAt;
const record: Activity = {
...data,
createdAt: Date.now(),
updatedAt: Date.now(),
};

db.activities[index] = record;
} else {
db.activities.push(record);
}
if (index > -1) {
record.createdAt = db.activities[index].createdAt;

ws.clients.forEach((c) => {
send(c as any, DevtoolsEvent.DEVTOOLS_ACTIVITY_UPDATE, {
updatedActivities: [record],
});
});
});
db.activities[index] = record;
} else {
db.activities.push(record);
}

receive(
client as any,
DevtoolsEvent.DEVTOOLS_HIGHLIGHT_IN_MONITOR,
({ name }) => {
ws.clients.forEach((c) => {
send(c as any, DevtoolsEvent.DEVTOOLS_HIGHLIGHT_IN_MONITOR_ACTION, {
name,
send(c as any, DevtoolsEvent.DEVTOOLS_ACTIVITY_UPDATE, {
updatedActivities: [record],
});
});
},
);
});

receive(
client as any,
DevtoolsEvent.DEVTOOLS_INVALIDATE_QUERY,
({ queryKey }) => {
ws.clients.forEach((c) => {
send(c as any, DevtoolsEvent.DEVTOOLS_INVALIDATE_QUERY_ACTION, {
queryKey,
receive(
client as any,
DevtoolsEvent.DEVTOOLS_HIGHLIGHT_IN_MONITOR,
({ name }) => {
ws.clients.forEach((c) => {
send(c as any, DevtoolsEvent.DEVTOOLS_HIGHLIGHT_IN_MONITOR_ACTION, {
name,
});
});
});
},
);
},
);

receive(
client as any,
DevtoolsEvent.DEVTOOLS_INVALIDATE_QUERY,
({ queryKey }) => {
ws.clients.forEach((c) => {
send(c as any, DevtoolsEvent.DEVTOOLS_INVALIDATE_QUERY_ACTION, {
queryKey,
});
});
},
);

receive(client as any, DevtoolsEvent.DEVTOOLS_LOGIN_SUCCESS, () => {
ws.clients.forEach((c) => {
send(c as any, DevtoolsEvent.DEVTOOLS_RELOAD_AFTER_LOGIN, {});
receive(client as any, DevtoolsEvent.DEVTOOLS_LOGIN_SUCCESS, () => {
ws.clients.forEach((c) => {
send(c as any, DevtoolsEvent.DEVTOOLS_RELOAD_AFTER_LOGIN, {});
});
});
});

// close connected app if client disconnects
client.on("close", (_, reason) => {
if (__DEVELOPMENT__) {
console.log("Client disconnected", ws.clients.size);
}
// close connected app if client disconnects
client.on("close", (_, reason) => {
if (__DEVELOPMENT__) {
console.log("Client disconnected", ws.clients.size);
}

if (db.clientWs) {
if (!ws.clients.has(db.clientWs)) {
db.clientWs = null;
db.connectedApp = null;
if (db.clientWs) {
if (!ws.clients.has(db.clientWs)) {
db.clientWs = null;
db.connectedApp = null;

db.activities = [];
db.activities = [];

ws.clients.forEach((c) => {
send(c as any, DevtoolsEvent.DEVTOOLS_DISCONNECTED_APP, {
url: db.connectedApp,
ws.clients.forEach((c) => {
send(c as any, DevtoolsEvent.DEVTOOLS_DISCONNECTED_APP, {
url: db.connectedApp,
});
});
});
}
}
});

if (__DEVELOPMENT__) {
console.log("Client connected", ws.clients.size);
}
});

if (__DEVELOPMENT__) {
console.log("Client connected", ws.clients.size);
}
});
reloadOnChange(ws);
serveClient(app);
serveApi(app, db);
serveProxy(app);
serveOpenInEditor(app, projectPath);

reloadOnChange(ws);
serveClient(app);
setupServer(app);
serveApi(app, db);
serveProxy(app);
serveOpenInEditor(app, projectPath);
process.on("SIGTERM", () => {
reject();
});
});
};
1 change: 0 additions & 1 deletion packages/devtools-server/src/serve-proxy.ts
Original file line number Diff line number Diff line change
Expand Up @@ -137,7 +137,6 @@ export const serveProxy = async (app: Express) => {

const authProxy = createProxyMiddleware({
target: REFINE_API_URL,
// secure: false,
changeOrigin: true,
pathRewrite: { "^/api/.auth": "/.auth" },
cookieDomainRewrite: {
Expand Down
49 changes: 25 additions & 24 deletions packages/devtools-server/src/serve-ws.ts
Original file line number Diff line number Diff line change
@@ -1,34 +1,35 @@
import WebSocket from "ws";
import { SERVER_PORT, WS_PORT } from "./constants";
import { SERVER_PORT } from "./constants";
import { DevtoolsEvent, send } from "@refinedev/devtools-shared";
import { bold, cyanBright } from "chalk";
import http from "http";

export const serveWs = () => {
const ws = new WebSocket.Server({ port: WS_PORT }).on(
"error",
(error: any) => {
if (error?.code === "EADDRINUSE") {
console.error(
`\n${cyanBright.bold("\u2717 ")}${bold(
"refine devtools",
)} failed to start. Port ${WS_PORT} is already in use, please make sure no other devtools server is running\n`,
);
} else {
console.error(
`\n${cyanBright.bold("\u2717 ")}${bold(
"error from refine devtools",
)}`,
error,
);
export const serveWs = (
server: http.Server<typeof http.IncomingMessage, typeof http.ServerResponse>,
onError: () => void,
) => {
const ws = new WebSocket.Server({ server }).on("error", (error: any) => {
if (error?.code === "EADDRINUSE") {
console.error(
`\n${cyanBright.bold("\u2717 ")}${bold(
"refine devtools server",
)} (websocket) failed to start. Port ${SERVER_PORT} is already in use.\n`,
);
} else {
console.error(
`\n${cyanBright.bold("\u2717 ")}${bold("error from refine devtools")}`,
error,
);
}
ws.close(() => {
if (__DEVELOPMENT__) {
console.log("Process terminated");
}
process.exit(1);
},
);
});
onError();
});

ws.on("connection", (client) => {
if (__DEVELOPMENT__) {
console.log(`WebSocket server started on PORT ${WS_PORT}`);
}
// send client the devtools client url
send(client as any, DevtoolsEvent.DEVTOOLS_HANDSHAKE, {
url: `http://localhost:${SERVER_PORT}`,
Expand Down