Skip to content

Commit

Permalink
more fixes
Browse files Browse the repository at this point in the history
  • Loading branch information
Patrick Bergeron committed Jun 23, 2023
1 parent b071b62 commit 50c6811
Show file tree
Hide file tree
Showing 6 changed files with 198 additions and 182 deletions.
2 changes: 1 addition & 1 deletion app/.holium/configs/webpack.config.renderer.dev.ts
Original file line number Diff line number Diff line change
Expand Up @@ -138,7 +138,7 @@ const configuration: webpack.Configuration = {
NODE_ENV: 'development',
PLAYGROUND_PORT: playgroundPort,
USE_LOCAL_WALLET_API: useLocalWalletAPI,
API_URL: 'https://backend-server-test.thirdearth.com',
API_URL: 'https://backend-server.third.earth',
JOIN_API_URL: 'http://localhost:3000',
API_HEADERS_CLIENT_ID: '5',
API_HEADERS_VERSION: '2',
Expand Down
3 changes: 2 additions & 1 deletion app/src/main/helpers/power.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,12 +4,13 @@ const registerListeners = (mainWindow: BrowserWindow) => {
powerMonitor.on('suspend', () => {
if (mainWindow.isDestroyed()) return;

console.log('powerMonitor.suspend');
mainWindow.webContents.send('realm.sys.sleep');
mainWindow.webContents.send('realm.sys.suspend');
});
powerMonitor.on('resume', () => {
if (mainWindow.isDestroyed()) return;

console.log('powerMonitor.resume');
mainWindow.webContents.send('realm.sys.wake');
mainWindow.webContents.send('realm.sys.resume');
});
Expand Down
16 changes: 8 additions & 8 deletions app/src/os/services/api/api-connection.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,14 +19,14 @@ export class APIConnection {
private constructor(session: ConduitSession) {
this.conduitInstance = new Conduit(session.ship);
this.handleConnectionStatus(this.conduitInstance);
this.conduitInstance
.init(session.url, session.code, session.cookie ?? '')
// .then(() => {
// log.info('Conduit initialized');
// })
.catch((e) => {
log.error('Conduit initialization failed', e);
});
// this.conduitInstance
// .init(session.url, session.code, session.cookie ?? '')
// // .then(() => {
// // log.info('Conduit initialized');
// // })
// .catch((e) => {
// log.error('Conduit initialization failed', e);
// });

app.on('quit', () => {
this.closeChannel();
Expand Down
241 changes: 126 additions & 115 deletions app/src/os/services/api/conduit.ts
Original file line number Diff line number Diff line change
Expand Up @@ -133,10 +133,12 @@ export class Conduit extends EventEmitter {
mark: 'helm-hi',
json: 'Opening Realm API channel',
});
console.log('init: starting SSE');
await this.startSSE(this.channelUrl(this.uid));
}

async startSSE(channelUrl: string): Promise<void> {
console.log('start SSE => %o', this.status);
if (this.status === ConduitState.Connected) {
return Promise.resolve();
}
Expand All @@ -151,130 +153,135 @@ export class Conduit extends EventEmitter {
this.updateStatus(ConduitState.Initialized);

return new Promise((resolve, reject) => {
this.sse = new EventSource(channelUrl, {
headers: { Cookie: this.cookie },
});
console.log('start SSE');
try {
this.sse = new EventSource(channelUrl, {
headers: { Cookie: this.cookie },
});

this.sse.onopen = async (response) => {
if (response.type === 'open') {
this.updateStatus(ConduitState.Connected);
resolve();
} else {
this.updateStatus(ConduitState.Failed);
reject(new Error('failed to open sse'));
}
};
this.sse.onopen = async (response) => {
if (response.type === 'open') {
this.updateStatus(ConduitState.Connected);
resolve();
} else {
this.updateStatus(ConduitState.Failed);
reject(new Error('failed to open sse'));
}
};

this.sse.onmessage = async (event: MessageEvent) => {
if (this.status !== ConduitState.Connected) {
this.updateStatus(ConduitState.Connected);
}
const parsedData = JSON.parse(event.data);
const eventId = parseInt(parsedData.id, 10);
const type = parsedData.response as Responses;
const lastEventId = parseInt(event.lastEventId, 10);
if (lastEventId - this.lastAckId > 20) {
this.ack(lastEventId);
}
switch (type) {
case 'poke':
if (this.pokes.has(eventId)) {
const handler = this.pokes.get(eventId);
if (parsedData.ok && handler) {
// @ts-expect-error
handler.onSuccess();
} else if (parsedData.err && handler) {
// @ts-expect-error
handler.onError(parsedData.err);
} else {
log.error('poke sse error', parsedData.err);
this.sse.onmessage = async (event: MessageEvent) => {
if (this.status !== ConduitState.Connected) {
this.updateStatus(ConduitState.Connected);
}
const parsedData = JSON.parse(event.data);
const eventId = parseInt(parsedData.id, 10);
const type = parsedData.response as Responses;
const lastEventId = parseInt(event.lastEventId, 10);
if (lastEventId - this.lastAckId > 20) {
this.ack(lastEventId);
}
switch (type) {
case 'poke':
if (this.pokes.has(eventId)) {
const handler = this.pokes.get(eventId);
if (parsedData.ok && handler) {
// @ts-expect-error
handler.onSuccess();
} else if (parsedData.err && handler) {
// @ts-expect-error
handler.onError(parsedData.err);
} else {
log.error('poke sse error', parsedData.err);
}
}
}
this.pokes.delete(eventId);
break;
//
case 'subscribe':
if (parsedData.err) {
const watchHandler = this.watches.get(eventId);
if (watchHandler) {
watchHandler.onError?.(eventId, parsedData.err);
this.pokes.delete(eventId);
break;
//
case 'subscribe':
if (parsedData.err) {
const watchHandler = this.watches.get(eventId);
if (watchHandler) {
watchHandler.onError?.(eventId, parsedData.err);
} else {
log.error('watch sse error', parsedData.err);
}
this.setAsIdleWatch(eventId);
} else {
log.error('watch sse error', parsedData.err);
const watchHandler = this.watches.get(eventId);
if (watchHandler) {
watchHandler.onSubscribed?.(eventId);
}
}
this.setAsIdleWatch(eventId);
} else {
const watchHandler = this.watches.get(eventId);
if (watchHandler) {
watchHandler.onSubscribed?.(eventId);
break;
//
case 'diff': {
const json = parsedData.json;
const mark = parsedData.mark;
if (this.watches.has(eventId)) {
this.watches.get(eventId)?.onEvent?.(json, eventId, mark);
}
}
break;
//
case 'diff': {
const json = parsedData.json;
const mark = parsedData.mark;
if (this.watches.has(eventId)) {
this.watches.get(eventId)?.onEvent?.(json, eventId, mark);
}
const reaction = Object.keys(json)[0];
const maybeReactionPath = `${mark}.${reaction}`;
if (this.reactions.has(maybeReactionPath)) {
this.reactions.get(maybeReactionPath)?.(parsedData.json, mark);
this.reactions.delete(maybeReactionPath);
}
break;
}
// quit
case 'quit':
log.info('on quit', eventId, this.watches.has(eventId));
if (this.watches.has(eventId)) {
const reconnectSub = this.watches.get(eventId);
this.setAsIdleWatch(eventId);
if (reconnectSub?.onQuit) {
reconnectSub?.onQuit?.(parsedData);
} else {
this.resubscribe(eventId);
const reaction = Object.keys(json)[0];
const maybeReactionPath = `${mark}.${reaction}`;
if (this.reactions.has(maybeReactionPath)) {
this.reactions.get(maybeReactionPath)?.(parsedData.json, mark);
this.reactions.delete(maybeReactionPath);
}
break;
}
break;
//
default:
log.info('unrecognized', parsedData);
break;
}
};
this.sse.onerror = async (error) => {
log.info(this.watches.keys());
if (!error) {
this.handleError({ status: 500, message: 'Unknown error' });
}
log.error('sse error', error);
if (error.status === 403) {
// quit
case 'quit':
log.info('on quit', eventId, this.watches.has(eventId));
if (this.watches.has(eventId)) {
const reconnectSub = this.watches.get(eventId);
this.setAsIdleWatch(eventId);
if (reconnectSub?.onQuit) {
reconnectSub?.onQuit?.(parsedData);
} else {
this.resubscribe(eventId);
}
}
break;
//
default:
log.info('unrecognized', parsedData);
break;
}
};
this.sse.onerror = async (error) => {
log.info(this.watches.keys());
if (!error) {
this.handleError({ status: 500, message: 'Unknown error' });
}
log.error('sse error', error);
if (error.status === 403) {
// @ts-ignore
error.originator = 'sse';
this.handleError(error);
}
// @ts-ignore
error.originator = 'sse';
this.handleError(error);
}
// @ts-ignore
if (error.status === '404') {
return;
}
// @ts-expect-error
if (error.status >= 500) {
console.log('error', error);
this.updateStatus(ConduitState.Failed);
this.failGracefully();
}
if (!error.status) {
// this happens when the ship is offline
console.log('error.status', error);
if (error.status === '404') {
return;
}
// @ts-expect-error
if (error.status >= 500) {
console.log('error', error);
this.updateStatus(ConduitState.Failed);
this.failGracefully();
}
if (!error.status) {
// this happens when the ship is offline
console.log('error.status', error);

this.updateStatus(ConduitState.Failed);
this.disconnectGracefully();
}
};
this.sse.addEventListener('close', () => {
log.warn('Ship unexpectedly closed the connection');
});
this.updateStatus(ConduitState.Failed);
this.disconnectGracefully();
}
};
this.sse.addEventListener('close', () => {
log.warn('Ship unexpectedly closed the connection');
});
} catch (e) {
reject(e);
}
});
}

Expand Down Expand Up @@ -576,10 +583,14 @@ export class Conduit extends EventEmitter {
return false;
}
if (
// body.action !== Action.Delete &&
this.status !== ConduitState.Connected &&
this.status !== ConduitState.Initialized
) {
this.startSSE(this.channelUrl(this.uid));
console.info('postToChannel: status is not connected, starting SSE');
// you must await here for SSE to complete; otherwise init calls in other
// locations of the conduit can create 2nd connections
await this.startSSE(this.channelUrl(this.uid));
}

return true;
Expand Down
44 changes: 24 additions & 20 deletions app/src/os/services/auth/onboarding.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -539,27 +539,31 @@ export class OnboardingService extends AbstractService<OnboardingUpdateTypes> {
const { serverUrl, serverCode, serverId } = (this.credentials ||
creds) as OnboardingCredentials;
const cookie = await this.getCookie({ serverId, serverUrl, serverCode });
return new Promise((resolve, reject) => {
// after 10 seconds, give up
setTimeout(() => {
reject(
'conduit took too long to open (is the url supposed to be https instead of http?)'
);
}, 10000);
APIConnection.getInstance({
url: serverUrl,
code: serverCode,
ship: serverId,
cookie,
// return new Promise(async (resolve, reject) => {
// after 10 seconds, give up
setTimeout(() => {
throw new Error(
'conduit took too long to open (is the url supposed to be https instead of http?)'
);
}, 10000);

const conduit = APIConnection.getInstance({
url: serverUrl,
code: serverCode,
ship: serverId,
cookie,
}).conduit;
conduit
.on('connected', () => {
// resolve(null);
})
.conduit.on('connected', () => {
resolve(null);
})
.on('error', (err: any) => {
log.error('onboarding.service.ts:', 'Conduit error', err);
reject(err);
});
});
.on('error', (err: any) => {
log.error('onboarding.service.ts:', 'Conduit error', err);
// reject(err);
});
console.log('_openConduit: init');
await conduit.init(serverUrl, serverCode, cookie);
// });
}

private _createShipDB(
Expand Down
Loading

0 comments on commit 50c6811

Please sign in to comment.