Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Refactor to simplify strategy creation #6

Merged
merged 5 commits into from
Jun 3, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
.eslintcache
.nyc_output
.vscode
coverage
dist
lerna-debug.log
Expand Down
158 changes: 156 additions & 2 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

5 changes: 3 additions & 2 deletions packages/eth-rpc-cache/package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "eth-rpc-cache",
"version": "1.0.0",
"version": "2.0.0",
"description": "A simple cache for Ethereum RPC requests extensible with different caching strategies",
"keywords": [
"cache",
Expand Down Expand Up @@ -36,7 +36,8 @@
"@types/debug": "4.1.12",
"@types/json-stable-stringify": "1.0.36",
"ts-node": "10.9.2",
"typescript": "5.4.5"
"typescript": "5.4.5",
"viem": "2.13.2"
},
"type": "module",
"types": "dist/index.d.ts"
Expand Down
62 changes: 3 additions & 59 deletions packages/eth-rpc-cache/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,59 +1,3 @@
import debugConstructor from 'debug'

import { errors } from './error'
import { perBlockStrategy } from './strategies/per-block'
import { permanentStrategy } from './strategies/permanent'
import { type JsonRpcCallFn, type Strategy } from './types'
import { clone } from './utils/clone'

const debug = debugConstructor('eth-rpc-cache')

type Options = {
allowOthers?: boolean
cache?: Map<string, unknown>
strategies?: Strategy[]
}

export const createEthRpcCache = function (
rpc: JsonRpcCallFn,
options: Options = {}
): JsonRpcCallFn {
debug('Creating EVM RPC cache')

const {
allowOthers = true,
cache = new Map(),
strategies = [perBlockStrategy, permanentStrategy]
} = options

const cachedRpcByMethod: Record<string, ReturnType<Strategy['getRpc']>> = {}
strategies.forEach(function ({ getRpc, methods, name }) {
debug('Using strategy "%s"', name)
methods.forEach(function (method) {
// @ts-expect-error allow for options that can be dynamically forwarded to the strategy
cachedRpcByMethod[method] = getRpc(rpc, cache, options[name])
})
})

// Return the cached `rpc` function.
//
// If an strategy defined an RPC function for the incoming method, use that.
// Otherwise call the method directly if allowed or return proper errors.
//
// To prevent user code to mutate the cached results, the cached RPC functions
// will always return a clone of the result and not the result object itself.
return function (method, params) {
const cachedRpc = cachedRpcByMethod[method]

try {
return cachedRpc
? cachedRpc(method, params).then(clone)
: allowOthers
? rpc(method, params)
: Promise.reject(errors.methodNotFound())
} catch (err) {
// @ts-expect-error error is typed as unknown by default
return Promise.reject(errors.internalServerError(err))
}
}
}
export { createEthRpcCache } from './rpc'
export { perBlockStrategy } from './strategies/per-block'
export { permanentStrategy } from './strategies/permanent'
79 changes: 79 additions & 0 deletions packages/eth-rpc-cache/src/rpc.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
import debugConstructor from 'debug'
import pMemoize from 'promise-mem'

import { errors } from './error'
import { perBlockStrategy } from './strategies/per-block'
import { permanentStrategy } from './strategies/permanent'
import { type JsonRpcCallFn, type Strategy } from './types'
import { getKey } from './utils/cache-key'
import { clone } from './utils/clone'

const debug = debugConstructor('eth-rpc-cache')

type Options = {
allowOthers?: boolean
cache?: Map<string, unknown>
strategies?: Strategy[]
}

export const createEthRpcCache = function (
rpc: JsonRpcCallFn,
options: Options = {}
): JsonRpcCallFn {
debug('Creating EVM RPC cache')

const {
allowOthers = true,
cache = new Map(),
strategies = [perBlockStrategy, permanentStrategy]
} = options

// Each strategy resolves to a cache if it has a maxAge defined.
// Index all caches into the object by strategy name
const cachesByStrategy = strategies
.filter(({ maxAge }) => maxAge !== undefined)
.map(({ name, maxAge }) => ({
[name]: pMemoize(rpc, {
cache,
maxAge,
resolver: getKey,
...options
})
}))
.reduce((acc, curr) => ({ ...acc, ...curr }), {})

// This object indexed by method holds a function that returns which strategy (and cache)
// should be used. By default, each strategy resolves to use its own cache, but some strategies
// may resolve to other strategies' caches, depending on the method
const strategyResolver = strategies
.flatMap(({ methods, name, resolver = () => name }) =>
methods.map(method => ({
[method]: resolver
}))
)
.reduce((acc, curr) => ({ ...acc, ...curr }), {})

// Return the cached `rpc` function.
//
// If an strategy defined an RPC function for the incoming method, use that.
// Otherwise call the method directly if allowed or return proper errors.
//
// To prevent user code to mutate the cached results, the cached RPC functions
// will always return a clone of the result and not the result object itself.
return function (method, params) {
try {
const strategyName = strategyResolver[method]?.(method, params)
if (strategyName) {
return cachesByStrategy[strategyName](method, params).then(clone)
}
if (allowOthers) {
// not configured to be cached, call the method directly
return rpc(method, params)
}
return Promise.reject(errors.methodNotFound())
} catch (err) {
// @ts-expect-error error is typed as unknown by default
return Promise.reject(errors.internalServerError(err))
}
}
}
Loading