feat: support check delay

This commit is contained in:
GyDi
2022-02-16 02:22:01 +08:00
parent e7bba968b3
commit d0e678b5e9
5 changed files with 140 additions and 11 deletions

View File

@@ -60,10 +60,24 @@ export async function getRules() {
return instance.get("/rules") as Promise<ApiType.RuleItem[]>;
}
/// Get Proxy delay
export async function getProxyDelay(
name: string,
url?: string
): Promise<{ delay: number }> {
const params = {
timeout: 3000,
url: url || "http://www.gstatic.com/generate_204",
};
const instance = await getAxios();
return instance.get(`/proxies/${encodeURIComponent(name)}/delay`, { params });
}
/// Update the Proxy Choose
export async function updateProxy(group: string, proxy: string) {
const instance = await getAxios();
return instance.put(`/proxies/${group}`, { name: proxy });
return instance.put(`/proxies/${encodeURIComponent(group)}`, { name: proxy });
}
/// Get the Proxy infomation

37
src/services/delay.ts Normal file
View File

@@ -0,0 +1,37 @@
import { getProxyDelay } from "./api";
const hashKey = (name: string, group: string) => `${group ?? ""}::${name}`;
class DelayManager {
private cache = new Map<string, [number, number]>();
setDelay(name: string, group: string, delay: number) {
this.cache.set(hashKey(name, group), [Date.now(), delay]);
}
getDelay(name: string, group: string) {
if (!name) return -1;
const result = this.cache.get(hashKey(name, group));
if (result && Date.now() - result[0] <= 18e5) {
return result[1];
}
return -1;
}
async checkDelay(name: string, group: string) {
let delay = -1;
try {
const result = await getProxyDelay(name);
delay = result.delay;
} catch {
delay = 1e6; // error
}
this.setDelay(name, group, delay);
return delay;
}
}
export default new DelayManager();