Skip to content

Commit 11ac2f6

Browse files
docs: add observability, security, performance, and testing guides (#680)
1 parent 89a7d11 commit 11ac2f6

6 files changed

Lines changed: 271 additions & 0 deletions

File tree

Iss

Whitespace-only changes.

Issues.md

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
Completed documentation work for the current backlog items.
2+
3+
- Added testing and QA documentation in `docs/testing/index.md`
4+
- Added performance tuning and optimization guidance in `docs/performance/index.md`
5+
- Added security hardening and best practices documentation in `docs/security/index.md`
6+
- Added observability and monitoring guidance in `docs/observability/index.md`
7+
8+
These guides implement the requested scope and deliverables for the four open backlog issues.

docs/observability/index.md

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
# Monitoring, Logging & Observability Guide
2+
3+
This guide explains what to monitor, how to collect logs and metrics, and how to build useful dashboards and alerts for SoroScan.
4+
5+
## Observability Strategy
6+
7+
- Observe three pillars: metrics, logs, and traces.
8+
- Use RED (Rate, Errors, Duration) and USE (Utilization, Saturation, Errors) methods.
9+
- Define service-level objectives (SLOs) for availability and latency.
10+
11+
## Metrics & Prometheus
12+
13+
- Configure application metrics and export them to Prometheus.
14+
- Track key metrics such as request rate, error rate, latency, queue depth, and cache hit ratio.
15+
- Watch cardinality to prevent metric explosion.
16+
- Use PromQL to analyze service performance and build alerts.
17+
18+
## Logging Strategy
19+
20+
- Use structured logs for consistent fields and easier parsing.
21+
- Apply clear log levels: DEBUG, INFO, WARNING, ERROR, CRITICAL.
22+
- Aggregate logs in a central platform such as Loki, Elasticsearch, or hosted logging.
23+
- Define retention policies appropriate to support troubleshooting and compliance.
24+
25+
## Distributed Tracing
26+
27+
- Instrument services with OpenTelemetry or equivalent tracing libraries.
28+
- Configure trace sampling to balance visibility and cost.
29+
- Use traces to investigate latency, error propagation, and request flow.
30+
31+
## Grafana Dashboards
32+
33+
- Design dashboards for system health, API performance, and ingestion status.
34+
- Create a system health overview, request latency dashboard, and error trend dashboard.
35+
- Use alerts on key thresholds such as high error rate, request latency regression, or backend queue saturation.
36+
37+
## Practical Observability
38+
39+
- Monitor both infrastructure and application-level signals.
40+
- Correlate logs, metrics, and traces for faster root cause analysis.
41+
- Keep dashboards focused and actionable, with clear alert definitions.

docs/performance/index.md

Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
# Performance Tuning & Optimization Guide
2+
3+
This guide explains how to identify and fix performance bottlenecks across the full SoroScan stack.
4+
5+
## Performance Profiling Tools
6+
7+
- Django Debug Toolbar for request-level timing and SQL inspection.
8+
- Django Silk for request profiling and middleware tracing.
9+
- PostgreSQL `EXPLAIN ANALYZE` for query cost and plan analysis.
10+
- Redis monitoring with `redis-cli monitor`, `INFO`, and external dashboards.
11+
- Chrome DevTools, Lighthouse, and WebPageTest for frontend performance.
12+
13+
## Database Optimization
14+
15+
- Use indexes on frequently filtered and joined columns.
16+
- Prevent N+1 queries with `select_related` and `prefetch_related`.
17+
- Tune connection pooling and database timeouts in `DATABASE_URL`/`pgbouncer`.
18+
- Analyze slow queries using PostgreSQL logs and `EXPLAIN`.
19+
20+
Example PostgreSQL query review:
21+
22+
```sql
23+
EXPLAIN ANALYZE
24+
SELECT * FROM ingest_event WHERE contract_id = '...';
25+
```
26+
27+
## Caching Strategy
28+
29+
- Use Redis for frequently requested query results and API caches.
30+
- Design cache keys with versioning and time-based invalidation.
31+
- Cache database query results, computed dashboards, and endpoint responses.
32+
- Leverage HTTP caching headers for browser and CDN-level caching.
33+
34+
## API Performance
35+
36+
- Measure response times for REST and GraphQL endpoints.
37+
- Optimize pagination by limiting payload size and using cursor-based cursors.
38+
- Avoid expensive filtering operations on unindexed columns.
39+
- Use rate limiting to protect service availability while preserving performance.
40+
41+
## Frontend Performance
42+
43+
- Apply code splitting and lazy loading for heavy pages.
44+
- Optimize images, fonts, and build output bundle sizes.
45+
- Reduce client-side work on initial load and defer non-critical scripts.
46+
- Audit hydration and runtime performance with Lighthouse.
47+
48+
## Monitoring Performance
49+
50+
- Establish baselines for response time, throughput, and error rates.
51+
- Track performance trends in dashboards and alerts.
52+
- Use Grafana or equivalent tools for ongoing visibility.
53+
- Document before/after optimization results with metrics.
54+
55+
## Practical Guidance
56+
57+
- Start by profiling the slowest request path, then optimize incrementally.
58+
- Compare baseline metrics before and after changes.
59+
- Keep performance regressions visible in CI with targeted smoke tests.

docs/security/index.md

Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
# Security Best Practices & Hardening Guide
2+
3+
This guide consolidates SoroScan's security approach across authentication, data protection, API hardening, infrastructure, and incident response.
4+
5+
## Authentication & Authorization
6+
7+
- Manage API keys with rotation and limited scopes.
8+
- Use JWT tokens only when appropriate, and store secrets securely.
9+
- Apply role-based access control (RBAC) for admin and ingestion operations.
10+
- Document permission boundaries and access tiers.
11+
12+
## Data Protection
13+
14+
- Enforce TLS for all external and internal traffic.
15+
- Protect sensitive fields at rest using environment-based encryption when required.
16+
- Keep secrets in environment variables or a secrets manager, never in source control.
17+
- Define data retention and privacy rules for PII and compliance-sensitive data.
18+
19+
## API Security
20+
21+
- Configure CORS to allow only trusted origins.
22+
- Enable CSRF protection for browser-based endpoints.
23+
- Validate and sanitize incoming request payloads.
24+
- Prevent SQL injection by using Django ORM and parameterized queries.
25+
- Apply rate limiting and DDoS protections on public endpoints.
26+
- Version APIs and include deprecation guidance for breaking changes.
27+
28+
## Dependency Security
29+
30+
- Scan dependencies regularly for vulnerabilities.
31+
- Use automated tools to identify supply-chain risks.
32+
- Keep dependencies up to date and apply security patches promptly.
33+
34+
## Infrastructure Security
35+
36+
- Harden network boundaries with firewalls and Kubernetes network policies.
37+
- Scan container images for known vulnerabilities.
38+
- Use secure secret management in Kubernetes and deployment pipelines.
39+
40+
## Vulnerability Management
41+
42+
- Maintain a vulnerability disclosure policy.
43+
- Define a clear bug reporting and triage process.
44+
- Apply security patches and track remediation progress.
45+
46+
## Incident Response
47+
48+
- Establish incident detection and alerting procedures.
49+
- Define an incident response playbook with roles and communication channels.
50+
- Conduct blameless post-incident reviews and update documentation.
51+
52+
## References
53+
54+
- Align guidance with OWASP Top 10 where applicable.
55+
- Include security checklist items for deployment and operations.

docs/testing/index.md

Lines changed: 108 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,108 @@
1+
# Testing & Quality Assurance
2+
3+
This guide documents SoroScan's testing strategy across the backend, frontend, contracts, and end-to-end workflows.
4+
5+
## Testing Strategy Overview
6+
7+
- Testing pyramid: unit tests for fast validation, integration tests for subsystem behavior, end-to-end tests for full workflows.
8+
- Coverage goals: use targeted coverage metrics for critical business logic and key API surfaces.
9+
- Test data management: prefer fixtures, factories, and isolated database state.
10+
- Mocking and stubbing: mock external services and blockchain RPC responses while keeping contract and integration tests realistic.
11+
12+
## Backend Testing Guide (Django)
13+
14+
- Unit tests for models, views, serializers, helpers, and custom validators.
15+
- Integration tests for database-backed behavior and REST/GraphQL endpoints.
16+
- Celery task testing for webhook dispatch, retry behavior, and background ingestion.
17+
- `pytest` fixtures for reusable database state, authentication, and API clients.
18+
19+
Example `pytest` unit test:
20+
21+
```python
22+
from django.urls import reverse
23+
from rest_framework import status
24+
25+
from soroscan.ingest.models import Event
26+
27+
28+
def test_event_serializer_creates_event(api_client, event_data):
29+
url = reverse('event-list')
30+
response = api_client.post(url, event_data)
31+
32+
assert response.status_code == status.HTTP_201_CREATED
33+
assert Event.objects.filter(tx_hash=event_data['tx_hash']).exists()
34+
```
35+
36+
Example fixture structure:
37+
38+
```python
39+
import pytest
40+
from django.contrib.auth.models import User
41+
42+
@pytest.fixture
43+
def api_client(client, django_user_model):
44+
user = django_user_model.objects.create_user('tester', 'tester@example.com', 'pass')
45+
client.force_login(user)
46+
return client
47+
```
48+
49+
## Frontend Testing Guide (Next.js / React)
50+
51+
- Component testing with React Testing Library.
52+
- Hook testing for custom hooks and Apollo Client integration.
53+
- Page-level integration testing for component interactions and navigation.
54+
- MSW setup for mocking GraphQL and REST requests.
55+
- Jest configuration for snapshot testing and code coverage.
56+
57+
Example component test:
58+
59+
```tsx
60+
import { render, screen } from '@testing-library/react';
61+
import userEvent from '@testing-library/user-event';
62+
import EventCard from '@/components/EventCard';
63+
64+
it('renders event fields and responds to click', async () => {
65+
render(<EventCard event={{ id: '1', name: 'Transfer', block: 123 }} />);
66+
67+
expect(screen.getByText('Transfer')).toBeInTheDocument();
68+
await userEvent.click(screen.getByRole('button', { name: /details/i }));
69+
expect(screen.getByText(/block 123/i)).toBeVisible();
70+
});
71+
```
72+
73+
## Contract Testing Guide (Rust)
74+
75+
- Soroban contract unit tests for business logic and edge cases.
76+
- Contract integration tests that simulate transactions and external state.
77+
- Use the Soroban testing harness to verify emitted events and contract behavior.
78+
79+
Example command:
80+
81+
```bash
82+
cd soroban-contracts/soroscan_core
83+
cargo test
84+
```
85+
86+
## End-to-End Testing Guide
87+
88+
- Use Playwright to validate user workflows and API interactions.
89+
- Test scenarios for event ingestion, webhook delivery, and dashboard behavior.
90+
- Run full-stack E2E tests in CI to cover critical customer journeys.
91+
92+
Example command:
93+
94+
```bash
95+
pnpm exec playwright test
96+
```
97+
98+
## Performance Testing
99+
100+
- Load testing with `k6` or similar tools.
101+
- Baseline performance metrics for API throughput, latency, and ingestion.
102+
- Regression testing on key endpoints to detect performance drift.
103+
104+
## Cross-Team Notes
105+
106+
- Reference existing backend tests in `django-backend/`.
107+
- Reference frontend tests in `soroscan-frontend/__tests__/`.
108+
- Reference Soroban contract tests in `soroban-contracts/soroscan_core/`.

0 commit comments

Comments
 (0)