trie.ts 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639
  1. /**
  2. * Hostbane-Optimized Trie based on Mnemonist Trie
  3. */
  4. import { fastStringCompare } from './misc';
  5. import util from 'node:util';
  6. import { noop } from 'foxts/noop';
  7. import { fastStringArrayJoin } from 'foxts/fast-string-array-join';
  8. import FIFO from 'fast-fifo';
  9. import { deleteBit, getBit, missingBit, setBit } from 'foxts/bitwise';
  10. const START = 1 << 1;
  11. const INCLUDE_ALL_SUBDOMAIN = 1 << 2;
  12. type TrieNode<Meta = any> = [
  13. flag: number, /** end, includeAllSubdomain (.example.org, ||example.com) */
  14. TrieNode | null, /** parent */
  15. Map<string, TrieNode>, /** children */
  16. Meta /** meta */
  17. ];
  18. function deepTrieNodeToJSON(node: TrieNode,
  19. unpackMeta: ((meta?: any) => string) | undefined) {
  20. const obj: Record<string, any> = {};
  21. obj['[start]'] = getBit(node[0], START);
  22. obj['[subdomain]'] = getBit(node[0], INCLUDE_ALL_SUBDOMAIN);
  23. if (node[3] != null) {
  24. if (unpackMeta) {
  25. obj['[meta]'] = unpackMeta(node[3]);
  26. } else {
  27. obj['[meta]'] = node[3];
  28. }
  29. }
  30. node[2].forEach((value, key) => {
  31. obj[key] = deepTrieNodeToJSON(value, unpackMeta);
  32. });
  33. return obj;
  34. }
  35. const createNode = <Meta = any>(parent: TrieNode | null = null): TrieNode => [1, parent, new Map<string, TrieNode>(), null] as TrieNode<Meta>;
  36. export function hostnameToTokens(hostname: string, hostnameFromIndex: number): string[] {
  37. const tokens = hostname.split('.');
  38. const results: string[] = [];
  39. let token = '';
  40. for (let i = hostnameFromIndex, l = tokens.length; i < l; i++) {
  41. token = tokens[i];
  42. if (token.length > 0) {
  43. results.push(token);
  44. }
  45. }
  46. return results;
  47. }
  48. function walkHostnameTokens(hostname: string, onToken: (token: string) => boolean | null, hostnameFromIndex: number): boolean | null {
  49. const tokens = hostname.split('.');
  50. const l = tokens.length - 1;
  51. // we are at the first of hostname, no splitor there
  52. let token = '';
  53. for (let i = l; i >= hostnameFromIndex; i--) {
  54. token = tokens[i];
  55. if (token.length > 0) {
  56. const t = onToken(token);
  57. if (t === null) {
  58. return null;
  59. }
  60. // if the callback returns true, we should skip the rest
  61. if (t) {
  62. return true;
  63. }
  64. }
  65. }
  66. return false;
  67. }
  68. interface FindSingleChildLeafResult<Meta> {
  69. node: TrieNode<Meta>,
  70. toPrune: TrieNode<Meta> | null,
  71. tokenToPrune: string | null,
  72. parent: TrieNode<Meta>
  73. }
  74. abstract class Triebase<Meta = any> {
  75. protected readonly $root: TrieNode<Meta> = createNode();
  76. protected $size = 0;
  77. get root() {
  78. return this.$root;
  79. }
  80. constructor(from?: string[] | Set<string> | null) {
  81. // Actually build trie
  82. if (Array.isArray(from)) {
  83. for (let i = 0, l = from.length; i < l; i++) {
  84. this.add(from[i]);
  85. }
  86. } else if (from) {
  87. from.forEach((value) => this.add(value));
  88. }
  89. }
  90. public abstract add(suffix: string, includeAllSubdomain?: boolean, meta?: Meta, hostnameFromIndex?: number): void;
  91. protected walkIntoLeafWithTokens(
  92. tokens: string[],
  93. onLoop: (node: TrieNode, parent: TrieNode, token: string) => void = noop
  94. ) {
  95. let node: TrieNode = this.$root;
  96. let parent: TrieNode = node;
  97. let token: string;
  98. for (let i = tokens.length - 1; i >= 0; i--) {
  99. token = tokens[i];
  100. // if (token === '') {
  101. // break;
  102. // }
  103. parent = node;
  104. if (node[2].has(token)) {
  105. node = node[2].get(token)!;
  106. } else {
  107. return null;
  108. }
  109. onLoop(node, parent, token);
  110. }
  111. return { node, parent };
  112. };
  113. protected walkIntoLeafWithSuffix(
  114. suffix: string,
  115. hostnameFromIndex: number,
  116. onLoop: (node: TrieNode, parent: TrieNode, token: string) => void = noop
  117. ) {
  118. let node: TrieNode = this.$root;
  119. let parent: TrieNode = node;
  120. const onToken = (token: string) => {
  121. // if (token === '') {
  122. // return true;
  123. // }
  124. parent = node;
  125. if (node[2].has(token)) {
  126. node = node[2].get(token)!;
  127. } else {
  128. return null;
  129. }
  130. onLoop(node, parent, token);
  131. return false;
  132. };
  133. if (walkHostnameTokens(suffix, onToken, hostnameFromIndex) === null) {
  134. return null;
  135. }
  136. return { node, parent };
  137. };
  138. public contains(suffix: string, includeAllSubdomain = suffix[0] === '.'): boolean {
  139. const hostnameFromIndex = suffix[0] === '.' ? 1 : 0;
  140. const res = this.walkIntoLeafWithSuffix(suffix, hostnameFromIndex);
  141. if (!res) return false;
  142. if (includeAllSubdomain) return getBit(res.node[0], INCLUDE_ALL_SUBDOMAIN);
  143. return true;
  144. };
  145. private static bfsResults: [node: TrieNode | null, suffix: string[]] = [null, []];
  146. private static bfs<Meta>(this: void, nodeStack: FIFO<TrieNode<Meta>>, suffixStack: FIFO<string[]>) {
  147. const node = nodeStack.shift()!;
  148. const suffix = suffixStack.shift()!;
  149. node[2].forEach((childNode, k) => {
  150. // Pushing the child node to the stack for next iteration of DFS
  151. nodeStack.push(childNode);
  152. suffixStack.push([k, ...suffix]);
  153. });
  154. Triebase.bfsResults[0] = node;
  155. Triebase.bfsResults[1] = suffix;
  156. return Triebase.bfsResults;
  157. }
  158. private static bfsWithSort<Meta>(this: void, nodeStack: FIFO<TrieNode<Meta>>, suffixStack: FIFO<string[]>) {
  159. const node = nodeStack.shift()!;
  160. const suffix = suffixStack.shift()!;
  161. if (node[2].size) {
  162. const keys = Array.from(node[2].keys()).sort(Triebase.compare);
  163. for (let i = 0, l = keys.length; i < l; i++) {
  164. const key = keys[i];
  165. const childNode = node[2].get(key)!;
  166. // Pushing the child node to the stack for next iteration of DFS
  167. nodeStack.push(childNode);
  168. suffixStack.push([key, ...suffix]);
  169. }
  170. }
  171. Triebase.bfsResults[0] = node;
  172. Triebase.bfsResults[1] = suffix;
  173. return Triebase.bfsResults;
  174. }
  175. private walk(
  176. onMatches: (suffix: string[], subdomain: boolean, meta: Meta) => void,
  177. initialNode = this.$root,
  178. initialSuffix: string[] = [],
  179. withSort = false
  180. ) {
  181. const bfsImpl = withSort ? Triebase.bfsWithSort : Triebase.bfs;
  182. const nodeStack = new FIFO<TrieNode<Meta>>();
  183. nodeStack.push(initialNode);
  184. // Resolving initial string (begin the start of the stack)
  185. const suffixStack = new FIFO<string[]>();
  186. suffixStack.push(initialSuffix);
  187. let node: TrieNode<Meta> = initialNode;
  188. let r;
  189. do {
  190. r = bfsImpl(nodeStack, suffixStack);
  191. node = r[0]!;
  192. const suffix = r[1];
  193. // If the node is a sentinel, we push the suffix to the results
  194. if (getBit(node[0], START)) {
  195. onMatches(suffix, getBit(node[0], INCLUDE_ALL_SUBDOMAIN), node[3]);
  196. }
  197. } while (nodeStack.length);
  198. };
  199. static compare(this: void, a: string, b: string) {
  200. if (a === b) return 0;
  201. return (a.length - b.length) || fastStringCompare(a, b);
  202. }
  203. private walkWithSort(
  204. onMatches: (suffix: string[], subdomain: boolean, meta: Meta) => void,
  205. initialNode = this.$root,
  206. initialSuffix: string[] = []
  207. ) {
  208. const nodeStack = new FIFO<TrieNode<Meta>>();
  209. nodeStack.push(initialNode);
  210. // Resolving initial string (begin the start of the stack)
  211. const suffixStack = new FIFO<string[]>();
  212. suffixStack.push(initialSuffix);
  213. let node: TrieNode<Meta> = initialNode;
  214. do {
  215. node = nodeStack.shift()!;
  216. const suffix = suffixStack.shift()!;
  217. if (node[2].size) {
  218. const keys = Array.from(node[2].keys()).sort(Triebase.compare);
  219. for (let i = 0, l = keys.length; i < l; i++) {
  220. const key = keys[i];
  221. const childNode = node[2].get(key)!;
  222. // Pushing the child node to the stack for next iteration of DFS
  223. nodeStack.push(childNode);
  224. suffixStack.push([key, ...suffix]);
  225. }
  226. }
  227. // If the node is a sentinel, we push the suffix to the results
  228. if (getBit(node[0], START)) {
  229. onMatches(suffix, getBit(node[0], INCLUDE_ALL_SUBDOMAIN), node[3]);
  230. }
  231. } while (nodeStack.length);
  232. };
  233. protected getSingleChildLeaf(tokens: string[]): FindSingleChildLeafResult<Meta> | null {
  234. let toPrune: TrieNode | null = null;
  235. let tokenToPrune: string | null = null;
  236. const onLoop = (node: TrieNode, parent: TrieNode, token: string) => {
  237. // Keeping track of a potential branch to prune
  238. // Even if the node size is 1, but the single child is ".", we should retain the branch
  239. // Since the "." could be special if it is the leaf-est node
  240. const onlyChild = node[2].size === 0 && !node[1];
  241. if (toPrune != null) { // the top-est branch that could potentially being pruned
  242. if (!onlyChild) {
  243. // The branch has moew than single child, retain the branch.
  244. // And we need to abort prune the parent, so we set it to null
  245. toPrune = null;
  246. tokenToPrune = null;
  247. }
  248. } else if (onlyChild) {
  249. // There is only one token child, or no child at all, we can prune it safely
  250. // It is now the top-est branch that could potentially being pruned
  251. toPrune = parent;
  252. tokenToPrune = token;
  253. }
  254. };
  255. const res = this.walkIntoLeafWithTokens(tokens, onLoop);
  256. if (res === null) return null;
  257. return { node: res.node, toPrune, tokenToPrune, parent: res.parent };
  258. };
  259. /**
  260. * Method used to retrieve every item in the trie with the given prefix.
  261. */
  262. public find(
  263. inputSuffix: string,
  264. subdomainOnly = inputSuffix[0] === '.',
  265. hostnameFromIndex = inputSuffix[0] === '.' ? 1 : 0
  266. // /** @default true */ includeEqualWithSuffix = true
  267. ): string[] {
  268. const inputTokens = hostnameToTokens(inputSuffix, hostnameFromIndex);
  269. const res = this.walkIntoLeafWithTokens(inputTokens);
  270. if (res === null) return [];
  271. const results: string[] = [];
  272. const onMatches = subdomainOnly
  273. ? (suffix: string[], subdomain: boolean) => { // fast path (default option)
  274. const d = fastStringArrayJoin(suffix, '.');
  275. if (!subdomain && subStringEqual(inputSuffix, d, 1)) return;
  276. results.push(subdomain ? '.' + d : d);
  277. }
  278. : (suffix: string[], subdomain: boolean) => { // fast path (default option)
  279. const d = fastStringArrayJoin(suffix, '.');
  280. results.push(subdomain ? '.' + d : d);
  281. };
  282. this.walk(
  283. onMatches,
  284. res.node, // Performing DFS from prefix
  285. inputTokens
  286. );
  287. return results;
  288. };
  289. /**
  290. * Method used to delete a prefix from the trie.
  291. */
  292. public remove(suffix: string): boolean {
  293. const res = this.getSingleChildLeaf(hostnameToTokens(suffix, 0));
  294. if (res === null) return false;
  295. if (missingBit(res.node[0], START)) return false;
  296. this.$size--;
  297. const { node, toPrune, tokenToPrune } = res;
  298. if (tokenToPrune && toPrune) {
  299. toPrune[2].delete(tokenToPrune);
  300. } else {
  301. node[0] = deleteBit(node[0], START);
  302. }
  303. return true;
  304. };
  305. // eslint-disable-next-line @typescript-eslint/unbound-method -- safe
  306. public delete = this.remove;
  307. /**
  308. * Method used to assert whether the given prefix exists in the Trie.
  309. */
  310. public has(suffix: string, includeAllSubdomain = suffix[0] === '.'): boolean {
  311. const hostnameFromIndex = suffix[0] === '.' ? 1 : 0;
  312. const res = this.walkIntoLeafWithSuffix(suffix, hostnameFromIndex);
  313. if (res === null) return false;
  314. if (missingBit(res.node[0], START)) return false;
  315. if (includeAllSubdomain) return getBit(res.node[0], INCLUDE_ALL_SUBDOMAIN);
  316. return true;
  317. };
  318. public dumpWithoutDot(onSuffix: (suffix: string, subdomain: boolean) => void, withSort = false) {
  319. const handleSuffix = (suffix: string[], subdomain: boolean) => {
  320. onSuffix(fastStringArrayJoin(suffix, '.'), subdomain);
  321. };
  322. if (withSort) {
  323. this.walkWithSort(handleSuffix);
  324. } else {
  325. this.walk(handleSuffix);
  326. }
  327. }
  328. public dump(onSuffix: (suffix: string) => void, withSort?: boolean): void;
  329. public dump(onSuffix?: null, withSort?: boolean): string[];
  330. public dump(onSuffix?: ((suffix: string) => void) | null, withSort = false): string[] | void {
  331. const results: string[] = [];
  332. const handleSuffix = onSuffix
  333. ? (suffix: string[], subdomain: boolean) => {
  334. const d = fastStringArrayJoin(suffix, '.');
  335. onSuffix(subdomain ? '.' + d : d);
  336. }
  337. : (suffix: string[], subdomain: boolean) => {
  338. const d = fastStringArrayJoin(suffix, '.');
  339. results.push(subdomain ? '.' + d : d);
  340. };
  341. if (withSort) {
  342. this.walkWithSort(handleSuffix);
  343. } else {
  344. this.walk(handleSuffix);
  345. }
  346. return results;
  347. };
  348. public dumpMeta(onMeta: (meta: Meta) => void, withSort?: boolean): void;
  349. public dumpMeta(onMeta?: null, withSort?: boolean): Meta[];
  350. public dumpMeta(onMeta?: ((meta: Meta) => void) | null, withSort = false): Meta[] | void {
  351. const results: Meta[] = [];
  352. const handleMeta = onMeta
  353. ? (_suffix: string[], _subdomain: boolean, meta: Meta) => onMeta(meta)
  354. : (_suffix: string[], _subdomain: boolean, meta: Meta) => results.push(meta);
  355. if (withSort) {
  356. this.walkWithSort(handleMeta);
  357. } else {
  358. this.walk(handleMeta);
  359. }
  360. return results;
  361. };
  362. public dumpWithMeta(onSuffix: (suffix: string, meta: Meta | undefined) => void, withSort?: boolean): void;
  363. public dumpWithMeta(onMeta?: null, withSort?: boolean): Array<[string, Meta | undefined]>;
  364. public dumpWithMeta(onSuffix?: ((suffix: string, meta: Meta | undefined) => void) | null, withSort = false): Array<[string, Meta | undefined]> | void {
  365. const results: Array<[string, Meta | undefined]> = [];
  366. const handleSuffix = onSuffix
  367. ? (suffix: string[], subdomain: boolean, meta: Meta | undefined) => {
  368. const d = fastStringArrayJoin(suffix, '.');
  369. return onSuffix(subdomain ? '.' + d : d, meta);
  370. }
  371. : (suffix: string[], subdomain: boolean, meta: Meta | undefined) => {
  372. const d = fastStringArrayJoin(suffix, '.');
  373. results.push([subdomain ? '.' + d : d, meta]);
  374. };
  375. if (withSort) {
  376. this.walkWithSort(handleSuffix);
  377. } else {
  378. this.walk(handleSuffix);
  379. }
  380. return results;
  381. };
  382. public inspect(depth: number, unpackMeta?: (meta?: Meta) => any) {
  383. return fastStringArrayJoin(
  384. JSON.stringify(deepTrieNodeToJSON(this.$root, unpackMeta), null, 2).split('\n').map((line) => ' '.repeat(depth) + line),
  385. '\n'
  386. );
  387. }
  388. public [util.inspect.custom](depth: number) {
  389. return this.inspect(depth);
  390. };
  391. }
  392. export class HostnameSmolTrie<Meta = any> extends Triebase<Meta> {
  393. public smolTree = true;
  394. add(suffix: string, includeAllSubdomain = suffix[0] === '.', meta?: Meta, hostnameFromIndex = suffix[0] === '.' ? 1 : 0): void {
  395. let node: TrieNode<Meta> = this.$root;
  396. let curNodeChildren: Map<string, TrieNode<Meta>> = node[2];
  397. const onToken = (token: string) => {
  398. curNodeChildren = node[2];
  399. if (curNodeChildren.has(token)) {
  400. node = curNodeChildren.get(token)!;
  401. // During the adding of `[start]blog|.skk.moe` and find out that there is a `[start].skk.moe` in the trie, skip adding the rest of the node
  402. if (getBit(node[0], INCLUDE_ALL_SUBDOMAIN)) {
  403. return true;
  404. }
  405. } else {
  406. const newNode = createNode(node);
  407. curNodeChildren.set(token, newNode);
  408. node = newNode;
  409. }
  410. return false;
  411. };
  412. // When walkHostnameTokens returns true, we should skip the rest
  413. if (walkHostnameTokens(suffix, onToken, hostnameFromIndex)) {
  414. return;
  415. }
  416. // If we are in smolTree mode, we need to do something at the end of the loop
  417. if (includeAllSubdomain) {
  418. // Trying to add `[.]sub.example.com` where there is already a `blog.sub.example.com` in the trie
  419. // Make sure parent `[start]sub.example.com` (without dot) is removed (SETINEL to false)
  420. // (/** parent */ node[2]!)[0] = false;
  421. // Removing the rest of the parent's child nodes
  422. node[2].clear();
  423. // The SENTINEL of this node will be set to true at the end of the function, so we don't need to set it here
  424. // we can use else-if here, because the children is now empty, we don't need to check the leading "."
  425. } else if (getBit(node[0], INCLUDE_ALL_SUBDOMAIN)) {
  426. // Trying to add `example.com` when there is already a `.example.com` in the trie
  427. // No need to increment size and set SENTINEL to true (skip this "new" item)
  428. return;
  429. }
  430. node[0] = setBit(node[0], START);
  431. if (includeAllSubdomain) {
  432. node[0] = setBit(node[0], INCLUDE_ALL_SUBDOMAIN);
  433. } else {
  434. node[0] = deleteBit(node[0], INCLUDE_ALL_SUBDOMAIN);
  435. }
  436. node[3] = meta!;
  437. }
  438. public whitelist(suffix: string, includeAllSubdomain = suffix[0] === '.', hostnameFromIndex = suffix[0] === '.' ? 1 : 0) {
  439. const tokens = hostnameToTokens(suffix, hostnameFromIndex);
  440. const res = this.getSingleChildLeaf(tokens);
  441. if (res === null) return;
  442. const { node, toPrune, tokenToPrune } = res;
  443. // Trying to whitelist `[start].sub.example.com` where there might already be a `[start]blog.sub.example.com` in the trie
  444. if (includeAllSubdomain) {
  445. // If there is a `[start]sub.example.com` here, remove it
  446. node[0] = deleteBit(node[0], INCLUDE_ALL_SUBDOMAIN);
  447. node[0] = deleteBit(node[0], START);
  448. // Removing all the child nodes by empty the children
  449. node[2].clear();
  450. } else {
  451. // Trying to whitelist `example.com` when there is already a `.example.com` in the trie
  452. node[0] = deleteBit(node[0], INCLUDE_ALL_SUBDOMAIN);
  453. }
  454. // return early if not found
  455. if (missingBit(node[0], START)) return;
  456. if (tokenToPrune && toPrune) {
  457. toPrune[2].delete(tokenToPrune);
  458. } else {
  459. node[0] = deleteBit(node[0], START);
  460. }
  461. };
  462. }
  463. export class HostnameTrie<Meta = any> extends Triebase<Meta> {
  464. get size() {
  465. return this.$size;
  466. }
  467. add(suffix: string, includeAllSubdomain = suffix[0] === '.', meta?: Meta, hostnameFromIndex = suffix[0] === '.' ? 1 : 0): void {
  468. let node: TrieNode<Meta> = this.$root;
  469. const onToken = (token: string) => {
  470. if (node[2].has(token)) {
  471. node = node[2].get(token)!;
  472. } else {
  473. const newNode = createNode(node);
  474. node[2].set(token, newNode);
  475. node = newNode;
  476. }
  477. return false;
  478. };
  479. // When walkHostnameTokens returns true, we should skip the rest
  480. if (walkHostnameTokens(suffix, onToken, hostnameFromIndex)) {
  481. return;
  482. }
  483. // if same entry has been added before, skip
  484. if (getBit(node[0], START)) {
  485. return;
  486. }
  487. this.$size++;
  488. node[0] = setBit(node[0], START);
  489. if (includeAllSubdomain) {
  490. node[0] = setBit(node[0], INCLUDE_ALL_SUBDOMAIN);
  491. } else {
  492. node[0] = deleteBit(node[0], INCLUDE_ALL_SUBDOMAIN);
  493. }
  494. node[3] = meta!;
  495. }
  496. }
  497. // function deepEqualArray(a: string[], b: string[]) {
  498. // let len = a.length;
  499. // if (len !== b.length) return false;
  500. // while (len--) {
  501. // if (a[len] !== b[len]) return false;
  502. // }
  503. // return true;
  504. // };
  505. function subStringEqual(needle: string, haystack: string, needleIndex = 0) {
  506. for (let i = 0, l = haystack.length; i < l; i++) {
  507. if (needle[i + needleIndex] !== haystack[i]) return false;
  508. }
  509. return true;
  510. }