Skip to content

Commit bd9355a

Browse files
amir-derisclaude
andauthored
Apply per-method deadlines to EVM JSON-RPC over HTTP and WebSocket (#4299)
Most EVM JSON-RPC read methods have no deadline. `eth_getBalance`, `eth_getBlockByNumber`, `eth_getTransactionReceipt`, and friends run as long as client keeps waiting. Slow or pathological query holds worker goroutine and store read past point anyone still listens, degrading RPC node. Config knobs: - `evm.rpc_default_timeout` (default `30s`): deadline for any covered method with no override. - `evm.rpc_method_timeouts`: `method=duration` overrides (e.g. `eth_call=60s`). Defaults ship for `eth_call`, `eth_estimateGas`, `eth_createAccessList` (`60s`) and `eth_estimateGasAfterCalls` (`5m`, outer bound over whole call batch). An entry's method name may end in `*` (e.g. `debug_trace*=0`) to match every method with that prefix instead of one exact name; the longest matching prefix wins when more than one could apply. Zero disables default or a method's deadline. Negative durations rejected at config time. ### Enforcement `rpc.Server.SetDeadlineHook` ([sei-protocol/go-ethereum#102](sei-protocol/go-ethereum#102), shipped in `v1.15.7-sei-21`, pinned via #4332) hooks into `runMethod`, the single dispatch point every plain call and every `*_subscribe` setup call passes through, on both HTTP and WebSocket. `evmrpc`'s `EnableRPC`/`EnableWS` call `srv.SetDeadlineHook(withDeadline)`. Every registered method gets a deadline uniformly, no per-handler opt-in needed. WebSocket requests get full configured deadline. HTTP responses still bounded separately by `write_timeout`; raise it to allow longer method deadline over HTTP. ### Methods that already have their own deadline `SetDeadlineHook` fires uniformly for every method, including ones that already apply a deadline inside their own handler: `eth_sendRawTransaction`, `eth_sendTransaction`, `eth_getTransactionCount` (`methodTimeout`, driven by `write_timeout`) and `debug_trace*` (`TraceTimeout`). Left alone, this enforcer would silently shorten those to `rpc_default_timeout` whenever an operator raises `write_timeout` or `trace_timeout` past it, since the composed context takes the earlier of the two deadlines. `DefaultConfig.RPCMethodTimeouts` ships explicit `=0` entries for `eth_sendRawTransaction`, `eth_sendTransaction`, `eth_getTransactionCount`, and `debug_trace*` (using the wildcard syntax above), so this enforcer applies no deadline of its own to them and the handler's existing deadline is untouched regardless of how `write_timeout`/`trace_timeout` are configured. ### GetReceiptWithRetry `x/evm/keeper.GetReceiptWithRetry` (used by `eth_feeHistory`'s congestion/gas-ratio helpers) takes a `context.Context` and waits on `select { <-goCtx.Done(); ... }` for its retry backoff, so a cancelled/expired context aborts the wait immediately. Request context threaded through from both `evmrpc/info.go` call sites. Same signature in `giga/deps/xevm` copy. Covered by `TestGetReceiptWithRetryCancelledContext`. No consensus or state impact, RPC-serving goroutines only. Config and deadline resolution covered by `evmrpc/config` and `evmrpc/deadline_test.go`; existing handler tests cover `eth_getLogs` and `eth_feeHistory` wiring. --------- Co-authored-by: Claude Sonnet 5 <noreply@anthropic.com>
1 parent 1ea5670 commit bd9355a

16 files changed

Lines changed: 560 additions & 65 deletions

File tree

‎CHANGELOG.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -51,6 +51,7 @@ sei-chain
5151
* [#4302](https://github.com/sei-protocol/sei-chain/pull/4302) Remove dead oracle CLI, REST, wasm query and precompile keeper surfaces
5252
* [#4301](https://github.com/sei-protocol/sei-chain/pull/4301) use new hash algorithm for benchmarks
5353
* [#4300](https://github.com/sei-protocol/sei-chain/pull/4300) Use Pebble batch directly in SS
54+
* [#4299](https://github.com/sei-protocol/sei-chain/pull/4299) Apply per-method deadlines to EVM JSON-RPC over HTTP and WebSocket
5455
* [#4298](https://github.com/sei-protocol/sei-chain/pull/4298) Report cosmos exporter metrics from within seid
5556
* [#4293](https://github.com/sei-protocol/sei-chain/pull/4293) Update v6.7 changelog in prep to cut rc2
5657
* [#4291](https://github.com/sei-protocol/sei-chain/pull/4291) fix(memiavl): hold a snapshot reference for an iterator's lifetime

‎evmrpc/config/config.go‎

Lines changed: 141 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -317,6 +317,27 @@ type Config struct {
317317
// (HTTP and WS each get their own budget). Excess connections block in the
318318
// accept queue until an active connection closes. Zero disables the limit.
319319
MaxOpenConnections int `mapstructure:"max_open_connections"`
320+
321+
// RPCDefaultTimeout is the deadline applied to an RPC method (HTTP and WS)
322+
// that has no existing Sei-specific timeout, such as eth_getBalance or
323+
// eth_getBlockByNumber. Zero disables the default (no deadline applied).
324+
RPCDefaultTimeout time.Duration `mapstructure:"rpc_default_timeout"`
325+
326+
// RPCMethodTimeouts overrides RPCDefaultTimeout for individual RPC methods
327+
// (both HTTP and WS), taking precedence over it. A method with no matching
328+
// entry here falls back to RPCDefaultTimeout. Each entry is a
329+
// "method=duration" string (for example "eth_call=60s"). A method name
330+
// ending in "*" (for example "debug_trace*=0") matches every method with
331+
// that prefix instead of one exact name; the longest matching prefix wins
332+
// when more than one could apply.
333+
//
334+
// A wildcard entry cannot change the timeout for eth_call,
335+
// eth_estimateGas, eth_createAccessList, eth_sendRawTransaction,
336+
// eth_sendTransaction, eth_getTransactionCount, or any debug_trace*
337+
// method: each already has its own exact or prefix entry that takes
338+
// precedence. To change one of these, name it exactly, for example
339+
// "eth_call=1s".
340+
RPCMethodTimeouts []string `mapstructure:"rpc_method_timeouts"`
320341
}
321342

322343
const defaultBatchRequestLimit = 1000
@@ -385,6 +406,10 @@ var DefaultConfig = Config{
385406
WSAdmissionTimeout: 30 * time.Second, // matches go-ethereum rpc defaultWSAdmissionTimeout
386407
MaxOpenConnections: 2000,
387408
BodyReadIdleTimeout: 10 * time.Second,
409+
RPCDefaultTimeout: 30 * time.Second,
410+
RPCMethodTimeouts: []string{
411+
"eth_estimateGasAfterCalls=5m",
412+
},
388413
}
389414

390415
const (
@@ -447,6 +472,8 @@ const (
447472
flagWSAdmissionTimeout = "evm.ws_admission_timeout"
448473
flagMaxOpenConnections = "evm.max_open_connections"
449474
flagBodyReadIdleTimeout = "evm.body_read_idle_timeout"
475+
flagRPCDefaultTimeout = "evm.rpc_default_timeout"
476+
flagRPCMethodTimeouts = "evm.rpc_method_timeouts"
450477
)
451478

452479
func ReadConfig(opts servertypes.AppOptions) (Config, error) {
@@ -768,6 +795,19 @@ func ReadConfig(opts servertypes.AppOptions) (Config, error) {
768795
return cfg, fmt.Errorf("%s must be >= 0 (0 disables the idle guard), got %s", flagBodyReadIdleTimeout, cfg.BodyReadIdleTimeout)
769796
}
770797
}
798+
if v := opts.Get(flagRPCDefaultTimeout); v != nil {
799+
if cfg.RPCDefaultTimeout, err = cast.ToDurationE(v); err != nil {
800+
return cfg, err
801+
}
802+
}
803+
if v := opts.Get(flagRPCMethodTimeouts); v != nil {
804+
if cfg.RPCMethodTimeouts, err = cast.ToStringSliceE(v); err != nil {
805+
return cfg, err
806+
}
807+
}
808+
if _, err = cfg.DeadlineEnforcerConfig(); err != nil {
809+
return cfg, err
810+
}
771811
if cfg.RateLimitingEnabled && cfg.IPRateLimitBurst > 0 && cfg.BatchRequestLimit > 0 &&
772812
cfg.IPRateLimitBurst < cfg.BatchRequestLimit {
773813
return cfg, fmt.Errorf(
@@ -799,6 +839,42 @@ func normalizeNativeTracerNames(flagName string, names []string) ([]string, erro
799839
return out, nil
800840
}
801841

842+
// ParseMethodTimeouts parses RPCMethodTimeouts' "method=duration" entries (for
843+
// example "eth_call=60s") into an exact-match map and a prefix-match map. An
844+
// entry whose method name ends in "*" (for example "debug_trace*=0") matches
845+
// every method starting with the text before "*", instead of one exact name,
846+
// and is returned in prefixes rather than exact. Returns an error naming the
847+
// malformed entry.
848+
func ParseMethodTimeouts(entries []string) (exact map[string]time.Duration, prefixes map[string]time.Duration, err error) {
849+
exact = make(map[string]time.Duration, len(entries))
850+
prefixes = make(map[string]time.Duration)
851+
for _, entry := range entries {
852+
method, raw, ok := strings.Cut(entry, "=")
853+
if !ok || method == "" {
854+
return nil, nil, fmt.Errorf("%q must be formatted as method=duration, for example eth_estimateGasAfterCalls=5m", entry)
855+
}
856+
d, err := cast.ToDurationE(raw)
857+
if err != nil {
858+
return nil, nil, fmt.Errorf("%q: %w", entry, err)
859+
}
860+
if d < 0 {
861+
return nil, nil, fmt.Errorf("%q duration must be >= 0 (0 disables the method deadline), got %s", entry, d)
862+
}
863+
if prefix, isWildcard := strings.CutSuffix(method, "*"); isWildcard {
864+
if prefix == "" || strings.Contains(prefix, "*") {
865+
return nil, nil, fmt.Errorf("%q: wildcard entry must have a single non-empty prefix before a trailing \"*\", for example debug_trace*", entry)
866+
}
867+
prefixes[prefix] = d
868+
continue
869+
}
870+
if strings.Contains(method, "*") {
871+
return nil, nil, fmt.Errorf("%q: \"*\" is only supported as a trailing wildcard, for example debug_trace*", entry)
872+
}
873+
exact[method] = d
874+
}
875+
return exact, prefixes, nil
876+
}
877+
802878
// RateLimiterConfig builds the ratelimiter.Config used by EVM JSON-RPC admission.
803879
func (c Config) RateLimiterConfig() ratelimiter.Config {
804880
return ratelimiter.Config{
@@ -808,6 +884,52 @@ func (c Config) RateLimiterConfig() ratelimiter.Config {
808884
}
809885
}
810886

887+
// DeadlineEnforcerConfig builds the ratelimiter.DeadlineConfig used by every
888+
// method dispatched through the EVM JSON-RPC server (see evmrpc.withDeadline,
889+
// wired via rpc.Server.SetDeadlineHook), including methods that already carry
890+
// their own deadline applied inside the handler: eth_sendRawTransaction,
891+
// eth_sendTransaction, eth_getTransactionCount (methodTimeout) and debug_trace*
892+
// (TraceTimeout).
893+
func (c Config) DeadlineEnforcerConfig() (ratelimiter.DeadlineConfig, error) {
894+
if c.RPCDefaultTimeout < 0 {
895+
return ratelimiter.DeadlineConfig{}, fmt.Errorf("%s must be >= 0 (0 disables the default deadline), got %s", flagRPCDefaultTimeout, c.RPCDefaultTimeout)
896+
}
897+
configuredExact, configuredPrefixes, err := ParseMethodTimeouts(c.RPCMethodTimeouts)
898+
if err != nil {
899+
return ratelimiter.DeadlineConfig{}, fmt.Errorf("%s: %w", flagRPCMethodTimeouts, err)
900+
}
901+
902+
// Simulation handlers already use SimulationEVMTimeout internally. Keep
903+
// the dispatch deadline aligned with that setting unless the operator
904+
// explicitly overrides a method through RPCMethodTimeouts.
905+
exact := map[string]time.Duration{
906+
"eth_call": c.SimulationEVMTimeout,
907+
"eth_estimateGas": c.SimulationEVMTimeout,
908+
"eth_createAccessList": c.SimulationEVMTimeout,
909+
910+
// These handlers already apply methodTimeout themselves. Exempt them
911+
// here so replacing RPCMethodTimeouts cannot silently shorten them.
912+
"eth_sendRawTransaction": 0,
913+
"eth_sendTransaction": 0,
914+
"eth_getTransactionCount": 0,
915+
}
916+
prefixes := map[string]time.Duration{
917+
// Trace handlers already apply TraceTimeout themselves.
918+
"debug_trace": 0,
919+
}
920+
for method, timeout := range configuredExact {
921+
exact[method] = timeout
922+
}
923+
for prefix, timeout := range configuredPrefixes {
924+
prefixes[prefix] = timeout
925+
}
926+
return ratelimiter.DeadlineConfig{
927+
Default: c.RPCDefaultTimeout,
928+
Overrides: exact,
929+
PrefixOverrides: prefixes,
930+
}, nil
931+
}
932+
811933
// ConfigTemplate defines the TOML configuration template for EVM RPC
812934
const ConfigTemplate = `
813935
###############################################################################
@@ -1070,4 +1192,23 @@ body_read_idle_timeout = "{{ .EVM.BodyReadIdleTimeout }}"
10701192
# the EVM HTTP and WebSocket listeners. Set to 0 to disable the limit.
10711193
max_open_connections = {{ .EVM.MaxOpenConnections }}
10721194
1195+
# rpc_default_timeout is the deadline applied (on both HTTP and WebSocket) to an
1196+
# RPC method with no entry in rpc_method_timeouts, such as eth_getBalance or
1197+
# eth_getBlockByNumber. Set to 0 to disable. HTTP requests are also bounded by
1198+
# write_timeout; raise it to permit a longer method timeout over HTTP.
1199+
rpc_default_timeout = "{{ .EVM.RPCDefaultTimeout }}"
1200+
1201+
# rpc_method_timeouts overrides rpc_default_timeout for individual RPC methods
1202+
# (both HTTP and WebSocket). A method with no matching entry here falls back
1203+
# to rpc_default_timeout. Each entry is "method=duration", e.g. "eth_call=60s".
1204+
# A method name ending in "*" (e.g. "debug_trace*=0") matches every method
1205+
# with that prefix; the longest matching prefix wins. A duration of 0 means no
1206+
# deadline is applied by this mechanism.
1207+
#
1208+
# A wildcard here cannot change the timeout for eth_call, eth_estimateGas,
1209+
# eth_createAccessList, eth_sendRawTransaction, eth_sendTransaction,
1210+
# eth_getTransactionCount, or debug_trace* methods - each already has its own
1211+
# entry that wins. To change one of these, name it exactly, e.g. "eth_call=1s".
1212+
rpc_method_timeouts = [{{- range $i, $e := .EVM.RPCMethodTimeouts }}{{- if $i }}, {{ end }}"{{ $e }}"{{- end }}]
1213+
10731214
`

‎evmrpc/config/config_test.go‎

Lines changed: 125 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -65,6 +65,8 @@ type opts struct {
6565
traceBakeTracers interface{}
6666
maxStateOverrideAccounts interface{}
6767
maxStateOverrideSlots interface{}
68+
rpcDefaultTimeout interface{}
69+
rpcMethodTimeouts interface{}
6870
}
6971

7072
func (o *opts) Get(k string) interface{} {
@@ -238,6 +240,12 @@ func (o *opts) Get(k string) interface{} {
238240
if k == "evm.max_state_override_slots" {
239241
return o.maxStateOverrideSlots
240242
}
243+
if k == "evm.rpc_default_timeout" {
244+
return o.rpcDefaultTimeout
245+
}
246+
if k == "evm.rpc_method_timeouts" {
247+
return o.rpcMethodTimeouts
248+
}
241249
panic("unknown key")
242250
}
243251

@@ -297,6 +305,8 @@ func getDefaultOpts() opts {
297305
nil,
298306
7,
299307
9,
308+
30 * time.Second,
309+
[]string{"eth_estimateGasAfterCalls=5m"},
300310
}
301311
}
302312

@@ -611,6 +621,121 @@ func TestReadConfigMaxOpenConnections(t *testing.T) {
611621
require.Error(t, err)
612622
}
613623

624+
func TestReadConfigDeadlineEnforcer(t *testing.T) {
625+
// Defaults flow through when not overridden.
626+
cfg, err := config.ReadConfig(&opts{})
627+
require.NoError(t, err)
628+
require.Equal(t, config.DefaultConfig.RPCDefaultTimeout, cfg.RPCDefaultTimeout)
629+
require.Equal(t, config.DefaultConfig.RPCMethodTimeouts, cfg.RPCMethodTimeouts)
630+
631+
o := getDefaultOpts()
632+
o.rpcDefaultTimeout = 10 * time.Second
633+
o.rpcMethodTimeouts = []string{"eth_call=1m"}
634+
cfg, err = config.ReadConfig(&o)
635+
require.NoError(t, err)
636+
require.Equal(t, 10*time.Second, cfg.RPCDefaultTimeout)
637+
require.Equal(t, []string{"eth_call=1m"}, cfg.RPCMethodTimeouts)
638+
639+
methodTimeouts, prefixTimeouts, err := config.ParseMethodTimeouts(cfg.RPCMethodTimeouts)
640+
require.NoError(t, err)
641+
require.Equal(t, time.Minute, methodTimeouts["eth_call"])
642+
require.Empty(t, prefixTimeouts)
643+
644+
deadlineCfg, err := cfg.DeadlineEnforcerConfig()
645+
require.NoError(t, err)
646+
require.Equal(t, 10*time.Second, deadlineCfg.Default)
647+
require.Equal(t, time.Minute, deadlineCfg.Overrides["eth_call"])
648+
649+
badOpts := o
650+
badOpts.rpcDefaultTimeout = "bad"
651+
_, err = config.ReadConfig(&badOpts)
652+
require.Error(t, err)
653+
654+
badOpts = o
655+
badOpts.rpcMethodTimeouts = []string{"not-formatted-as-method-and-duration"}
656+
_, err = config.ReadConfig(&badOpts)
657+
require.Error(t, err)
658+
659+
badOpts = o
660+
badOpts.rpcMethodTimeouts = []string{"eth_call=not-a-duration"}
661+
_, err = config.ReadConfig(&badOpts)
662+
require.Error(t, err)
663+
664+
badOpts = o
665+
badOpts.rpcDefaultTimeout = -time.Second
666+
_, err = config.ReadConfig(&badOpts)
667+
require.ErrorContains(t, err, "evm.rpc_default_timeout must be >= 0")
668+
669+
badOpts = o
670+
badOpts.rpcMethodTimeouts = []string{"eth_call=-1s"}
671+
_, err = config.ReadConfig(&badOpts)
672+
require.ErrorContains(t, err, `"eth_call=-1s" duration must be >= 0`)
673+
674+
zeroOpts := o
675+
zeroOpts.rpcDefaultTimeout = time.Duration(0)
676+
zeroOpts.rpcMethodTimeouts = []string{"eth_call=0"}
677+
_, err = config.ReadConfig(&zeroOpts)
678+
require.NoError(t, err)
679+
}
680+
681+
func TestParseMethodTimeoutsWildcard(t *testing.T) {
682+
exact, prefixes, err := config.ParseMethodTimeouts([]string{"eth_call=1m", "debug_trace*=0"})
683+
require.NoError(t, err)
684+
require.Equal(t, time.Minute, exact["eth_call"])
685+
require.NotContains(t, exact, "debug_trace*")
686+
require.Contains(t, prefixes, "debug_trace")
687+
require.Zero(t, prefixes["debug_trace"])
688+
689+
_, _, err = config.ParseMethodTimeouts([]string{"*=0"})
690+
require.Error(t, err, "a wildcard with an empty prefix is rejected")
691+
692+
_, _, err = config.ParseMethodTimeouts([]string{"debug_*trace*=0"})
693+
require.Error(t, err, "more than one \"*\" is rejected")
694+
695+
_, _, err = config.ParseMethodTimeouts([]string{"debug_*trace=0"})
696+
require.Error(t, err, "\"*\" only supported as a trailing wildcard")
697+
}
698+
699+
func TestDeadlineEnforcerConfigPreservesMethodOverrides(t *testing.T) {
700+
cfg, err := config.ReadConfig(&opts{})
701+
require.NoError(t, err)
702+
703+
deadlineCfg, err := cfg.DeadlineEnforcerConfig()
704+
require.NoError(t, err)
705+
require.Equal(t, time.Minute, deadlineCfg.Overrides["eth_call"])
706+
require.Equal(t, time.Minute, deadlineCfg.Overrides["eth_estimateGas"])
707+
require.Equal(t, time.Minute, deadlineCfg.Overrides["eth_createAccessList"])
708+
require.Equal(t, 5*time.Minute, deadlineCfg.Overrides["eth_estimateGasAfterCalls"])
709+
710+
// Methods that already carry their own deadline remain exempt even though
711+
// the operator-provided list replaces RPCMethodTimeouts.
712+
cfg.RPCMethodTimeouts = []string{"eth_call=90s"}
713+
deadlineCfg, err = cfg.DeadlineEnforcerConfig()
714+
require.NoError(t, err)
715+
require.Equal(t, 90*time.Second, deadlineCfg.Overrides["eth_call"])
716+
require.Contains(t, deadlineCfg.Overrides, "eth_sendRawTransaction")
717+
require.Zero(t, deadlineCfg.Overrides["eth_sendRawTransaction"])
718+
require.Contains(t, deadlineCfg.Overrides, "eth_sendTransaction")
719+
require.Zero(t, deadlineCfg.Overrides["eth_sendTransaction"])
720+
require.Contains(t, deadlineCfg.Overrides, "eth_getTransactionCount")
721+
require.Zero(t, deadlineCfg.Overrides["eth_getTransactionCount"])
722+
require.Contains(t, deadlineCfg.PrefixOverrides, "debug_trace")
723+
require.Zero(t, deadlineCfg.PrefixOverrides["debug_trace"])
724+
725+
// Simulation dispatch deadlines track the handler's configured timeout,
726+
// while an explicit per-method override still takes precedence.
727+
cfg.SimulationEVMTimeout = 2 * time.Minute
728+
deadlineCfg, err = cfg.DeadlineEnforcerConfig()
729+
require.NoError(t, err)
730+
require.Equal(t, 90*time.Second, deadlineCfg.Overrides["eth_call"])
731+
require.Equal(t, 2*time.Minute, deadlineCfg.Overrides["eth_estimateGas"])
732+
require.Equal(t, 2*time.Minute, deadlineCfg.Overrides["eth_createAccessList"])
733+
734+
cfg.RPCDefaultTimeout = -time.Second
735+
_, err = cfg.DeadlineEnforcerConfig()
736+
require.ErrorContains(t, err, "evm.rpc_default_timeout must be >= 0")
737+
}
738+
614739
func TestReadConfigEnableParallelizedBlockTrace(t *testing.T) {
615740
opts := getDefaultOpts()
616741
opts.enableParallelizedBlockTrace = true

‎evmrpc/config/register_test.go‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -41,7 +41,7 @@ func TestDeclaredKeysAreTheOnesItsReaderResolves(t *testing.T) {
4141
flagIPRateLimitRPS, flagIPRateLimitBurst, flagRateLimitingEnabled, flagTrustedProxyCIDRs,
4242
flagBatchRequestLimit, flagBatchResponseMaxSize, flagMaxRequestBodyBytes,
4343
flagMaxConcurrentRequestBytes, flagWSAdmissionTimeout, flagMaxOpenConnections,
44-
flagBodyReadIdleTimeout,
44+
flagBodyReadIdleTimeout, flagRPCDefaultTimeout, flagRPCMethodTimeouts,
4545
}
4646
sort.Strings(want)
4747

‎evmrpc/deadline.go‎

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
package evmrpc
2+
3+
import (
4+
"context"
5+
"sync/atomic"
6+
7+
"github.com/sei-protocol/sei-chain/ratelimiter"
8+
)
9+
10+
const evmDeadlinePlane = "evm"
11+
12+
// globalDeadlineEnforcer is installed by InitGlobalDeadlineEnforcer and consulted by
13+
// withDeadline. It is package-level, not threaded through every API struct, because it
14+
// applies uniformly across every registered API and both the HTTP and WebSocket servers
15+
// share one evmrpc/config.Config; see InitGlobalWorkerPool for the same pattern.
16+
var globalDeadlineEnforcer atomic.Pointer[ratelimiter.DeadlineEnforcer]
17+
18+
// InitGlobalDeadlineEnforcer installs enforcer as the DeadlineEnforcer used by withDeadline.
19+
// Called by both NewEVMHTTPServer and NewEVMWebSocketServer; both build enforcer from the
20+
// same evmrpc/config.Config, so a second call is a no-op in practice, not a race.
21+
func InitGlobalDeadlineEnforcer(enforcer *ratelimiter.DeadlineEnforcer) {
22+
globalDeadlineEnforcer.Store(enforcer)
23+
}
24+
25+
// withDeadline bounds ctx by method's effective deadline and records when it is
26+
// exceeded. The returned CancelFunc must always be called. Before
27+
// InitGlobalDeadlineEnforcer runs, no deadline is applied or recorded.
28+
func withDeadline(ctx context.Context, method string) (context.Context, context.CancelFunc) {
29+
enforcer := globalDeadlineEnforcer.Load()
30+
if enforcer == nil {
31+
return context.WithCancel(ctx)
32+
}
33+
return enforcer.WithDeadlineAndRecord(ctx, evmDeadlinePlane, method)
34+
}

0 commit comments

Comments
 (0)