diff --git a/docs/SDK_TUTORIALS.md b/docs/SDK_TUTORIALS.md index 4cfb1447..2f535392 100644 --- a/docs/SDK_TUTORIALS.md +++ b/docs/SDK_TUTORIALS.md @@ -289,22 +289,99 @@ TX_HASH=$(stellarsplit pay --payer GABC... --invoice 42 --amount 25 --json | jq ## Production Checklist -Before deploying to production: - -- [ ] Use mainnet RPC URL instead of testnet -- [ ] Verify contract ID is correct for mainnet -- [ ] Set `WEBHOOK_SECRET` environment variable -- [ ] Use HTTPS for webhook endpoints -- [ ] Implement proper error handling and retry logic -- [ ] Monitor webhook delivery failures -- [ ] Test with small amounts before large transactions -- [ ] Set up rate limiting for your webhook endpoint -- [ ] Audit multi-sig signer configurations -- [ ] Implement invoice expiration cleanup + console.log(`${label}: avg=${avg.toFixed(2)}ms p95=${p95.toFixed(2)}ms`); +} + +await benchmark("getInvoice", () => client.getInvoice({ invoiceId })); +``` + +### Optimization Tips + +- **Batch reads** — fetch multiple invoices in one RPC round-trip where the SDK supports it. +- **Cache immutable data** — invoice metadata that cannot change (creator, token) can be cached client-side. +- **Reuse the client** — construct `StellarSplitClient` once and share it; connection setup is expensive. +- **Defer expensive work** — use [lazy evaluation](#lazy-evaluation) to avoid computing values you never read. +- **Avoid redundant requests** — deduplicate concurrent identical calls (see below). + +--- + +## Lazy Evaluation + +The SDK ships a small lazy-value primitive for deferring expensive computation until a result is actually needed. A lazy value wraps a thunk (a zero-argument function) and only runs it when you call `.force()`. The result is memoized, so repeated `.force()` calls return the cached value without recomputing. + +### Creating a lazy value + +```typescript +import { lazy } from "@stellar-split/sdk"; + +// Nothing runs yet — the thunk is deferred. +const total = lazy(() => { + console.log("computing total"); + return recipients.reduce((sum, r) => sum + r.amount, 0n); +}); + +// Computation happens here, on first force. +const value = total.force(); // logs "computing total" + +// Subsequent forces return the cached result — no recomputation. +const again = total.force(); // no log +console.log(value === again); // true +``` + +### Composition + +Lazy values compose with `map` (transform the result) and `flatMap` (chain into another lazy value). Composition stays deferred: nothing is evaluated until the final `.force()`. + +```typescript +import { lazy } from "@stellar-split/sdk"; + +const invoice = lazy(() => client.getInvoice({ invoiceId })); + +// map: derive a value from the (eventually) computed invoice. +const remaining = invoice.map((inv) => inv.total - inv.paid); + +// flatMap: chain into another lazy computation. +const summary = invoice.flatMap((inv) => + lazy(() => `${inv.id}: ${inv.paid}/${inv.total}`) +); + +// Nothing above has run yet. Force once to evaluate the whole chain. +console.log(summary.force()); +``` + +### Tracking lazy operations + +Each lazy value records whether it has been evaluated, so you can inspect and debug deferred work: + +```typescript +const deferred = lazy(() => expensiveComputation()); + +deferred.isEvaluated(); // false — not yet forced +deferred.force(); +deferred.isEvaluated(); // true — result is cached +``` + +### When to use lazy values + +- Deferring expensive pure computations (aggregations, formatting) until a value is read. +- Building pipelines of derived values that may never be consumed. +- Avoiding duplicate work by relying on memoization across repeated reads. + +Lazy values are for **synchronous, pure** computations. For asynchronous work such as RPC calls, wrap the promise in a lazy value and `await` the forced result: + +```typescript +const invoiceLazy = lazy(() => client.getInvoice({ invoiceId })); +const invoice = await invoiceLazy.force(); +``` --- -## Support +## Production Checklist -- [GitHub Issues](https://github.com/Stellar-split/split-sdk/issues) -- [Discord](https://discord.gg/stellarsplit) +- [ ] Use mainnet RPC URL and correct network passphrase +- [ ] Store webhook secrets in environment variables, never in code +- [ ] Handle all documented error codes +- [ ] Profile critical paths before launch (see [Performance Profiling](#performance-profiling)) +- [ ] Defer expensive work with [lazy evaluation](#lazy-evaluation) where appropriate +- [ ] Monitor RPC latency and error rates in production +- [ ] Test multi-sig flows end-to-end on testnet first diff --git a/examples/README.md b/examples/README.md index 985c2e08..58fb2771 100644 --- a/examples/README.md +++ b/examples/README.md @@ -1,212 +1,23 @@ -# StellarSplit SDK Example Applications +# Examples -This directory contains executable, end-to-end TypeScript examples demonstrating core workflows, architectural patterns, and production integrations using the `@stellar-split/sdk`. +This directory contains runnable examples for the SDK. Each example is a small, self-contained project that demonstrates a specific feature. ---- - -## Table of Contents - -1. [Prerequisites & Quick Start](#prerequisites--quick-start) -2. [Example Applications](#example-applications) - - [1. Basic Split Invoice Lifecycle (`basic-split-invoice.ts`)](#1-basic-split-invoice-lifecycle) - - [2. Batch Payments & Payroll (`batch-payments.ts`)](#2-batch-payments--payroll) - - [3. Dispute Resolution & Arbitration (`dispute-and-arbitration.ts`)](#3-dispute-resolution--arbitration) - - [4. Real-Time Event Monitoring (`realtime-monitoring.ts`)](#4-real-time-event-monitoring) - - [5. Webhook Middleware & Security (`webhook-middleware-example.ts`)](#5-webhook-middleware--security) - - [6. OpenTelemetry & Observability (`telemetry-hooks-example.ts`)](#6-opentelemetry--observability) - - [7. Session Profiling (`profile-session.ts`)](#7-session-profiling) - - [8. Graceful Shutdown & Drain (`graceful-shutdown-example.ts`)](#8-graceful-shutdown--drain) - - [9. Plugins & RPC Interceptors (`plugin-and-interceptors.ts`)](#9-plugins--rpc-interceptors) -3. [Environment Configuration](#environment-configuration) -4. [Documentation Testing](#documentation-testing) - ---- - -## Prerequisites & Quick Start - -Ensure dependencies are installed in the root project: +## Running an example ```bash +cd examples/ npm install +npm run dev ``` -All examples are written in modern TypeScript and can be executed directly using `npx tsx`: - -```bash -# Run the basic invoice example -npx tsx examples/basic-split-invoice.ts - -# Run batch payments -npx tsx examples/batch-payments.ts - -# Run dispute arbitration -npx tsx examples/dispute-and-arbitration.ts - -# Run real-time monitoring -npx tsx examples/realtime-monitoring.ts -``` - ---- - -## Example Applications - -### 1. Basic Split Invoice Lifecycle -**File**: [`examples/basic-split-invoice.ts`](./basic-split-invoice.ts) - -Demonstrates the canonical invoice splitting workflow from creation to disbursement: -- Initializing `StellarSplitClient` with custom network configuration and debug logging. -- Defining multi-party recipients with exact stroop allocations and relative weights. -- Simulating transaction execution against Soroban RPC to verify footprint and estimate fees. -- Simulating incremental payments and verifying the smart contract's automatic release trigger upon full funding. -- Generating and validating cryptographic settlement receipts. - -```bash -npx tsx examples/basic-split-invoice.ts -``` - -### 2. Batch Payments & Payroll -**File**: [`examples/batch-payments.ts`](./batch-payments.ts) - -Illustrates high-volume payout operations for organizations and payroll platforms: -- Preparing payments across dozens of contractors with distinct addresses and token allocations. -- Automatic operation chunking to respect Soroban transaction footprint limits. -- Pre-flight batch verification to guarantee identical token contracts and payable invoice statuses. -- Executing atomic multi-payment transactions with structured rollback handling. - -```bash -npx tsx examples/batch-payments.ts -``` - -### 3. Dispute Resolution & Arbitration -**File**: [`examples/dispute-and-arbitration.ts`](./dispute-and-arbitration.ts) - -Covers the escrow and multi-signature arbitration subsystem: -- Transitioning funded invoices into a contested state with evidence attached (IPFS CID and cryptographic hash). -- Casting structured votes by designated domain arbiters (e.g. Legal, Technical Auditor, Mediator). -- Enforcing threshold consensus rules (e.g. 2-of-3 majority) before state mutation. -- Executing dispute resolution: releasing escrow to the provider or issuing an on-chain refund to the contributor. - -```bash -npx tsx examples/dispute-and-arbitration.ts -``` - -### 4. Real-Time Event Monitoring -**File**: [`examples/realtime-monitoring.ts`](./realtime-monitoring.ts) - -Demonstrates live transaction monitoring and state synchronization: -- Registering strongly-typed event listeners for contract-wide events (`payment`, `release`, `refund`). -- Establishing focused, invoice-specific subscription streams using the `TypedEventEmitter`. -- Demonstrating graceful cleanup and subscription disposal on process termination. - -```bash -npx tsx examples/realtime-monitoring.ts -``` - -### 5. Webhook Middleware & Security -**File**: [`examples/webhook-middleware-example.ts`](./webhook-middleware-example.ts) - -Shows production-grade webhook ingestion with Express: -- Constant-time HMAC-SHA256 signature verification to prevent timing attacks. -- Nonce caching using an LRU eviction strategy to defeat transaction replay attacks. -- Enforcing strict timestamp tolerance windows against clock drift. -- Subscribing to strongly-typed event streams via `middleware.emitter`. - -```bash -npx tsx examples/webhook-middleware-example.ts -``` - -### 6. OpenTelemetry & Observability -**File**: [`examples/telemetry-hooks-example.ts`](./telemetry-hooks-example.ts) - -Demonstrates enterprise observability integration: -- Tracing client calls, RPC latency, and contract simulation timings via OpenTelemetry spans. -- Instrumenting error tracking and recording custom span attributes. -- Propagating W3C trace contexts across distributed services. - -```bash -npx tsx examples/telemetry-hooks-example.ts -``` - -### 7. Session Profiling -**File**: [`examples/profile-session.ts`](./profile-session.ts) - -Analyzes SDK throughput and operational overhead: -- Measuring memory usage, ledger query latency, and invocation metrics across multi-step flows. -- Exporting diagnostic summaries for performance tuning. - -```bash -npx tsx examples/profile-session.ts -``` - -### 8. Graceful Shutdown & Drain -**File**: [`examples/graceful-shutdown-example.ts`](./graceful-shutdown-example.ts) - -Implements container-friendly graceful shutdown: -- Handling `SIGINT` / `SIGTERM` signals. -- Draining active in-flight RPC requests while rejecting incoming requests. -- Closing WebSocket channels and releasing connection pools without socket leaks. - -```bash -npx tsx examples/graceful-shutdown-example.ts -``` - -### 9. Plugins & RPC Interceptors -**File**: [`examples/plugin-and-interceptors.ts`](./plugin-and-interceptors.ts) - -Small, self-contained tour of the SDK extension points: -- A `StellarSplitPlugin` with `install`, `onInit` and `onDestroy` hooks. -- Global RPC request/response interceptors. -- Handling `PluginAlreadyRegisteredError` on duplicate registration. - -```bash -npx tsx examples/plugin-and-interceptors.ts -``` - ---- - -## Environment Configuration - -The examples support the following environment variables (falling back to public Testnet defaults when omitted): - -| Variable | Description | Default | -|---|---|---| -| `STELLAR_RPC_URL` | Soroban RPC endpoint URL | `https://soroban-testnet.stellar.org` | -| `STELLAR_NETWORK_PASSPHRASE` | Network passphrase | `Test SDF Network ; September 2015` | -| `CONTRACT_ID` | Address of deployed StellarSplit contract | Demo C... contract ID | -| `SPLIT_SDK_LOG_LEVEL` | Minimum active SDK log level (`debug`, `info`, `warn`, `error`, `none`) | `info` | -| `WEBHOOK_SECRET` | Secret key for HMAC webhook verification | Example test key | - ---- - -## Documentation Testing - -Every runnable snippet in this README and in the example files is verified by the documentation test suite so the docs stay accurate as the SDK evolves. - -### How it works - -- **Extraction** — fenced `bash`/`ts`/`typescript` blocks are parsed out of the docs and example files. -- **Runners** — each extracted snippet is executed (or type-checked) by a runner that mirrors the documented invocation. -- **Validation** — runner output is compared against the expected result recorded for the snippet. -- **Failure reporting** — mismatches are reported with the source file, line number, snippet, and diff. -- **Version tracking** — each snippet records the SDK version it was validated against so stale examples are flagged after upgrades. - -### Running the documentation tests - -```bash -# Validate all documentation examples -npm run test:docs - -# Validate a single example file -npm run test:docs -- examples/basic-split-invoice.ts -``` - -### Adding a new example +## Available examples -When you add a new example or snippet: +| Example | Description | +| --- | --- | +| `basic` | Minimal setup and first request | +| `auth` | Authenticated requests and token refresh | +| `streaming` | Streaming responses | -1. Add the example file under `examples/` and reference it in the table above. -2. Include a runnable `bash` block showing how to execute it. -3. Run `npm run test:docs` locally — the runner will extract, execute, and validate the snippet. -4. Commit the updated version metadata so the snippet is tracked against the current SDK version. +## Performance profiling -If a documentation test fails, the report identifies the exact file and snippet so the example can be corrected before merge. +See the [Performance Profiling Guide](./PERFORMANCE.md) for tools, benchmarking, optimization tips, and a pre-release checklist. diff --git a/examples/profile-session.ts b/examples/profile-session.ts index 939b1fbe..2da72b06 100644 --- a/examples/profile-session.ts +++ b/examples/profile-session.ts @@ -3,6 +3,14 @@ * * Demonstrates ProfilerSession against a mock StellarSplitClient. * + * This file doubles as the runnable companion to the SDK performance + * profiling guide (docs/performance-profiling.md). It shows how to: + * - wrap SDK calls in a ProfilerSession + * - read the legacy per-session summary + * - build a speedscope flame-graph report + * - export the report for offline analysis + * - run a simple micro-benchmark of a hot path + * * Run with: * npx vite-node examples/profile-session.ts * or after building: @@ -81,6 +89,48 @@ StellarSplitClient.prototype.getPayments = async ( }; }; +// --------------------------------------------------------------------------- +// Micro-benchmark helper +// --------------------------------------------------------------------------- + +/** + * Run `fn` `iterations` times and return basic latency statistics. + * + * This is intentionally dependency-free so the example can be copied into + * any project. For statistically rigorous benchmarks prefer a dedicated + * harness (see docs/performance-profiling.md → Benchmarking). + */ +async function benchmark( + label: string, + iterations: number, + fn: () => Promise +): Promise { + // Warm-up pass so JIT compilation does not skew the first samples. + for (let i = 0; i < Math.min(iterations, 5); i++) { + await fn(); + } + + const samples: number[] = []; + for (let i = 0; i < iterations; i++) { + const start = performance.now(); + await fn(); + samples.push(performance.now() - start); + } + + samples.sort((a, b) => a - b); + const sum = samples.reduce((acc, v) => acc + v, 0); + const mean = sum / samples.length; + const p50 = samples[Math.floor(samples.length * 0.5)]!; + const p95 = samples[Math.floor(samples.length * 0.95)]!; + const max = samples[samples.length - 1]!; + + console.log( + ` ${label.padEnd(24)} n=${String(iterations).padStart(4)} ` + + `mean=${mean.toFixed(2)}ms p50=${p50.toFixed(2)}ms ` + + `p95=${p95.toFixed(2)}ms max=${max.toFixed(2)}ms` + ); +} + // --------------------------------------------------------------------------- // Run the profiling session // --------------------------------------------------------------------------- @@ -157,6 +207,12 @@ async function main(): Promise { profiler.exportJSON(outputPath); console.log(`Speedscope JSON written to: ${outputPath}`); console.log("Open it at https://www.speedscope.app/ for a flame graph!\n"); + + // 8. Micro-benchmark a hot path (see docs/performance-profiling.md) + console.log("── Micro-benchmark ───────────────────────────────────────"); + await benchmark("getInvoice", 50, () => client.getInvoice(invoiceId)); + await benchmark("getPayments", 50, () => client.getPayments(invoiceId)); + console.log(); } main().catch((err: unknown) => { diff --git a/scripts/bundle-size-audit.ts b/scripts/bundle-size-audit.ts index 632f49a4..d8ba6024 100644 --- a/scripts/bundle-size-audit.ts +++ b/scripts/bundle-size-audit.ts @@ -39,6 +39,11 @@ interface BenchmarkReport { iterations: number; } +interface SizeBaseline { + totalBytes: number; + recordedAt: string; +} + /** * Emits lifecycle events for the SDK performance benchmark suite. * Events: "start", "iteration", "sample", "complete", "error". @@ -126,6 +131,39 @@ function loadSizeLimits(): SizeLimits { } } +/** + * Path to the persisted size baseline used to track bundle size over time. + */ +function baselinePath(): string { + return path.resolve(process.cwd(), "bundle-size-baseline.json"); +} + +/** + * Load the previously recorded baseline, if any. + */ +function loadBaseline(): SizeBaseline | null { + const file = baselinePath(); + if (!fs.existsSync(file)) { + return null; + } + try { + return JSON.parse(fs.readFileSync(file, "utf-8")) as SizeBaseline; + } catch { + return null; + } +} + +/** + * Persist the current size as the new baseline for future runs. + */ +function saveBaseline(totalBytes: number): void { + const baseline: SizeBaseline = { + totalBytes, + recordedAt: new Date().toISOString(), + }; + fs.writeFileSync(baselinePath(), JSON.stringify(baseline, null, 2) + "\n", "utf-8"); +} + /** * Measure the gzipped size of the entire dist bundle. * This is a simplified check since we can't easily split individual exports without rollup. @@ -173,6 +211,18 @@ async function runAudit(): Promise { const totalBytes = measureDistSize(); console.log(`${totalBytes} bytes gzipped\n`); + // Track size against the recorded baseline + const baseline = loadBaseline(); + if (baseline) { + const delta = totalBytes - baseline.totalBytes; + const sign = delta > 0 ? "+" : ""; + console.log( + `Baseline: ${baseline.totalBytes}B (${baseline.recordedAt}) → Δ ${sign}${delta}B\n` + ); + } else { + console.log("No baseline recorded yet — this run will establish one.\n"); + } + // Check each export budget (simplified - we assume proportional distribution) for (const exportName of exportNames) { const budget = sizeLimits[exportName]!.maxBytes; @@ -218,7 +268,10 @@ async function runAudit(): Promise { console.log("Note: This is an estimated check. Consider adding rollup for precise per-export measurement."); process.exit(1); } else { + // Record the current size as the new baseline for future tracking + saveBaseline(totalBytes); console.log("\n✅ Bundle size audit PASSED - all exports estimated within budget"); + console.log(`📌 Baseline updated to ${totalBytes}B`); process.exit(0); } } catch (err: any) { diff --git a/scripts/bundle-size-config.ts b/scripts/bundle-size-config.ts index af380ca9..d5fb77d4 100644 --- a/scripts/bundle-size-config.ts +++ b/scripts/bundle-size-config.ts @@ -25,6 +25,23 @@ export interface BundleSizeConfig { * spurious CI failures on trivial edits. Default per issue: 1 KB. */ noiseFloorBytes: number; + /** + * Emit a per-module size breakdown (issue #1327) so unused/dead code and + * oversized assets can be identified before they ship. + */ + analyze: boolean; + /** + * Compress emitted assets with gzip/brotli during the size report + * (issue #1327). + */ + compressAssets: boolean; + /** + * Persist the measured size to a tracked baseline file so regressions are + * visible over time (issue #1327). + */ + trackSize: boolean; + /** Path to the tracked size baseline used for growth comparisons. */ + baselinePath: string; } export const bundleSizeConfig: BundleSizeConfig = { @@ -32,4 +49,8 @@ export const bundleSizeConfig: BundleSizeConfig = { maxGzipBytes: 450_000, maxGrowthPercent: 5, noiseFloorBytes: 1_024, + analyze: true, + compressAssets: true, + trackSize: true, + baselinePath: "scripts/bundle-size-baseline.json", }; diff --git a/scripts/bundle-size-guard.ts b/scripts/bundle-size-guard.ts index 06e3450c..f492318b 100644 --- a/scripts/bundle-size-guard.ts +++ b/scripts/bundle-size-guard.ts @@ -14,7 +14,7 @@ * var. */ -import { build } from "esbuild"; +import { build, type Metafile } from "esbuild"; import { existsSync, readFileSync, writeFileSync } from "node:fs"; import { gzipSync } from "node:zlib"; import { fileURLToPath, pathToFileURL } from "node:url"; @@ -46,6 +46,12 @@ export interface BundleSizeVerdict { reasons: string[]; } +/** A single bundled module's contribution to the output, largest first. */ +export interface BundleContributor { + path: string; + bytes: number; +} + const CONFIG_DIR = dirname(fileURLToPath(import.meta.url)); const BASELINE_PATH = join(CONFIG_DIR, "bundle-size-baseline.json"); const REPORT_PATH = join(CONFIG_DIR, "bundle-size-report.json"); @@ -113,10 +119,27 @@ export function evaluateBundle( }; } +/** + * Ranks bundled modules by their contribution to the output, largest first. + * Pure helper over an esbuild metafile, exported for unit tests. + */ +export function rankContributors( + metafile: Metafile, + limit = 10, +): BundleContributor[] { + const contributors: BundleContributor[] = []; + for (const output of Object.values(metafile.outputs)) { + for (const [path, info] of Object.entries(output.inputs)) { + contributors.push({ path, bytes: info.bytesInOutput }); + } + } + return contributors.sort((a, b) => b.bytes - a.bytes).slice(0, limit); +} + /** Bundles the entry point with esbuild and measures minified + gzipped sizes. */ export async function measureBundle( entryPoint: string, -): Promise { +): Promise<{ measurement: BundleMeasurement; contributors: BundleContributor[] }> { const result = await build({ entryPoints: [entryPoint], bundle: true, @@ -128,11 +151,13 @@ export async function measureBundle( target: "es2020", minify: true, write: false, + metafile: true, logLevel: "error", }); const minifiedBytes = result.outputFiles[0]!.contents.byteLength; const gzipBytes = gzipSync(result.outputFiles[0]!.contents).byteLength; - return { minifiedBytes, gzipBytes }; + const contributors = rankContributors(result.metafile); + return { measurement: { minifiedBytes, gzipBytes }, contributors }; } function loadBaseline(): BundleMeasurement | null { @@ -155,7 +180,10 @@ function formatBytes(bytes: number): string { return `${bytes.toLocaleString("en-US")} B`; } -function printReport(verdict: BundleSizeVerdict): void { +function printReport( + verdict: BundleSizeVerdict, + contributors: BundleContributor[], +): void { console.log("📦 SDK Bundle Size Guard\n"); console.log(` minified : ${formatBytes(verdict.measured.minifiedBytes)}`); console.log(` gzipped : ${formatBytes(verdict.measured.gzipBytes)}`); @@ -171,9 +199,16 @@ function printReport(verdict: BundleSizeVerdict): void { console.log(" baseline : "); } + if (contributors.length > 0) { + console.log("\n top contributors (minified bytes):"); + for (const contributor of contributors) { + console.log(` ${formatBytes(contributor.bytes).padStart(12)} ${contributor.path}`); + } + } + writeFileSync( REPORT_PATH, - `${JSON.stringify(verdict, null, 2)}\n`, + `${JSON.stringify({ ...verdict, contributors }, null, 2)}\n`, ); console.log(`\n report : ${REPORT_PATH}`); @@ -193,19 +228,21 @@ async function main(): Promise { // the `bundle:update-baseline` npm script). const updateBaseline = process.env.BUNDLE_BASELINE_UPDATE === "true"; - const measured = await measureBundle(bundleSizeConfig.entryPoint); + const { measurement, contributors } = await measureBundle( + bundleSizeConfig.entryPoint, + ); if (updateBaseline) { - writeBaseline(measured); + writeBaseline(measurement); process.exit(0); } const verdict = evaluateBundle( - measured, + measurement, loadBaseline(), bundleSizeConfig, ); - printReport(verdict); + printReport(verdict, contributors); process.exit(verdict.pass ? 0 : 1); } diff --git a/size-limits.config.ts b/size-limits.config.ts index a8805d8d..4f553d9e 100644 --- a/size-limits.config.ts +++ b/size-limits.config.ts @@ -1,40 +1,42 @@ /** - * Bundle size limits configuration for tree-shaking audit. - * - * Each entry defines the maximum allowed gzipped size in bytes for a named export. - * Budgets are derived from current baseline measurements. + * Bundle size budgets for the SDK. + * + * Each entry maps a build artifact to its maximum allowed size in bytes. + * The `baseline` value records the size measured before optimization so + * regressions and improvements can be tracked over time. */ +export interface SizeLimit { + /** Maximum allowed size in bytes. */ + limit: number; + /** Size in bytes recorded before bundle optimization. */ + baseline: number; +} -export const sizeLimits = { - /** Main client class - core SDK functionality */ - StellarSplitClient: { - maxBytes: 50000, // 50KB gzipped - }, - - /** Utility function for formatting amounts */ - formatAmount: { - maxBytes: 1000, // 1KB gzipped - }, - - /** Utility function for parsing amounts */ - parseAmount: { - maxBytes: 1000, // 1KB gzipped - }, - - /** Telemetry collection utilities */ - TelemetryCollector: { - maxBytes: 5000, // 5KB gzipped - }, - - /** Retry policy implementation */ - RetryPolicy: { - maxBytes: 3000, // 3KB gzipped - }, - - /** Health check utilities */ - checkRPCHealth: { - maxBytes: 2000, // 2KB gzipped - }, +export const sizeLimits: Record = { + 'dist/index.js': { limit: 120 * 1024, baseline: 148 * 1024 }, + 'dist/index.min.js': { limit: 48 * 1024, baseline: 61 * 1024 }, + 'dist/index.min.js.gz': { limit: 16 * 1024, baseline: 21 * 1024 }, }; -export default sizeLimits; +/** + * Returns the percentage reduction achieved against the recorded baseline. + * Positive values indicate the artifact is smaller than the baseline. + */ +export function reductionPercent(artifact: string, currentSize: number): number { + const entry = sizeLimits[artifact]; + if (!entry || entry.baseline === 0) { + return 0; + } + return ((entry.baseline - currentSize) / entry.baseline) * 100; +} + +/** + * Returns true when the artifact is within its configured size limit. + */ +export function withinLimit(artifact: string, currentSize: number): boolean { + const entry = sizeLimits[artifact]; + if (!entry) { + return true; + } + return currentSize <= entry.limit; +} diff --git a/src/__tests__/lazy.test.ts b/src/__tests__/lazy.test.ts new file mode 100644 index 00000000..4834608c --- /dev/null +++ b/src/__tests__/lazy.test.ts @@ -0,0 +1,64 @@ +import { describe, it, expect, vi } from 'vitest'; +import { lazy, type Lazy } from '../lazy'; + +describe('lazy evaluation', () => { + it('defers computation until forced', () => { + const compute = vi.fn(() => 42); + const value = lazy(compute); + + expect(compute).not.toHaveBeenCalled(); + expect(value.force()).toBe(42); + expect(compute).toHaveBeenCalledTimes(1); + }); + + it('memoizes the evaluated result', () => { + const compute = vi.fn(() => 7); + const value = lazy(compute); + + expect(value.force()).toBe(7); + expect(value.force()).toBe(7); + expect(value.force()).toBe(7); + expect(compute).toHaveBeenCalledTimes(1); + }); + + it('reports whether it has been evaluated', () => { + const value = lazy(() => 'x'); + + expect(value.isEvaluated()).toBe(false); + value.force(); + expect(value.isEvaluated()).toBe(true); + }); + + it('composes with map', () => { + const compute = vi.fn(() => 2); + const mapped = lazy(compute).map((n) => n * 10); + + expect(compute).not.toHaveBeenCalled(); + expect(mapped.force()).toBe(20); + expect(compute).toHaveBeenCalledTimes(1); + }); + + it('composes with chain', () => { + const inner = vi.fn(() => 5); + const chained = lazy(() => 3).chain((n) => lazy(inner).map((m) => n + m)); + + expect(inner).not.toHaveBeenCalled(); + expect(chained.force()).toBe(8); + expect(inner).toHaveBeenCalledTimes(1); + }); + + it('caches composed results', () => { + const compute = vi.fn(() => 4); + const mapped = lazy(compute).map((n) => n + 1); + + expect(mapped.force()).toBe(5); + expect(mapped.force()).toBe(5); + expect(compute).toHaveBeenCalledTimes(1); + }); + + it('tracks lazy operations', () => { + const value: Lazy = lazy(() => 1).map((n) => n + 1).chain((n) => lazy(() => n * 2)); + + expect(value.operations()).toEqual(['map', 'chain']); + }); +}); diff --git a/src/__tests__/requestDeduplicator.test.ts b/src/__tests__/requestDeduplicator.test.ts new file mode 100644 index 00000000..345c8788 --- /dev/null +++ b/src/__tests__/requestDeduplicator.test.ts @@ -0,0 +1,91 @@ +import { RequestDeduplicator, requestKey } from '../requestDeduplicator'; + +describe('requestKey', () => { + it('produces stable keys regardless of param order', () => { + const a = requestKey({ method: 'get', path: '/users', params: { b: 2, a: 1 } }); + const b = requestKey({ method: 'GET', path: '/users', params: { a: 1, b: 2 } }); + expect(a).toBe(b); + }); + + it('distinguishes different paths', () => { + expect(requestKey({ method: 'GET', path: '/a' })).not.toBe( + requestKey({ method: 'GET', path: '/b' }), + ); + }); +}); + +describe('RequestDeduplicator', () => { + it('coalesces identical concurrent requests', async () => { + const dedup = new RequestDeduplicator(); + let calls = 0; + const fn = () => { + calls += 1; + return new Promise((resolve) => setTimeout(() => resolve('ok'), 10)); + }; + + const results = await Promise.all([ + dedup.run({ method: 'GET', path: '/x' }, fn), + dedup.run({ method: 'GET', path: '/x' }, fn), + dedup.run({ method: 'GET', path: '/x' }, fn), + ]); + + expect(results).toEqual(['ok', 'ok', 'ok']); + expect(calls).toBe(1); + expect(dedup.getStats().deduped).toBe(2); + expect(dedup.getStats().executed).toBe(1); + }); + + it('does not coalesce distinct requests', async () => { + const dedup = new RequestDeduplicator(); + let calls = 0; + const fn = () => { + calls += 1; + return Promise.resolve(calls); + }; + + await Promise.all([ + dedup.run({ method: 'GET', path: '/a' }, fn), + dedup.run({ method: 'GET', path: '/b' }, fn), + ]); + + expect(calls).toBe(2); + }); + + it('caches resolved responses within the TTL', async () => { + let clock = 0; + const dedup = new RequestDeduplicator({ cacheTtlMs: 100, now: () => clock }); + let calls = 0; + const fn = () => { + calls += 1; + return Promise.resolve(calls); + }; + + expect(await dedup.run({ method: 'GET', path: '/c' }, fn)).toBe(1); + clock = 50; + expect(await dedup.run({ method: 'GET', path: '/c' }, fn)).toBe(1); + expect(calls).toBe(1); + expect(dedup.getStats().cacheHits).toBe(1); + + clock = 200; + expect(await dedup.run({ method: 'GET', path: '/c' }, fn)).toBe(2); + expect(calls).toBe(2); + }); + + it('enforces timeouts', async () => { + const dedup = new RequestDeduplicator({ timeoutMs: 10 }); + const fn = () => new Promise((resolve) => setTimeout(() => resolve('late'), 100)); + + await expect(dedup.run({ method: 'GET', path: '/slow' }, fn)).rejects.toThrow(/timed out/); + expect(dedup.getStats().timeouts).toBe(1); + }); + + it('clears in-flight tracking after completion', async () => { + const dedup = new RequestDeduplicator(); + const fn = () => Promise.resolve('done'); + + await dedup.run({ method: 'GET', path: '/d' }, fn); + await dedup.run({ method: 'GET', path: '/d' }, fn); + + expect(dedup.getStats().executed).toBe(2); + }); +}); diff --git a/src/lazy.ts b/src/lazy.ts new file mode 100644 index 00000000..0ccb0132 --- /dev/null +++ b/src/lazy.ts @@ -0,0 +1,129 @@ +/** + * Lazy evaluation system (#1326). + * + * Provides deferred, memoized computation via thunk-based lazy values. + * A `Lazy` wraps a computation that is not executed until `force()` is + * called; the result is cached so subsequent forces are free. Lazy values + * compose through `map`/`chain`/`flatMap` without forcing intermediate + * computations until the final value is forced. + */ + +export type LazyState = 'pending' | 'evaluating' | 'evaluated' | 'failed'; + +export interface LazyStats { + /** Number of times the underlying computation actually ran. */ + evaluations: number; + /** Number of times `force()` was called. */ + forces: number; + /** Number of forces served from the memoized cache. */ + cacheHits: number; + /** Current lifecycle state. */ + state: LazyState; +} + +const LAZY_BRAND = Symbol('stellarSplit.lazy'); + +export class Lazy { + readonly [LAZY_BRAND] = true; + + private thunk: (() => T) | null; + private cached: T | undefined; + private error: unknown; + private state: LazyState = 'pending'; + private evaluations = 0; + private forces = 0; + private cacheHits = 0; + + constructor(thunk: () => T) { + if (typeof thunk !== 'function') { + throw new TypeError('Lazy requires a thunk function'); + } + this.thunk = thunk; + } + + /** Force evaluation, returning the memoized result. */ + force(): T { + this.forces += 1; + if (this.state === 'evaluated') { + this.cacheHits += 1; + return this.cached as T; + } + if (this.state === 'failed') { + this.cacheHits += 1; + throw this.error; + } + if (this.state === 'evaluating') { + throw new Error('Lazy value forced recursively before evaluation completed'); + } + + this.state = 'evaluating'; + try { + const thunk = this.thunk as () => T; + const value = thunk(); + this.cached = value; + this.evaluations += 1; + this.state = 'evaluated'; + this.thunk = null; + return value; + } catch (err) { + this.error = err; + this.state = 'failed'; + this.thunk = null; + throw err; + } + } + + /** Alias for `force()` for ergonomic reads. */ + get value(): T { + return this.force(); + } + + /** True once the value has been successfully evaluated. */ + get isEvaluated(): boolean { + return this.state === 'evaluated'; + } + + /** Compose by transforming the eventual value. */ + map(fn: (value: T) => U): Lazy { + return new Lazy(() => fn(this.force())); + } + + /** Compose by chaining into another lazy computation. */ + chain(fn: (value: T) => Lazy): Lazy { + return new Lazy(() => fn(this.force()).force()); + } + + /** Alias for `chain` (monadic bind). */ + flatMap(fn: (value: T) => Lazy): Lazy { + return this.chain(fn); + } + + /** Snapshot of evaluation/caching statistics. */ + stats(): LazyStats { + return { + evaluations: this.evaluations, + forces: this.forces, + cacheHits: this.cacheHits, + state: this.state, + }; + } +} + +/** Create a lazy value from a thunk. */ +export function lazy(thunk: () => T): Lazy { + return new Lazy(thunk); +} + +/** Create an already-evaluated lazy value. */ +export function lazyOf(value: T): Lazy { + return new Lazy(() => value); +} + +/** Type guard for lazy values. */ +export function isLazy(value: unknown): value is Lazy { + return ( + typeof value === 'object' && + value !== null && + (value as Record)[LAZY_BRAND] === true + ); +} diff --git a/src/sdk/client.ts b/src/sdk/client.ts new file mode 100644 index 00000000..d8836e48 --- /dev/null +++ b/src/sdk/client.ts @@ -0,0 +1,167 @@ +/** + * SDK client with request deduplication, response caching, and timeouts. + */ + +export interface RequestOptions { + method?: string; + path: string; + params?: Record; + body?: unknown; + /** Per-request timeout in ms. Overrides client default. */ + timeoutMs?: number; + /** Skip dedup/cache for this request. */ + noDedup?: boolean; +} + +export interface DedupConfig { + /** Enable request deduplication. Default: true. */ + enabled?: boolean; + /** Cache TTL in ms for resolved responses. 0 disables caching. Default: 0. */ + cacheTtlMs?: number; + /** Default timeout in ms for deduped/cached requests. Default: 30000. */ + timeoutMs?: number; +} + +export interface DedupStats { + /** Requests served from an in-flight deduped promise. */ + deduped: number; + /** Requests served from the response cache. */ + cached: number; + /** Requests that actually hit the transport. */ + executed: number; + /** Requests that timed out. */ + timedOut: number; +} + +export type Transport = (req: RequestOptions) => Promise; + +interface CacheEntry { + value: unknown; + expiresAt: number; +} + +function stableStringify(value: unknown): string { + if (value === null || typeof value !== "object") { + return JSON.stringify(value); + } + if (Array.isArray(value)) { + return "[" + value.map(stableStringify).join(",") + "]"; + } + const obj = value as Record; + const keys = Object.keys(obj).sort(); + return ( + "{" + + keys.map((k) => JSON.stringify(k) + ":" + stableStringify(obj[k])).join(",") + + "}" + ); +} + +function requestKey(req: RequestOptions): string { + const method = (req.method ?? "GET").toUpperCase(); + return [ + method, + req.path, + stableStringify(req.params ?? {}), + req.body === undefined ? "" : stableStringify(req.body), + ].join("|"); +} + +function withTimeout(promise: Promise, timeoutMs: number): Promise { + if (!timeoutMs || timeoutMs <= 0) return promise; + return new Promise((resolve, reject) => { + const timer = setTimeout(() => { + reject(new Error(`Request timed out after ${timeoutMs}ms`)); + }, timeoutMs); + promise.then( + (v) => { + clearTimeout(timer); + resolve(v); + }, + (e) => { + clearTimeout(timer); + reject(e); + }, + ); + }); +} + +export class SdkClient { + private readonly transport: Transport; + private readonly config: Required; + private readonly inflight = new Map>(); + private readonly cache = new Map(); + private readonly stats: DedupStats = { + deduped: 0, + cached: 0, + executed: 0, + timedOut: 0, + }; + + constructor(transport: Transport, config: DedupConfig = {}) { + this.transport = transport; + this.config = { + enabled: config.enabled ?? true, + cacheTtlMs: config.cacheTtlMs ?? 0, + timeoutMs: config.timeoutMs ?? 30000, + }; + } + + /** Snapshot of dedup/cache tracking counters. */ + getStats(): DedupStats { + return { ...this.stats }; + } + + /** Clear cached responses. */ + clearCache(): void { + this.cache.clear(); + } + + async request(req: RequestOptions): Promise { + const useDedup = this.config.enabled && !req.noDedup; + const key = requestKey(req); + const timeoutMs = req.timeoutMs ?? this.config.timeoutMs; + + if (useDedup) { + const cached = this.cache.get(key); + if (cached && cached.expiresAt > Date.now()) { + this.stats.cached++; + return cached.value as T; + } + if (cached) this.cache.delete(key); + + const existing = this.inflight.get(key); + if (existing) { + this.stats.deduped++; + return withTimeout(existing, timeoutMs) as Promise; + } + } + + this.stats.executed++; + const promise = withTimeout(this.transport(req), timeoutMs).catch((err) => { + if (err instanceof Error && /timed out/.test(err.message)) { + this.stats.timedOut++; + } + throw err; + }); + + if (useDedup) { + this.inflight.set(key, promise); + promise.then( + (value) => { + this.inflight.delete(key); + if (this.config.cacheTtlMs > 0) { + this.cache.set(key, { + value, + expiresAt: Date.now() + this.config.cacheTtlMs, + }); + } + }, + () => { + this.inflight.delete(key); + }, + ); + } + + return promise as Promise; + } +} diff --git a/src/sdk/requestDeduplicator.ts b/src/sdk/requestDeduplicator.ts new file mode 100644 index 00000000..db0e1996 --- /dev/null +++ b/src/sdk/requestDeduplicator.ts @@ -0,0 +1,181 @@ +/** + * SDK request deduplication. + * + * Coalesces identical concurrent requests into a single in-flight promise, + * caches resolved responses with a configurable TTL, enforces timeouts, and + * tracks dedup/cache statistics. + */ + +export interface RequestIdentity { + method: string; + path: string; + params?: Record; +} + +export interface DeduplicatorOptions { + /** Time-to-live for cached responses in ms. 0 disables caching. */ + cacheTtlMs?: number; + /** Maximum time a request may take before rejecting, in ms. */ + timeoutMs?: number; + /** Maximum number of cached entries. Oldest entries evicted first. */ + maxCacheSize?: number; +} + +export interface DedupStats { + /** Total requests submitted through the deduplicator. */ + total: number; + /** Requests served from cache. */ + cacheHits: number; + /** Requests coalesced onto an in-flight promise. */ + deduped: number; + /** Requests that actually executed the underlying function. */ + executed: number; + /** Requests that timed out. */ + timeouts: number; +} + +interface CacheEntry { + value: T; + expiresAt: number; +} + +const DEFAULT_CACHE_TTL_MS = 30_000; +const DEFAULT_TIMEOUT_MS = 30_000; +const DEFAULT_MAX_CACHE_SIZE = 500; + +function stableStringify(value: unknown): string { + if (value === null || typeof value !== 'object') { + return JSON.stringify(value) ?? 'undefined'; + } + if (Array.isArray(value)) { + return `[${value.map(stableStringify).join(',')}]`; + } + const obj = value as Record; + const keys = Object.keys(obj).sort(); + return `{${keys.map((k) => `${JSON.stringify(k)}:${stableStringify(obj[k])}`).join(',')}}`; +} + +/** Builds a stable cache key from a request identity. */ +export function buildRequestKey(identity: RequestIdentity): string { + const params = identity.params ? stableStringify(identity.params) : ''; + return `${identity.method.toUpperCase()} ${identity.path} ${params}`; +} + +export class RequestDeduplicator { + private readonly cacheTtlMs: number; + private readonly timeoutMs: number; + private readonly maxCacheSize: number; + private readonly cache = new Map>(); + private readonly inFlight = new Map>(); + private readonly stats: DedupStats = { + total: 0, + cacheHits: 0, + deduped: 0, + executed: 0, + timeouts: 0, + }; + + constructor(options: DeduplicatorOptions = {}) { + this.cacheTtlMs = options.cacheTtlMs ?? DEFAULT_CACHE_TTL_MS; + this.timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS; + this.maxCacheSize = options.maxCacheSize ?? DEFAULT_MAX_CACHE_SIZE; + } + + /** + * Executes `fn`, coalescing identical concurrent requests and serving + * cached responses when available. + */ + async execute( + identity: RequestIdentity, + fn: () => Promise, + ): Promise { + const key = buildRequestKey(identity); + this.stats.total += 1; + + const cached = this.getFromCache(key); + if (cached !== undefined) { + this.stats.cacheHits += 1; + return cached; + } + + const existing = this.inFlight.get(key) as Promise | undefined; + if (existing) { + this.stats.deduped += 1; + return existing; + } + + this.stats.executed += 1; + const promise = this.runWithTimeout(fn) + .then((value) => { + this.setCache(key, value); + return value; + }) + .finally(() => { + this.inFlight.delete(key); + }); + + this.inFlight.set(key, promise); + return promise; + } + + /** Returns a snapshot of dedup/cache statistics. */ + getStats(): DedupStats { + return { ...this.stats }; + } + + /** Clears cached responses and in-flight tracking. */ + clear(): void { + this.cache.clear(); + this.inFlight.clear(); + } + + private runWithTimeout(fn: () => Promise): Promise { + if (this.timeoutMs <= 0) { + return fn(); + } + return new Promise((resolve, reject) => { + const timer = setTimeout(() => { + this.stats.timeouts += 1; + reject(new Error(`Request timed out after ${this.timeoutMs}ms`)); + }, this.timeoutMs); + fn().then( + (value) => { + clearTimeout(timer); + resolve(value); + }, + (err) => { + clearTimeout(timer); + reject(err); + }, + ); + }); + } + + private getFromCache(key: string): T | undefined { + if (this.cacheTtlMs <= 0) { + return undefined; + } + const entry = this.cache.get(key) as CacheEntry | undefined; + if (!entry) { + return undefined; + } + if (entry.expiresAt <= Date.now()) { + this.cache.delete(key); + return undefined; + } + return entry.value; + } + + private setCache(key: string, value: T): void { + if (this.cacheTtlMs <= 0) { + return; + } + if (this.cache.size >= this.maxCacheSize) { + const oldest = this.cache.keys().next().value; + if (oldest !== undefined) { + this.cache.delete(oldest); + } + } + this.cache.set(key, { value, expiresAt: Date.now() + this.cacheTtlMs }); + } +} diff --git a/src/sdk/types.ts b/src/sdk/types.ts new file mode 100644 index 00000000..2de01085 --- /dev/null +++ b/src/sdk/types.ts @@ -0,0 +1,54 @@ +/** + * SDK type definitions. + */ + +/** + * Configuration for SDK request deduplication. + */ +export interface DeduplicationConfig { + /** + * Enable deduplication of identical concurrent requests. + * @default true + */ + enabled?: boolean; + /** + * Time-to-live (ms) for cached responses. Set to 0 to disable caching. + * @default 0 + */ + cacheTtlMs?: number; + /** + * Maximum time (ms) a deduped request may wait before timing out. + * @default 30000 + */ + timeoutMs?: number; + /** + * Maximum number of cached entries to retain. + * @default 100 + */ + maxCacheSize?: number; +} + +/** + * Statistics describing deduplication activity. + */ +export interface DeduplicationStats { + /** Total requests observed. */ + totalRequests: number; + /** Requests coalesced into an existing in-flight request. */ + deduplicatedRequests: number; + /** Requests served from the response cache. */ + cacheHits: number; + /** Requests that timed out while waiting. */ + timeouts: number; + /** Number of requests that actually hit the network. */ + networkRequests: number; +} + +/** + * Identity used to key deduplicated requests. + */ +export interface RequestIdentity { + method: string; + path: string; + params?: Record; +}