Refactor: minor changes here and there

This commit is contained in:
SukkaW 2024-11-21 00:10:32 +08:00
parent 484afab42c
commit ff8163eccc
7 changed files with 82 additions and 55 deletions

View File

@ -1,5 +1,7 @@
import { TTL } from '../lib/cache-filesystem'; import { TTL } from '../lib/cache-filesystem';
export const DEBUG_DOMAIN_TO_FIND: string | null = null; // example.com | null
type HostsSource = [main: string, mirrors: string[] | null, includeAllSubDomain: boolean, ttl: number]; type HostsSource = [main: string, mirrors: string[] | null, includeAllSubDomain: boolean, ttl: number];
export const HOSTS: HostsSource[] = [ export const HOSTS: HostsSource[] = [

View File

@ -12,11 +12,9 @@ function createKeywordFilter(keys: string[] | Set<string>) {
// Create a trie with extra fields and information // Create a trie with extra fields and information
const put = (key: string) => { const put = (key: string) => {
const len = key.length;
let node = root; let node = root;
for (let idx = 0; idx < len; idx++) { for (let idx = 0, len = key.length; idx < len; idx++) {
const char = key[idx]; const char = key[idx];
if (node.has(char)) { if (node.has(char)) {

View File

@ -153,7 +153,7 @@ export class Cache<S = string> {
} }
const end = performance.now(); const end = performance.now();
console.log(`${picocolors.gray(`[${((end - start) / 1e6).toFixed(3)}ms]`)} cache initialized from ${this.cachePath}`); console.log(`${picocolors.gray(`[${((end - start)).toFixed(3)}ns]`)} cache initialized from ${this.tableName} @ ${this.cachePath}`);
} }
set(key: string, value: string, ttl = 60 * 1000): void { set(key: string, value: string, ttl = 60 * 1000): void {

View File

@ -4,12 +4,13 @@ import * as tldts from 'tldts-experimental';
import { dummySpan, printTraceResult } from '../trace'; import { dummySpan, printTraceResult } from '../trace';
import type { Span } from '../trace'; import type { Span } from '../trace';
import { appendArrayInPlaceCurried } from './append-array-in-place'; import { appendArrayInPlaceCurried } from './append-array-in-place';
import { PHISHING_DOMAIN_LISTS_EXTRA, PHISHING_HOSTS_EXTRA } from '../constants/reject-data-source'; import { DEBUG_DOMAIN_TO_FIND, PHISHING_DOMAIN_LISTS_EXTRA, PHISHING_HOSTS_EXTRA } from '../constants/reject-data-source';
import { loosTldOptWithPrivateDomains } from '../constants/loose-tldts-opt'; import { loosTldOptWithPrivateDomains } from '../constants/loose-tldts-opt';
import picocolors from 'picocolors'; import picocolors from 'picocolors';
import createKeywordFilter from './aho-corasick'; import createKeywordFilter from './aho-corasick';
import { createCacheKey, deserializeArray, serializeArray } from './cache-filesystem'; import { createCacheKey, deserializeArray, serializeArray } from './cache-filesystem';
import { cache } from './fs-memo'; import { cache } from './fs-memo';
import { isCI } from 'ci-info';
const BLACK_TLD = new Set([ const BLACK_TLD = new Set([
'accountant', 'art', 'autos', 'accountant', 'art', 'autos',
@ -112,12 +113,22 @@ const processPhihsingDomains = cache(function processPhihsingDomains(domainArr:
const domainCountMap = new Map<string, number>(); const domainCountMap = new Map<string, number>();
const domainScoreMap: Record<string, number> = {}; const domainScoreMap: Record<string, number> = {};
let line = '';
let tld: string | null = ''; let tld: string | null = '';
let apexDomain: string | null = ''; let apexDomain: string | null = '';
let subdomain: string | null = ''; let subdomain: string | null = '';
// const set = new Set<string>();
// let duplicateCount = 0;
for (let i = 0, len = domainArr.length; i < len; i++) { for (let i = 0, len = domainArr.length; i < len; i++) {
const line = domainArr[i]; line = domainArr[i];
// if (set.has(line)) {
// duplicateCount++;
// } else {
// set.add(line);
// }
const parsed = tldts.parse(line, loosTldOptWithPrivateDomains); const parsed = tldts.parse(line, loosTldOptWithPrivateDomains);
if (parsed.isPrivate) { if (parsed.isPrivate) {
@ -183,11 +194,13 @@ const processPhihsingDomains = cache(function processPhihsingDomains(domainArr:
// count: domainCountMap.get('flk-ipfs.xyz') // count: domainCountMap.get('flk-ipfs.xyz')
// }); // });
// console.log({ duplicateCount, domainArrLen: domainArr.length });
return Promise.resolve(domainArr); return Promise.resolve(domainArr);
}, { }, {
serializer: serializeArray, serializer: serializeArray,
deserializer: deserializeArray, deserializer: deserializeArray,
temporaryBypass: true temporaryBypass: !isCI || DEBUG_DOMAIN_TO_FIND !== null
}); });
const cacheKey = createCacheKey(__filename); const cacheKey = createCacheKey(__filename);
@ -205,6 +218,8 @@ export function getPhishingDomains(parentSpan: Span) {
return domainArr; return domainArr;
}); });
console.log({ len: domainArr.length });
return span.traceChildAsync( return span.traceChildAsync(
'process phishing domain set', 'process phishing domain set',
() => processPhihsingDomains(domainArr) () => processPhihsingDomains(domainArr)

View File

@ -9,8 +9,8 @@ import type { Span } from '../trace';
import createKeywordFilter from './aho-corasick'; import createKeywordFilter from './aho-corasick';
import { looseTldtsOpt } from '../constants/loose-tldts-opt'; import { looseTldtsOpt } from '../constants/loose-tldts-opt';
import { identity } from './misc'; import { identity } from './misc';
import { DEBUG_DOMAIN_TO_FIND } from '../constants/reject-data-source';
const DEBUG_DOMAIN_TO_FIND: string | null = null; // example.com | null
let foundDebugDomain = false; let foundDebugDomain = false;
const temporaryBypass = typeof DEBUG_DOMAIN_TO_FIND === 'string'; const temporaryBypass = typeof DEBUG_DOMAIN_TO_FIND === 'string';

View File

@ -65,7 +65,11 @@ export abstract class RuleOutput<TPreprocessed = unknown> {
return result; return result;
}; };
constructor(protected readonly span: Span, protected readonly id: string) { } protected readonly span: Span;
constructor($span: Span, protected readonly id: string) {
this.span = $span.traceChild('RuleOutput#' + id);
}
protected title: string | null = null; protected title: string | null = null;
withTitle(title: string) { withTitle(title: string) {
@ -201,7 +205,7 @@ export abstract class RuleOutput<TPreprocessed = unknown> {
return this; return this;
} }
static readonly ipToCidr = (ip: string, version: 4 | 6 = 4) => { static readonly ipToCidr = (ip: string, version: 4 | 6) => {
if (ip.includes('/')) return ip; if (ip.includes('/')) return ip;
if (version === 4) { if (version === 4) {
return ip + '/32'; return ip + '/32';
@ -257,7 +261,7 @@ export abstract class RuleOutput<TPreprocessed = unknown> {
if (this.$$preprocessed === null) { if (this.$$preprocessed === null) {
this.guardPendingPromise(); this.guardPendingPromise();
this.$$preprocessed = this.span.traceChildSync('RuleOutput#preprocess: ' + this.id, () => this.preprocess()); this.$$preprocessed = this.span.traceChildSync('preprocess', () => this.preprocess());
} }
return this.$$preprocessed; return this.$$preprocessed;
} }
@ -280,56 +284,56 @@ export abstract class RuleOutput<TPreprocessed = unknown> {
); );
} }
async write(): Promise<void> { write(): Promise<void> {
await this.done(); return this.done().then(() => this.span.traceChildAsync('write all', async () => {
invariant(this.title, 'Missing title');
invariant(this.description, 'Missing description');
invariant(this.title, 'Missing title'); const promises = [
invariant(this.description, 'Missing description'); compareAndWriteFile(
this.span,
const promises = [ withBannerArray(
compareAndWriteFile( this.title,
this.span, this.description,
withBannerArray( this.date,
this.title, this.surge()
this.description, ),
this.date, path.join(OUTPUT_SURGE_DIR, this.type, this.id + '.conf')
this.surge()
), ),
path.join(OUTPUT_SURGE_DIR, this.type, this.id + '.conf') compareAndWriteFile(
), this.span,
compareAndWriteFile( withBannerArray(
this.span, this.title,
withBannerArray( this.description,
this.title, this.date,
this.description, this.clash()
this.date, ),
this.clash() path.join(OUTPUT_CLASH_DIR, this.type, this.id + '.txt')
), ),
path.join(OUTPUT_CLASH_DIR, this.type, this.id + '.txt') compareAndWriteFile(
), this.span,
compareAndWriteFile( this.singbox(),
this.span, path.join(OUTPUT_SINGBOX_DIR, this.type, this.id + '.json')
this.singbox(), )
path.join(OUTPUT_SINGBOX_DIR, this.type, this.id + '.json') ];
)
];
if (this.mitmSgmodule) { if (this.mitmSgmodule) {
const sgmodule = this.mitmSgmodule(); const sgmodule = this.mitmSgmodule();
const sgModulePath = this.mitmSgmodulePath ?? path.join(this.type, this.id + '.sgmodule'); const sgModulePath = this.mitmSgmodulePath ?? path.join(this.type, this.id + '.sgmodule');
if (sgmodule) { if (sgmodule) {
promises.push( promises.push(
compareAndWriteFile( compareAndWriteFile(
this.span, this.span,
sgmodule, sgmodule,
path.join(OUTPUT_MODULES_DIR, sgModulePath) path.join(OUTPUT_MODULES_DIR, sgModulePath)
) )
); );
}
} }
}
await Promise.all(promises); await Promise.all(promises);
}));
} }
abstract surge(): string[]; abstract surge(): string[];

View File

@ -148,7 +148,15 @@ export async function whyIsNodeRunning() {
export function printTraceResult(traceResult: TraceResult = rootTraceResult) { export function printTraceResult(traceResult: TraceResult = rootTraceResult) {
printStats(traceResult.children); printStats(traceResult.children);
printTree(traceResult, node => `${node.name} ${picocolors.bold(`${(node.end - node.start).toFixed(3)}ms`)}`); printTree(
traceResult,
node => {
if (node.end - node.start < 0) {
return node.name;
}
return `${node.name} ${picocolors.bold(`${(node.end - node.start).toFixed(3)}ms`)}`;
}
);
} }
function printTree(initialTree: TraceResult, printNode: (node: TraceResult, branch: string) => string) { function printTree(initialTree: TraceResult, printNode: (node: TraceResult, branch: string) => string) {