Skip to content

Emit dial events rather than logging them #563

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

Open
wants to merge 7 commits into
base: main
Choose a base branch
from
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
15 changes: 8 additions & 7 deletions src/events.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
type Callback = (args: unknown) => void;
type Callback<T = unknown> = (args: T) => void;

/**
* MachineConnectionEvent events are emitted by a Client's EventDispatcher when
Expand All @@ -9,21 +9,22 @@ export enum MachineConnectionEvent {
CONNECTED = 'connected',
DISCONNECTING = 'disconnecting',
DISCONNECTED = 'disconnected',
DIAL_EVENT = 'dialing',
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is DIALING different than CONNECTING?

}

export class EventDispatcher {
listeners: Partial<Record<string, Set<Callback>>> = {};

on(type: string, listener: Callback) {
on<T>(type: string, listener: Callback<T>) {
const { listeners } = this;
listeners[type] ??= new Set();
listeners[type]?.add(listener);
listeners[type]?.add(listener as Callback);
}

once(type: string, listener: Callback) {
const fn = (args: unknown) => {
once<T>(type: string, listener: Callback<T>) {
const fn = (args: T) => {
listener(args);
this.off(type, listener);
this.off(type, listener as Callback);
};
this.on(type, fn);
}
Expand All @@ -36,7 +37,7 @@ export class EventDispatcher {
this.listeners[type]?.delete(listener);
}
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why aren't we passing <T> to once, has, and off?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Added to once, can't think of any type safety added by the others can you?

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

No, once make sense.


emit(type: string, args: unknown) {
emit<T = unknown>(type: string, args: T) {
for (const callback of this.listeners[type] ?? []) {
callback(args);
}
Expand Down
28 changes: 16 additions & 12 deletions src/robot/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -210,17 +210,18 @@ export class RobotClient extends EventDispatcher implements Robot {
return;
}

// eslint-disable-next-line no-console
console.debug('Connection closed, will try to reconnect');
this.emit(MachineConnectionEvent.DIAL_EVENT, {
message: 'Connection closed, attempting to reconnect',
});

const backOffOpts: Partial<IBackOffOptions> = {
retry: (error, attemptNumber) => {
retry: (error: Error, attemptNumber) => {
// TODO: This ought to check exceptional errors so as to not keep failing forever.

// eslint-disable-next-line no-console
console.debug(
`Failed to connect, attempt ${attemptNumber} with backoff`,
error
);
this.emit(MachineConnectionEvent.DIAL_EVENT, {
message: `Failed to connect, attempt ${attemptNumber} with backoff`,
error,
});

// Always retry the next attempt
return true;
Expand All @@ -234,12 +235,14 @@ export class RobotClient extends EventDispatcher implements Robot {
}
void backOff(async () => this.connect(), backOffOpts)
.then(() => {
// eslint-disable-next-line no-console
console.debug('Reconnected successfully!');
this.emit(MachineConnectionEvent.DIAL_EVENT, {
message: 'Reconnected successfully',
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why is this a DIAL_EVENT and not CONNECTED?

});
})
.catch(() => {
// eslint-disable-next-line no-console
console.debug(`Reached max attempts: ${this.reconnectMaxAttempts}`);
this.emit(MachineConnectionEvent.DIAL_EVENT, {
message: `Reached max attempts: ${this.reconnectMaxAttempts}`,
});
});
}

Expand Down Expand Up @@ -502,6 +505,7 @@ export class RobotClient extends EventDispatcher implements Robot {
}

const webRTCConn = await dialWebRTC(
this,
this.webrtcOptions.signalingAddress || this.serviceHost,
this.webrtcOptions.host,
opts
Expand Down
93 changes: 56 additions & 37 deletions src/robot/dial.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,11 @@
import { backOff, type IBackOffOptions } from 'exponential-backoff';
import { backOff } from 'exponential-backoff';
import { isCredential } from '../app/viam-transport';
import { DIAL_TIMEOUT } from '../constants';
import type { AccessToken, Credential } from '../main';
import {
MachineConnectionEvent,
type AccessToken,
type Credential,
} from '../main';
import { RobotClient } from './client';

/** Options required to dial a robot via gRPC. */
Expand All @@ -27,9 +31,6 @@ const isPosInt = (x: number): boolean => {
const isLocalConnection = (url: string) => url.includes('local');

const dialDirect = async (conf: DialDirectConf): Promise<RobotClient> => {
// eslint-disable-next-line no-console
console.debug('dialing via gRPC...');

if (!isLocalConnection(conf.host)) {
throw new Error(
`cannot dial "${conf.host}" directly, please use a local url instead.`
Expand All @@ -48,13 +49,18 @@ const dialDirect = async (conf: DialDirectConf): Promise<RobotClient> => {
}
const client = new RobotClient(conf.host, undefined, sessOpts, clientConf);

client.emit(MachineConnectionEvent.DIAL_EVENT, {
message: 'dialing via gRPC',
});

await client.connect({
creds: conf.credentials,
dialTimeout: conf.dialTimeout ?? DIAL_TIMEOUT,
});

// eslint-disable-next-line no-console
console.debug('connected via gRPC');
client.emit(MachineConnectionEvent.DIAL_EVENT, {
message: 'connected via gRPC',
});

return client;
};
Expand Down Expand Up @@ -92,9 +98,6 @@ export interface DialWebRTCConf {
}

const dialWebRTC = async (conf: DialWebRTCConf): Promise<RobotClient> => {
// eslint-disable-next-line no-console
console.debug('dialing via WebRTC...');

const impliedURL = conf.serviceHost ?? conf.host;
const { signalingAddress } = conf;
const iceServers = conf.iceServers ?? [];
Expand All @@ -115,14 +118,19 @@ const dialWebRTC = async (conf: DialWebRTCConf): Promise<RobotClient> => {
}
const client = new RobotClient(impliedURL, clientConf, sessOpts);

client.emit(MachineConnectionEvent.DIAL_EVENT, {
message: 'Dialing via WebRTC.',
});

await client.connect({
priority: conf.priority,
dialTimeout: conf.dialTimeout ?? DIAL_TIMEOUT,
creds: conf.credentials,
});

// eslint-disable-next-line no-console
console.debug('connected via WebRTC');
client.emit(MachineConnectionEvent.DIAL_EVENT, {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Similarly, why is this a DIAL_EVENT and not CONNECTED?

message: 'Connected via WebRTC.',
});

return client;
};
Expand Down Expand Up @@ -160,33 +168,28 @@ export const createRobotClient = async (
): Promise<RobotClient> => {
validateDialConf(conf);

const backOffOpts: Partial<IBackOffOptions> = {
retry: (error, attemptNumber) => {
// TODO: This ought to check exceptional errors so as to not keep failing forever.

// eslint-disable-next-line no-console
console.debug(
`Failed to connect, attempt ${attemptNumber} with backoff`,
error
);

// Abort reconnects if the the caller specifies, otherwise retry
return !conf.reconnectAbortSignal?.abort;
},
};
if (conf.reconnectMaxWait !== undefined) {
backOffOpts.maxDelay = conf.reconnectMaxWait;
}
if (conf.reconnectMaxAttempts !== undefined) {
backOffOpts.numOfAttempts = conf.reconnectMaxAttempts;
}

// Try to dial via WebRTC first.
if (isDialWebRTCConf(conf) && !conf.reconnectAbortSignal?.abort) {
try {
return conf.noReconnect
const client = conf.noReconnect
? await dialWebRTC(conf)
: await backOff(async () => dialWebRTC(conf), backOffOpts);
: await backOff(async () => dialWebRTC(conf), {
maxDelay: conf.reconnectMaxWait,
numOfAttempts: conf.reconnectMaxAttempts,
retry: (error: Error, attemptNumber) => {
// TODO: This ought to check exceptional errors so as to not keep failing forever.

client.emit(MachineConnectionEvent.DIAL_EVENT, {
message: `Failed to connect via WebRTC, attempt ${attemptNumber} with backoff.`,
error,
});

// Abort reconnects if the the caller specifies, otherwise retry
return !conf.reconnectAbortSignal?.abort;
},
});

return client;
} catch {
// eslint-disable-next-line no-console
console.debug('Failed to connect via WebRTC');
Expand All @@ -195,9 +198,25 @@ export const createRobotClient = async (

if (!conf.reconnectAbortSignal?.abort) {
try {
return conf.noReconnect
const client = conf.noReconnect
? await dialDirect(conf)
: await backOff(async () => dialDirect(conf), backOffOpts);
: await backOff(async () => dialDirect(conf), {
maxDelay: conf.reconnectMaxWait,
numOfAttempts: conf.reconnectMaxAttempts,
retry: (error: Error, attemptNumber) => {
// TODO: This ought to check exceptional errors so as to not keep failing forever.

client.emit(MachineConnectionEvent.DIAL_EVENT, {
message: `Failed to connect via gRPC, attempt ${attemptNumber} with backoff.`,
error,
});

// Abort reconnects if the the caller specifies, otherwise retry
return !conf.reconnectAbortSignal?.abort;
},
});

return client;
} catch {
// eslint-disable-next-line no-console
console.debug('Failed to connect via gRPC');
Expand Down
14 changes: 13 additions & 1 deletion src/rpc/dial.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,8 @@ import { newPeerConnectionForClient } from './peer';
import { createGrpcWebTransport } from '@connectrpc/connect-web';
import { isCredential, type Credentials } from '../app/viam-transport';
import { SignalingExchange } from './signaling-exchange';
import type { RobotClient } from '../robot';
import { MachineConnectionEvent } from '../events';

export interface DialOptions {
credentials?: Credentials | undefined;
Expand Down Expand Up @@ -337,6 +339,7 @@ const getOptionalWebRTCConfig = async (
* to handle reconnect on connection termination
*/
export const dialWebRTC = async (
client: RobotClient,
signalingAddress: string,
host: string,
dialOpts?: DialOptions
Expand Down Expand Up @@ -397,6 +400,12 @@ export const dialWebRTC = async (
dc,
webrtcOpts
);

exchange.on<{ message: string; error?: Error }>(
MachineConnectionEvent.DIAL_EVENT,
(event) => client.emit(MachineConnectionEvent.DIAL_EVENT, event)
);

try {
// set timeout for dial attempt if a timeout is specified
if (dialOpts?.dialTimeout !== undefined) {
Expand Down Expand Up @@ -426,7 +435,10 @@ export const dialWebRTC = async (
dataChannel: dc,
};
} catch (error) {
console.error('error dialing', error); // eslint-disable-line no-console
client.emit(MachineConnectionEvent.DIAL_EVENT, {
message: 'Error dialing.',
error,
});
throw error;
} finally {
if (!successful) {
Expand Down
Loading