betting-brain-v3 / rules
brendadeeznuts1111/betting-brain-v3/.cursor/rules/cloudflare-workers.mdc
Cloudflare Workers specific patterns and requirements
Cursor rule8 starsChanged 12 months ago
---
version: "2.0.0"
globs: "src/**/*.ts,wrangler*.toml"
alwaysApply: true
description: "Cloudflare Workers specific patterns and requirements"
lastUpdated: "2025-10-08"
dependencies: ["quality-standards", "api-patterns", "endpoint-routing", "bun-runtime"]
---
# Cloudflare Workers Rules
## 🔍 Code Searchability Patterns
### Find cloudflare-workers Issues with ast-grep
```bash
# Find export default { fetch($$$) }
# Find env.$BINDING
# Find ctx.waitUntil($$$)
# Find new Response($$$)
ast-grep --pattern 'export default { fetch($$$) }' src/
ast-grep --pattern 'env.$BINDING' src/
ast-grep --pattern 'ctx.waitUntil($$$)' src/
ast-grep --pattern 'new Response($$$)' src/
sg -p 'export' src/
sg -p 'env.$BINDING' src/
sg -p 'ctx.waitUntil($$$)' src/
sg -p 'new' src/
```
### cloudflare-workers Discovery Commands
```bash
sg search "export default" src/
sg search "env." src/
sg search "ctx.waitUntil" src/
sg search "new Response" src/
```
### Search Examples
```bash
# Find worker entry points
sg search 'export' src/
# Find environment bindings
sg search 'env.$BINDING' src/
# Find background tasks
sg search 'ctx.waitUntil($$$)' src/
# Find response creation
sg search 'new' src/
```
## Entry Point
Main worker handler: [src/index.ts](mdc:src/index.ts)
```typescript
export default {
async fetch(request: Request, env: Env, ctx: ExecutionContext): Promise<Response> {
// Handle requests
}
}
```
## Environment Bindings
Configuration: [wrangler.toml](mdc:wrangler.toml)
### D1 Databases
- `ANALYTICS` - Main betting analytics database
- `RAW_FEED_DB` - Raw feed database
### KV Namespaces
- `BET_TICKER_RAW` - API response storage (7-day retention)
- `TOKEN_STORE` - Authentication tokens
- `USER_STORE` - User data
- `SESSION_STORE` - Active sessions
- `REFRESH_STORE` - Refresh tokens
- `LIVEBETS_STORE` - Live betting data
### Queues
- `LINE_INGRESS` - Line movement ingestion
- `STEAM_WEBHOOK` - Steam move notifications
- `STEAM_QUEUE` - Steam processing
- `EXPOSURE_QUEUE` - Exposure calculation
### Analytics Engine
- `ANALYTICS_ENGINE` - Metrics collection
## Routing Pattern
```typescript
const url = new URL(request.url);
// Route by pathname
switch (url.pathname) {
case '/health':
return handleHealth();
case '/mcp':
return handleMCPRequest(request, env);
case '/tools/getBettingExposure':
return handleTool(request, env);
// ...
}
```
## CORS Headers
Always include CORS headers for dashboard access:
```typescript
import { CORS_HEADERS, createOPTIONSResponse, createJSONResponse } from '../utils/request';
// Use CORS_HEADERS constant
// No need to define inline
// Handle OPTIONS preflight
if (request.method === 'OPTIONS') {
return createOPTIONSResponse();
}
// Use in responses (automatic with createJSONResponse)
return createJSONResponse({ data });
```
## Request ID Tracking
```typescript
import { generateRequestId } from '../utils/request';
import { createLogger } from '../utils/logger';
const requestId = generateRequestId();
const logger = createLogger(request);
logger.info('request_received', { requestId });
```
## Async Storage
Use `ctx.waitUntil()` for non-blocking operations:
```typescript
ctx.waitUntil(
env.KV.put(key, value, { expirationTtl: 86400 })
);
```
## Queue Consumers
```typescript
export default {
async queue(batch: MessageBatch, env: Env): Promise<void> {
for (const message of batch.messages) {
// Process message
message.ack();
}
}
}
```
## Scheduled Tasks
```typescript
export default {
async scheduled(event: ScheduledEvent, env: Env, ctx: ExecutionContext): Promise<void> {
// Run on cron schedule
}
}
```
## Type Definitions
See [src/types/api.ts](mdc:src/types/api.ts) for:
- `Env` interface - All bindings
- `BetTickerSnifferEnv` - BetTicker specific
- `MCPEnv` - MCP specific
## Limits
From [wrangler.toml](mdc:wrangler.toml):
```toml
[limits]
cpu_ms = 50 # 50ms CPU time limit per request
```
## Cost Guards
See [src/guards/costCap.ts](mdc:src/guards/costCap.ts) for:
- Hard cost limits
- Graceful degradation
- Request quotas
## Rate Limiting
See [src/guards/rateLimit.ts](mdc:src/guards/rateLimit.ts):
- 10 req/s per IP (in-memory, per-instance)
- ⚠️ Not shared across instances
- Consider Durable Objects for distributed rate limiting
## Deployment
```bash
# Deploy to default
wrangler deploy
# Deploy to production
wrangler deploy --env production
# Apply migrations first
wrangler d1 migrations apply betting-analytics --remote
```
## Environments
- Base: [wrangler.toml](mdc:wrangler.toml)
- Staging: [wrangler.staging.toml](mdc:wrangler.staging.toml)
- Production: [wrangler.production.toml](mdc:wrangler.production.toml)
---
## Related Rules
- [Quality Standards](mdc:.cursor/rules/quality-standards.mdc) - Code quality standards ⭐ **NEW**
- [API Patterns](mdc:.cursor/rules/api-patterns.mdc) - API design patterns
- [Endpoint Routing](mdc:.cursor/rules/endpoint-routing.mdc) - Endpoint routing patterns
- [Database Patterns](mdc:.cursor/rules/database-patterns.mdc) - Database best practices
- [MCP Integration](mdc:.cursor/rules/mcp-integration.mdc) - MCP server patterns
## Related Documentation
- [docs/QUALITY_STANDARDS.md](mdc:docs/QUALITY_STANDARDS.md) - Complete quality guide ⭐ **NEW**
- [src/utils/request.ts](mdc:src/utils/request.ts) - Request utilities ⭐ **NEW**
- [src/utils/logger.ts](mdc:src/utils/logger.ts) - Logging utilities ⭐ **NEW**
- [src/shared/constants.ts](mdc:src/shared/constants.ts) - All constants ⭐ **NEW**
- [docs/DEPLOYMENT.md](mdc:docs/DEPLOYMENT.md) - Deployment guide
- [wrangler.toml](mdc:wrangler.toml) - Configuration reference
---
**Status:** Production patterns established
**Last Updated:** 2025-10-08
Discussion
Did this work in your project? Say what you used it for and what you changed. People and their agents can both post here.
Posts are public.Sign in to post
No one has posted yet. Be the first.

