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 the SDK to use the new HTTP event tracker #410

Merged
merged 23 commits into from
Aug 23, 2024
Merged
Show file tree
Hide file tree
Changes from 5 commits
Commits
Show all changes
23 commits
Select commit Hold shift + click to select a range
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
23 changes: 0 additions & 23 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 0 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -39,8 +39,6 @@
"jest": "^29.3.1",
"jest-environment-jsdom": "^29.3.1",
"jest-extended": "^4.0.0",
"jest-websocket-mock": "^2.4.0",
"mock-socket": "^9.1.5",
"node-fetch": "^2.6.7",
"ts-jest": "^29.0.3",
"typescript": "^5.0.0"
Expand Down
153 changes: 0 additions & 153 deletions src/channel/beaconSocketChannel.ts

This file was deleted.

117 changes: 117 additions & 0 deletions src/channel/httpBeaconChannel.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,117 @@
import {ChannelListener, DuplexChannel} from './channel';
import {Envelope} from './guaranteedChannel';
import {Logger, NullLogger} from '../logging';
import {CidAssigner} from '../cid';
import {formatMessage} from '../error';
import {CLIENT_LIBRARY} from '../constants';

export type Configuration = {
appId: string,
endpointUrl: string,
cidAssigner: CidAssigner,
logger?: Logger,
};

type ApiProblem = {
type: string,
title: string,
status: number,
detail: string,
};

export class HttpBeaconChannel implements DuplexChannel<string, Envelope<string, string>> {
private static readonly NON_RETRYABLE_STATUSES: ReadonlySet<number> = new Set([
403, // API usage limit exceeded
401, // Invalid token
]);

private readonly configuration: Omit<Configuration, 'logger'>;

private readonly logger: Logger;

private readonly listeners: Array<ChannelListener<string>> = [];

private closed = false;

public constructor({logger = new NullLogger(), ...configuration}: Configuration) {
this.configuration = configuration;
this.logger = logger;
}

public async publish({id: receiptId, message}: Envelope<string, string>): Promise<void> {
if (this.closed) {
return Promise.reject(new Error('Channel is closed'));
}

const {token, timestamp, context, payload} = JSON.parse(message);
const {endpointUrl, appId, cidAssigner} = this.configuration;

return fetch(endpointUrl, {
method: 'POST',
headers: {
'X-App-Id': appId,
'X-Client-Id': await cidAssigner.assignCid(),
'X-Client-Library': CLIENT_LIBRARY,
denis-rossati marked this conversation as resolved.
Show resolved Hide resolved
...(token !== undefined ? {'X-Token': token} : {}),
},
body: JSON.stringify({
context: context,
payload: payload,
originalTime: timestamp,
departureTime: Date.now(),
}),
}).then(async response => {
if (response.ok) {
this.notify(receiptId);

return;
}

const problem: ApiProblem = await response.json().catch(
() => ({
type: 'https://croct.help/api/event-tracker#unexpected-error',
title: response.statusText,
status: response.status,
}),
);

if (HttpBeaconChannel.NON_RETRYABLE_STATUSES.has(problem.status)) {
marcospassos marked this conversation as resolved.
Show resolved Hide resolved
this.logger.error(`Beacon rejected with non-retryable status: ${problem.title}`);

this.notify(receiptId);

return Promise.resolve();
}

return Promise.reject(new Error(problem.title));
}).catch(error => {
this.logger.error(`Failed to publish beacon: ${formatMessage(error)}`);

return Promise.reject(error);
});
}

public subscribe(listener: ChannelListener<string>): void {
if (!this.listeners.includes(listener)) {
this.listeners.push(listener);
}
}

public unsubscribe(listener: ChannelListener<string>): void {
const index = this.listeners.indexOf(listener);

if (index >= 0) {
this.listeners.splice(index, 1);
}
}

private notify(receiptId: string): void {
this.listeners.forEach(dispatch => dispatch(receiptId));
}

public close(): Promise<void> {
this.closed = true;

return Promise.resolve();
}
}
3 changes: 1 addition & 2 deletions src/channel/index.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,7 @@
export * from './channel';
export {BeaconSocketChannel, DuplexChannelFactory} from './beaconSocketChannel';
export {EncodedChannel} from './encodedChannel';
export {GuaranteedChannel} from './guaranteedChannel';
export {QueuedChannel} from './queuedChannel';
export {RetryChannel} from './retryChannel';
export {SandboxChannel} from './sandboxChannel';
export {SocketChannel} from './socketChannel';
export {HttpBeaconChannel} from './httpBeaconChannel';
Loading
Loading