trie.ts 18 KB

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