Skip to content

Commit

Permalink
Chore: minor changes
Browse files Browse the repository at this point in the history
  • Loading branch information
SukkaW committed Nov 17, 2023
1 parent f88c364 commit a5e36a1
Show file tree
Hide file tree
Showing 10 changed files with 51 additions and 50 deletions.
4 changes: 2 additions & 2 deletions Build/build-chn-cidr.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,12 +11,12 @@ const EXCLUDE_CIDRS = [
];

export const buildChnCidr = task(__filename, async () => {
const [{ exclude: excludeCidrs }, cidr] = await Promise.all([
const [{ exclude }, cidr] = await Promise.all([
import('cidr-tools-wasm'),
processLineFromReadline(await fetchRemoteTextAndCreateReadlineInterface('https://raw.githubusercontent.com/misakaio/chnroutes2/master/chnroutes.txt'))
]);

const filteredCidr = excludeCidrs(cidr, EXCLUDE_CIDRS, true);
const filteredCidr = exclude(cidr, EXCLUDE_CIDRS, true);

const description = [
'License: CC BY-SA 2.0',
Expand Down
23 changes: 18 additions & 5 deletions Build/build-speedtest-domainset.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,18 +6,29 @@ import domainSorter from './lib/stable-sort-domain';
import { Sema } from 'async-sema';
import * as tldts from 'tldts';
import { task } from './lib/trace-runner';
const s = new Sema(2);
const s = new Sema(3);

const latestTopUserAgentsPromise = fetch('https://unpkg.com/top-user-agents@latest/index.json')
.then(res => res.json() as Promise<string[]>);

const querySpeedtestApi = async (keyword: string): Promise<(string | null)[]> => {
await s.acquire();
const [topUserAgents] = await Promise.all([
latestTopUserAgentsPromise,
s.acquire()
]);

const randomUserAgent = topUserAgents[Math.floor(Math.random() * topUserAgents.length)];

try {
const key = `fetch speedtest endpoints: ${keyword}`;
console.time(key);

const res = await fetch(`https://www.speedtest.net/api/js/servers?engine=js&search=${keyword}&limit=100`, {
headers: {
dnt: '1',
Referer: 'https://www.speedtest.net/',
accept: 'application/json, text/plain, */*',
'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/115.0.0.0 Safari/537.36',
'User-Agent': randomUserAgent,
'Accept-Language': 'en-US,en;q=0.9',
'Sec-Ch-Ua': '"Not/A)Brand";v="99", "Google Chrome";v="115", "Chromium";v="115"',
'Sec-Ch-Ua-Mobile': '?0',
Expand All @@ -28,12 +39,14 @@ const querySpeedtestApi = async (keyword: string): Promise<(string | null)[]> =>
}
});
if (!res.ok) {
const text = await res.text();
throw new Error(text);
throw new Error(res.statusText + '\n' + await res.text());
}

const json = await res.json() as { url: string; }[];
s.release();

console.timeEnd(key);

return json.map(({ url }) => tldts.getHostname(url, { detectIp: false }));
} catch (e) {
s.release();
Expand Down
2 changes: 0 additions & 2 deletions Build/download-previous-build.ts
Original file line number Diff line number Diff line change
Expand Up @@ -75,8 +75,6 @@ export const downloadPreviousBuild = task(__filename, async () => {
);
}
}));

// return fsp.unlink(extractedPath).catch(() => { });
});

export const downloadPublicSuffixList = task(__filename, async () => {
Expand Down
46 changes: 12 additions & 34 deletions Build/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,39 +16,11 @@ import { buildRedirectModule } from './build-redirect-module';
import { validate } from './validate-domainset';

import { buildPublicHtml } from './build-public';

import { Worker } from 'jest-worker';

type WithWorker<T> = import('jest-worker').Worker & { __sukka_worker_name: string } & T

const requireWorker = <T>(path: string, exposedMethods?: (keyof T & string)[]): WithWorker<T> => {
const _worker = new Worker(
import.meta.require.resolve(path),
{
numWorkers: 1,
maxRetries: 0,
enableWorkerThreads: true,
exposedMethods
}
) as WithWorker<T>;
_worker.getStderr().pipe(process.stderr);
_worker.getStdout().pipe(process.stdout);
_worker.__sukka_worker_name = path;
return _worker;
};

const endWorker = async <T>(worker: WithWorker<T>) => {
const { forceExited } = await worker.end();
if (forceExited && worker.__sukka_worker_name) {
console.log(worker.__sukka_worker_name, 'forceExited');
}
};
import { TaskResult } from './lib/trace-runner';

(async () => {
const buildInternalReverseChnCIDRWorker: WithWorker<typeof import('./build-internal-reverse-chn-cidr')> = requireWorker('./build-internal-reverse-chn-cidr', ['buildInternalReverseChnCIDR']);
const buildInternalReverseChnCIDRWorker = new Worker(new URL('./workers/build-internal-reverse-chn-cidr-worker.ts', import.meta.url));
try {
const { buildInternalReverseChnCIDR } = buildInternalReverseChnCIDRWorker;

const downloadPreviousBuildPromise = downloadPreviousBuild();
const downloadPublicSuffixListPromise = downloadPublicSuffixList();
const buildCommonPromise = downloadPreviousBuildPromise.then(() => buildCommon());
Expand All @@ -75,7 +47,15 @@ const endWorker = async <T>(worker: WithWorker<T>) => {
buildCommonPromise,
buildCdnConfPromise
]).then(() => buildInternalCDNDomains());
const buildInternalReverseChnCIDRPromise = buildInternalReverseChnCIDR();

const buildInternalReverseChnCIDRPromise = new Promise<TaskResult>(resolve => {
buildInternalReverseChnCIDRWorker.postMessage(null);
buildInternalReverseChnCIDRWorker.onmessage = (e: MessageEvent<TaskResult>) => {
buildInternalReverseChnCIDRWorker.terminate();
resolve(e.data);
};
});

const buildInternalChnDomainsPromise = buildInternalChnDomains();
const buildDomesticRulesetPromise = downloadPreviousBuildPromise.then(() => buildDomesticRuleset());

Expand Down Expand Up @@ -109,9 +89,7 @@ const endWorker = async <T>(worker: WithWorker<T>) => {

printStats(stats);
} catch (e) {
console.error(e)
} finally {
await endWorker(buildInternalReverseChnCIDRWorker)
console.error(e);
}
})();

Expand Down
5 changes: 2 additions & 3 deletions Build/lib/fetch-remote-text-by-line.ts
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,6 @@ export async function* createReadlineInterfaceFromResponse(resp: Response): Asyn
}
}

export async function fetchRemoteTextAndCreateReadlineInterface(url: string | URL, opt?: RequestInit): Promise<AsyncGenerator<string>> {
const resp = await fetchWithRetry(url, opt);
return createReadlineInterfaceFromResponse(resp);
export function fetchRemoteTextAndCreateReadlineInterface(url: string | URL, opt?: RequestInit): Promise<AsyncGenerator<string>> {
return fetchWithRetry(url, opt).then(res => createReadlineInterfaceFromResponse(res));
}
2 changes: 1 addition & 1 deletion Build/lib/parse-filter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,7 @@ export async function processDomainLists(domainListsUrl: string | URL) {
}

export async function processHosts(hostsUrl: string | URL, includeAllSubDomain = false) {
console.time(` - processHosts: ${hostsUrl}`);
console.time(`- processHosts: ${hostsUrl}`);

if (typeof hostsUrl === 'string') {
hostsUrl = new URL(hostsUrl);
Expand Down
8 changes: 7 additions & 1 deletion Build/lib/trace-runner.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,12 @@ const traceAsync = async <T>(prefix: string, fn: () => Promise<T>): Promise<T> =
};
export { traceAsync };

export interface TaskResult {
readonly start: number;
readonly end: number;
readonly taskName: string;
}

const task = <T>(__filename: string, fn: () => Promise<T>, customname: string | null = null) => {
const taskName = customname ?? path.basename(__filename, path.extname(__filename));
return async () => {
Expand All @@ -27,7 +33,7 @@ const task = <T>(__filename: string, fn: () => Promise<T>, customname: string |
const end = performance.now();
console.log(`✅ [${taskName}] Executed successfully: ${(end - start).toFixed(3)}ms`);

return { start, end, taskName } as const;
return { start, end, taskName } as TaskResult;
};
};
export { task };
8 changes: 8 additions & 0 deletions Build/workers/build-internal-reverse-chn-cidr-worker.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
declare const self: Worker;

import { buildInternalReverseChnCIDR } from '../build-internal-reverse-chn-cidr';

self.onmessage = async () => {
const stat = await buildInternalReverseChnCIDR();
postMessage(stat);
};
Binary file modified bun.lockb
Binary file not shown.
3 changes: 1 addition & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -19,10 +19,9 @@
"@vercel/fetch-retry": "^5.1.3",
"async-sema": "^3.1.1",
"ci-info": "^4.0.0",
"cidr-tools-wasm": "^0.0.11",
"cidr-tools-wasm": "^0.0.13",
"eslint": "^8.53.0",
"gorhill-publicsuffixlist": "github:gorhill/publicsuffixlist.js",
"jest-worker": "^29.7.0",
"mnemonist": "^0.39.5",
"path-scurry": "^1.10.1",
"picocolors": "^1.0.0",
Expand Down

0 comments on commit a5e36a1

Please sign in to comment.