From b3ef9b5e013cdf6c352dbfc288f832af6751d29d Mon Sep 17 00:00:00 2001 From: "P. Reis" Date: Mon, 12 Aug 2024 17:07:59 -0300 Subject: [PATCH] feat: create and implement nodeInfoCache function --- src/utils/domains.ts | 41 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 41 insertions(+) create mode 100644 src/utils/domains.ts diff --git a/src/utils/domains.ts b/src/utils/domains.ts new file mode 100644 index 00000000..21f2977c --- /dev/null +++ b/src/utils/domains.ts @@ -0,0 +1,41 @@ +import { fetchWorker } from '@/workers/fetch.ts'; +import { SimpleLRU } from '@/utils/SimpleLRU.ts'; +import { Time } from '@/utils/time.ts'; + +type NodeInfoV1 = { + usage: { + users: { + total: number; + activeMonth: number; + activeHalfyear: number; + }; + }; +}; + +type Domain = string; + +export const nodeInfoCache = new SimpleLRU( + async (key, { signal }) => { + try { + const url = new URL('/.well-known/nodeinfo', `https://${key}/`); + const res = await fetchWorker(url, { signal }); + + const { links } = await res.json(); + if (links.length < 1) throw new Error(`${key} does not have NodeInfo schemas`); + + // NodeInfo is backwards compatible, and we only care about the 'usage' field, + // which is present across all versions, so we can make a request to any version + const urlNodeInfo = links[0].href; + + const resNodeIndo = await fetchWorker(urlNodeInfo, { signal }); + const { usage } = await resNodeIndo.json(); + + return { + usage, + }; + } catch (e) { + throw e; + } + }, + { max: 500, ttl: Time.hours(1) }, +);