trie.ts 18 KB

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