Skip to content

Commit

Permalink
refactor(flat-server-api): choose server domain logic
Browse files Browse the repository at this point in the history
  • Loading branch information
hyrious committed Aug 25, 2023
1 parent d073b49 commit 8524e5c
Show file tree
Hide file tree
Showing 7 changed files with 66 additions and 20 deletions.
1 change: 1 addition & 0 deletions cspell.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -125,6 +125,7 @@ module.exports = {
"mpegurl", // hls.js
"wopjs", // @wopjs/dom
"xstate",
"mrmime",

// less
"isstring",
Expand Down
5 changes: 5 additions & 0 deletions packages/flat-server-api/src/constants.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,8 @@
export const FLAT_REGION = process.env.FLAT_REGION;

// { CN: '...', SG: '...' }
export const SERVER_DOMAINS = process.env.FLAT_SERVER_DOMAINS as unknown as Record<string, string>;

export const CURRENT_SERVER_DOMAIN = process.env.FLAT_SERVER_DOMAIN;

export const FLAT_SERVER_BASE_URL = `https://${CURRENT_SERVER_DOMAIN}`;
Expand Down
46 changes: 28 additions & 18 deletions packages/flat-server-api/src/utils.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,11 @@
import { FLAT_SERVER_BASE_URL_V1, FLAT_SERVER_BASE_URL_V2, Region, Status } from "./constants";
import {
FLAT_REGION,
FLAT_SERVER_BASE_URL_V1,
FLAT_SERVER_BASE_URL_V2,
Region,
SERVER_DOMAINS,
Status,
} from "./constants";
import { ServerRequestError, RequestErrorCode } from "./error";
import { v4 as uuidv4 } from "uuid";

Expand Down Expand Up @@ -26,7 +33,17 @@ export function setFlatAuthToken(token: string): void {
localStorage.setItem("FlatAuthToken", token);
}

const defaultRegion = FLAT_SERVER_BASE_URL_V1.includes("-sg") ? Region.SG : Region.CN_HZ;
function getDefaultRegion(): Region {
if (FLAT_REGION === "CN") {
return Region.CN_HZ;
}
if (FLAT_REGION === "SG") {
return Region.SG;
}
throw new Error("Unknown FLAT_REGION: " + FLAT_REGION);
}

const defaultRegion = getDefaultRegion();

export function chooseServer(payload: any, enableFlatServerV2?: boolean): string {
let server = enableFlatServerV2 ? FLAT_SERVER_BASE_URL_V2 : FLAT_SERVER_BASE_URL_V1;
Expand All @@ -44,28 +61,21 @@ export function chooseServer(payload: any, enableFlatServerV2?: boolean): string
if ((uuid.length === 11 && uuid[0] === "2") || uuid.startsWith("SG-")) {
region = Region.SG;
}
// Legacy room
if (uuid.length === 10) {
region = Region.CN_HZ;
}
}
}
if (region === defaultRegion) {
return server;
}

// replace the left most part of domain, currently we have "{api}" for cn-hz, "{api}-sg" for sg
server = server.replace(/^https:\/\/([-\w]+)/, (_, name: string) => {
// normalize
if (name.endsWith("-sg")) {
name = name.slice(0, -3);
}
// add suffix if needed
if (region === Region.SG) {
name += "-sg";
}
return `https://${name}`;
});
// replace server domain with another region's
server = `https://${SERVER_DOMAINS[region.slice(0, 2).toUpperCase()]}/${
enableFlatServerV2 ? "v2" : "v1"
}`;

if (server.includes("undefined")) {
console.log("server domains:", SERVER_DOMAINS);
throw new Error(`Failed to choose server for region: ${region}`);
}

return server;
}
Expand Down
21 changes: 21 additions & 0 deletions packages/flat-vite-plugins/dotenv.js
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,9 @@ exports.dotenv = function dotenv(envDir) {
define["process.env.FLAT_REGION"] = JSON.stringify(configRegion());
}

define["process.env.FLAT_SERVER_DOMAINS"] = JSON.stringify(
getServerDomains(envDir, mode),
);
define["process.env.VERSION"] = JSON.stringify(version);

config.define = { ...config.define, ...define };
Expand All @@ -60,3 +63,21 @@ const getEnvConfigContent = (envDir, mode) => {

return null;
};

/**
* @param {string} envDir e.g. "path/to/flat/config/CN"
* @param {'development' | 'production'} mode
* @returns {{CN: string, US: string}}
*/
const getServerDomains = (envDir, mode) => {
const configDir = path.dirname(envDir);
const regions = fs.readdirSync(configDir); // should be ['CN', 'SG']
const result = {};
for (const region of regions) {
const content = getEnvConfigContent(path.join(configDir, region), mode);
if (content) {
result[region] = dotenvReal.parse(content).FLAT_SERVER_DOMAIN;
}
}
return result;
};
8 changes: 8 additions & 0 deletions pnpm-lock.yaml

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

1 change: 1 addition & 0 deletions web/flat-web/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,7 @@
"dotenv": "^16.0.2",
"dotenv-expand": "^9.0.0",
"eslint-loader": "^4.0.2",
"mrmime": "^1.0.1",
"vite-plugin-compression": "^0.5.1"
}
}
4 changes: 2 additions & 2 deletions web/flat-web/scripts/vite-plugin-inline-assets.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import type { Plugin } from "vite";
import { promises as fsp } from "fs";
import mime from "mime/lite";
import { lookup } from "mrmime";
import svgToTinyDataUri from "@netless/mini-svg-data-uri";

// e.g:
Expand All @@ -17,7 +17,7 @@ export function inlineAssets(): Plugin {
const content = await fsp.readFile(id);
const url = id.endsWith(".svg")
? svgToTinyDataUri(content.toString("utf-8"), "utf8")
: `data:${mime.getType(id)};base64,${content.toString("base64")}`;
: `data:${lookup(id)};base64,${content.toString("base64")}`;
return `export default ${JSON.stringify(url)};`;
}
return null;
Expand Down

0 comments on commit 8524e5c

Please sign in to comment.