6.4 KiB
6.4 KiB
Wynncraft Tools TypeScript Codebase Documentation
Overview
This is a TypeScript application that provides tools and services for the Wynncraft Minecraft server. It synchronizes game data, manages a Discord bot, and provides API services for in-game authentication.
Architecture
Technology Stack
- Runtime: Node.js with TypeScript (ESNext target)
- Workflow Engine: Temporal.io for orchestration and scheduling
- Database: PostgreSQL with
postgresclient - Cache: Redis via BentoCache
- Discord: Discordeno library for bot functionality
- DI Container: @needle-di/core for dependency injection
- Validation: Arktype and Zod for runtime type validation
- CLI: Clipanion for command-line interface
- Logging: Pino with logfmt formatting
Project Structure
ts/
├── src/
│ ├── activities/ # Temporal activities (atomic operations)
│ ├── apiserver/ # REST API contract definitions
│ ├── bot/ # Discord bot implementation
│ ├── cmd/ # CLI commands (worker, bot)
│ ├── config/ # Environment configuration
│ ├── constants/ # Application constants
│ ├── di/ # Dependency injection setup
│ ├── lib/ # Shared libraries and utilities
│ ├── logger/ # Logging configuration
│ ├── services/ # Service layer (database, cache, etc.)
│ └── workflows/ # Temporal workflows (orchestration)
├── package.json # Dependencies and scripts
└── tsconfig.json # TypeScript configuration
Core Components
1. CLI Commands
WorkerCommand (src/cmd/worker.ts)
- Runs the Temporal worker that processes workflows and activities
- Schedules 4 recurring workflows:
update-guild-players: Every 15 minutes - Updates guild member dataupdate_guild_leaderboards: Every 5 minutes - Updates guild leaderboard statsupdate-all-guilds: Every hour - Full guild data syncupdate-online-players: Every 31 seconds - Tracks online players
BotCommand (src/cmd/bot.ts)
- Initializes and runs the Discord bot
- Registers slash commands
- Connects to Discord gateway
- Handles user interactions
2. Workflows (Orchestration Layer)
Guild Workflows (src/workflows/guilds.ts)
workflowSyncAllGuilds: Fetches and updates all guild dataworkflowSyncGuildLeaderboardInfo: Updates guild leaderboard statisticsworkflowSyncGuilds: Syncs specific guild data including members and territories
Player Workflows (src/workflows/players.ts)
workflowSyncOnline: Tracks currently online players and their server locations- Integrates with PlayerDB API for UUID resolution
Item Workflows (src/workflows/items.ts)
workflowSyncItemDatabase: Synchronizes Wynncraft item database- Uses hash-based change detection to minimize updates
Discord Workflows (src/workflows/discord.ts)
workflowDiscordInteraction: Handles Discord slash commands and interactions- Manages response lifecycle and modal interactions
3. Activities (Business Logic)
Activities are the atomic units of work in Temporal:
- Database Activities: Direct PostgreSQL operations
- Guild Activities: Fetch and update guild data from Wynncraft API
- Player Activities: Track online players and fetch UUIDs
- Leaderboard Activities: Process guild rankings and statistics
- Discord Activities: Send messages and handle interactions
4. Services
PostgreSQL Service (src/services/pg/index.ts)
- Manages database connections
- Provides SQL query interface
- Configured via environment variables
Temporal Service (src/services/temporal/index.ts)
- Manages Temporal client connections
- Custom data converter configuration
- Graceful shutdown handling
Wynncraft API Service (src/lib/wynn/wapi.ts)
- Centralized API client for Wynncraft endpoints
- Implements intelligent caching with BentoCache
- Request coalescing and retry logic
- Namespace-based cache organization
5. Data Models
Guild System
- Guilds: UUID, name, prefix, level, XP, territories, war stats
- Guild Members: Player association, rank, join date, contributions
- Season Results: Historical guild performance data
Player System
- Players: UUID, username, current server location
- Online Status: Real-time tracking of player locations
Item System
- Items: Internal name, display name, tier, type, full JSON data
- Metadata: Hash tracking for change detection
6. API Contract (src/apiserver/contract.ts)
REST API using ts-rest for in-game authentication:
GET /api/v1/ingame/challenge: Generate authentication challengePOST /api/v1/ingame/solve: Solve challenge and receive token
Key Patterns
Dependency Injection
All services use constructor injection via @needle-di/core:
@injectable()
class MyService {
constructor(private pg: PG) {}
}
Error Handling
- Temporal retry policies for transient failures
- Transaction rollback on database errors
- Structured logging with context
Caching Strategy
- Multi-tier caching with Redis backend
- TTL-based expiration
- Stale-while-revalidate for better performance
- Request deduplication
Database Patterns
- Upsert operations with
ON CONFLICT - Transactional consistency for related updates
- Prepared statements for performance
Configuration
Environment variables (loaded from .env):
DISCORD_TOKEN: Discord bot authenticationTEMPORAL_ADDRESS: Temporal server locationTEMPORAL_NAMESPACE: Workflow namespaceDATABASE_URLor individual DB paramsREDIS_URL: Cache backendWYNN_API_URL: Wynncraft API endpoint
Development
Path Aliases
#/*maps to./src/*for clean imports
Build Tools
- TypeScript with strict mode
- Barrelsby for automatic barrel exports
- Webpack bundling for Temporal workflows
Commands
yarn barrels: Generate barrel export files
Security Considerations
- No hardcoded credentials
- Environment-based configuration
- Prepared statements for SQL injection prevention
- Token-based authentication for API
Performance Optimizations
- Connection pooling for database
- Request caching and coalescing
- Hash-based change detection
- Batch operations where possible
- Indexed database queries
Monitoring and Observability
- Structured logging with Pino
- Request IDs for tracing
- Error tracking with full context
- Performance metrics via Temporal