Skip to content

Commit

Permalink
Add heartbeat for api connection
Browse files Browse the repository at this point in the history
  • Loading branch information
riichinomics committed Feb 18, 2022
1 parent 8092cf1 commit 55af21f
Show file tree
Hide file tree
Showing 5 changed files with 39 additions and 7 deletions.
14 changes: 10 additions & 4 deletions api/src/connector.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,12 +11,9 @@ import { Majsoul, Store } from ".";
import { google } from "googleapis";
import { ContestTracker } from "./ContestTracker";
import { parseGameRecordResponse } from "./majsoul/types/parseGameRecordResponse";
import { Codec } from "./majsoul/Codec";
import * as util from "util";

const nameofFactory = <T>() => (name: keyof T) => name;
export const nameofContest = nameofFactory<store.Contest<ObjectId>>();
const nameofConfig = nameofFactory<store.Config<ObjectId>>();

async function main() {
const secrets = getSecrets();
Expand All @@ -32,6 +29,10 @@ async function main() {
// console.log(api.majsoulCodec.decodeMessage(Buffer.from("", "hex")));

await api.logIn(secrets.majsoul.uid, secrets.majsoul.accessToken);
api.errors$.subscribe((error => {
console.log("error detected with api connection: ", error);
process.exit(1);
}));

//spreadsheet.addGameDetails(await api.getGame(decodePaipuId("jijpnt-q3r346x6-y108-64fk-hbbn-lkptsjjyoszx_a925250810_2").split('_')[0]));

Expand All @@ -46,7 +47,12 @@ async function main() {
// });

const mongoStore = new store.Store();
await mongoStore.init(secrets.mongo?.username ?? "root", secrets.mongo?.password ?? "example");
try {
await mongoStore.init(secrets.mongo?.username ?? "root", secrets.mongo?.password ?? "example");
} catch (error) {
console.log("failed to connect to mongo db: ", error);
process.exit(1);
}

const googleAuth = new google.auth.OAuth2(
secrets.google.clientId,
Expand Down
21 changes: 19 additions & 2 deletions api/src/majsoul/Api.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import * as uuidv4 from "uuid/v4";
import { Root } from "protobufjs";
import fetch from "node-fetch";
import { Observable, using } from 'rxjs';
import { filter, map } from 'rxjs/operators';
import { from, interval, merge, Observable, of, pipe, using } from 'rxjs';
import { catchError, filter, map, mergeAll, timeout } from 'rxjs/operators';
import { Contest, Player } from "./types/types";
import { Codec } from "./Codec";
import { MessageType } from "./types/MessageType";
Expand Down Expand Up @@ -85,12 +85,29 @@ export class Api {
return PlayerZone.Unknown;
}

public get errors$(): Observable<any> {
return merge(
this.connection.errors$,
interval(1000 * 60).pipe(
map((number) => from(this.lobbyService.rpcCall<lq.ReqHeatBeat>("heatbeat", {
no_operation_counter: number,
})).pipe(
timeout(3000),
filter(() => false),
catchError(() => of("heartbeat failed")),
)),
mergeAll(),
)
);
}

public get majsoulCodec(): Codec {
return this.codec;
}

public async init(): Promise<void> {
await this.connection.init();
// this.lobbyService.rpcCall
}

public async logIn(userId: string, accessToken: string): Promise<void> {
Expand Down
9 changes: 9 additions & 0 deletions api/src/majsoul/Connection.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import { MessageType } from "./types/MessageType";

export class Connection {
private readonly messagesSubject = new Subject<any>();
private readonly errorSubject = new Subject<any>();
private socket: WebSocket;
constructor(private readonly server) { }

Expand All @@ -15,6 +16,10 @@ export class Connection {
return this.messagesSubject;
}

public get errors$(): Observable<any> {
return this.errorSubject;
}

public init(): Promise<void> {
return this.reconnect();
}
Expand Down Expand Up @@ -42,13 +47,17 @@ export class Connection {
});

this.socket.onerror = (event) => {
this.errorSubject.next(event);
console.log(`websocker onerror`, event);
}
this.socket.onclose = (event) => {
this.errorSubject.next(event);
}
this.socket.on("close", (a, b) => {
this.errorSubject.next();
});
this.socket.on("error", (e) => {
this.errorSubject.next(e);
console.log(`websocket error`, e);
});
this.socket.on("open", () => resolve());
Expand Down
1 change: 1 addition & 0 deletions api/src/store/Store.ts
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,7 @@ export class Store {
public async init(username: string, password: string): Promise<void> {
const url = `mongodb://${username}:${password}@${process.env.NODE_ENV === "production" ? 'majsoul_mongo' : 'localhost'}:27017/?authMechanism=SCRAM-SHA-256&authSource=admin`;
const client = new MongoClient(url);

await client.connect();

console.log("Connected successfully to server");
Expand Down
1 change: 0 additions & 1 deletion nginx.conf
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@ events {
worker_connections 1024;
}


http {
include /etc/nginx/mime.types;
default_type application/octet-stream;
Expand Down

0 comments on commit 55af21f

Please sign in to comment.