cortex-agents 1.1.0 → 2.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.opencode/agents/build.md +34 -3
- package/.opencode/agents/debug.md +24 -2
- package/.opencode/agents/devops.md +1 -2
- package/.opencode/agents/fullstack.md +1 -2
- package/.opencode/agents/plan.md +5 -3
- package/.opencode/agents/security.md +1 -2
- package/.opencode/agents/testing.md +1 -2
- package/.opencode/skills/api-design/SKILL.md +348 -0
- package/.opencode/skills/architecture-patterns/SKILL.md +323 -0
- package/.opencode/skills/backend-development/SKILL.md +329 -0
- package/.opencode/skills/code-quality/SKILL.md +12 -0
- package/.opencode/skills/database-design/SKILL.md +347 -0
- package/.opencode/skills/deployment-automation/SKILL.md +7 -0
- package/.opencode/skills/design-patterns/SKILL.md +295 -0
- package/.opencode/skills/desktop-development/SKILL.md +295 -0
- package/.opencode/skills/frontend-development/SKILL.md +210 -0
- package/.opencode/skills/mobile-development/SKILL.md +407 -0
- package/.opencode/skills/performance-optimization/SKILL.md +330 -0
- package/.opencode/skills/testing-strategies/SKILL.md +33 -0
- package/README.md +390 -76
- package/dist/cli.js +249 -27
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +38 -0
- package/dist/plugin.js +3 -2
- package/dist/registry.d.ts +45 -0
- package/dist/registry.d.ts.map +1 -0
- package/dist/registry.js +140 -0
- package/dist/tools/cortex.d.ts.map +1 -1
- package/dist/tools/cortex.js +2 -3
- package/dist/tools/docs.d.ts +52 -0
- package/dist/tools/docs.d.ts.map +1 -0
- package/dist/tools/docs.js +328 -0
- package/package.json +11 -4
- package/.opencode/skills/web-development/SKILL.md +0 -122
|
@@ -0,0 +1,323 @@
|
|
|
1
|
+
---
|
|
2
|
+
name: architecture-patterns
|
|
3
|
+
description: Microservices, monolith, event-driven, CQRS, hexagonal, clean architecture, serverless, and the twelve-factor methodology
|
|
4
|
+
license: Apache-2.0
|
|
5
|
+
compatibility: opencode
|
|
6
|
+
---
|
|
7
|
+
|
|
8
|
+
# Architecture Patterns Skill
|
|
9
|
+
|
|
10
|
+
This skill provides guidance on choosing and implementing software architecture patterns for scalable systems.
|
|
11
|
+
|
|
12
|
+
## When to Use
|
|
13
|
+
|
|
14
|
+
Use this skill when:
|
|
15
|
+
- Designing new systems or services from scratch
|
|
16
|
+
- Evaluating architecture for scaling or refactoring
|
|
17
|
+
- Choosing between monolith, microservices, or serverless
|
|
18
|
+
- Implementing event-driven, CQRS, or clean architecture
|
|
19
|
+
- Making technology and infrastructure decisions
|
|
20
|
+
|
|
21
|
+
## Architecture Decision Framework
|
|
22
|
+
|
|
23
|
+
### Key Questions
|
|
24
|
+
1. **Scale** — How many users/requests? Expected growth?
|
|
25
|
+
2. **Team** — How large? How autonomous? How distributed?
|
|
26
|
+
3. **Complexity** — How complex is the domain logic?
|
|
27
|
+
4. **Velocity** — How fast do you need to ship?
|
|
28
|
+
5. **Constraints** — Budget, compliance, existing infrastructure?
|
|
29
|
+
|
|
30
|
+
### Quick Decision Matrix
|
|
31
|
+
| Situation | Recommended Architecture |
|
|
32
|
+
|-----------|--------------------------|
|
|
33
|
+
| Small team, new product, uncertain requirements | Modular Monolith |
|
|
34
|
+
| Large team, well-defined domains, independent deploy | Microservices |
|
|
35
|
+
| High throughput, loose coupling, eventual consistency OK | Event-Driven |
|
|
36
|
+
| Read-heavy with complex queries, different read/write models | CQRS |
|
|
37
|
+
| Spiky workloads, pay-per-use, rapid prototyping | Serverless |
|
|
38
|
+
| Complex domain logic, long-lived system | Clean/Hexagonal + DDD |
|
|
39
|
+
|
|
40
|
+
## Monolithic Architecture
|
|
41
|
+
|
|
42
|
+
### When to Use
|
|
43
|
+
- Early-stage products — ship fast, iterate quickly
|
|
44
|
+
- Small teams (< 10 developers)
|
|
45
|
+
- Simple domain with clear boundaries
|
|
46
|
+
- Shared database is acceptable
|
|
47
|
+
|
|
48
|
+
### Modular Monolith (Recommended Starting Point)
|
|
49
|
+
```
|
|
50
|
+
src/
|
|
51
|
+
modules/
|
|
52
|
+
users/ # Self-contained user module
|
|
53
|
+
routes.ts
|
|
54
|
+
service.ts
|
|
55
|
+
repository.ts
|
|
56
|
+
models.ts
|
|
57
|
+
orders/ # Self-contained order module
|
|
58
|
+
routes.ts
|
|
59
|
+
service.ts
|
|
60
|
+
repository.ts
|
|
61
|
+
models.ts
|
|
62
|
+
shared/ # Shared kernel
|
|
63
|
+
auth/
|
|
64
|
+
database/
|
|
65
|
+
events/
|
|
66
|
+
app.ts
|
|
67
|
+
```
|
|
68
|
+
|
|
69
|
+
### Laravel Modular Monolith
|
|
70
|
+
```
|
|
71
|
+
app/
|
|
72
|
+
Modules/
|
|
73
|
+
Users/ # Self-contained user module
|
|
74
|
+
Controllers/
|
|
75
|
+
Models/
|
|
76
|
+
Services/
|
|
77
|
+
Repositories/
|
|
78
|
+
Routes/
|
|
79
|
+
Providers/UserServiceProvider.php
|
|
80
|
+
Orders/ # Self-contained order module
|
|
81
|
+
Controllers/
|
|
82
|
+
Models/
|
|
83
|
+
Services/
|
|
84
|
+
Events/
|
|
85
|
+
Providers/OrderServiceProvider.php
|
|
86
|
+
Providers/ # Core service providers
|
|
87
|
+
```
|
|
88
|
+
- Use Laravel service providers to register each module
|
|
89
|
+
- Communicate between modules via events or defined interfaces
|
|
90
|
+
- Laravel's service container makes modular DI natural
|
|
91
|
+
- Can also use packages like `nwidart/laravel-modules`
|
|
92
|
+
|
|
93
|
+
### Key Principles
|
|
94
|
+
- Module boundaries enforced by convention or linting
|
|
95
|
+
- Modules communicate through defined interfaces, not direct DB access
|
|
96
|
+
- Each module owns its database tables
|
|
97
|
+
- Can extract to microservices later with minimal refactoring
|
|
98
|
+
|
|
99
|
+
### Strangler Fig Migration
|
|
100
|
+
- Incrementally replace monolith functionality with new services
|
|
101
|
+
- Route traffic through a facade that delegates to old or new
|
|
102
|
+
- Never big-bang rewrite — decompose gradually
|
|
103
|
+
|
|
104
|
+
## Microservices Architecture
|
|
105
|
+
|
|
106
|
+
### Service Design
|
|
107
|
+
- One service per business capability (bounded context)
|
|
108
|
+
- Services own their data — no shared databases
|
|
109
|
+
- API contracts between services (REST, gRPC, events)
|
|
110
|
+
- Independent deployment and scaling
|
|
111
|
+
|
|
112
|
+
### Communication Patterns
|
|
113
|
+
| Pattern | Type | Use When |
|
|
114
|
+
|---------|------|----------|
|
|
115
|
+
| REST/gRPC | Synchronous | Request needs immediate response |
|
|
116
|
+
| Message Queue | Asynchronous | Fire-and-forget, decoupled processing |
|
|
117
|
+
| Event Bus | Asynchronous | Multiple consumers need to react |
|
|
118
|
+
| Saga | Orchestrated | Distributed transactions across services |
|
|
119
|
+
|
|
120
|
+
### Saga Pattern for Distributed Transactions
|
|
121
|
+
```mermaid
|
|
122
|
+
sequenceDiagram
|
|
123
|
+
participant OS as Order Service
|
|
124
|
+
participant PS as Payment Service
|
|
125
|
+
participant IS as Inventory Service
|
|
126
|
+
|
|
127
|
+
OS->>PS: Process payment
|
|
128
|
+
PS-->>OS: Payment confirmed
|
|
129
|
+
OS->>IS: Reserve inventory
|
|
130
|
+
IS-->>OS: Inventory reserved
|
|
131
|
+
OS->>OS: Order confirmed
|
|
132
|
+
|
|
133
|
+
Note over OS,IS: If any step fails,<br/>compensating actions<br/>undo previous steps
|
|
134
|
+
```
|
|
135
|
+
|
|
136
|
+
### Service Mesh & Discovery
|
|
137
|
+
- Service discovery — Consul, Kubernetes DNS, AWS Cloud Map
|
|
138
|
+
- Load balancing — round-robin, least connections, weighted
|
|
139
|
+
- Circuit breaker — prevent cascade failures (Hystrix pattern)
|
|
140
|
+
- Service mesh — Istio, Linkerd for observability and traffic management
|
|
141
|
+
|
|
142
|
+
### Anti-Patterns to Avoid
|
|
143
|
+
- Distributed monolith — services tightly coupled, must deploy together
|
|
144
|
+
- Nano-services — too granular, excessive network overhead
|
|
145
|
+
- Shared database — defeats data ownership principle
|
|
146
|
+
- Synchronous chains — fragile, high latency
|
|
147
|
+
|
|
148
|
+
## Event-Driven Architecture
|
|
149
|
+
|
|
150
|
+
### Core Concepts
|
|
151
|
+
- **Event** — Immutable fact that something happened
|
|
152
|
+
- **Producer** — Service that emits events
|
|
153
|
+
- **Consumer** — Service that reacts to events
|
|
154
|
+
- **Event Bus** — Infrastructure for routing events (Kafka, RabbitMQ, NATS)
|
|
155
|
+
|
|
156
|
+
### Event Types
|
|
157
|
+
| Type | Description | Example |
|
|
158
|
+
|------|-------------|---------|
|
|
159
|
+
| Domain Event | Business-meaningful occurrence | `OrderPlaced`, `UserRegistered` |
|
|
160
|
+
| Integration Event | Cross-boundary notification | `PaymentProcessed` |
|
|
161
|
+
| Command Event | Request to perform action | `ProcessPayment` |
|
|
162
|
+
|
|
163
|
+
### Event Sourcing
|
|
164
|
+
- Store state as a sequence of events, not current snapshot
|
|
165
|
+
- Rebuild state by replaying events from the beginning
|
|
166
|
+
- Enables audit trail, temporal queries, debugging
|
|
167
|
+
- **Trade-off**: Complex to implement, eventual consistency
|
|
168
|
+
|
|
169
|
+
```
|
|
170
|
+
Event Store:
|
|
171
|
+
1. OrderCreated { items: [...], userId: "123" }
|
|
172
|
+
2. ItemAdded { itemId: "abc", quantity: 2 }
|
|
173
|
+
3. PaymentProcessed { amount: 99.99 }
|
|
174
|
+
4. OrderShipped { trackingId: "XYZ" }
|
|
175
|
+
|
|
176
|
+
Current State = replay(events) → Order { status: "shipped", ... }
|
|
177
|
+
```
|
|
178
|
+
|
|
179
|
+
### Best Practices
|
|
180
|
+
- Events are immutable — never modify published events
|
|
181
|
+
- Include correlation ID for tracing across services
|
|
182
|
+
- Use schema registry for event versioning (Avro, Protobuf)
|
|
183
|
+
- Dead letter queue for failed event processing
|
|
184
|
+
- Idempotent consumers — safe to process the same event twice
|
|
185
|
+
|
|
186
|
+
## CQRS (Command Query Responsibility Segregation)
|
|
187
|
+
|
|
188
|
+
### Core Idea
|
|
189
|
+
- Separate read model (queries) from write model (commands)
|
|
190
|
+
- Read side optimized for queries — denormalized, cached
|
|
191
|
+
- Write side optimized for business rules — normalized, validated
|
|
192
|
+
|
|
193
|
+
```
|
|
194
|
+
┌─────────────┐ ┌─────────────┐
|
|
195
|
+
│ Command │ │ Query │
|
|
196
|
+
│ (Write) │ │ (Read) │
|
|
197
|
+
├─────────────┤ ├─────────────┤
|
|
198
|
+
│ Validate │ │ Optimized │
|
|
199
|
+
│ Business │ │ Read Models │
|
|
200
|
+
│ Rules │ │ (Views) │
|
|
201
|
+
├─────────────┤ ├─────────────┤
|
|
202
|
+
│ Write DB │────>│ Read DB │
|
|
203
|
+
│ (Normalized) │event│ (Denorm.) │
|
|
204
|
+
└─────────────┘ └─────────────┘
|
|
205
|
+
```
|
|
206
|
+
|
|
207
|
+
### When to Use
|
|
208
|
+
- Read and write workloads have very different characteristics
|
|
209
|
+
- Complex domain logic on write side, simple queries on read side
|
|
210
|
+
- Need to scale reads and writes independently
|
|
211
|
+
- Combined with event sourcing for full audit trail
|
|
212
|
+
|
|
213
|
+
### When NOT to Use
|
|
214
|
+
- Simple CRUD applications — adds unnecessary complexity
|
|
215
|
+
- Strong consistency required — read model has eventual consistency lag
|
|
216
|
+
- Small team — operational overhead not justified
|
|
217
|
+
|
|
218
|
+
## Clean / Hexagonal Architecture
|
|
219
|
+
|
|
220
|
+
### Hexagonal Architecture (Ports & Adapters)
|
|
221
|
+
```
|
|
222
|
+
┌─────────────────────────────────┐
|
|
223
|
+
│ Adapters (Outer) │
|
|
224
|
+
│ ┌─────────────────────────┐ │
|
|
225
|
+
│ │ Application Core │ │
|
|
226
|
+
│ │ ┌───────────────────┐ │ │
|
|
227
|
+
Driving │ │ │ │ │ │ Driven
|
|
228
|
+
Adapters │ │ │ Domain Model │ │ │ Adapters
|
|
229
|
+
(API, │──│──│ (Entities, Value │──│────│──(DB, Email,
|
|
230
|
+
CLI, │ │ │ Objects, Rules) │ │ │ Queue,
|
|
231
|
+
Tests) │ │ │ │ │ │ External)
|
|
232
|
+
│ │ └───────────────────┘ │ │
|
|
233
|
+
│ │ Use Cases / Ports │ │
|
|
234
|
+
│ └─────────────────────────┘ │
|
|
235
|
+
└─────────────────────────────────┘
|
|
236
|
+
```
|
|
237
|
+
|
|
238
|
+
### Key Rules
|
|
239
|
+
- Domain has ZERO external dependencies — no frameworks, no DB
|
|
240
|
+
- Ports (interfaces) define what the domain needs
|
|
241
|
+
- Adapters implement ports — pluggable infrastructure
|
|
242
|
+
- Dependencies point inward — outer layers depend on inner
|
|
243
|
+
- Test domain logic without infrastructure
|
|
244
|
+
|
|
245
|
+
### Clean Architecture Layers
|
|
246
|
+
| Layer | Contains | Depends On |
|
|
247
|
+
|-------|----------|------------|
|
|
248
|
+
| Entities | Business objects, rules | Nothing |
|
|
249
|
+
| Use Cases | Application logic, orchestration | Entities |
|
|
250
|
+
| Interface Adapters | Controllers, presenters, gateways | Use Cases |
|
|
251
|
+
| Frameworks | Web framework, DB, external services | Interface Adapters |
|
|
252
|
+
|
|
253
|
+
## Serverless Architecture
|
|
254
|
+
|
|
255
|
+
### Patterns
|
|
256
|
+
- **API + Functions** — API Gateway + Lambda/Cloud Functions
|
|
257
|
+
- **Event Processing** — Functions triggered by events (S3, Queue, DB)
|
|
258
|
+
- **Scheduled Jobs** — CRON-triggered functions
|
|
259
|
+
- **Step Functions** — Orchestrated workflows
|
|
260
|
+
|
|
261
|
+
### Benefits
|
|
262
|
+
- Zero idle cost — pay only for execution
|
|
263
|
+
- Auto-scaling — from 0 to thousands of instances
|
|
264
|
+
- No server management — focus on business logic
|
|
265
|
+
|
|
266
|
+
### Limitations
|
|
267
|
+
- Cold starts — latency spike on first invocation (mitigated with provisioned concurrency)
|
|
268
|
+
- Execution duration limits (15 min Lambda, 60 min Cloud Run)
|
|
269
|
+
- Stateless — no local state between invocations
|
|
270
|
+
- Vendor lock-in — tight coupling to cloud provider APIs
|
|
271
|
+
- Debugging complexity — distributed tracing required
|
|
272
|
+
|
|
273
|
+
### Best Practices
|
|
274
|
+
- Keep functions small and focused — one function, one purpose
|
|
275
|
+
- Use environment variables for configuration
|
|
276
|
+
- Implement structured logging with correlation IDs
|
|
277
|
+
- Use layers/extensions for shared code
|
|
278
|
+
- Test locally with emulators (SAM, serverless-offline, Functions Framework)
|
|
279
|
+
|
|
280
|
+
## The Twelve-Factor App
|
|
281
|
+
|
|
282
|
+
| # | Factor | Summary |
|
|
283
|
+
|---|--------|---------|
|
|
284
|
+
| 1 | Codebase | One codebase tracked in version control, many deploys |
|
|
285
|
+
| 2 | Dependencies | Explicitly declare and isolate dependencies |
|
|
286
|
+
| 3 | Config | Store config in environment variables |
|
|
287
|
+
| 4 | Backing Services | Treat databases, queues, caches as attached resources |
|
|
288
|
+
| 5 | Build, Release, Run | Strictly separate build, release, and run stages |
|
|
289
|
+
| 6 | Processes | Execute app as stateless processes |
|
|
290
|
+
| 7 | Port Binding | Export services via port binding |
|
|
291
|
+
| 8 | Concurrency | Scale out via the process model |
|
|
292
|
+
| 9 | Disposability | Fast startup, graceful shutdown |
|
|
293
|
+
| 10 | Dev/Prod Parity | Keep development and production as similar as possible |
|
|
294
|
+
| 11 | Logs | Treat logs as event streams |
|
|
295
|
+
| 12 | Admin Processes | Run admin tasks as one-off processes |
|
|
296
|
+
|
|
297
|
+
### Modern Additions
|
|
298
|
+
- **API First** — Design APIs before implementation
|
|
299
|
+
- **Telemetry** — Built-in observability (metrics, traces, logs)
|
|
300
|
+
- **Security** — Security as a first-class concern, not an afterthought
|
|
301
|
+
- **Authentication** — Externalize auth (OAuth, OIDC)
|
|
302
|
+
|
|
303
|
+
## Data Architecture Patterns
|
|
304
|
+
|
|
305
|
+
### Data Mesh
|
|
306
|
+
- Domain-oriented data ownership — each team owns their data products
|
|
307
|
+
- Data as a product — treat datasets with the same care as user-facing features
|
|
308
|
+
- Self-serve data platform — infrastructure that enables domain teams
|
|
309
|
+
- Federated governance — global policies, local implementation
|
|
310
|
+
|
|
311
|
+
### Event Streaming Platform
|
|
312
|
+
- Central event bus (Kafka, Pulumi) as source of truth
|
|
313
|
+
- Services produce and consume events
|
|
314
|
+
- Enables real-time analytics and derived views
|
|
315
|
+
- Replay capability for rebuilding state
|
|
316
|
+
|
|
317
|
+
### OLTP vs OLAP
|
|
318
|
+
| Characteristic | OLTP | OLAP |
|
|
319
|
+
|---------------|------|------|
|
|
320
|
+
| Operations | INSERT, UPDATE, DELETE | SELECT, aggregate |
|
|
321
|
+
| Queries | Simple, row-level | Complex, analytical |
|
|
322
|
+
| Schema | Normalized (3NF) | Denormalized (star/snowflake) |
|
|
323
|
+
| Examples | PostgreSQL, MySQL | BigQuery, Snowflake, ClickHouse |
|
|
@@ -0,0 +1,329 @@
|
|
|
1
|
+
---
|
|
2
|
+
name: backend-development
|
|
3
|
+
description: Server architecture, framework patterns, data access, caching, authentication, and error handling for backend applications
|
|
4
|
+
license: Apache-2.0
|
|
5
|
+
compatibility: opencode
|
|
6
|
+
---
|
|
7
|
+
|
|
8
|
+
# Backend Development Skill
|
|
9
|
+
|
|
10
|
+
This skill provides patterns and best practices for building robust backend applications and services.
|
|
11
|
+
|
|
12
|
+
## When to Use
|
|
13
|
+
|
|
14
|
+
Use this skill when:
|
|
15
|
+
- Building APIs or server-side applications
|
|
16
|
+
- Choosing a backend framework or architecture
|
|
17
|
+
- Implementing data access layers, caching, or auth
|
|
18
|
+
- Setting up middleware, error handling, or background processing
|
|
19
|
+
- Designing server architecture for scalability
|
|
20
|
+
|
|
21
|
+
## Server Architecture
|
|
22
|
+
|
|
23
|
+
### Layered Architecture
|
|
24
|
+
```
|
|
25
|
+
┌──────────────────────────┐
|
|
26
|
+
│ Routes / Controllers │ ← HTTP handling, validation
|
|
27
|
+
├──────────────────────────┤
|
|
28
|
+
│ Services / Use Cases │ ← Business logic
|
|
29
|
+
├──────────────────────────┤
|
|
30
|
+
│ Repositories / DAL │ ← Data access
|
|
31
|
+
├──────────────────────────┤
|
|
32
|
+
│ Database / External │ ← Persistence, third-party
|
|
33
|
+
└──────────────────────────┘
|
|
34
|
+
```
|
|
35
|
+
|
|
36
|
+
### Key Principles
|
|
37
|
+
- Separate concerns — routes, business logic, data access in distinct layers
|
|
38
|
+
- Dependency injection — invert dependencies for testability
|
|
39
|
+
- Single responsibility — each module handles one concern
|
|
40
|
+
- Fail fast — validate inputs at the boundary
|
|
41
|
+
- Configuration via environment — never hardcode secrets or URLs
|
|
42
|
+
|
|
43
|
+
## Framework Patterns
|
|
44
|
+
|
|
45
|
+
### Node.js
|
|
46
|
+
|
|
47
|
+
**Express** — Minimal, middleware-based
|
|
48
|
+
```typescript
|
|
49
|
+
// Layered Express app structure
|
|
50
|
+
src/
|
|
51
|
+
routes/ // Route definitions, input validation
|
|
52
|
+
middleware/ // Auth, logging, error handling
|
|
53
|
+
services/ // Business logic
|
|
54
|
+
repositories/ // Database queries
|
|
55
|
+
models/ // Type definitions, schemas
|
|
56
|
+
utils/ // Shared utilities
|
|
57
|
+
app.ts // Express app setup
|
|
58
|
+
server.ts // Server startup
|
|
59
|
+
```
|
|
60
|
+
|
|
61
|
+
**Fastify** — Performance-focused, schema-based validation
|
|
62
|
+
- Use JSON Schema for request/response validation (built-in)
|
|
63
|
+
- Plugin system for encapsulated modules
|
|
64
|
+
- Decorators for extending request/reply
|
|
65
|
+
|
|
66
|
+
**NestJS** — Opinionated, Angular-inspired
|
|
67
|
+
- Modules for feature encapsulation
|
|
68
|
+
- Decorators for routing, validation, guards
|
|
69
|
+
- Built-in DI container
|
|
70
|
+
- Pipes, Guards, Interceptors for request pipeline
|
|
71
|
+
|
|
72
|
+
### Python
|
|
73
|
+
|
|
74
|
+
**FastAPI** — Modern, async, type-driven
|
|
75
|
+
- Pydantic models for validation and serialization
|
|
76
|
+
- Dependency injection via `Depends()`
|
|
77
|
+
- Auto-generated OpenAPI docs
|
|
78
|
+
- Background tasks with `BackgroundTasks`
|
|
79
|
+
- Async database with SQLAlchemy + asyncpg
|
|
80
|
+
|
|
81
|
+
**Django** — Batteries-included, ORM-centric
|
|
82
|
+
- Models define schema and business rules
|
|
83
|
+
- Class-based views for CRUD operations
|
|
84
|
+
- Django REST Framework for API endpoints
|
|
85
|
+
- Admin interface for quick data management
|
|
86
|
+
- Middleware pipeline for cross-cutting concerns
|
|
87
|
+
|
|
88
|
+
### Go
|
|
89
|
+
|
|
90
|
+
**Gin/Echo** — Fast, minimal HTTP frameworks
|
|
91
|
+
- Handler functions with context
|
|
92
|
+
- Middleware chains for cross-cutting concerns
|
|
93
|
+
- Struct tags for binding and validation
|
|
94
|
+
- Goroutines for concurrent processing
|
|
95
|
+
|
|
96
|
+
```go
|
|
97
|
+
// Clean handler pattern in Go
|
|
98
|
+
func (h *UserHandler) GetUser(c *gin.Context) {
|
|
99
|
+
id := c.Param("id")
|
|
100
|
+
user, err := h.service.FindByID(c.Request.Context(), id)
|
|
101
|
+
if err != nil {
|
|
102
|
+
c.JSON(http.StatusNotFound, gin.H{"error": "user not found"})
|
|
103
|
+
return
|
|
104
|
+
}
|
|
105
|
+
c.JSON(http.StatusOK, user)
|
|
106
|
+
}
|
|
107
|
+
```
|
|
108
|
+
|
|
109
|
+
### PHP
|
|
110
|
+
|
|
111
|
+
**Laravel** — Full-featured, elegant, batteries-included
|
|
112
|
+
```php
|
|
113
|
+
// Layered Laravel app structure
|
|
114
|
+
app/
|
|
115
|
+
Http/
|
|
116
|
+
Controllers/ // Route handlers, form requests
|
|
117
|
+
Middleware/ // Auth, CORS, rate limiting
|
|
118
|
+
Requests/ // Form request validation
|
|
119
|
+
Resources/ // API resource transformations
|
|
120
|
+
Models/ // Eloquent models
|
|
121
|
+
Services/ // Business logic
|
|
122
|
+
Repositories/ // Data access abstraction (optional)
|
|
123
|
+
Jobs/ // Queued background jobs
|
|
124
|
+
Events/ // Domain events
|
|
125
|
+
Listeners/ // Event handlers
|
|
126
|
+
Policies/ // Authorization logic
|
|
127
|
+
routes/
|
|
128
|
+
api.php // API routes
|
|
129
|
+
web.php // Web routes
|
|
130
|
+
```
|
|
131
|
+
|
|
132
|
+
- Service container for dependency injection (auto-resolving)
|
|
133
|
+
- Middleware pipeline (global, route groups, per-route)
|
|
134
|
+
- Eloquent ORM with expressive Active Record pattern
|
|
135
|
+
- Artisan CLI for code generation, migrations, and tasks
|
|
136
|
+
- Built-in auth scaffolding (Breeze, Jetstream, Fortify)
|
|
137
|
+
|
|
138
|
+
**Symfony** — Enterprise-grade, component-based
|
|
139
|
+
- Bundle architecture for modular features
|
|
140
|
+
- Doctrine ORM (Data Mapper pattern)
|
|
141
|
+
- Flex for automated package configuration
|
|
142
|
+
- Powerful DI container and event dispatcher
|
|
143
|
+
- Strong enterprise and long-term support tradition
|
|
144
|
+
|
|
145
|
+
### Rust
|
|
146
|
+
|
|
147
|
+
**Actix Web / Axum** — Type-safe, async, performant
|
|
148
|
+
- Extractors for type-safe request parsing
|
|
149
|
+
- Tower middleware (Axum) for composable layers
|
|
150
|
+
- Strong type system prevents runtime errors
|
|
151
|
+
- Shared state via Arc<AppState>
|
|
152
|
+
|
|
153
|
+
## Middleware & Request Pipeline
|
|
154
|
+
|
|
155
|
+
### Common Middleware Stack (in order)
|
|
156
|
+
1. **Request ID** — Generate unique ID for tracing
|
|
157
|
+
2. **Logging** — Log request method, path, duration
|
|
158
|
+
3. **CORS** — Configure allowed origins, methods, headers
|
|
159
|
+
4. **Rate limiting** — Protect against abuse (token bucket, sliding window)
|
|
160
|
+
5. **Authentication** — Verify JWT/session/API key
|
|
161
|
+
6. **Authorization** — Check permissions for resource
|
|
162
|
+
7. **Validation** — Validate request body, params, query
|
|
163
|
+
8. **Handler** — Execute business logic
|
|
164
|
+
9. **Error handler** — Catch and format errors consistently
|
|
165
|
+
|
|
166
|
+
### Middleware Best Practices
|
|
167
|
+
- Keep middleware focused — one concern each
|
|
168
|
+
- Order matters — auth before authorization, logging first
|
|
169
|
+
- Short-circuit early — return 401/403 before processing
|
|
170
|
+
- Use async middleware for I/O-bound operations
|
|
171
|
+
|
|
172
|
+
## Data Access
|
|
173
|
+
|
|
174
|
+
### Repository Pattern
|
|
175
|
+
```typescript
|
|
176
|
+
// Abstract data access behind interfaces
|
|
177
|
+
interface UserRepository {
|
|
178
|
+
findById(id: string): Promise<User | null>;
|
|
179
|
+
findByEmail(email: string): Promise<User | null>;
|
|
180
|
+
create(data: CreateUserDTO): Promise<User>;
|
|
181
|
+
update(id: string, data: UpdateUserDTO): Promise<User>;
|
|
182
|
+
delete(id: string): Promise<void>;
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
// Implement with your ORM of choice
|
|
186
|
+
class PrismaUserRepository implements UserRepository {
|
|
187
|
+
constructor(private prisma: PrismaClient) {}
|
|
188
|
+
|
|
189
|
+
async findById(id: string): Promise<User | null> {
|
|
190
|
+
return this.prisma.user.findUnique({ where: { id } });
|
|
191
|
+
}
|
|
192
|
+
// ...
|
|
193
|
+
}
|
|
194
|
+
```
|
|
195
|
+
|
|
196
|
+
### ORM Selection Guide
|
|
197
|
+
| ORM | Language | Style | Best For |
|
|
198
|
+
|-----|----------|-------|----------|
|
|
199
|
+
| Prisma | TypeScript | Schema-first, type-safe | New Node.js projects |
|
|
200
|
+
| Drizzle | TypeScript | SQL-like, lightweight | Performance-critical |
|
|
201
|
+
| SQLAlchemy | Python | Flexible, powerful | Complex queries |
|
|
202
|
+
| Django ORM | Python | Active Record | Django projects |
|
|
203
|
+
| Eloquent | PHP | Active Record, expressive | Laravel projects |
|
|
204
|
+
| Doctrine | PHP | Data Mapper, enterprise | Symfony projects |
|
|
205
|
+
| GORM | Go | Convention-based | Go web apps |
|
|
206
|
+
| Diesel | Rust | Compile-time checked | Rust applications |
|
|
207
|
+
|
|
208
|
+
### Query Best Practices
|
|
209
|
+
- Use parameterized queries — never string concatenation
|
|
210
|
+
- Eager load relations to avoid N+1 queries
|
|
211
|
+
- Paginate large result sets — cursor or offset-based
|
|
212
|
+
- Use transactions for multi-step writes
|
|
213
|
+
- Index frequently queried columns
|
|
214
|
+
|
|
215
|
+
## Caching Strategies
|
|
216
|
+
|
|
217
|
+
| Strategy | How It Works | Use Case |
|
|
218
|
+
|----------|-------------|----------|
|
|
219
|
+
| Cache-aside | App checks cache, falls back to DB | General purpose |
|
|
220
|
+
| Read-through | Cache loads from DB on miss | Transparent caching |
|
|
221
|
+
| Write-through | Write to cache and DB simultaneously | Consistency-critical |
|
|
222
|
+
| Write-behind | Write to cache, async write to DB | High write throughput |
|
|
223
|
+
|
|
224
|
+
### Implementation Patterns
|
|
225
|
+
- **Redis** for distributed cache — sessions, rate limiting, computed results
|
|
226
|
+
- **In-memory** (Map/LRU) for hot local data — config, feature flags
|
|
227
|
+
- **CDN** for static assets and API responses with proper Cache-Control
|
|
228
|
+
- **HTTP caching** — ETag, Last-Modified, Cache-Control headers
|
|
229
|
+
|
|
230
|
+
### Cache Invalidation
|
|
231
|
+
- TTL-based — set reasonable expiry times
|
|
232
|
+
- Event-based — invalidate on write operations
|
|
233
|
+
- Version-based — include version in cache key
|
|
234
|
+
- Pattern: `cache:${entity}:${id}:${version}`
|
|
235
|
+
|
|
236
|
+
## Authentication & Authorization
|
|
237
|
+
|
|
238
|
+
### Authentication Methods
|
|
239
|
+
| Method | Stateless | Best For |
|
|
240
|
+
|--------|-----------|----------|
|
|
241
|
+
| JWT (access + refresh) | Yes | SPAs, mobile apps |
|
|
242
|
+
| Session cookies | No | Traditional web apps |
|
|
243
|
+
| API keys | Yes | Service-to-service |
|
|
244
|
+
| OAuth 2.0 / OIDC | Yes | Third-party login |
|
|
245
|
+
|
|
246
|
+
### JWT Best Practices
|
|
247
|
+
- Short-lived access tokens (15 min) + long-lived refresh tokens
|
|
248
|
+
- Use RS256 or ES256 (asymmetric) over HS256 for distributed systems
|
|
249
|
+
- Store refresh tokens in httpOnly cookies (not localStorage)
|
|
250
|
+
- Implement token rotation on refresh
|
|
251
|
+
- Include minimal claims — don't put sensitive data in payload
|
|
252
|
+
|
|
253
|
+
### Authorization Patterns
|
|
254
|
+
- **RBAC** (Role-Based) — user has roles, roles have permissions
|
|
255
|
+
- **ABAC** (Attribute-Based) — policies based on user/resource attributes
|
|
256
|
+
- **Resource-based** — check ownership before access
|
|
257
|
+
- Centralize authorization logic — use middleware or decorators
|
|
258
|
+
|
|
259
|
+
## Error Handling
|
|
260
|
+
|
|
261
|
+
### Consistent Error Response
|
|
262
|
+
```typescript
|
|
263
|
+
// Standardized error response (RFC 7807 inspired)
|
|
264
|
+
interface ErrorResponse {
|
|
265
|
+
status: number; // HTTP status code
|
|
266
|
+
code: string; // Machine-readable error code
|
|
267
|
+
message: string; // Human-readable description
|
|
268
|
+
details?: unknown; // Validation errors, context
|
|
269
|
+
requestId?: string; // For support/debugging
|
|
270
|
+
}
|
|
271
|
+
```
|
|
272
|
+
|
|
273
|
+
### HTTP Status Code Guide
|
|
274
|
+
| Code | Meaning | Use When |
|
|
275
|
+
|------|---------|----------|
|
|
276
|
+
| 400 | Bad Request | Validation failure, malformed input |
|
|
277
|
+
| 401 | Unauthorized | Missing or invalid authentication |
|
|
278
|
+
| 403 | Forbidden | Authenticated but not authorized |
|
|
279
|
+
| 404 | Not Found | Resource doesn't exist |
|
|
280
|
+
| 409 | Conflict | Duplicate, version conflict |
|
|
281
|
+
| 422 | Unprocessable | Semantic validation failure |
|
|
282
|
+
| 429 | Too Many Requests | Rate limit exceeded |
|
|
283
|
+
| 500 | Internal Error | Unexpected server failure |
|
|
284
|
+
|
|
285
|
+
### Error Handling Best Practices
|
|
286
|
+
- Catch errors at the boundary — global error handler middleware
|
|
287
|
+
- Log errors with context (request ID, user, stack trace)
|
|
288
|
+
- Never expose internal details to clients in production
|
|
289
|
+
- Use custom error classes for business logic errors
|
|
290
|
+
- Return actionable error messages when possible
|
|
291
|
+
|
|
292
|
+
## Background Processing
|
|
293
|
+
|
|
294
|
+
### Job Queue Patterns
|
|
295
|
+
- **Laravel Queues** (PHP) — Redis/SQS/database drivers, retries, rate limiting, Horizon dashboard
|
|
296
|
+
- **BullMQ** (Node.js) — Redis-based, reliable, with retry and scheduling
|
|
297
|
+
- **Celery** (Python) — Distributed task queue with multiple brokers
|
|
298
|
+
- **Temporal** — Durable workflow orchestration (any language)
|
|
299
|
+
- **Asynq** (Go) — Simple Redis-based task queue
|
|
300
|
+
|
|
301
|
+
### Common Use Cases
|
|
302
|
+
- Email sending and notifications
|
|
303
|
+
- Image/video processing
|
|
304
|
+
- Report generation
|
|
305
|
+
- Data imports/exports
|
|
306
|
+
- Webhook delivery with retry
|
|
307
|
+
|
|
308
|
+
### Best Practices
|
|
309
|
+
- Idempotent jobs — safe to retry on failure
|
|
310
|
+
- Dead letter queue for permanently failed jobs
|
|
311
|
+
- Monitor queue depth and processing latency
|
|
312
|
+
- Set appropriate timeouts and retry limits
|
|
313
|
+
- Log job lifecycle (enqueued, started, completed, failed)
|
|
314
|
+
|
|
315
|
+
## Technology Recommendations
|
|
316
|
+
|
|
317
|
+
### By Use Case
|
|
318
|
+
| Use Case | Recommended Stack |
|
|
319
|
+
|----------|-------------------|
|
|
320
|
+
| REST API (TypeScript) | Fastify + Prisma + Redis |
|
|
321
|
+
| REST API (Python) | FastAPI + SQLAlchemy + Redis |
|
|
322
|
+
| REST API (PHP) | Laravel + Eloquent + Redis |
|
|
323
|
+
| Full-stack web (PHP) | Laravel + Livewire or Inertia.js |
|
|
324
|
+
| GraphQL API | NestJS + Apollo + Prisma |
|
|
325
|
+
| Microservice | Go + Gin + gRPC + NATS |
|
|
326
|
+
| Full-stack web (JS) | Next.js API routes or Django |
|
|
327
|
+
| High-performance | Rust + Axum + SQLx |
|
|
328
|
+
| Enterprise (PHP) | Laravel + Horizon + Octane |
|
|
329
|
+
| Enterprise (TS) | NestJS + TypeORM + BullMQ |
|
|
@@ -156,6 +156,14 @@ Sort alphabetically within groups.
|
|
|
156
156
|
- Use interfaces for abstraction
|
|
157
157
|
- Write table-driven tests
|
|
158
158
|
|
|
159
|
+
### PHP
|
|
160
|
+
- Follow PSR-12 coding standard
|
|
161
|
+
- Use strict types (`declare(strict_types=1)`)
|
|
162
|
+
- Leverage PHP 8+ features (enums, readonly, named args, match)
|
|
163
|
+
- Use type declarations for params, returns, and properties
|
|
164
|
+
- Follow Laravel conventions (if using Laravel)
|
|
165
|
+
- Use dependency injection over facades in application code
|
|
166
|
+
|
|
159
167
|
### Rust
|
|
160
168
|
- Run cargo fmt and clippy
|
|
161
169
|
- Use Result/Option
|
|
@@ -208,6 +216,10 @@ Sort alphabetically within groups.
|
|
|
208
216
|
### Tools
|
|
209
217
|
- **ESLint** - JavaScript/TypeScript
|
|
210
218
|
- **Prettier** - Multi-language formatter
|
|
219
|
+
- **PHP CS Fixer** - PHP formatter (PSR-12)
|
|
220
|
+
- **Laravel Pint** - Laravel's opinionated PHP formatter (built on CS Fixer)
|
|
221
|
+
- **PHPStan / Larastan** - PHP static analysis (levels 0-9)
|
|
222
|
+
- **Psalm** - PHP static analysis with type inference
|
|
211
223
|
- **Black** - Python formatter
|
|
212
224
|
- **Ruff** - Python linter
|
|
213
225
|
- **gofmt** - Go formatter
|