urbit/pkg/interface/src/views/apps/dojo/subscription.js

79 lines
1.6 KiB
JavaScript
Raw Normal View History

export default class Subscription {
constructor(store, api, channel) {
this.store = store;
this.api = api;
this.channel = channel;
this.channel.setOnChannelError(this.onChannelError.bind(this));
this.firstRoundComplete = false;
}
2020-05-01 05:54:12 +03:00
start() {
if (this.api.ship) {
this.firstRound();
2020-05-01 05:54:12 +03:00
} else {
console.error('~~~ ERROR: Must set api.ship before operation ~~~');
2020-05-01 05:54:12 +03:00
}
this.setupSlog();
}
setupSlog() {
const slog = new EventSource('/~/slog', { withCredentials: true });
slog.onopen = e => {
console.log('slog: opened stream');
}
slog.onmessage = e => {
this.handleEvent({ txt: e.data });
}
slog.onerror = e => {
console.error('slog: eventsource error:', e);
window.setTimeout(() => {
if (slog.readyState !== EventSource.CLOSED) return;
console.log('slog: reconnecting...');
this.setupSlog();
}, 10000);
}
2020-05-01 05:54:12 +03:00
}
delete() {
this.channel.delete();
2020-05-01 05:54:12 +03:00
}
onChannelError(err) {
console.error('event source error: ', err);
console.log('initiating new channel');
this.firstRoundComplete = false;
setTimeout(2000, () => {
this.store.handleEvent({
data: { clear : true }
});
this.start();
});
2020-05-01 05:54:12 +03:00
}
subscribe(path, app) {
this.api.bind(path, 'PUT', this.api.ship, app,
2020-05-01 05:54:12 +03:00
this.handleEvent.bind(this),
(err) => {
console.log(err);
this.subscribe(path, app);
},
() => {
this.subscribe(path, app);
});
}
firstRound() {
this.subscribe('/sole/' + this.api.dojoId, 'dojo');
}
handleEvent(diff) {
this.store.handleEvent(diff);
2020-05-01 05:54:12 +03:00
}
}