Skip to content

Commit 89ad799

Browse files
committed
Read most recent socket path from file
1 parent 3097166 commit 89ad799

File tree

5 files changed

+156
-18
lines changed

5 files changed

+156
-18
lines changed

ci/dev/vscode.patch

+25
Original file line numberDiff line numberDiff line change
@@ -3009,6 +3009,31 @@ index b3c89e51cfc25a53293a352a2a8ad50d5f26d595..e21abe4e13bc25a5b72f556bbfb61085
30093009
registerSingleton(IExtHostTerminalService, ExtHostTerminalService);
30103010
registerSingleton(IExtHostTunnelService, ExtHostTunnelService);
30113011
+registerSingleton(IExtHostNodeProxy, class extends NotImplementedProxy<IExtHostNodeProxy>(String(IExtHostNodeProxy)) { whenReady = Promise.resolve(); });
3012+
diff --git a/src/vs/workbench/api/node/extHostCLIServer.ts b/src/vs/workbench/api/node/extHostCLIServer.ts
3013+
index 7cae126cc0f804273850933468690e0f9f10a5b8..08c2aa5cdae3f3d06bb08b7055dc7e7def260132 100644
3014+
--- a/src/vs/workbench/api/node/extHostCLIServer.ts
3015+
+++ b/src/vs/workbench/api/node/extHostCLIServer.ts
3016+
@@ -11,6 +11,8 @@ import { IWindowOpenable, IOpenWindowOptions } from 'vs/platform/windows/common/
3017+
import { URI } from 'vs/base/common/uri';
3018+
import { hasWorkspaceFileExtension } from 'vs/platform/workspaces/common/workspaces';
3019+
import { ILogService } from 'vs/platform/log/common/log';
3020+
+import { join } from 'vs/base/common/path';
3021+
+import { tmpdir } from 'os';
3022+
3023+
export interface OpenCommandPipeArgs {
3024+
type: 'open';
3025+
@@ -54,6 +56,11 @@ export class CLIServer {
3026+
private async setup(): Promise<string> {
3027+
this._ipcHandlePath = generateRandomPipeName();
3028+
3029+
+ // NOTE@coder: Write this out so we can get the most recent path.
3030+
+ fs.promises.writeFile(join(tmpdir(), "vscode-ipc"), this._ipcHandlePath).catch((error) => {
3031+
+ this.logService.error(error);
3032+
+ });
3033+
+
3034+
try {
3035+
this._server.listen(this.ipcHandlePath);
3036+
this._server.on('error', err => this.logService.error(err));
30123037
diff --git a/src/vs/workbench/api/worker/extHost.worker.services.ts b/src/vs/workbench/api/worker/extHost.worker.services.ts
30133038
index 3843fdec386edc09a1d361b63de892a04e0070ed..8aac4df527857e964798362a69f5591bef07c165 100644
30143039
--- a/src/vs/workbench/api/worker/extHost.worker.services.ts

src/node/cli.ts

+30-2
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@ import * as os from "os"
55
import * as path from "path"
66
import { Args as VsArgs } from "../../lib/vscode/src/vs/server/ipc"
77
import { AuthType } from "./http"
8-
import { generatePassword, humanPath, paths } from "./util"
8+
import { canConnect, generatePassword, humanPath, paths } from "./util"
99

1010
export class Optional<T> {
1111
public constructor(public readonly value?: T) {}
@@ -469,7 +469,35 @@ export const shouldOpenInExistingInstance = async (args: Args): Promise<string |
469469
return process.env.VSCODE_IPC_HOOK_CLI
470470
}
471471

472-
// TODO: implement
472+
const readSocketPath = async (): Promise<string | undefined> => {
473+
try {
474+
return await fs.readFile(path.join(os.tmpdir(), "vscode-ipc"), "utf8")
475+
} catch (error) {
476+
if (error.code !== "ENOENT") {
477+
throw error
478+
}
479+
}
480+
return undefined
481+
}
482+
483+
// If these flags are set then assume the user is trying to open in an
484+
// existing instance since these flags have no effect otherwise.
485+
const openInFlagCount = ["reuse-window", "new-window"].reduce((prev, cur) => {
486+
return args[cur as keyof Args] ? prev + 1 : prev
487+
}, 0)
488+
if (openInFlagCount > 0) {
489+
return readSocketPath()
490+
}
491+
492+
// It's possible the user is trying to spawn another instance of code-server.
493+
// Check if any unrelated flags are set (add one for `_` which always exists),
494+
// that a file or directory was passed, and that the socket is active.
495+
if (Object.keys(args).length === openInFlagCount + 1 && args._.length > 0) {
496+
const socketPath = await readSocketPath()
497+
if (socketPath && (await canConnect(socketPath))) {
498+
return socketPath
499+
}
500+
}
473501

474502
return undefined
475503
}

src/node/socket.ts

+1-12
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@ import * as path from "path"
44
import * as tls from "tls"
55
import { Emitter } from "../common/emitter"
66
import { generateUuid } from "../common/util"
7-
import { tmpdir } from "./util"
7+
import { canConnect, tmpdir } from "./util"
88

99
/**
1010
* Provides a way to proxy a TLS socket. Can be used when you need to pass a
@@ -89,17 +89,6 @@ export class SocketProxyProvider {
8989
}
9090

9191
public async findFreeSocketPath(basePath: string, maxTries = 100): Promise<string> {
92-
const canConnect = (path: string): Promise<boolean> => {
93-
return new Promise((resolve) => {
94-
const socket = net.connect(path)
95-
socket.once("error", () => resolve(false))
96-
socket.once("connect", () => {
97-
socket.destroy()
98-
resolve(true)
99-
})
100-
})
101-
}
102-
10392
let i = 0
10493
let path = basePath
10594
while ((await canConnect(path)) && i < maxTries) {

src/node/util.ts

+15
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ import * as cp from "child_process"
22
import * as crypto from "crypto"
33
import envPaths from "env-paths"
44
import * as fs from "fs-extra"
5+
import * as net from "net"
56
import * as os from "os"
67
import * as path from "path"
78
import * as util from "util"
@@ -246,3 +247,17 @@ export function pathToFsPath(path: string, keepDriveLetterCasing = false): strin
246247
}
247248
return value
248249
}
250+
251+
/**
252+
* Return a promise that resolves with whether the socket path is active.
253+
*/
254+
export function canConnect(path: string): Promise<boolean> {
255+
return new Promise((resolve) => {
256+
const socket = net.connect(path)
257+
socket.once("error", () => resolve(false))
258+
socket.once("connect", () => {
259+
socket.destroy()
260+
resolve(true)
261+
})
262+
})
263+
}

test/cli.test.ts

+85-4
Original file line numberDiff line numberDiff line change
@@ -1,16 +1,24 @@
11
import { Level, logger } from "@coder/logger"
22
import * as assert from "assert"
3+
import * as fs from "fs-extra"
4+
import * as net from "net"
5+
import * as os from "os"
36
import * as path from "path"
4-
import { parse, setDefaults } from "../src/node/cli"
5-
import { paths } from "../src/node/util"
7+
import { Args, parse, setDefaults, shouldOpenInExistingInstance } from "../src/node/cli"
8+
import { paths, tmpdir } from "../src/node/util"
69

7-
describe("cli", () => {
10+
type Mutable<T> = {
11+
-readonly [P in keyof T]: T[P]
12+
}
13+
14+
describe("parser", () => {
815
beforeEach(() => {
916
delete process.env.LOG_LEVEL
1017
})
1118

1219
// The parser should not set any defaults so the caller can determine what
13-
// values the user actually set. These are set after calling `setDefaults`.
20+
// values the user actually set. These are only set after explicitly calling
21+
// `setDefaults`.
1422
const defaults = {
1523
"extensions-dir": path.join(paths.data, "extensions"),
1624
"user-data-dir": paths.data,
@@ -225,3 +233,76 @@ describe("cli", () => {
225233
})
226234
})
227235
})
236+
237+
describe("cli", () => {
238+
let args: Mutable<Args> = { _: [] }
239+
const testDir = path.join(tmpdir, "tests/cli")
240+
const vscodeIpcPath = path.join(os.tmpdir(), "vscode-ipc")
241+
242+
before(async () => {
243+
await fs.remove(testDir)
244+
await fs.mkdirp(testDir)
245+
})
246+
247+
beforeEach(async () => {
248+
delete process.env.VSCODE_IPC_HOOK_CLI
249+
args = { _: [] }
250+
await fs.remove(vscodeIpcPath)
251+
})
252+
253+
it("should use existing if inside code-server", async () => {
254+
process.env.VSCODE_IPC_HOOK_CLI = "test"
255+
assert.strictEqual(await shouldOpenInExistingInstance(args), "test")
256+
257+
args.port = 8081
258+
args._.push("./file")
259+
assert.strictEqual(await shouldOpenInExistingInstance(args), "test")
260+
})
261+
262+
it("should use existing if --reuse-window is set", async () => {
263+
args["reuse-window"] = true
264+
assert.strictEqual(await shouldOpenInExistingInstance(args), undefined)
265+
266+
await fs.writeFile(vscodeIpcPath, "test")
267+
assert.strictEqual(await shouldOpenInExistingInstance(args), "test")
268+
269+
args.port = 8081
270+
assert.strictEqual(await shouldOpenInExistingInstance(args), "test")
271+
})
272+
273+
it("should use existing if --new-window is set", async () => {
274+
args["new-window"] = true
275+
assert.strictEqual(await shouldOpenInExistingInstance(args), undefined)
276+
277+
await fs.writeFile(vscodeIpcPath, "test")
278+
assert.strictEqual(await shouldOpenInExistingInstance(args), "test")
279+
280+
args.port = 8081
281+
assert.strictEqual(await shouldOpenInExistingInstance(args), "test")
282+
})
283+
284+
it("should use existing if no unrelated flags are set, has positional, and socket is active", async () => {
285+
assert.strictEqual(await shouldOpenInExistingInstance(args), undefined)
286+
287+
args._.push("./file")
288+
assert.strictEqual(await shouldOpenInExistingInstance(args), undefined)
289+
290+
const socketPath = path.join(testDir, "socket")
291+
await fs.writeFile(vscodeIpcPath, socketPath)
292+
assert.strictEqual(await shouldOpenInExistingInstance(args), undefined)
293+
294+
await new Promise((resolve) => {
295+
const server = net.createServer(() => {
296+
// Close after getting the first connection.
297+
server.close()
298+
})
299+
server.once("listening", () => resolve(server))
300+
server.listen(socketPath)
301+
})
302+
303+
assert.strictEqual(await shouldOpenInExistingInstance(args), socketPath)
304+
305+
args.port = 8081
306+
assert.strictEqual(await shouldOpenInExistingInstance(args), undefined)
307+
})
308+
})

0 commit comments

Comments
 (0)