|
| 1 | +package metrics |
| 2 | + |
| 3 | +import ( |
| 4 | + "sort" |
| 5 | + "strings" |
| 6 | + "sync" |
| 7 | +) |
| 8 | + |
| 9 | +const ( |
| 10 | + // batchMethodSeparator mirrors chainlib's SEP — the token batch parsing uses to |
| 11 | + // join every sub-method into one synthetic api name (protocol/chainlib/jsonRPC.go, |
| 12 | + // protocol/chainlib/tendermintRPC.go). It is redeclared here rather than imported |
| 13 | + // because chainlib already imports this package; importing back would be a cycle. |
| 14 | + batchMethodSeparator = "&" |
| 15 | + |
| 16 | + // BatchMethodPrefix namespaces every collapsed batch label value so dashboards can |
| 17 | + // separate batch traffic from single-method traffic with a prefix match |
| 18 | + // (method=~"batch:.*") rather than an allowlist of method names. |
| 19 | + BatchMethodPrefix = "batch:" |
| 20 | + |
| 21 | + // BatchMethodOther is the overflow bucket, emitted when a batch's signature is past |
| 22 | + // the per-spec cap or spans more distinct methods than maxBatchSignatureElements. |
| 23 | + // It is what makes the `method` label bounded no matter what a client sends. |
| 24 | + BatchMethodOther = BatchMethodPrefix + "other" |
| 25 | + |
| 26 | + // batchSignatureElementSeparator joins sub-methods inside a signature. It is |
| 27 | + // deliberately NOT batchMethodSeparator: that is what keeps normalization |
| 28 | + // idempotent, since an already-collapsed value then carries no separator. |
| 29 | + batchSignatureElementSeparator = "+" |
| 30 | + |
| 31 | + // maxBatchSignaturesPerSpec caps how many distinct signatures one spec may |
| 32 | + // register. Distinct method SETS are 2^N in theory but a handful in practice — |
| 33 | + // batch shapes are emitted by customer code, not drawn at random. The cap is the |
| 34 | + // backstop for when that assumption is wrong, and |
| 35 | + // smartrouter_batch_signature_overflow_total reports when it binds. |
| 36 | + maxBatchSignaturesPerSpec = 64 |
| 37 | + |
| 38 | + // maxBatchSignatureElements caps how many distinct methods a single signature may |
| 39 | + // name, so one pathological batch can't mint a kilobyte-long label value. |
| 40 | + maxBatchSignatureElements = 8 |
| 41 | +) |
| 42 | + |
| 43 | +// Reasons for the smartrouter_batch_signature_overflow_total `reason` label. |
| 44 | +const ( |
| 45 | + batchOverflowReasonCap = "cap" |
| 46 | + batchOverflowReasonWide = "wide" |
| 47 | +) |
| 48 | + |
| 49 | +// buildBatchSignature turns a raw joined batch api name into an order-invariant and |
| 50 | +// repetition-invariant signature: the sorted SET of its sub-methods. |
| 51 | +// |
| 52 | +// Dropping order and repetition is the entire point. They are what made the raw name |
| 53 | +// unbounded — order contributes permutations, repetition contributes length variants — |
| 54 | +// while the set is what a client's code actually determines. So |
| 55 | +// |
| 56 | +// eth_callð_call&…ð_callð_getBalance → batch:eth_call+eth_getBalance |
| 57 | +// |
| 58 | +// collapses thousands of observed series onto one, and the magnitude that repetition |
| 59 | +// used to (uselessly) encode is recovered from the smartrouter_batch_size histogram. |
| 60 | +// |
| 61 | +// Sub-methods need no allowlist check: chainlib resolves every element against the spec |
| 62 | +// through getSupportedApi and hard-fails the parse before any batch name is built, so a |
| 63 | +// name reaching here only ever contains spec-declared api names, never raw client input. |
| 64 | +// |
| 65 | +// size is the batch's element count including repeats. tooWide reports a batch spanning |
| 66 | +// more than maxBatchSignatureElements distinct methods, for which the caller emits |
| 67 | +// BatchMethodOther instead of an unwieldy label value. |
| 68 | +func buildBatchSignature(apiName string) (signature string, size int, tooWide bool) { |
| 69 | + parts := strings.Split(apiName, batchMethodSeparator) |
| 70 | + seen := make(map[string]struct{}, len(parts)) |
| 71 | + distinct := make([]string, 0, len(parts)) |
| 72 | + |
| 73 | + for _, part := range parts { |
| 74 | + part = strings.TrimSpace(part) |
| 75 | + if part == "" { |
| 76 | + continue |
| 77 | + } |
| 78 | + size++ |
| 79 | + if _, duplicate := seen[part]; duplicate { |
| 80 | + continue |
| 81 | + } |
| 82 | + seen[part] = struct{}{} |
| 83 | + distinct = append(distinct, part) |
| 84 | + } |
| 85 | + |
| 86 | + if len(distinct) == 0 || len(distinct) > maxBatchSignatureElements { |
| 87 | + return BatchMethodOther, size, true |
| 88 | + } |
| 89 | + |
| 90 | + sort.Strings(distinct) |
| 91 | + return BatchMethodPrefix + strings.Join(distinct, batchSignatureElementSeparator), size, false |
| 92 | +} |
| 93 | + |
| 94 | +// batchSignatureRegistry bounds the set of batch signatures allowed to become label |
| 95 | +// values, tracked per spec so a chatty chain can't consume another chain's budget. |
| 96 | +type batchSignatureRegistry struct { |
| 97 | + lock sync.RWMutex |
| 98 | + admitted map[string]map[string]struct{} // spec -> set of admitted signatures |
| 99 | +} |
| 100 | + |
| 101 | +func newBatchSignatureRegistry() *batchSignatureRegistry { |
| 102 | + return &batchSignatureRegistry{admitted: make(map[string]map[string]struct{})} |
| 103 | +} |
| 104 | + |
| 105 | +// admit reports whether signature may be used as a label value for spec. |
| 106 | +// |
| 107 | +// Admission is monotone: an admitted signature stays admitted, and a full cap stays |
| 108 | +// full. That is what keeps paired call sites consistent — the in-flight gauge's Add at |
| 109 | +// relay start and Sub at relay end normalize the same api name to the same string, so |
| 110 | +// the gauge cannot leak a stuck non-zero series. |
| 111 | +func (r *batchSignatureRegistry) admit(spec, signature string) bool { |
| 112 | + if r == nil { |
| 113 | + return false |
| 114 | + } |
| 115 | + |
| 116 | + r.lock.RLock() |
| 117 | + if signatures, ok := r.admitted[spec]; ok { |
| 118 | + if _, alreadyAdmitted := signatures[signature]; alreadyAdmitted { |
| 119 | + r.lock.RUnlock() |
| 120 | + return true |
| 121 | + } |
| 122 | + } |
| 123 | + r.lock.RUnlock() |
| 124 | + |
| 125 | + r.lock.Lock() |
| 126 | + defer r.lock.Unlock() |
| 127 | + |
| 128 | + signatures, ok := r.admitted[spec] |
| 129 | + if !ok { |
| 130 | + signatures = make(map[string]struct{}, maxBatchSignaturesPerSpec) |
| 131 | + r.admitted[spec] = signatures |
| 132 | + } |
| 133 | + if _, alreadyAdmitted := signatures[signature]; alreadyAdmitted { |
| 134 | + return true |
| 135 | + } |
| 136 | + if len(signatures) >= maxBatchSignaturesPerSpec { |
| 137 | + return false |
| 138 | + } |
| 139 | + signatures[signature] = struct{}{} |
| 140 | + return true |
| 141 | +} |
| 142 | + |
| 143 | +// normalizeMethodLabel collapses a raw batch api name into a bounded signature and |
| 144 | +// returns single-method names untouched. |
| 145 | +// |
| 146 | +// It is idempotent, because a collapsed value carries no batchMethodSeparator. That |
| 147 | +// matters: the public recorders delegate to one another (RecordDirectRelayEnd → |
| 148 | +// RecordRelaySuccess → AddEndpointRelayServiced), and each normalizes at its own |
| 149 | +// boundary so that calling any of them directly is still safe. |
| 150 | +func (m *SmartRouterMetricsManager) normalizeMethodLabel(spec, method string) string { |
| 151 | + if m == nil || !strings.Contains(method, batchMethodSeparator) { |
| 152 | + return method |
| 153 | + } |
| 154 | + |
| 155 | + signature, _, tooWide := buildBatchSignature(method) |
| 156 | + if tooWide { |
| 157 | + m.recordBatchSignatureOverflow(spec, batchOverflowReasonWide) |
| 158 | + return BatchMethodOther |
| 159 | + } |
| 160 | + if !m.batchSignatures.admit(spec, signature) { |
| 161 | + m.recordBatchSignatureOverflow(spec, batchOverflowReasonCap) |
| 162 | + return BatchMethodOther |
| 163 | + } |
| 164 | + return signature |
| 165 | +} |
| 166 | + |
| 167 | +func (m *SmartRouterMetricsManager) recordBatchSignatureOverflow(spec, reason string) { |
| 168 | + if m == nil || m.batchSignatureOverflow == nil { |
| 169 | + return |
| 170 | + } |
| 171 | + m.batchSignatureOverflow.WithLabelValues(spec, reason).Inc() |
| 172 | +} |
| 173 | + |
| 174 | +// observeBatchSize records how many sub-requests a batch carried — the magnitude that |
| 175 | +// the collapsed `method` label deliberately no longer encodes. |
| 176 | +// |
| 177 | +// This must be called from exactly ONE place (RecordDirectRelayEnd, once per completed |
| 178 | +// relay). The other recorders normalize but must not observe, or a single request would |
| 179 | +// be counted once per recorder it passes through. |
| 180 | +// |
| 181 | +// Single-element batches carry no separator in their api name, so they are |
| 182 | +// indistinguishable from single requests here and are not observed. |
| 183 | +func (m *SmartRouterMetricsManager) observeBatchSize(spec, apiInterface, method string) { |
| 184 | + if m == nil || m.batchSize == nil || !strings.Contains(method, batchMethodSeparator) { |
| 185 | + return |
| 186 | + } |
| 187 | + |
| 188 | + _, size, _ := buildBatchSignature(method) |
| 189 | + if size == 0 { |
| 190 | + return |
| 191 | + } |
| 192 | + m.batchSize.WithLabelValues(spec, apiInterface).Observe(float64(size)) |
| 193 | +} |
0 commit comments