From af4e6155bc3072f9ef9c8aa68cb74e1bd153fe8d Mon Sep 17 00:00:00 2001 From: Derrick Hammer Date: Mon, 19 Dec 2022 15:28:22 -0500 Subject: [PATCH] *Make dht cache optional, but enabled by default --- src/config.ts | 1 + src/modules/rpc/server.ts | 31 ++++++++++++++++++++++--------- 2 files changed, 23 insertions(+), 9 deletions(-) diff --git a/src/config.ts b/src/config.ts index 20c3c2f..b2cb551 100644 --- a/src/config.ts +++ b/src/config.ts @@ -29,6 +29,7 @@ config.inject({ logLevel: "info", pluginDir: path.resolve(configDir, "..", "plugins"), plugins: ["core"], + cache: true, }); config.load(); diff --git a/src/modules/rpc/server.ts b/src/modules/rpc/server.ts index c182a3a..1c04b5d 100644 --- a/src/modules/rpc/server.ts +++ b/src/modules/rpc/server.ts @@ -18,6 +18,7 @@ import { Mutex } from "async-mutex"; import { RPCCache } from "./cache"; // @ts-ignore import jsonStringify from "json-stringify-deterministic"; +import config from "../../config"; const sodium = require("sodium-universal"); let server: RPCServer; @@ -54,9 +55,16 @@ export class RPCServer extends EventEmitter { >(); private pendingRequests: Map = new Map(); - private _cache: RPCCache = new RPCCache(this); + private _cache?: RPCCache; - get cache(): RPCCache { + constructor() { + super(); + if (config.bool("cache")) { + this._cache = new RPCCache(this); + } + } + + get cache(): RPCCache | undefined { return this._cache; } @@ -137,7 +145,7 @@ export class RPCServer extends EventEmitter { } return crypto - .sign(Buffer.from(raw), this._cache.swarm.keyPair.secretKey) + .sign(Buffer.from(raw), this._cache?.swarm.keyPair.secretKey) .toString("hex"); } @@ -201,8 +209,8 @@ export class RPCServer extends EventEmitter { } method = method as RPCMethod; - if (method.cacheable) { - this.cache.addItem(request, rpcResult); + if (config.bool("cache") && method.cacheable) { + this.cache?.addItem(request, rpcResult); } this.getRequestLock(request)?.release(); @@ -211,9 +219,14 @@ export class RPCServer extends EventEmitter { } private getCachedRequest(request: RPCRequest): RPCCacheItem | boolean { + if (!config.bool("cache")) { + return false; + } + const req = RPCServer.hashQuery(request); - if (this._cache.data.has(req)) { - return this._cache.data.get(req) as RPCCacheItem; + + if (this._cache?.data.has(req)) { + return this._cache?.data.get(req) as RPCCacheItem; } return false; @@ -256,8 +269,8 @@ export class RPCServer extends EventEmitter { if (lock.isLocked()) { await lock.waitForUnlock(); - if (this._cache.data.has(reqId)) { - return this._cache.data.get(reqId) as RPCCacheItem; + if (this._cache?.data.has(reqId)) { + return this._cache?.data.get(reqId) as RPCCacheItem; } }