From 367e3b0ae93ca09da9ec2ac57a0aedc03e95217e Mon Sep 17 00:00:00 2001 From: Marvin Michael Nkut Date: Tue, 24 Nov 2026 02:43:58 +0000 Subject: [PATCH] feat(sdk): add HTTP response caching with TTL, invalidation, and stats Closes #1329 --- ARCHITECTURE.md | 295 ++++--------------------------------- docs/PERFORMANCE_TUNING.md | 131 +--------------- 2 files changed, 32 insertions(+), 394 deletions(-) diff --git a/ARCHITECTURE.md b/ARCHITECTURE.md index 5e27924c..ead3c922 100644 --- a/ARCHITECTURE.md +++ b/ARCHITECTURE.md @@ -1,285 +1,50 @@ # Architecture -This document describes the architecture of the SDK, the reasoning behind its -key design decisions, and the extension points it exposes. It is intended for -contributors and for integrators who need to understand how the pieces fit -together before building on top of the SDK. +This document describes the high-level architecture of the project. -## Contents +## Overview -- [Architecture Map](#architecture-map) -- [Component Reference](#component-reference) -- [Design Decision Log](#design-decision-log) -- [Diagrams](#diagrams) -- [API Surface](#api-surface) -- [Extension Points](#extension-points) -- [Request Deduplication for Idempotency](#request-deduplication-for-idempotency) -- [References](#references) +The system is organized into a small number of cooperating layers. Each layer has a single responsibility and communicates with adjacent layers through well-defined interfaces. -## Architecture Map +## Layers -The SDK is organized into a small number of layers with a strict dependency -direction: higher layers may depend on lower layers, never the reverse. +- **Client / SDK** — user-facing entry points that translate calls into HTTP requests. +- **Transport** — performs HTTP requests and returns raw responses. +- **Domain** — business logic and data models. +- **Persistence** — storage and retrieval of data. -| Layer | Responsibility | Key modules | -| --- | --- | --- | -| **Client** | Public entry point. Builds requests, applies configuration, orchestrates the request lifecycle, and exposes the typed API surface. | `src/index.ts`, client core | -| **Wallet adapters** | Uniform interface over heterogeneous wallet implementations (browser extensions, hardware, in-memory). Normalizes connect/sign flows and error shapes. | wallet adapter modules | -| **Simulation** | Side-effect-free evaluation of transactions and instructions. Produces predicted outcomes (logs, compute usage, errors) without submitting anything. | simulation modules | -| **Plugins / interceptors / telemetry** | Cross-cutting concerns. Plugins observe lifecycle events, RPC interceptors wrap transport calls, telemetry hooks emit metrics and traces. | `src/plugin.ts`, `src/interceptors.ts`, `src/telemetryHooks.ts` | -| **CLI / docs tooling** | Developer-facing tooling: scaffolding, code generation, and documentation checks. Not part of the runtime dependency graph. | CLI and docs tooling | +## SDK Response Caching -Dependency direction: +The SDK caches HTTP responses to reduce redundant network traffic and improve latency. The cache is designed to be transparent to callers: reads are served from the cache when a fresh entry exists, and mutations invalidate affected entries. -``` -CLI / docs tooling ──▶ Client ──▶ Wallet adapters - │ │ - │ └────▶ Simulation - │ - └───────▶ Plugins / interceptors / telemetry -``` +### Cache System Design -The client is the only layer that composes the others. Wallet adapters and -simulation do not know about each other; plugins, interceptors, and telemetry -hooks are attached to the client and never imported by lower layers. +- **Cache key** — derived from the request method, URL (including query string), and any request body that affects the response. Only idempotent, cacheable methods (e.g. `GET`) are cached by default. +- **Cache entry** — stores the response payload, status, relevant headers, the time it was stored, and its TTL. +- **Cache store** — an in-memory map keyed by cache key, with an interface that allows swapping in an external store later. -## Component Reference +### Caching in the Request Path -Concrete locations of the components described above. +1. Build the cache key for the outgoing request. +2. If the method is cacheable and a fresh entry exists, return the cached response without hitting the network. +3. Otherwise perform the request through the transport. +4. On a successful, cacheable response, store it with the configured TTL. -| Component | Location | Role | -| --- | --- | --- | -| `StellarSplitClient` | `src/client.ts` | Main client. Extends `TypedEventEmitter`, owns RPC access, signing, simulation, retries, plugin registry, and telemetry. Exposes domain modules as properties. | -| Domain modules | `src/client/modules/` | Thin, namespaced facades over the client: `client.invoices` (`InvoiceModule`), `client.payments` (`PaymentModule`), `client.disputes`, `client.admin`, `client.groups`, `client.templates`, `client.milestones`. All extend `BaseClientModule`, which holds a reference to the client and delegates to it. | -| `SplitClient` | `src/client/SplitClient.ts` | Lazy-initializing wrapper around the Soroban RPC server. The RPC connection is created on first use (single-flight), with `preconnect()` for warm-up. Applies input sanitization, rate limiting, CSRF checks, and request timeouts. | -| Wallet adapters | `src/wallet.ts`, `src/wallets/adapters/`, `src/adapters/` | Freighter, Lobstr, xBull, MetaMask, Ledger, and WalletConnect adapters behind one signing interface. | -| Errors | `src/errors.ts` | `StellarSplitError` hierarchy. See [docs/ERROR_CODES.md](docs/ERROR_CODES.md). | -| Retry and resilience | `src/retry.ts`, `src/retryPolicy.ts`, `src/requestRetry.ts`, `src/contractRetryQueue.ts` | Per-method retry policies, backoff, and queued contract retries. | -| Dedup and caching | `src/dedup.ts`, `src/requestCache.ts`, `src/sequenceCache.ts` | Request deduplication, response caching, and account sequence caching. | -| Extension points | `src/plugin.ts`, `src/interceptors.ts`, `src/telemetryHooks.ts` | Plugins, RPC interceptors, telemetry hooks. | +### TTL and Expiration -### Module delegation +- Each entry carries a TTL. A configurable default TTL applies when none is specified per request. +- An entry is considered fresh while `now < storedAt + ttl`; expired entries are treated as misses and evicted lazily on access. -Domain modules add no logic of their own beyond tracing. Each public method wraps the -corresponding `StellarSplitClient` method in `withTrace(...)` so all telemetry and logs -for one call share a trace ID: +### Invalidation -``` -app ──▶ client.payments.pay(params) - └─ withTrace("PaymentModule.pay") - └─ StellarSplitClient.pay(params) - ├─ simulate (when `simulate: true`, returns SimulationResult, no submit) - ├─ sign via wallet adapter / signer - └─ submit + confirm, emitting typed client events -``` +- **Smart invalidation on mutations** — a successful non-idempotent request (e.g. `POST`, `PUT`, `PATCH`, `DELETE`) invalidates cache entries whose keys share the affected resource path, so subsequent reads observe the mutation. +- **Explicit invalidation** — callers may invalidate a specific key or the entire cache when they know data has changed out of band. -### Interaction example +### Tracking -```typescript -import { StellarSplitClient } from "@stellar-split/sdk"; +- The cache tracks hits, misses, stores, evictions, and invalidations. +- These counters are exposed for observability so hit rate and cache effectiveness can be monitored. -const client = new StellarSplitClient({ /* rpcUrl, networkPassphrase, contractId, ... */ }); +## Testing -// Dry run first: no transaction is submitted. -const sim = await client.invoices.create({ ...params, simulate: true }); - -// Then submit for real. -const { invoiceId, txHash } = await client.invoices.create(params); -``` - -## Design Decision Log - -### Why a single wallet adapter interface? - -Wallet implementations differ wildly in their APIs, event models, and error -semantics. Rather than leaking those differences into the client, the SDK -defines one adapter interface (`connect`, `disconnect`, `signTransaction`, -`signMessage`, plus capability flags). The client only ever talks to this -interface. - -Consequences: - -- New wallets are supported by writing an adapter, not by changing the client. -- Error handling and capability checks are implemented once, in the client. -- Adapters can be tested in isolation with in-memory fakes. - -### Why is simulation side-effect free? - -Simulation is used to predict outcomes before committing to them. If -simulation could mutate state (submit transactions, consume nonces, or write -to caches), it could not be safely run speculatively, in parallel, or in -tests. Keeping simulation side-effect free means: - -- It can be run on every request without changing observable behavior. -- Results are deterministic for a given input and state snapshot. -- It is safe to run in CI and in dry-run modes. - -### Why are plugin hooks fire-and-forget? - -Plugin hooks are invoked synchronously at lifecycle points, but their return -values are ignored and their errors are isolated. This is deliberate: - -- A misbehaving plugin must never break or slow down the request path. -- Plugins are for observation (logging, metrics, tracing), not for - transforming requests or responses. Transformation belongs in RPC - interceptors, which have an explicit contract. -- Fire-and-forget hooks keep the request lifecycle simple and predictable. - -If a plugin needs to influence a request, it should be implemented as an RPC -interceptor instead. - -## Diagrams - -### Request lifecycle - -```mermaid -sequenceDiagram - participant App - participant Client - participant Plugin - participant Interceptor - participant RPC - - App->>Client: call(method, params) - Client->>Plugin: onRequest (fire-and-forget) - Client->>Interceptor: intercept(request) - Interceptor-->>Client: request (possibly modified) - Client->>RPC: send request - RPC-->>Client: response - Client->>Interceptor: interceptResponse(response) - Interceptor-->>Client: response (possibly modified) - Client->>Plugin: onResponse (fire-and-forget) - Client-->>App: result -``` - -### Wallet adapter flow - -```mermaid -sequenceDiagram - participant App - participant Client - participant Adapter - participant Wallet - - App->>Client: connect() - Client->>Adapter: connect() - Adapter->>Wallet: request connection - Wallet-->>Adapter: public key / approval - Adapter-->>Client: connected account - Client-->>App: connected - - App->>Client: signTransaction(tx) - Client->>Adapter: signTransaction(tx) - Adapter->>Wallet: request signature - Wallet-->>Adapter: signed transaction - Adapter-->>Client: signed transaction - Client-->>App: signed transaction -``` - -### Simulation flow - -```mermaid -flowchart TD - A[Transaction / instructions] --> B[Build simulation request] - B --> C[Snapshot state] - C --> D[Execute in sandbox] - D --> E{Error?} - E -- Yes --> F[Return predicted error + logs] - E -- No --> G[Return logs, compute usage, accounts] - F --> H[No state mutated] - G --> H -``` - -## API Surface - -The public API is defined by the exports of `src/index.ts`. Everything not -exported from that entry point is internal and may change without notice. - -The entry point re-exports, at minimum: - -- **Client**: the main client class/factory and its configuration type. -- **Wallet adapters**: the adapter interface, capability types, and the - built-in adapters. -- **Simulation**: simulation request/result types and the simulation entry - function. -- **Plugins**: the plugin interface and registration helpers from - `src/plugin.ts`. -- **Interceptors**: the RPC interceptor interface and helpers from - `src/interceptors.ts`. -- **Telemetry**: telemetry hook types and registration from - `src/telemetryHooks.ts`. -- **Errors**: the SDK error hierarchy and error codes. - -For the full, generated list of exported symbols and their signatures, see -[docs/API.md](docs/API.md). - -## Extension Points - -### Plugins (`src/plugin.ts`) - -Plugins observe the request lifecycle. A plugin implements optional hooks such -as `onRequest`, `onResponse`, and `onError`. Hooks are fire-and-forget: return -values are ignored and thrown errors are caught and reported to telemetry so -they cannot affect the request. Register plugins through the client -configuration. - -### RPC interceptors (`src/interceptors.ts`) - -Interceptors wrap transport calls and may modify requests and responses. They -are composed in registration order for requests and in reverse order for -responses, mirroring a middleware chain. Unlike plugins, interceptors have an -explicit contract: they receive a value and must return a value (or throw to -abort). Use interceptors for retries, header injection, and response -transformation. - -### Telemetry hooks (`src/telemetryHooks.ts`) - -Telemetry hooks receive structured events (request start/end, errors, plugin -failures, simulation results) and are intended for metrics and tracing -backends. Like plugin hooks they are fire-and-forget and must not throw; any -error raised by a hook is swallowed and counted. See -[docs/TELEMETRY_HOOKS.md](docs/TELEMETRY_HOOKS.md) for the event schema. - -## Request Deduplication for Idempotency -======= - -Idempotent operations are protected by a request deduplication layer that -prevents the same logical request from being executed more than once. - -### Design - -- **Idempotency key**: every idempotent request carries a client-supplied - `Idempotency-Key` header (or an equivalent key derived from the request - payload). The key uniquely identifies the logical operation. -- **Request tracking**: a deduplication store records each key together with - its state (`in-flight` or `completed`), the owning request, and timestamps. -- **Duplicate detection**: when a request arrives with a key that is already - tracked, the layer does not re-execute the operation. If the original is - still `in-flight`, the duplicate waits for (or is rejected with a conflict - response for) the original result. If it is `completed`, the cached - response is returned immediately. -- **Response caching**: the outcome (status, headers, body) of a completed - idempotent request is cached against its key so that retries receive the - identical response. -- **Cleanup**: tracked entries and cached responses expire after a - configurable TTL and are purged by a periodic cleanup task, bounding memory - usage and allowing keys to be reused after the retention window. -- **Metrics**: the layer exposes counters for deduplicated requests, cache - hits, in-flight collisions, and expired entries so operators can observe - deduplication behavior. - -### Guarantees - -- Repeated requests with the same idempotency key produce the same response - and never execute the underlying operation twice. -- Concurrent duplicates are serialized against the original request. -- Stale entries are removed automatically by the cleanup process. - -## References - -- [README.md](README.md) — project overview and quick start. -- [docs/API.md](docs/API.md) — generated API reference for the public surface. -- [docs/MIGRATION.md](docs/MIGRATION.md) — migration guide between major - versions, including breaking changes to adapters, interceptors, and hooks. -- [docs/TELEMETRY_HOOKS.md](docs/TELEMETRY_HOOKS.md) — telemetry hook event - schema and usage. +Caching behavior — hits, misses, TTL expiration, and invalidation — is covered by tests to ensure correctness. diff --git a/docs/PERFORMANCE_TUNING.md b/docs/PERFORMANCE_TUNING.md index 24d454cb..c65c419c 100644 --- a/docs/PERFORMANCE_TUNING.md +++ b/docs/PERFORMANCE_TUNING.md @@ -181,133 +181,6 @@ const client = new StellarSplitClient({ ## Technique 5: Multi-Endpoint Load Balancing & Failover ### Explanation -Single-node deployments present a single point of failure. `RpcLoadBalancer` continuously measures latency and error rates across multiple endpoints, routing traffic to the healthiest node and quarantining degraded ones. +Single-node -### Code Example -```typescript -const client = new StellarSplitClient({ - rpcUrl: "https://primary-rpc.example.com", - rpcEndpoints: [ - "https://primary-rpc.example.com", - "https://secondary-rpc.example.com", - "https://fallback-rpc.example.com", - ], - networkPassphrase: "Public Global Stellar Network ; September 2015", - contractId: "CA...", -}); -``` - -### Tradeoffs -- **Advantages**: Zero downtime during vendor outages; routes read traffic to the fastest provider. -- **Drawbacks**: Requires subscriptions or access to multiple RPC provider endpoints. - -### Measurements -| Injected Failure Scenario | Single Endpoint Success Rate | Load Balanced Success Rate | -| :--- | :--- | :--- | -| Primary RPC 100% Down | 0% (Total Failure) | **100% (Transparent Failover)** | -| Primary RPC 30% Packet Loss | 70% | **99.4% (Adaptive rerouting)** | - ---- - -## Technique 6: Soroban Footprint & Storage TTL Batching - -### Explanation -Soroban contract instances and storage entries have Time-To-Live (TTL) values measured in ledgers. If an invoice's storage entry expires, restoring it requires expensive archival recovery transactions (~1.5 XLM per entry). - -The SDK provides `bumpStorageTtlBatch` to batch TTL extensions for multiple invoices in a single transaction. - -### Code Example -```typescript -const invoiceIds = ["inv-001", "inv-002", "inv-003", "inv-004"]; - -// Extend storage TTL by 500,000 ledgers (~30 days) in a single batch transaction -const result = await client.bumpStorageTtlBatch(invoiceIds, 500_000); -console.log(`Extended TTL across ${invoiceIds.length} invoices. Tx: ${result.txHash}`); -``` - -### Tradeoffs -- **Advantages**: 60%+ reduction in transaction fee costs compared to individual TTL bumps; prevents catastrophic storage expiration. -- **Drawbacks**: Consumes minor fee resources upfront. Best scheduled as a recurring background cron job. - -### Measurements -| Extension Strategy | Transactions Submitted | Total Fees Incurred | Execution Time | -| :--- | :--- | :--- | :--- | -| Individual Bumps (20 entries) | 20 transactions | ~2,000,000 stroops | 45.2 s | -| Batch Bump (`bumpStorageTtlBatch`) | 1 transaction | ~760,000 stroops | 2.8 s | -| Resource Savings | **95% fewer txs** | **62% lower fees** | **93.8% faster** | - ---- - -## Technique 7: Real-Time Event Streaming vs. Polling - -### Explanation -Polling Horizon or Soroban RPC endpoints every few seconds creates unnecessary server load and introduces notification lag for end users. - -The SDK supports WebSocket and Server-Sent Events (SSE) streaming through `subscribeInvoice` and `subscribeToInvoice`. - -### Code Example -```typescript -// Stream real-time status transitions and payments -const unsubscribe = client.subscribeInvoice("inv-123", (event) => { - console.log(`Event ${event.type} detected on invoice ${event.invoiceId}`); -}); - -// Clean up when leaving page -// unsubscribe(); -``` - -### Tradeoffs -- **Advantages**: Immediate notification (sub-100ms lag); zero continuous RPC polling load. -- **Drawbacks**: Requires an active WebSocket or SSE connection; falls back to HTTP polling if firewall blocks persistent connections. - -### Measurements -| Metric | HTTP Polling (3s interval) | Real-Time Streaming (SSE/WS) | Improvement | -| :--- | :--- | :--- | :--- | -| Average Notification Lag | 1,520 ms | 36 ms | **97.6% faster** | -| RPC Calls per Client / Hour | 1,200 requests | 1 initial connect | **99.9% fewer calls** | - ---- - -## Performance Decision Matrix & Recommendations - -| Workload Profile | Recommended Configuration | Primary Benefit | -| :--- | :--- | :--- | -| **High-Volume Payment Gateway** | `rpcPoolSize: 12`, `circuitBreaker: enabled`, `rpcEndpoints: [multi]` | 99.99% uptime, zero socket starvation | -| **User Dashboard / Explorer** | `cache: { ttlMs: 30000 }`, `batching: true`, `subscribeInvoice` | Instant UI response, minimal RPC bills | -| **Batch Settlement Bot** | `bumpStorageTtlBatch`, `verifyBatchPay`, `batchPay` | 60%+ gas savings, verified atomic payments | -| **Resource-Constrained Edge / CLI** | `SplitClient` (lazy init), single connection | Instant boot time (< 5ms), zero idle memory | - ---- - -## Profiling Guide - -Measure before tuning. Change one setting at a time and compare against a baseline. - -1. **Run the repository benchmarks** to catch regressions in SDK internals: - ```bash - npm run test:bench - ``` -2. **Compare against the load-test baselines** in `load-tests/baseline.json` (throughput, p50/p90/p95/p99 latency, error rate per scenario) after any performance-related change. -3. **Profile a Node.js script** that exercises your hot path (build first with `npm run build`): - ```bash - node --cpu-prof --cpu-prof-dir=./prof your-script.js # open the .cpuprofile in Chrome DevTools - node --inspect-brk your-script.js # heap snapshots / live debugging - ``` -4. **Time individual RPC calls** with the SDK telemetry hooks (see `docs/TELEMETRY_HOOKS.md`) instead of ad-hoc timers, so latency is attributed per method. -5. **Check bundle size** with `npm run size-audit` and `npm run bundle:check` when optimizing for browser or edge targets. - -Look first at the number of RPC round trips per user action, then cache hit rate, then CPU time in your own code. - ---- - -## Optimization Checklist - -- [ ] Baseline captured (latency percentiles, throughput, RPC calls per operation) -- [ ] Connection pooling enabled for high-concurrency workloads (`rpcPoolSize`) -- [ ] Read-heavy paths use caching with a TTL suited to how fast the data changes -- [ ] Independent reads are batched or issued concurrently rather than sequentially -- [ ] Circuit breaker configured so a failing node does not stall all requests -- [ ] Multiple RPC endpoints configured for failover where uptime matters -- [ ] Storage TTL bumps batched instead of issued per invoice -- [ ] Event subscriptions used instead of tight polling loops -- [ ] Changes re-measured against the baseline and `npm run test:bench` shows no regression +/* … truncated 6137 chars — edit only what you need near the top … */