Appendix E: Troubleshooting Guide
Common Issues and Solutions
Installation and Setup Issues
Issue: CLI Installation Fails
Symptoms:
$ dart pub global activate hypermodern_cli
Error: Could not resolve package hypermodern_cli
Solutions:
- Check Dart SDK version:
dart --version
# Ensure you have Dart 3.0.0 or later
- Update pub cache:
dart pub cache repair
dart pub global activate hypermodern_cli
- Install from source:
git clone https://github.com/hypermodern/hypermodern_cli.git
cd hypermodern_cli
dart pub global activate --source path .
Issue: Command Not Found After Installation
Symptoms:
$ hypermodern --version
command not found: hypermodern
Solutions:
- Add pub global bin to PATH:
# Add to ~/.bashrc or ~/.zshrc
export PATH="$PATH":"$HOME/.pub-cache/bin"
- Verify installation:
dart pub global list
# Should show hypermodern_cli in the list
- Use full path temporarily:
~/.pub-cache/bin/hypermodern --version
Code Generation Issues
Issue: Schema Validation Errors
Symptoms:
$ hypermodern generate
Error: Schema validation failed
- Invalid type reference '@unknown_model' in field 'user.profile'
Solutions:
- Check model references:
{
"models": {
"user": {
"profile": "@user_profile" // Ensure user_profile exists
},
"user_profile": { // Define the referenced model
"bio": "string"
}
}
}
- Validate schema syntax:
hypermodern schema validate schemas/
- Check for circular references:
// Avoid this:
{
"models": {
"user": {
"posts": ["@post"]
},
"post": {
"author": "@user" // This creates a circular reference
}
}
}
// Use this instead:
{
"models": {
"user": {
"id": "int64",
"posts": ["@post"]
},
"post": {
"author_id": "int64" // Reference by ID
}
}
}
Issue: Generated Code Compilation Errors
Symptoms:
$ dart analyze
error: The method 'fromJson' isn't defined for the class 'User'
Solutions:
- Regenerate code:
hypermodern generate --clean
- Check schema field types:
{
"models": {
"user": {
"id": "int64", // Use int64, not int
"name": "string", // Use string, not String
"active": "bool" // Use bool, not boolean
}
}
}
- Verify imports in generated code:
// Check that generated files have proper imports
import 'dart:convert';
import 'dart:typed_data';
Server Issues
Issue: Server Won't Start
Symptoms:
$ hypermodern serve
Error: Failed to bind to port 8080
Solutions:
- Check port availability:
# Check if port is in use
lsof -i :8080
netstat -an | grep 8080
- Use different ports:
hypermodern serve --http-port 3000 --ws-port 3001 --tcp-port 3002
- Check permissions:
# On Linux/macOS, ports < 1024 require root
sudo hypermodern serve --http-port 80
# Or use ports > 1024
hypermodern serve --http-port 8080
Issue: Database Connection Errors
Symptoms:
Error: Failed to connect to database
Connection refused: postgresql://localhost:5432/myapp
Solutions:
- Verify database is running:
# PostgreSQL
pg_isready -h localhost -p 5432
# Check service status
systemctl status postgresql
brew services list | grep postgresql
- Check connection string:
# Test connection manually
psql postgresql://username:password@localhost:5432/database_name
- Update configuration:
# hypermodern.yaml
database:
url: "postgresql://user:pass@localhost:5432/myapp"
# Or use environment variable
url: "${DATABASE_URL}"
- Create database if it doesn't exist:
createdb myapp
Issue: Hot Reload Not Working
Symptoms:
- File changes don't trigger server restart
- Generated code is not updated
Solutions:
- Check file watching:
# Start with explicit watch
hypermodern serve --watch
- Verify file patterns:
# hypermodern.yaml
server:
watch_patterns:
- "schemas/**/*.json"
- "lib/**/*.dart"
- "config/**/*.yaml"
- Check file permissions:
# Ensure files are readable
chmod -R 644 schemas/
- Restart with clean generation:
hypermodern generate --clean
hypermodern serve
Client Issues
Issue: Connection Refused
Symptoms:
Exception: Connection refused: ws://localhost:8082
Solutions:
- Verify server is running:
# Check if server is listening on the port
netstat -an | grep 8082
- Check protocol and port:
// Ensure correct protocol and port
final client = HypermodernClient('ws://localhost:8082'); // WebSocket
// or
final client = HypermodernClient('http://localhost:8080'); // HTTP
- Test with curl:
# Test HTTP endpoint
curl http://localhost:8080/health
# Test WebSocket (using websocat)
websocat ws://localhost:8082
Issue: Authentication Errors
Symptoms:
UnauthorizedException: Invalid token
Solutions:
- Check token format:
// Ensure token is properly formatted
client.setAuthToken('Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...');
// or
client.setAuthToken('eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...');
- Verify token expiration:
// Check if token is expired
final jwt = JWT.verify(token, SecretKey('your-secret'));
print('Token expires at: ${DateTime.fromMillisecondsSinceEpoch(jwt.payload['exp'] * 1000)}');
- Check server configuration:
// Ensure JWT secret matches
final jwtService = JWTService(
secretKey: 'your-secret-key', // Must match client
issuer: 'your-app',
);
Issue: Request Timeout
Symptoms:
TimeoutException: Request timed out after 30 seconds
Solutions:
- Increase timeout:
final response = await client.request<User>(
'get_user',
request,
timeout: Duration(minutes: 2),
);
- Check server performance:
# Monitor server logs
hypermodern serve --verbose
- Optimize database queries:
// Add database indexes
CREATE INDEX idx_users_email ON users(email);
// Use connection pooling
final pool = ConnectionPool(
maxConnections: 20,
connectionTimeout: Duration(seconds: 10),
);
Performance Issues
Issue: Slow Response Times
Symptoms:
- API responses taking > 1 second
- High CPU usage
- Memory leaks
Solutions:
- Enable performance monitoring:
server.middleware.add(PerformanceMiddleware());
- Check database query performance:
-- Enable query logging in PostgreSQL
ALTER SYSTEM SET log_statement = 'all';
ALTER SYSTEM SET log_min_duration_statement = 1000; -- Log queries > 1s
- Use connection pooling:
final pool = ConnectionPool(
minConnections: 5,
maxConnections: 20,
connectionTimeout: Duration(seconds: 10),
);
- Enable caching:
server.middleware.add(CacheMiddleware(
defaultTtl: Duration(minutes: 5),
));
Issue: Memory Leaks
Symptoms:
- Memory usage continuously increasing
- Server crashes with out-of-memory errors
Solutions:
- Monitor memory usage:
Timer.periodic(Duration(minutes: 1), (_) {
final rss = ProcessInfo.currentRss;
print('Memory usage: ${rss ~/ (1024 * 1024)}MB');
});
- Check for unclosed streams:
// Always close streams
final subscription = stream.listen(handler);
// Later...
await subscription.cancel();
- Use weak references for caches:
final cache = <String, WeakReference<CachedData>>{};
- Profile memory usage:
dart --observe lib/main.dart
# Then use Dart DevTools to analyze memory
Module Issues
Issue: Module Installation Fails
Symptoms:
$ hypermodern module install hypermodern_auth
Error: Module not found in registry
Solutions:
- Check module name:
# Search for available modules
hypermodern module search auth
- Install from local path:
hypermodern module install ./path/to/module
- Check registry configuration:
# hypermodern.yaml
modules:
registry_url: "https://registry.hypermodern.dev"
Issue: Module Dependency Conflicts
Symptoms:
Error: Dependency conflict
Module A requires hypermodern_auth ^1.0.0
Module B requires hypermodern_auth ^2.0.0
Solutions:
- Update modules:
hypermodern module update
- Check compatibility:
hypermodern module list --outdated
- Use specific versions:
hypermodern module install hypermodern_auth@1.5.0
Deployment Issues
Issue: Docker Build Fails
Symptoms:
$ docker build -t myapp .
Error: dart: command not found
Solutions:
- Use correct base image:
FROM dart:3.2-sdk AS build
# Not FROM ubuntu:latest
- Multi-stage build:
# Build stage
FROM dart:3.2-sdk AS build
WORKDIR /app
COPY pubspec.yaml pubspec.lock ./
RUN dart pub get
COPY . .
RUN dart compile exe lib/main.dart -o server
# Runtime stage
FROM debian:bookworm-slim AS runtime
RUN apt-get update && apt-get install -y ca-certificates
COPY --from=build /app/server /app/server
EXPOSE 8080 8082 8081
CMD ["/app/server"]
Issue: Kubernetes Deployment Fails
Symptoms:
Pod status: CrashLoopBackOff
Error: Failed to bind to 0.0.0.0:8080
Solutions:
- Check resource limits:
resources:
requests:
memory: "256Mi"
cpu: "250m"
limits:
memory: "512Mi"
cpu: "500m"
- Verify environment variables:
env:
- name: DATABASE_URL
valueFrom:
secretKeyRef:
name: app-secrets
key: database-url
- Check health probes:
livenessProbe:
httpGet:
path: /health
port: 8080
initialDelaySeconds: 30
periodSeconds: 10
readinessProbe:
httpGet:
path: /ready
port: 8080
initialDelaySeconds: 5
periodSeconds: 5
Debugging Techniques
Enable Debug Logging
// Server-side
Logger.instance.setLevel(LogLevel.debug);
// Client-side
final client = HypermodernClient(
'ws://localhost:8082',
config: ClientConfig(
logLevel: LogLevel.debug,
),
);
Use Request Tracing
server.middleware.add(TracingMiddleware());
// Each request gets a trace ID
final traceId = request.context['trace_id'];
logger.debug('Processing request', extra: {'trace_id': traceId});
Monitor Metrics
server.middleware.add(MetricsMiddleware());
// View metrics
final metrics = server.getMetrics();
print('Request count: ${metrics.requestCount}');
print('Average response time: ${metrics.averageResponseTime}ms');
Database Query Logging
final database = Database(pool, config: DatabaseConfig(
logQueries: true,
logSlowQueries: Duration(milliseconds: 100),
));
Performance Profiling
CPU Profiling
# Start server with profiling
dart --observe lib/main.dart
# Open Dart DevTools
dart devtools
Memory Profiling
import 'dart:developer';
void trackMemoryUsage() {
Timeline.startSync('memory_check');
final rss = ProcessInfo.currentRss;
Timeline.finishSync();
print('Memory usage: ${rss ~/ (1024 * 1024)}MB');
}
Network Profiling
# Monitor network traffic
tcpdump -i lo0 port 8080
# Monitor WebSocket connections
websocat -v ws://localhost:8082
Common Error Messages
Schema Errors
| Error | Cause | Solution |
|---|---|---|
Invalid type reference '@model' |
Referenced model doesn't exist | Define the model or fix the reference |
Circular reference detected |
Models reference each other | Use ID references instead of object references |
Invalid field name 'class' |
Using reserved keyword | Rename field to non-reserved name |
Runtime Errors
| Error | Cause | Solution |
|---|---|---|
Connection refused |
Server not running or wrong port | Check server status and port configuration |
Invalid token |
JWT token expired or malformed | Refresh token or check token format |
Database connection failed |
Database not accessible | Check database status and connection string |
Build Errors
| Error | Cause | Solution |
|---|---|---|
dart: command not found |
Dart SDK not installed | Install Dart SDK |
Package not found |
Missing dependency | Run dart pub get |
Compilation failed |
Syntax errors in generated code | Regenerate code with hypermodern generate --clean |
Getting Help
Community Resources
- GitHub Issues: Report bugs and feature requests
- Discord Server: Real-time community support
- Stack Overflow: Tag questions with
hypermodern - Documentation: Official docs at docs.hypermodern.dev
Diagnostic Information
When reporting issues, include:
# System information
hypermodern doctor
# Version information
hypermodern --version
dart --version
# Configuration
hypermodern config list
# Logs
hypermodern serve --verbose > server.log 2>&1
Creating Minimal Reproductions
- Create a minimal project that reproduces the issue
- Include schema files and configuration
- Provide step-by-step instructions
- Include error messages and logs
- Specify environment details (OS, Dart version, etc.)
This troubleshooting guide covers the most common issues you might encounter when working with Hypermodern. For issues not covered here, consult the community resources or create a detailed bug report.
No Comments