Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 20 additions & 0 deletions src/Config/CliInfo.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
import { CliInfo } from './CliInfo';

describe('CliInfo', () => {
it('should assign 8 random hex characters as the instance ID', () => {
Comment thread
YarikMamykin marked this conversation as resolved.
Resolved
// act
const info = new CliInfo(process.cwd());

// assert
expect(info.instanceId).toMatch(/^[0-9a-f]{8}$/);
});

it('should assign a different instance ID to every process', () => {
// act
const first = new CliInfo(process.cwd());
const second = new CliInfo(process.cwd());

// assert
expect(first.instanceId).not.toBe(second.instanceId);
});
});
4 changes: 4 additions & 0 deletions src/Config/CliInfo.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,15 @@
import { sync } from 'find-up';
import path from 'node:path';
import { readFileSync } from 'node:fs';
import { randomBytes } from 'node:crypto';

export class CliInfo {
public readonly cwd: string;
public readonly version: string;
public readonly distribution: string | undefined;
// Per process, so the server can tell apart two processes sharing a Repeater ID.
// Only those few processes need to differ, so 32 bits keep it short to read out.
public readonly instanceId: string = randomBytes(4).toString('hex');
Comment thread
YarikMamykin marked this conversation as resolved.
Resolved

constructor(cwd: string) {
const packagePath = this.getPackagePath(cwd);
Expand Down
45 changes: 44 additions & 1 deletion src/Repeater/DefaultRepeaterServer.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,11 @@ import {
} from './DefaultRepeaterServer';
import { RepeaterErrorCodes, RepeaterServerEvents } from './RepeaterServer';
import { ProxyFactory } from '../Utils';
import { CliInfo } from '../Config';
import { instance, mock, reset } from 'ts-mockito';
import io from 'socket.io-client';
import { EventEmitter } from 'node:events';
import { hostname } from 'node:os';

jest.mock('socket.io-client', () => jest.fn());

Expand Down Expand Up @@ -67,6 +69,10 @@ describe('DefaultRepeaterServer', () => {
uri: 'http://localhost:8080',
token: 'dummy-token'
};
const info = {
version: '13.18.0',
instanceId: '3f9a1c07'
} as CliInfo;
const proxyFactoryMock = mock<ProxyFactory>();
const lookupMock = io as unknown as jest.MockedFunction<() => FakeSocket>;

Expand Down Expand Up @@ -97,7 +103,11 @@ describe('DefaultRepeaterServer', () => {
socket = new FakeSocket();
lookupMock.mockReturnValue(socket);

server = new DefaultRepeaterServer(instance(proxyFactoryMock), options);
server = new DefaultRepeaterServer(
instance(proxyFactoryMock),
options,
info
);
});

afterEach(() => {
Expand All @@ -107,6 +117,39 @@ describe('DefaultRepeaterServer', () => {
});

describe('connect', () => {
it('should identify the process in the handshake auth', async () => {
// act
await connect();

// assert
expect(lookupMock).toHaveBeenCalledWith(
options.uri,
expect.objectContaining({
auth: {
token: options.token,
domain: 'example.com',
instanceId: info.instanceId,
version: info.version,
hostname: hostname()
}
})
);
});

it('should keep the instance ID by reusing the socket on reconnection', async () => {
// arrange
await connect();

// act
socket.emit('connect_error', connectionError());
jest.advanceTimersByTime(6_500);
socket.emit('disconnect', 'io server disconnect');

// assert
expect(socket.connect).toHaveBeenCalledTimes(2);
expect(lookupMock).toHaveBeenCalledTimes(1);
});

it('should reconnect after a retryable connection error', async () => {
// arrange
await connect();
Expand Down
12 changes: 10 additions & 2 deletions src/Repeater/DefaultRepeaterServer.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { logger, ProxyFactory } from '../Utils';
import { CliInfo } from '../Config/CliInfo';
import {
DeployCommandOptions,
DeploymentRuntime,
Expand All @@ -24,6 +25,7 @@ import io, { Socket } from 'socket.io-client';
import parser from 'socket.io-msgpack-parser';
import { captureException, captureMessage, withScope } from '@sentry/node';
import { EventEmitter, once } from 'node:events';
import { hostname as osHostname } from 'node:os';

export interface DefaultRepeaterServerOptions {
readonly uri: string;
Expand Down Expand Up @@ -112,7 +114,8 @@ export class DefaultRepeaterServer implements RepeaterServer {
constructor(
@inject(ProxyFactory) private readonly proxyFactory: ProxyFactory,
@inject(DefaultRepeaterServerOptions)
private readonly options: DefaultRepeaterServerOptions
private readonly options: DefaultRepeaterServerOptions,
@inject(CliInfo) private readonly info: CliInfo
) {}

public disconnect() {
Expand Down Expand Up @@ -176,9 +179,14 @@ export class DefaultRepeaterServer implements RepeaterServer {
rejectUnauthorized: !this.options.insecure
})
: undefined,
// Servers that predate instanceId/version/hostname ignore unknown auth
// keys, unlike the deploy runtime payload, which rejects them.
auth: {
token: this.options.token,
domain: hostname
domain: hostname,
instanceId: this.info.instanceId,
version: this.info.version,
hostname: osHostname()
}
});

Expand Down
27 changes: 26 additions & 1 deletion src/Repeater/ServerRepeaterLauncher.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,8 @@ describe('ServerRepeaterLauncher', () => {
beforeEach(() => {
loggerSpy = spy(logger);
when(loggerSpy.warn(anything(), anything())).thenReturn();
when(loggerSpy.log(anything(), anything())).thenReturn();
when(loggerSpy.log(anything(), anything(), anything())).thenReturn();
when(mockedRepeaterServer.on(anything(), anything())).thenCall(
(event: string, handler: (payload?: unknown) => unknown) =>
handlers.set(event, handler)
Expand All @@ -34,7 +36,10 @@ describe('ServerRepeaterLauncher', () => {
instance(mock<Certificates>()),
instance(mock<ScriptLoader>()),
{} as RequestExecutorOptions,
{ version: '1.0.0' } as CliInfo
{
version: '1.0.0',
instanceId: '3f9a1c07'
} as CliInfo
);
});

Expand All @@ -44,6 +49,26 @@ describe('ServerRepeaterLauncher', () => {
});

describe('run', () => {
it('should print the instance ID once the Repeater is deployed', async () => {
// arrange
when(mockedRepeaterServer.deploy(anything(), anything())).thenResolve({
repeaterId: '8PY6wKetVqmfMC9K9g4A7Y'
});
await launcher.run('8PY6wKetVqmfMC9K9g4A7Y');

// act
await handlers.get(RepeaterServerEvents.CONNECTED)?.();

// assert
verify(
loggerSpy.log(
'The Repeater (%s) started, instance ID: %s',
'1.0.0',
'3f9a1c07'
)
).once();
});

it('should log a reconnecting warning on a reconnection attempt', async () => {
// arrange
await launcher.run('8PY6wKetVqmfMC9K9g4A7Y');
Expand Down
6 changes: 5 additions & 1 deletion src/Repeater/ServerRepeaterLauncher.ts
Original file line number Diff line number Diff line change
Expand Up @@ -208,7 +208,11 @@ export class ServerRepeaterLauncher implements RepeaterLauncher {
},
this.getRuntime()
);
logger.log('The Repeater (%s) started', this.info.version);
logger.log(
'The Repeater (%s) started, instance ID: %s',
this.info.version,
this.info.instanceId
);
} catch {
// noop
}
Expand Down
Loading