From 1e44c7db7a289e7ce9dec3d84c797f1c65dda020 Mon Sep 17 00:00:00 2001 From: Face <69168154+face-hh@users.noreply.github.com> Date: Fri, 30 May 2025 12:24:21 +0300 Subject: [PATCH] quick production test script --- .dockerignore | 22 +++ Dockerfile | 86 ++++++++++++ README.md | 318 +++++++++++++++++++++++++++++++++++++++++++ build.sh | 31 +++++ cluster-server.js | 22 +++ docker-compose.yml | 54 ++++++++ website/.env.example | 31 ++++- 7 files changed, 562 insertions(+), 2 deletions(-) create mode 100644 .dockerignore create mode 100644 Dockerfile create mode 100644 README.md create mode 100644 build.sh create mode 100644 cluster-server.js create mode 100644 docker-compose.yml diff --git a/.dockerignore b/.dockerignore new file mode 100644 index 0000000..d705ec8 --- /dev/null +++ b/.dockerignore @@ -0,0 +1,22 @@ +node_modules +.DS_Store +Thumbs.db +.env +.env.* +!.env.example +*.log +npm-debug.log* +yarn-debug.log* +yarn-error.log* +.pnpm-debug.log* +.svelte-kit +build/ +.output +.vercel +.netlify +vite.config.js.timestamp-* +vite.config.ts.timestamp-* +.git +.gitignore +README.md +drizzle/ diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 0000000..ba6a1a9 --- /dev/null +++ b/Dockerfile @@ -0,0 +1,86 @@ +# syntax = docker/dockerfile:1 + +ARG NODE_VERSION=20 +FROM node:${NODE_VERSION}-slim AS base-node +WORKDIR /app +ENV NODE_ENV="production" + +# Install system dependencies for building native modules +RUN apt-get update -qq && \ + apt-get install --no-install-recommends -y \ + build-essential \ + node-gyp \ + pkg-config \ + python-is-python3 \ + curl \ + ca-certificates && \ + rm -rf /var/lib/apt/lists/* + +FROM base-node AS build-main + +# Copy package files +COPY website/package.json website/package-lock.json* ./ + +# Install dependencies +RUN npm ci --include=dev + +# Copy source files +COPY website/. ./ + +# Build the application +RUN npm run build + +# Remove dev dependencies +RUN npm prune --omit=dev + +FROM base-node AS build-websocket +WORKDIR /websocket + +# Install Bun +RUN curl -fsSL https://bun.sh/install | bash +ENV PATH="/root/.bun/bin:${PATH}" + +# Copy websocket package files +COPY website/websocket/package.json website/websocket/bun.lock* ./ +COPY website/websocket/tsconfig.json ./ + +# Install dependencies +RUN bun install + +# Copy websocket source +COPY website/websocket/src ./src/ + +# Build websocket +RUN bun build src/main.ts --outdir dist --target bun + +FROM base-node AS production-main + +# Copy built application from build stage +COPY --from=build-main --chown=node:node /app/build ./build +COPY --from=build-main --chown=node:node /app/node_modules ./node_modules +COPY --from=build-main --chown=node:node /app/package.json ./package.json + +# Copy cluster server +COPY cluster-server.js ./cluster-server.js + +USER node +EXPOSE 3000 + +# Use cluster server for better performance +CMD ["node", "cluster-server.js"] + +FROM base-node AS production-websocket +WORKDIR /websocket + +# Install Bun in production stage +RUN curl -fsSL https://bun.sh/install | bash +ENV PATH="/root/.bun/bin:${PATH}" + +# Copy built websocket from build stage +COPY --from=build-websocket /websocket/node_modules ./node_modules +COPY --from=build-websocket /websocket/dist ./dist +COPY --from=build-websocket /websocket/package.json ./package.json + +USER node +EXPOSE 8080 +CMD ["bun", "run", "dist/main.js"] diff --git a/README.md b/README.md new file mode 100644 index 0000000..9bbc5a7 --- /dev/null +++ b/README.md @@ -0,0 +1,318 @@ +# Rugplay + +A realistic cryptocurrency trading simulation platform built with SvelteKit and Svelte 5, focusing on decentralized exchange mechanics and the inherent risks of "rug pulls." + +## Features + +- **Coin Creation**: Create simulated cryptocurrencies with customizable parameters +- **Liquidity Pools**: AMM-based trading with realistic price mechanics and slippage +- **Trading**: Buy/sell coins against base currency (*BUSS) with supply/demand pricing +- **Rug Pull Simulation**: Experience realistic market crashes when large holders sell +- **Portfolio Tracking**: Monitor holdings and transaction history +- **Real-time Updates**: WebSocket-powered live price feeds and trade notifications +- **Prediction Markets**: "Hopium" betting system for market predictions +- **Gambling**: Coinflip and slots games +- **Leaderboards**: Track top performers + +## Tech Stack + +- **Frontend**: SvelteKit + Svelte 5 with runes +- **Backend**: Node.js API routes +- **WebSocket**: Bun-based real-time server +- **Database**: PostgreSQL with Drizzle ORM +- **Cache**: Redis for real-time messaging +- **Storage**: AWS S3/Backblaze B2 compatible +- **Auth**: Better Auth with Google OAuth +- **UI**: ShadCN UI components + Tailwind CSS + +## Pre-Deployment Checklist + +Before running on your Linux machine, ensure: + +- [ ] **Docker & Docker Compose installed**: `docker --version && docker compose version` +- [ ] **Ports available**: 3002, 8081, 5432, 6379 are not in use +- [ ] **Git access**: Repository is cloned with all files +- [ ] **Environment configured**: `website/.env` file created from `website/.env.example` +- [ ] **Permissions set**: `chmod +x build.sh` executed +- [ ] **Minimum system requirements**: 2GB RAM, 10GB disk space + +### Essential Environment Variables + +The following must be configured in `website/.env`: + +```bash +# Required for database connection +DATABASE_URL=postgresql://rugplay_user:your_secure_password@postgres:5432/rugplay +POSTGRES_USER=rugplay_user +POSTGRES_PASSWORD=your_secure_password +POSTGRES_DB=rugplay + +# Required for real-time features +REDIS_URL=redis://redis:6379 + +# Required for authentication (generate a 32+ character random string) +PRIVATE_BETTER_AUTH_SECRET=your_super_secret_auth_key_minimum_32_characters +PUBLIC_BETTER_AUTH_URL=http://localhost:3002 +``` + +## Quick Start + +### Prerequisites + +- Docker & Docker Compose +- Git + +### Installation + +1. **Clone the repository**: + ```bash + git clone + cd rugplay + ``` + +2. **Configure environment**: + ```bash + cp website/.env.example website/.env + # Edit website/.env with your actual values (see Configuration section) + ``` + +3. **Deploy**: + ```bash + chmod +x build.sh + ./build.sh + ``` + +The application will be available at: +- **Main App**: http://localhost:3002 +- **WebSocket**: http://localhost:8081 +- **Database**: localhost:5432 +- **Redis**: localhost:6379 + +## Configuration + +### Required Environment Variables + +Copy `website/.env.example` to `website/.env` and configure: + +```bash +# Database Configuration +DATABASE_URL=postgresql://rugplay_user:your_secure_password@postgres:5432/rugplay +POSTGRES_USER=rugplay_user +POSTGRES_PASSWORD=your_secure_password +POSTGRES_DB=rugplay + +# Redis Configuration +REDIS_URL=redis://redis:6379 + +# Authentication +PRIVATE_BETTER_AUTH_SECRET=your_super_secret_auth_key_minimum_32_chars +PUBLIC_BETTER_AUTH_URL=http://localhost:3002 +``` + +### Optional Environment Variables + +```bash +# Google OAuth (for social login) +GOOGLE_CLIENT_ID=your_google_client_id +GOOGLE_CLIENT_SECRET=your_google_client_secret + +# AWS S3/Backblaze B2 Storage (for file uploads) +PRIVATE_B2_KEY_ID=your_b2_key_id +PRIVATE_B2_APP_KEY=your_b2_app_key +PUBLIC_B2_BUCKET=your_bucket_name +PUBLIC_B2_ENDPOINT=https://s3.us-west-002.backblazeb2.com +PUBLIC_B2_REGION=us-west-002 + +# OpenAI (for AI features) +OPENAI_API_KEY=your_openai_api_key + +# Application Settings +NODE_ENV=production +PORT=3000 +``` + +## Architecture + +### Services + +- **app**: Main SvelteKit application (port 3002) +- **websocket**: Bun-based WebSocket server for real-time features (port 8081) +- **postgres**: PostgreSQL database with pgvector extension +- **redis**: Redis for caching and pub/sub messaging + +### Key Components + +- **AMM Trading**: Automated Market Maker with constant product formula (x*y=k) +- **Real-time Price Updates**: WebSocket broadcasting for live price feeds +- **Comment System**: Real-time coin discussions +- **Prediction Markets**: AI-resolved betting on future events +- **Portfolio Management**: Track holdings across multiple coins +- **Admin Panel**: Manage promo codes and system settings + +## Development + +### Local Development + +```bash +# Start only database and redis +docker compose up -d postgres redis + +# Install dependencies and run main app +cd website +npm install +npm run dev + +# Run websocket server (in separate terminal) +cd website/websocket +bun install +bun run src/main.ts +``` + +### Database Management + +```bash +# Run migrations +docker compose exec app npm run db:migrate + +# Open Drizzle Studio +docker compose exec app npm run db:studio + +# Push schema changes +docker compose exec app npm run db:push +``` + +## Deployment Commands + +### Manual Deployment + +```bash +# Build and start all services +docker compose build --no-cache +docker compose up -d + +# Check service status +docker compose ps + +# View logs +docker compose logs -f + +# View specific service logs +docker compose logs -f app +docker compose logs -f websocket +``` + +### Maintenance + +```bash +# Restart all services +docker compose restart + +# Stop services +docker compose down + +# Clean rebuild (removes volumes - WARNING: deletes data) +docker compose down --volumes --remove-orphans +docker compose build --no-cache +docker compose up -d + +# Update and redeploy +git pull +./build.sh +``` + +## Troubleshooting + +### Common Issues + +1. **Port conflicts**: Ensure ports 3002, 8081, 5432, 6379 are available +2. **Database connection**: Check DATABASE_URL format and postgres service status +3. **WebSocket issues**: Verify REDIS_URL and redis service connectivity +4. **File uploads**: Confirm S3/B2 credentials and bucket permissions + +### Health Checks + +```bash +# Check all container status +docker compose ps + +# Test main app +curl http://localhost:3002 + +# Test websocket health +curl http://localhost:8081/health + +# Check database connectivity +docker compose exec postgres pg_isready -U rugplay_user + +# Check redis connectivity +docker compose exec redis redis-cli ping +``` + +### Log Analysis + +```bash +# Follow all logs +docker compose logs -f + +# Application errors +docker compose logs app | grep -i error + +# WebSocket logs +docker compose logs websocket + +# Database logs +docker compose logs postgres +``` + +## Production Considerations + +### Security + +- [ ] Change all default passwords and secrets +- [ ] Use strong PRIVATE_BETTER_AUTH_SECRET (minimum 32 characters) +- [ ] Configure firewall rules for exposed ports +- [ ] Use HTTPS in production (reverse proxy recommended) +- [ ] Rotate API keys and database credentials regularly + +### Performance + +- [ ] Configure PostgreSQL for your hardware +- [ ] Set up Redis persistence if needed +- [ ] Monitor container resource usage +- [ ] Configure log rotation +- [ ] Set up database connection pooling + +### Monitoring + +- [ ] Set up health check endpoints +- [ ] Configure log aggregation +- [ ] Monitor database performance +- [ ] Track WebSocket connection metrics +- [ ] Set up alerts for service failures + +### Backup Strategy + +- [ ] Database backups: `pg_dump` scheduled backups +- [ ] Redis persistence: Configure RDB snapshots +- [ ] File storage: S3/B2 versioning and backup +- [ ] Configuration: Version control for .env files (encrypted) + +## Contributing + +1. Fork the repository +2. Create a feature branch +3. Make your changes +4. Test with Docker locally +5. Submit a pull request + +## License + +[Add your license here] + +## Support + +For issues and questions: +- Open GitHub issues for bugs +- Check logs first: `docker compose logs -f` +- Verify environment configuration +- Test with clean rebuild if needed diff --git a/build.sh b/build.sh new file mode 100644 index 0000000..14b984a --- /dev/null +++ b/build.sh @@ -0,0 +1,31 @@ +#!/bin/bash +set -e + +cd "$(dirname "$0")" + +echo "🚀 Starting Rugplay deployment..." + +echo "📥 Pulling latest changes..." +git pull + +echo "🔨 Building Docker images..." +docker compose build --no-cache + +echo "🛑 Stopping existing containers..." +docker compose down --volumes --remove-orphans + +echo "🏗️ Starting containers..." +docker compose up -d + +echo "⏳ Waiting for services to start..." +sleep 10 + +echo "🔍 Checking container status..." +docker compose ps + +echo "📊 Checking service health..." +echo "Main app: http://localhost:3002" +echo "WebSocket: http://localhost:8081/health" + +echo "📋 Tailing logs (press Ctrl+C to stop)..." +docker compose logs -f \ No newline at end of file diff --git a/cluster-server.js b/cluster-server.js new file mode 100644 index 0000000..b7d7b65 --- /dev/null +++ b/cluster-server.js @@ -0,0 +1,22 @@ +import cluster from 'cluster'; +import { cpus } from 'os'; +import { handler } from './build/handler.js'; +import express from 'express'; + +const numCPUs = cpus().length; + +if (cluster.isPrimary) { + console.log(`Primary ${process.pid} spawning ${numCPUs} workers…`); + for (let i = 0; i < numCPUs; i++) cluster.fork(); + cluster.on('exit', (w) => { + console.warn(`Worker ${w.process.pid} died — restarting…`); + cluster.fork(); + }); +} else { + const app = express(); + app.use(handler); + const port = process.env.PORT || 3000; + app.listen(port, () => + console.log(`Worker ${process.pid} listening on ${port}`) + ); +} diff --git a/docker-compose.yml b/docker-compose.yml new file mode 100644 index 0000000..a6601c2 --- /dev/null +++ b/docker-compose.yml @@ -0,0 +1,54 @@ +version: '3.8' + +services: + app: + build: + context: . + target: production-main + dockerfile: Dockerfile + ports: + - "3002:3000" + env_file: + - website/.env + depends_on: + - websocket + - redis + - postgres + restart: unless-stopped + + websocket: + build: + context: . + target: production-websocket + dockerfile: Dockerfile + ports: + - "8081:8080" + env_file: + - website/.env + depends_on: + - redis + restart: unless-stopped + + redis: + image: redis:8-alpine + volumes: + - rugplay_redisdata:/data + command: "redis-server --save 60 1" + restart: unless-stopped + + postgres: + image: pgvector/pgvector:pg16 + container_name: rugplay-postgres + environment: + POSTGRES_USER: ${POSTGRES_USER} + POSTGRES_PASSWORD: ${POSTGRES_PASSWORD} + POSTGRES_DB: ${POSTGRES_DB:-rugplay} + ports: + - "5432:5432" + volumes: + - rugplay_pgdata:/var/lib/postgresql/data + restart: unless-stopped + +volumes: + rugplay_pgdata: + rugplay_redisdata: diff --git a/website/.env.example b/website/.env.example index ec707ff..50db989 100644 --- a/website/.env.example +++ b/website/.env.example @@ -1,2 +1,29 @@ -# Replace with your DB credentials! -DATABASE_URL="postgres://user:password@host:port/db-name" +# Rugplay Environment Configuration +# Copy this file to .env and fill in your actual values + +# Database Configuration +DATABASE_URL=postgresql://username:password@postgres:5432/rugplay +POSTGRES_USER=rugplay_user +POSTGRES_PASSWORD=your_secure_password_here +POSTGRES_DB=rugplay + +# Redis Configuration +REDIS_URL=redis://redis:6379 + +# Authentication +PRIVATE_BETTER_AUTH_SECRET=your_super_secret_auth_key_here +PUBLIC_BETTER_AUTH_URL=http://localhost:3002 + +# Google OAuth (optional - for social login) +GOOGLE_CLIENT_ID=your_google_client_id +GOOGLE_CLIENT_SECRET=your_google_client_secret + +# AWS S3/B2 Storage (for file uploads) +PRIVATE_B2_KEY_ID=your_b2_key_id +PRIVATE_B2_APP_KEY=your_b2_app_key +PUBLIC_B2_BUCKET=your_bucket_name +PUBLIC_B2_ENDPOINT=https://s3.us-west-002.backblazeb2.com +PUBLIC_B2_REGION=us-west-002 + +# OpenAI (for AI features) +OPENROUTER_API_KEY=your_openrouter_api_key \ No newline at end of file