Enhance skills with improved metadata and Quick Reference sections
- Shorten all skill descriptions to under 200 characters (Claude requirement) - Add dependencies field to 22 skills for better context - Add Quick Reference sections to key skills (project-rules, security, testing-patterns, api-design, resilience-patterns) - Significantly expand resilience-patterns skill with: - Bulkhead pattern implementation - Combined ResilienceService class - Health check integration example - Expanded Common Mistakes with code examples - Standardize skill structure following Claude and agentskills.io best practices 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
This commit is contained in:
@@ -1,6 +1,7 @@
|
||||
---
|
||||
name: api-design
|
||||
description: RESTful API design standards for GoodGo microservices. Use when creating new API endpoints, designing DTOs, implementing controllers, writing OpenAPI documentation, or standardizing API responses.
|
||||
description: RESTful API design standards for GoodGo microservices. Use for new API endpoints, DTOs, controllers, OpenAPI documentation, or standardized responses.
|
||||
dependencies: "express>=4.18, zod>=3, @types/express"
|
||||
---
|
||||
|
||||
# RESTful API Design Standards
|
||||
@@ -482,4 +483,42 @@ export function errorHandler(
|
||||
- Keep OpenAPI spec up to date
|
||||
- Include examples in documentation
|
||||
- Document error responses
|
||||
- Version your documentation
|
||||
- Version your documentation
|
||||
|
||||
## Quick Reference
|
||||
|
||||
| HTTP Method | Action | Idempotent | Status Codes |
|
||||
|-------------|--------|------------|--------------|
|
||||
| **GET** | Retrieve | Yes | 200, 404 |
|
||||
| **POST** | Create | No | 201, 400, 409 |
|
||||
| **PUT** | Full update | Yes | 200, 400, 404 |
|
||||
| **PATCH** | Partial update | Yes | 200, 400, 404 |
|
||||
| **DELETE** | Remove | Yes | 204, 404 |
|
||||
|
||||
**Response Format:**
|
||||
```typescript
|
||||
// Success
|
||||
{ success: true, data: T, pagination?: {...} }
|
||||
|
||||
// Error
|
||||
{ success: false, error: { code: string, message: string, details?: any } }
|
||||
```
|
||||
|
||||
**URL Patterns:**
|
||||
```
|
||||
GET /v1/users # List
|
||||
POST /v1/users # Create
|
||||
GET /v1/users/:id # Get by ID
|
||||
PUT /v1/users/:id # Update
|
||||
DELETE /v1/users/:id # Delete
|
||||
GET /v1/users/:id/orders # Sub-resource
|
||||
```
|
||||
|
||||
**Common Error Codes:**
|
||||
- `400` - Bad Request (validation)
|
||||
- `401` - Unauthorized (no token)
|
||||
- `403` - Forbidden (no permission)
|
||||
- `404` - Not Found
|
||||
- `409` - Conflict (duplicate)
|
||||
- `422` - Unprocessable (business rule)
|
||||
- `429` - Rate limited
|
||||
@@ -1,6 +1,7 @@
|
||||
---
|
||||
name: api-gateway-advanced
|
||||
description: Advanced API Gateway patterns for GoodGo microservices including API composition, request/response transformation, service mesh integration, advanced routing, and gateway-level resilience. Use when implementing API aggregation, service composition, or advanced gateway features.
|
||||
description: Advanced API Gateway patterns for GoodGo. Use for API composition, request/response transformation, service mesh, or gateway resilience.
|
||||
dependencies: "traefik>=2.10"
|
||||
---
|
||||
|
||||
# API Gateway Advanced Patterns
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
---
|
||||
name: api-versioning-strategy
|
||||
description: API versioning strategies for GoodGo microservices including semantic versioning, backward compatibility patterns, API deprecation, version negotiation, and breaking changes handling. Use when versioning APIs, handling breaking changes, or implementing API deprecation strategies.
|
||||
description: API versioning strategies for GoodGo services. Use for semantic versioning, backward compatibility, API deprecation, or breaking change handling.
|
||||
---
|
||||
|
||||
# API Versioning Strategy
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
---
|
||||
name: caching-patterns
|
||||
description: Caching strategies and patterns for GoodGo microservices including multi-layer cache, Redis caching, cache key naming, TTL strategies, cache invalidation, and cache-aside patterns.
|
||||
description: Caching patterns for GoodGo microservices. Use for Redis caching, cache invalidation, TTL strategies, or cache-aside patterns.
|
||||
dependencies: "ioredis>=5"
|
||||
---
|
||||
|
||||
# Caching Patterns
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
---
|
||||
name: cicd-advanced-patterns
|
||||
description: Advanced CI/CD patterns for GoodGo microservices including blue-green deployments, canary releases, automated rollback, deployment verification, and progressive delivery. Use when implementing advanced deployment strategies, automated rollbacks, or progressive delivery pipelines.
|
||||
description: Advanced CI/CD patterns for GoodGo services. Use for blue-green deployments, canary releases, automated rollbacks, or progressive delivery.
|
||||
dependencies: "github-actions, docker, kubernetes"
|
||||
---
|
||||
|
||||
# CI/CD Advanced Patterns
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
---
|
||||
name: comment-code
|
||||
description: Add bilingual code comments in Vietnamese and English for better documentation. Use when adding comments to code, documenting functions/classes, or when user requests Vietnamese/English documentation.
|
||||
description: Bilingual code comments in Vietnamese and English. Use for documenting functions, classes, or adding EN/VI documentation.
|
||||
---
|
||||
|
||||
# Bilingual Code Comments
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
---
|
||||
name: configuration-management
|
||||
description: Configuration management patterns for GoodGo microservices including feature flags, dynamic configuration reloading, environment-specific configurations, and secrets management. Use when implementing feature toggles, managing configuration, or handling environment variables.
|
||||
description: Configuration management for GoodGo services. Use for feature flags, dynamic config, environment variables, or secrets management.
|
||||
dependencies: "zod>=3"
|
||||
---
|
||||
|
||||
# Configuration Management Patterns
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
---
|
||||
name: data-consistency-patterns
|
||||
description: Data consistency patterns for distributed microservices including Saga patterns, distributed transactions, eventual consistency, compensation, and idempotency. Use when handling distributed transactions, implementing eventual consistency, or managing data synchronization across services.
|
||||
description: Data consistency patterns for distributed systems. Use for Saga patterns, distributed transactions, eventual consistency, or cross-service data sync.
|
||||
dependencies: "prisma>=5"
|
||||
---
|
||||
|
||||
# Data Consistency Patterns
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
---
|
||||
name: database-prisma
|
||||
description: Prisma ORM and database patterns for GoodGo microservices. Use when working with databases, creating Prisma schemas, writing migrations, implementing repositories, or optimizing queries.
|
||||
description: Prisma ORM and database patterns for GoodGo services. Use for schemas, migrations, repositories, or query optimization.
|
||||
dependencies: "prisma>=5, @prisma/client>=5"
|
||||
---
|
||||
|
||||
# Prisma Database Patterns
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
---
|
||||
name: deployment-kubernetes
|
||||
description: Kubernetes deployment patterns for GoodGo microservices. Use when deploying to staging/production, creating K8s manifests, configuring HPA, setting up ingress, or troubleshooting K8s deployments.
|
||||
description: Kubernetes deployment for GoodGo services. Use for K8s manifests, HPA, ingress, staging/production deployments, or troubleshooting.
|
||||
dependencies: "kubernetes>=1.28, helm>=3"
|
||||
---
|
||||
|
||||
# Kubernetes Deployment Patterns
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
---
|
||||
name: documentation
|
||||
description: Guidelines for writing technical documentation in the GoodGo project. Use when creating or updating README files, guides, architecture docs, or API documentation. Ensures bilingual (EN/VI) consistency and proper structure.
|
||||
description: Documentation guidelines for GoodGo project. Use for README, guides, architecture docs, or API docs. Ensures bilingual EN/VI consistency.
|
||||
---
|
||||
|
||||
# Documentation Writing Guidelines
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
---
|
||||
name: error-handling-patterns
|
||||
description: Error handling patterns and conventions for GoodGo microservices. Use when implementing error handling, creating custom error classes, handling exceptions, standardizing error responses, or debugging error scenarios.
|
||||
description: Error handling patterns for GoodGo services. Use for custom error classes, exception handling, standardized error responses, or debugging.
|
||||
dependencies: "typescript>=5, zod>=3"
|
||||
---
|
||||
|
||||
# Error Handling Patterns
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
---
|
||||
name: event-driven-architecture
|
||||
description: Event-driven architecture patterns with Apache Kafka for GoodGo microservices. Use when implementing async communication, event publishing/consuming, event sourcing, CQRS, or integrating event streams with HTTP endpoints.
|
||||
description: Event-driven patterns with Kafka for GoodGo services. Use for async communication, event sourcing, CQRS, or event stream integration.
|
||||
dependencies: "kafkajs>=2"
|
||||
---
|
||||
|
||||
# Event-Driven Architecture Patterns
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
---
|
||||
name: infrastructure-as-code
|
||||
description: Infrastructure as Code patterns for GoodGo platform including Terraform modules, Kubernetes operators, infrastructure testing, GitOps workflows, and multi-environment management. Use when managing infrastructure, implementing GitOps, or creating reusable infrastructure modules.
|
||||
description: Infrastructure as Code for GoodGo platform. Use for Terraform modules, Kubernetes operators, GitOps workflows, or multi-environment management.
|
||||
dependencies: "terraform>=1.5, kubectl"
|
||||
---
|
||||
|
||||
# Infrastructure as Code Patterns
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
---
|
||||
name: inter-service-communication
|
||||
description: Inter-service communication patterns for GoodGo microservices including gRPC, GraphQL, service-to-service authentication, protocol selection, and client patterns. Use when implementing service-to-service calls, choosing communication protocols, or building service clients.
|
||||
description: Inter-service communication for GoodGo microservices. Use for gRPC, GraphQL, service auth, protocol selection, or building service clients.
|
||||
dependencies: "@grpc/grpc-js, graphql"
|
||||
---
|
||||
|
||||
# Inter-Service Communication Patterns
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
---
|
||||
name: microservices-development-process
|
||||
description: Standard development process for creating and maintaining microservices in GoodGo platform. Use when creating new services, migrating services, refactoring services, or planning service implementations.
|
||||
description: Standard development process for GoodGo microservices. Use when creating, migrating, refactoring services, or planning implementations.
|
||||
dependencies: "node>=20, pnpm>=8, docker, kubernetes"
|
||||
---
|
||||
|
||||
# Microservices Development Process
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
---
|
||||
name: middleware-patterns
|
||||
description: Express middleware patterns and best practices for GoodGo microservices. Use when creating custom middleware, organizing middleware chains, handling request/response transformation, or implementing cross-cutting concerns.
|
||||
description: Express middleware patterns for GoodGo services. Use for custom middleware, middleware chains, request/response transformation, or cross-cutting concerns.
|
||||
dependencies: "node>=20, express>=4.18"
|
||||
---
|
||||
|
||||
# Middleware Patterns
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
---
|
||||
name: observability-monitoring
|
||||
description: Observability and monitoring patterns for GoodGo microservices. Use when adding metrics, implementing logging, setting up tracing, creating health checks, or debugging production issues.
|
||||
description: Observability and monitoring for GoodGo services. Use for metrics, logging, tracing, health checks, or production debugging.
|
||||
dependencies: "prom-client>=15, winston>=3, @opentelemetry/sdk-node"
|
||||
---
|
||||
|
||||
# Observability & Monitoring Patterns
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
---
|
||||
name: performance-optimization
|
||||
description: Performance optimization patterns for GoodGo microservices including database query optimization, memory leak detection, profiling, connection pooling, and caching strategies. Use when optimizing performance, profiling applications, or detecting performance bottlenecks.
|
||||
description: Performance optimization for GoodGo services. Use for query optimization, memory profiling, connection pooling, caching, or bottleneck detection.
|
||||
dependencies: "node>=20, prisma>=5"
|
||||
---
|
||||
|
||||
# Performance Optimization Patterns
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
---
|
||||
name: project-rules
|
||||
description: GoodGo Microservices Platform coding standards and architecture patterns. Use when working with services, apps, packages, or infrastructure.
|
||||
description: GoodGo Platform coding standards and architecture. Use when working with services, apps, packages, or infrastructure.
|
||||
dependencies: "node>=20, typescript>=5, pnpm>=8"
|
||||
---
|
||||
|
||||
# GoodGo Project Rules
|
||||
@@ -247,6 +248,34 @@ docker-compose ps
|
||||
docker-compose up -d --build
|
||||
```
|
||||
|
||||
## Quick Reference
|
||||
|
||||
| Category | Pattern/Standard |
|
||||
|----------|-----------------|
|
||||
| **Service structure** | `src/{config,modules,middlewares,routes,main.ts}` |
|
||||
| **File naming** | `kebab-case.type.ts` (e.g., `user.controller.ts`) |
|
||||
| **Package naming** | `@goodgo/package-name` |
|
||||
| **API response** | `{ success: true, data }` / `{ success: false, error: { code, message } }` |
|
||||
| **Password hashing** | bcrypt, cost 12 |
|
||||
| **JWT tokens** | Access: 15min, Refresh: 7 days |
|
||||
| **Coverage target** | >80% for unit tests |
|
||||
| **Commits** | `type(scope): subject` (conventional commits) |
|
||||
|
||||
**Common Commands:**
|
||||
```bash
|
||||
# Add dependency
|
||||
pnpm --filter @goodgo/service-name add package-name
|
||||
|
||||
# Run migrations
|
||||
pnpm --filter @goodgo/service-name prisma migrate dev
|
||||
|
||||
# Run tests
|
||||
pnpm --filter @goodgo/service-name test
|
||||
|
||||
# Start dev server
|
||||
pnpm --filter @goodgo/service-name dev
|
||||
```
|
||||
|
||||
## Resources
|
||||
|
||||
- [Architecture Docs](../../docs/architecture/)
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
---
|
||||
name: repository-pattern
|
||||
description: Repository pattern implementation and best practices for GoodGo microservices. Use when implementing data access layers, extending BaseRepository, writing database queries, handling transactions, or optimizing database operations.
|
||||
description: Repository pattern for GoodGo microservices. Use for data access layers, BaseRepository extension, transactions, or query optimization.
|
||||
dependencies: "prisma>=5, typescript>=5"
|
||||
---
|
||||
|
||||
# Repository Pattern
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
---
|
||||
name: resilience-patterns
|
||||
description: Resilience patterns for GoodGo microservices including circuit breaker, retry strategies, timeout handling, and graceful degradation. Use when implementing fault tolerance, handling external service failures, or improving system reliability.
|
||||
description: Resilience patterns for GoodGo services. Use for circuit breaker, retry strategies, timeout handling, or graceful degradation.
|
||||
dependencies: "opossum>=8"
|
||||
---
|
||||
|
||||
# Resilience Patterns
|
||||
@@ -144,6 +145,175 @@ async function getDataWithFallback() {
|
||||
}
|
||||
```
|
||||
|
||||
### Bulkhead Pattern
|
||||
|
||||
Isolate failures to prevent spread:
|
||||
|
||||
```typescript
|
||||
import PQueue from 'p-queue';
|
||||
|
||||
// Create separate queues for different operations
|
||||
const externalApiQueue = new PQueue({
|
||||
concurrency: 10, // Max 10 concurrent calls
|
||||
timeout: 30000 // 30 second timeout per operation
|
||||
});
|
||||
|
||||
const databaseQueue = new PQueue({
|
||||
concurrency: 20
|
||||
});
|
||||
|
||||
// Usage - operations are isolated
|
||||
async function fetchExternalData(id: string) {
|
||||
return externalApiQueue.add(async () => {
|
||||
return await externalApi.getData(id);
|
||||
});
|
||||
}
|
||||
|
||||
async function queryDatabase(query: string) {
|
||||
return databaseQueue.add(async () => {
|
||||
return await database.execute(query);
|
||||
});
|
||||
}
|
||||
```
|
||||
|
||||
### Combined Resilience Service
|
||||
|
||||
```typescript
|
||||
// src/core/resilience/resilience.service.ts
|
||||
import CircuitBreaker from 'opossum';
|
||||
import { logger } from '@goodgo/logger';
|
||||
|
||||
interface ResilienceOptions {
|
||||
timeout?: number;
|
||||
maxRetries?: number;
|
||||
circuitBreaker?: boolean;
|
||||
fallback?: () => Promise<any>;
|
||||
}
|
||||
|
||||
export class ResilienceService {
|
||||
async execute<T>(
|
||||
operation: () => Promise<T>,
|
||||
name: string,
|
||||
options: ResilienceOptions = {}
|
||||
): Promise<T> {
|
||||
const {
|
||||
timeout = 5000,
|
||||
maxRetries = 3,
|
||||
circuitBreaker = true,
|
||||
fallback
|
||||
} = options;
|
||||
|
||||
let fn = operation;
|
||||
|
||||
// Wrap with timeout
|
||||
fn = () => this.withTimeout(operation(), timeout);
|
||||
|
||||
// Wrap with retry
|
||||
fn = () => this.retryWithBackoff(fn, maxRetries);
|
||||
|
||||
// Wrap with circuit breaker
|
||||
if (circuitBreaker) {
|
||||
const breaker = this.createCircuitBreaker(fn, name);
|
||||
try {
|
||||
return await breaker.fire();
|
||||
} catch (error) {
|
||||
if (fallback) {
|
||||
logger.warn(`${name}: Using fallback`, { error: error.message });
|
||||
return await fallback();
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
try {
|
||||
return await fn();
|
||||
} catch (error) {
|
||||
if (fallback) {
|
||||
return await fallback();
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
private withTimeout<T>(promise: Promise<T>, ms: number): Promise<T> {
|
||||
const timeout = new Promise<never>((_, reject) => {
|
||||
setTimeout(() => reject(new Error('Operation timeout')), ms);
|
||||
});
|
||||
return Promise.race([promise, timeout]);
|
||||
}
|
||||
|
||||
private async retryWithBackoff<T>(
|
||||
fn: () => Promise<T>,
|
||||
maxRetries: number
|
||||
): Promise<T> {
|
||||
for (let attempt = 0; attempt <= maxRetries; attempt++) {
|
||||
try {
|
||||
return await fn();
|
||||
} catch (error) {
|
||||
if (attempt === maxRetries) throw error;
|
||||
const delay = 1000 * Math.pow(2, attempt);
|
||||
await new Promise(resolve => setTimeout(resolve, delay));
|
||||
}
|
||||
}
|
||||
throw new Error('Retry exhausted');
|
||||
}
|
||||
|
||||
private createCircuitBreaker<T>(
|
||||
fn: () => Promise<T>,
|
||||
name: string
|
||||
): CircuitBreaker<[], T> {
|
||||
return new CircuitBreaker(fn, {
|
||||
timeout: 3000,
|
||||
errorThresholdPercentage: 50,
|
||||
resetTimeout: 30000,
|
||||
name
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// Usage
|
||||
const resilience = new ResilienceService();
|
||||
|
||||
const result = await resilience.execute(
|
||||
() => externalApi.fetchUser(userId),
|
||||
'fetch-user',
|
||||
{
|
||||
timeout: 3000,
|
||||
maxRetries: 2,
|
||||
fallback: () => Promise.resolve({ id: userId, name: 'Unknown' })
|
||||
}
|
||||
);
|
||||
```
|
||||
|
||||
### Health Check with Resilience
|
||||
|
||||
```typescript
|
||||
// src/health/health.controller.ts
|
||||
export class HealthController {
|
||||
async checkDependencies(): Promise<HealthStatus> {
|
||||
const checks = await Promise.allSettled([
|
||||
this.checkDatabase(),
|
||||
this.checkRedis(),
|
||||
this.checkExternalApi()
|
||||
]);
|
||||
|
||||
const results = {
|
||||
database: checks[0].status === 'fulfilled' ? 'healthy' : 'unhealthy',
|
||||
redis: checks[1].status === 'fulfilled' ? 'healthy' : 'unhealthy',
|
||||
externalApi: checks[2].status === 'fulfilled' ? 'healthy' : 'degraded'
|
||||
};
|
||||
|
||||
// Service is healthy even if external API is down (graceful degradation)
|
||||
const isHealthy = results.database === 'healthy' && results.redis === 'healthy';
|
||||
|
||||
return {
|
||||
status: isHealthy ? 'healthy' : 'unhealthy',
|
||||
dependencies: results
|
||||
};
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## Best Practices
|
||||
|
||||
1. **Circuit Breaker**: Use for external service calls
|
||||
@@ -156,10 +326,94 @@ async function getDataWithFallback() {
|
||||
## Common Mistakes
|
||||
|
||||
1. **Retrying Non-Retryable Errors**: Retrying 4xx errors (client errors)
|
||||
```typescript
|
||||
// ❌ BAD: Retry all errors
|
||||
catch (error) {
|
||||
await retry(operation);
|
||||
}
|
||||
|
||||
// ✅ GOOD: Only retry transient errors
|
||||
catch (error) {
|
||||
if (isTransientError(error)) {
|
||||
await retry(operation);
|
||||
} else {
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
2. **No Timeout**: Missing timeouts on external calls
|
||||
```typescript
|
||||
// ❌ BAD: No timeout
|
||||
const data = await externalApi.fetch();
|
||||
|
||||
// ✅ GOOD: With timeout
|
||||
const data = await withTimeout(externalApi.fetch(), 5000);
|
||||
```
|
||||
|
||||
3. **No Fallback**: No graceful degradation strategy
|
||||
```typescript
|
||||
// ❌ BAD: Service crashes if dependency fails
|
||||
const user = await userService.get(id);
|
||||
|
||||
// ✅ GOOD: Fallback to cached/default data
|
||||
const user = await userService.get(id).catch(() => cachedUser);
|
||||
```
|
||||
|
||||
4. **Too Many Retries**: Excessive retries causing performance issues
|
||||
```typescript
|
||||
// ❌ BAD: Too many retries with short delay
|
||||
retry(fn, { maxRetries: 10, delay: 100 });
|
||||
|
||||
// ✅ GOOD: Limited retries with exponential backoff
|
||||
retry(fn, { maxRetries: 3, baseDelay: 1000, exponential: true });
|
||||
```
|
||||
|
||||
5. **Circuit Breaker Misconfiguration**: Wrong thresholds
|
||||
```typescript
|
||||
// ❌ BAD: Circuit opens too easily or never
|
||||
{ errorThresholdPercentage: 5 } // Opens after 5% errors
|
||||
{ errorThresholdPercentage: 99 } // Almost never opens
|
||||
|
||||
// ✅ GOOD: Balanced threshold
|
||||
{ errorThresholdPercentage: 50, resetTimeout: 30000 }
|
||||
```
|
||||
|
||||
## Quick Reference
|
||||
|
||||
| Pattern | Use Case | Key Config |
|
||||
|---------|----------|------------|
|
||||
| **Circuit Breaker** | External API calls | threshold: 50%, reset: 30s |
|
||||
| **Retry** | Transient failures | max: 3, exponential backoff |
|
||||
| **Timeout** | All external calls | 3-5s for API, 30s for batch |
|
||||
| **Bulkhead** | Resource isolation | 10-20 concurrent ops |
|
||||
| **Fallback** | Critical operations | Cache, default, or degraded |
|
||||
|
||||
**Opossum Circuit Breaker States:**
|
||||
```
|
||||
CLOSED → (errors exceed threshold) → OPEN
|
||||
OPEN → (reset timeout expires) → HALF-OPEN
|
||||
HALF-OPEN → (success) → CLOSED
|
||||
HALF-OPEN → (failure) → OPEN
|
||||
```
|
||||
|
||||
**Retry Delays (Exponential Backoff):**
|
||||
```
|
||||
Attempt 1: 1s
|
||||
Attempt 2: 2s
|
||||
Attempt 3: 4s
|
||||
Attempt 4: 8s
|
||||
```
|
||||
|
||||
**Essential Imports:**
|
||||
```typescript
|
||||
import CircuitBreaker from 'opossum';
|
||||
import PQueue from 'p-queue';
|
||||
import { logger } from '@goodgo/logger';
|
||||
```
|
||||
|
||||
## Resources
|
||||
|
||||
- [Circuit Breaker](../../services/iam-service/src/modules/common/circuit-breaker.ts) - Circuit breaker implementation
|
||||
- [Opossum Documentation](https://nodeshift.dev/opossum/)
|
||||
- [Microsoft Resilience Patterns](https://docs.microsoft.com/en-us/azure/architecture/patterns/category/resiliency)
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
---
|
||||
name: security
|
||||
description: Security best practices and patterns for GoodGo microservices platform. Use when implementing authentication, authorization, data protection, input validation, rate limiting, secrets management, or security testing across all services.
|
||||
description: Security patterns for GoodGo platform. Use for authentication, authorization, data protection, input validation, rate limiting, or secrets management.
|
||||
dependencies: "bcrypt>=5, helmet>=7, zod>=3, jsonwebtoken"
|
||||
---
|
||||
|
||||
# Security Patterns for GoodGo Microservices
|
||||
@@ -788,6 +789,29 @@ export class SecurityIncidentService {
|
||||
}
|
||||
```
|
||||
|
||||
## Quick Reference
|
||||
|
||||
| Security Area | Implementation |
|
||||
|--------------|----------------|
|
||||
| **Password hashing** | `bcrypt.hash(password, 12)` |
|
||||
| **JWT Access Token** | 15 minutes expiry |
|
||||
| **JWT Refresh Token** | 7 days expiry |
|
||||
| **Rate limiting** | Standard: 100/15min, Strict: 10/hour, Login: 5/15min |
|
||||
| **Encryption** | AES-256-GCM for PII |
|
||||
| **Input validation** | Zod schemas, always parse before use |
|
||||
| **SQL injection** | Use Prisma (parameterized by default) |
|
||||
| **Security headers** | helmet middleware |
|
||||
| **CORS** | Whitelist origins, credentials: true |
|
||||
|
||||
**Essential Imports:**
|
||||
```typescript
|
||||
import bcrypt from 'bcrypt';
|
||||
import helmet from 'helmet';
|
||||
import rateLimit from 'express-rate-limit';
|
||||
import { z } from 'zod';
|
||||
import { jwtService } from '@goodgo/auth-sdk';
|
||||
```
|
||||
|
||||
## Resources
|
||||
|
||||
- [OWASP Top 10](https://owasp.org/www-project-top-ten/)
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
---
|
||||
name: service-discovery-registry
|
||||
description: Service discovery and registry patterns for GoodGo microservices including service registry, health check orchestration, load balancing strategies, and service mesh integration. Use when implementing service discovery, managing service health, or integrating with service mesh.
|
||||
description: Service discovery patterns for GoodGo microservices. Use for service registry, health checks, load balancing, or service mesh integration.
|
||||
dependencies: "kubernetes, istio (optional)"
|
||||
---
|
||||
|
||||
# Service Discovery & Registry Patterns
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
---
|
||||
name: service-layer-patterns
|
||||
description: Service layer organization and patterns for GoodGo microservices. Use when implementing business logic, organizing service classes, using dependency injection, composing services, or separating concerns between controllers and repositories.
|
||||
description: Service layer patterns for GoodGo microservices. Use for business logic, dependency injection, service composition, or controller-repository separation.
|
||||
dependencies: "typescript>=5"
|
||||
---
|
||||
|
||||
# Service Layer Patterns
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
---
|
||||
name: testing-patterns
|
||||
description: Testing best practices for GoodGo microservices. Use when writing unit tests, integration tests, E2E tests, setting up Jest, mocking dependencies, or debugging test failures.
|
||||
description: Testing best practices for GoodGo microservices. Use for unit tests, integration tests, E2E tests, Jest setup, mocking, or debugging.
|
||||
dependencies: "jest>=29, supertest>=6, jest-mock-extended"
|
||||
---
|
||||
|
||||
# Testing Patterns for GoodGo Microservices
|
||||
@@ -489,4 +490,33 @@ test('should paginate results', async () => {
|
||||
- [ ] Maintain >70% code coverage
|
||||
- [ ] Run tests before committing
|
||||
- [ ] Keep test data realistic
|
||||
- [ ] Clean up after tests
|
||||
- [ ] Clean up after tests
|
||||
|
||||
## Quick Reference
|
||||
|
||||
| Test Type | Location | Speed | Mocking |
|
||||
|-----------|----------|-------|---------|
|
||||
| **Unit** | `*.test.ts` (next to source) | <1s | All dependencies |
|
||||
| **Integration** | `__tests__/` | 1-5s | Partial |
|
||||
| **E2E** | `__tests__/*.e2e.ts` | 5-10s | External APIs only |
|
||||
|
||||
**Coverage Targets:**
|
||||
- Global: 70%+ (branches, functions, lines)
|
||||
- Critical paths: 90%+
|
||||
- Repositories/Services: 80%+
|
||||
|
||||
**Essential Commands:**
|
||||
```bash
|
||||
pnpm test # Run all tests
|
||||
pnpm test:watch # Watch mode
|
||||
pnpm test:coverage # With coverage
|
||||
pnpm test -- --runInBand # Sequential (for debugging)
|
||||
pnpm test -- UserService # Run specific test file
|
||||
```
|
||||
|
||||
**Mock Imports:**
|
||||
```typescript
|
||||
import { mockDeep } from 'jest-mock-extended';
|
||||
import { prismaMock } from '../__mocks__/prisma';
|
||||
import supertest from 'supertest';
|
||||
```
|
||||
Reference in New Issue
Block a user