2020-11-13 18:00:22 +01:00
|
|
|
/**
|
|
|
|
* A class to get connections to the correct "api" server given a room name.
|
|
|
|
*/
|
2021-06-24 10:09:10 +02:00
|
|
|
import { RoomManagerClient } from "../Messages/generated/messages_grpc_pb";
|
|
|
|
import grpc from "grpc";
|
|
|
|
import crypto from "crypto";
|
|
|
|
import { API_URL } from "../Enum/EnvironmentVariable";
|
2020-11-13 18:00:22 +01:00
|
|
|
|
2020-12-14 22:20:43 +01:00
|
|
|
import Debug from "debug";
|
|
|
|
|
2021-06-24 10:09:10 +02:00
|
|
|
const debug = Debug("apiClientRespository");
|
2020-11-13 18:00:22 +01:00
|
|
|
|
|
|
|
class ApiClientRepository {
|
2020-12-14 22:20:43 +01:00
|
|
|
private roomManagerClients: RoomManagerClient[] = [];
|
|
|
|
|
2021-03-01 17:47:00 +01:00
|
|
|
public constructor(private apiUrls: string[]) {}
|
2020-11-13 18:00:22 +01:00
|
|
|
|
|
|
|
public async getClient(roomId: string): Promise<RoomManagerClient> {
|
2021-06-24 10:09:10 +02:00
|
|
|
const array = new Uint32Array(crypto.createHash("md5").update(roomId).digest());
|
2020-12-14 22:20:43 +01:00
|
|
|
const index = array[0] % this.apiUrls.length;
|
|
|
|
|
|
|
|
let client = this.roomManagerClients[index];
|
|
|
|
if (client === undefined) {
|
2021-06-24 10:09:10 +02:00
|
|
|
this.roomManagerClients[index] = client = new RoomManagerClient(
|
|
|
|
this.apiUrls[index],
|
|
|
|
grpc.credentials.createInsecure()
|
|
|
|
);
|
|
|
|
debug("Mapping room %s to API server %s", roomId, this.apiUrls[index]);
|
2020-11-13 18:00:22 +01:00
|
|
|
}
|
2020-12-14 22:20:43 +01:00
|
|
|
|
|
|
|
return Promise.resolve(client);
|
2020-11-13 18:00:22 +01:00
|
|
|
}
|
2020-12-11 12:23:50 +01:00
|
|
|
|
|
|
|
public async getAllClients(): Promise<RoomManagerClient[]> {
|
2021-06-24 10:09:10 +02:00
|
|
|
return [await this.getClient("")];
|
2020-12-11 12:23:50 +01:00
|
|
|
}
|
2020-11-13 18:00:22 +01:00
|
|
|
}
|
|
|
|
|
2021-06-24 10:09:10 +02:00
|
|
|
const apiClientRepository = new ApiClientRepository(API_URL.split(","));
|
2020-11-13 18:00:22 +01:00
|
|
|
|
|
|
|
export { apiClientRepository };
|