Skip to content

Commit 95a823a

Browse files
committed
chore: wip
1 parent c8dbbc2 commit 95a823a

File tree

10 files changed

+3100
-2
lines changed

10 files changed

+3100
-2
lines changed

docs/advanced/ci-cd-integration.md

Lines changed: 488 additions & 0 deletions
Large diffs are not rendered by default.

docs/advanced/configuration.md

Lines changed: 415 additions & 0 deletions
Large diffs are not rendered by default.

docs/advanced/custom-cas.md

Lines changed: 406 additions & 0 deletions
Large diffs are not rendered by default.

docs/advanced/performance.md

Lines changed: 357 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,357 @@
1+
# Performance
2+
3+
This guide covers performance optimization strategies for tlsx, including caching, parallel generation, and benchmarking.
4+
5+
## Performance Characteristics
6+
7+
tlsx is optimized for:
8+
9+
- **Fast generation**: ~50-100ms per certificate
10+
- **Low memory**: ~20MB peak usage
11+
- **Efficient storage**: Minimal disk I/O
12+
13+
## Certificate Generation Performance
14+
15+
### Key Size Impact
16+
17+
| Key Size | Generation Time | Security Level |
18+
|----------|-----------------|----------------|
19+
| 2048-bit | ~50ms | Standard |
20+
| 3072-bit | ~150ms | Enhanced |
21+
| 4096-bit | ~500ms | Maximum |
22+
23+
### Recommended Settings
24+
25+
```ts
26+
// Development (fast)
27+
const devCert = await generateCertificate({
28+
domain: 'app.localhost',
29+
keySize: 2048,
30+
validityDays: 90,
31+
})
32+
33+
// Production-like (secure)
34+
const prodCert = await generateCertificate({
35+
domain: 'app.example.com',
36+
keySize: 4096,
37+
validityDays: 365,
38+
})
39+
```
40+
41+
## Caching
42+
43+
### Certificate Caching
44+
45+
Cache generated certificates to avoid regeneration:
46+
47+
```ts
48+
// tlsx.config.ts
49+
export default {
50+
cache: {
51+
enabled: true,
52+
dir: '~/.stacks/ssl/cache',
53+
ttl: 86400 * 30, // 30 days
54+
},
55+
}
56+
```
57+
58+
### Programmatic Caching
59+
60+
```ts
61+
import { generateCertificate, getCachedCertificate, cacheCertificate } from '@stacksjs/tlsx'
62+
63+
async function getCertificate(domain: string) {
64+
// Check cache first
65+
const cached = await getCachedCertificate(domain)
66+
if (cached && !cached.isExpired) {
67+
return cached
68+
}
69+
70+
// Generate new certificate
71+
const cert = await generateCertificate({ domain })
72+
73+
// Cache for future use
74+
await cacheCertificate(domain, cert)
75+
76+
return cert
77+
}
78+
```
79+
80+
### Cache Invalidation
81+
82+
```bash
83+
# Clear all cached certificates
84+
tlsx cache clear
85+
86+
# Clear specific domain
87+
tlsx cache clear app.localhost
88+
```
89+
90+
## Parallel Generation
91+
92+
### Batch Certificate Generation
93+
94+
```ts
95+
import { generateCertificate, createRootCA } from '@stacksjs/tlsx'
96+
97+
const domains = [
98+
'api.localhost',
99+
'web.localhost',
100+
'admin.localhost',
101+
'docs.localhost',
102+
]
103+
104+
// Create shared CA once
105+
const ca = await createRootCA({
106+
commonName: 'Batch CA',
107+
})
108+
109+
// Generate certificates in parallel
110+
const startTime = performance.now()
111+
112+
const certificates = await Promise.all(
113+
domains.map((domain) =>
114+
generateCertificate({
115+
domain,
116+
rootCA: ca,
117+
validityDays: 365,
118+
}),
119+
),
120+
)
121+
122+
const duration = performance.now() - startTime
123+
console.log(`Generated ${domains.length} certificates in ${duration}ms`)
124+
// Generated 4 certificates in ~200ms
125+
```
126+
127+
### Concurrency Control
128+
129+
```ts
130+
import pLimit from 'p-limit'
131+
import { generateCertificate } from '@stacksjs/tlsx'
132+
133+
const limit = pLimit(4) // Max 4 concurrent generations
134+
135+
const domains = Array.from({ length: 20 }, (_, i) => `app${i}.localhost`)
136+
137+
const certificates = await Promise.all(
138+
domains.map((domain) =>
139+
limit(() => generateCertificate({ domain })),
140+
),
141+
)
142+
```
143+
144+
## Memory Optimization
145+
146+
### Streaming for Large Operations
147+
148+
```ts
149+
import { generateCertificateStream } from '@stacksjs/tlsx'
150+
151+
// Stream certificate to file instead of buffering
152+
await generateCertificateStream({
153+
domain: 'app.localhost',
154+
certStream: fs.createWriteStream('./cert.crt'),
155+
keyStream: fs.createWriteStream('./key.pem'),
156+
})
157+
```
158+
159+
### Cleanup
160+
161+
```ts
162+
import { cleanup } from '@stacksjs/tlsx'
163+
164+
// Clean up temporary files and memory
165+
await cleanup()
166+
```
167+
168+
## Benchmarking
169+
170+
### Built-in Benchmarks
171+
172+
```bash
173+
# Run performance benchmark
174+
tlsx benchmark
175+
176+
# Output:
177+
# Certificate Generation Benchmark
178+
# ================================
179+
# Key Size: 2048 bits
180+
# Iterations: 100
181+
#
182+
# Results:
183+
# Min: 45ms
184+
# Max: 89ms
185+
# Avg: 52ms
186+
# P95: 67ms
187+
# P99: 82ms
188+
```
189+
190+
### Custom Benchmarks
191+
192+
```ts
193+
import { generateCertificate } from '@stacksjs/tlsx'
194+
195+
async function benchmark(iterations: number = 100) {
196+
const times: number[] = []
197+
198+
for (let i = 0; i < iterations; i++) {
199+
const start = performance.now()
200+
201+
await generateCertificate({
202+
domain: `bench${i}.localhost`,
203+
keySize: 2048,
204+
})
205+
206+
times.push(performance.now() - start)
207+
}
208+
209+
// Calculate statistics
210+
const avg = times.reduce((a, b) => a + b) / times.length
211+
const sorted = times.sort((a, b) => a - b)
212+
const p95 = sorted[Math.floor(times.length * 0.95)]
213+
const p99 = sorted[Math.floor(times.length * 0.99)]
214+
215+
console.log({
216+
iterations,
217+
avgMs: avg.toFixed(2),
218+
p95Ms: p95.toFixed(2),
219+
p99Ms: p99.toFixed(2),
220+
minMs: sorted[0].toFixed(2),
221+
maxMs: sorted[sorted.length - 1].toFixed(2),
222+
})
223+
}
224+
225+
await benchmark(100)
226+
```
227+
228+
## Startup Optimization
229+
230+
### Lazy Loading
231+
232+
```ts
233+
// Only load tlsx when needed
234+
let tlsx: typeof import('@stacksjs/tlsx') | null = null
235+
236+
async function getTlsx() {
237+
if (!tlsx) {
238+
tlsx = await import('@stacksjs/tlsx')
239+
}
240+
return tlsx
241+
}
242+
243+
// Use when needed
244+
const { generateCertificate } = await getTlsx()
245+
```
246+
247+
### Preloading
248+
249+
```ts
250+
// preload.ts - Run at application startup
251+
import '@stacksjs/tlsx' // Preload the module
252+
253+
// main.ts - Module is already cached
254+
import { generateCertificate } from '@stacksjs/tlsx'
255+
```
256+
257+
## CI/CD Performance
258+
259+
### Caching in CI
260+
261+
```yaml
262+
# GitHub Actions
263+
- name: Cache certificates
264+
uses: actions/cache@v3
265+
with:
266+
path: ~/.stacks/ssl
267+
key: ${{ runner.os }}-certs-${{ hashFiles('tlsx.config.ts') }}
268+
269+
- name: Generate certificates
270+
run: tlsx secure app.localhost
271+
```
272+
273+
### Parallel Jobs
274+
275+
```yaml
276+
jobs:
277+
generate-certs:
278+
strategy:
279+
matrix:
280+
domain: [api, web, admin, docs]
281+
steps:
282+
- run: tlsx secure ${{ matrix.domain }}.localhost
283+
```
284+
285+
## Monitoring
286+
287+
### Performance Metrics
288+
289+
```ts
290+
import { getMetrics } from '@stacksjs/tlsx'
291+
292+
const metrics = await getMetrics()
293+
console.log(metrics)
294+
// {
295+
// certificatesGenerated: 150,
296+
// avgGenerationTime: 52,
297+
// cacheHits: 120,
298+
// cacheMisses: 30,
299+
// memoryUsage: 18500000,
300+
// }
301+
```
302+
303+
### Profiling
304+
305+
```bash
306+
# Enable profiling
307+
NODE_OPTIONS="--prof" tlsx secure app.localhost
308+
309+
# Analyze profile
310+
node --prof-process isolate-*.log > profile.txt
311+
```
312+
313+
## Best Practices
314+
315+
### Development
316+
317+
- Use 2048-bit keys for faster generation
318+
- Enable caching to avoid regeneration
319+
- Generate certificates in parallel
320+
321+
### Testing
322+
323+
- Pre-generate certificates before test runs
324+
- Cache certificates between test runs
325+
- Use shorter validity periods
326+
327+
### Production-like
328+
329+
- Use 4096-bit keys for maximum security
330+
- Pre-generate and store certificates
331+
- Implement certificate rotation
332+
333+
## Troubleshooting
334+
335+
### Slow Generation
336+
337+
1. Check key size (reduce to 2048 for development)
338+
2. Enable caching
339+
3. Verify disk I/O is not a bottleneck
340+
341+
### Memory Issues
342+
343+
1. Process certificates in batches
344+
2. Use streaming for large operations
345+
3. Call cleanup() after bulk operations
346+
347+
### CI Timeouts
348+
349+
1. Cache certificates between runs
350+
2. Parallelize generation
351+
3. Use smaller key sizes in CI
352+
353+
## Next Steps
354+
355+
- [CI/CD Integration](/advanced/ci-cd-integration) - Pipeline optimization
356+
- [Configuration](/advanced/configuration) - Performance-related config
357+
- [Custom CAs](/advanced/custom-cas) - Efficient CA management

0 commit comments

Comments
 (0)