Docs: Cleanup unused files and update README/DEPLOYMENT guides with auto-start instructions

This commit is contained in:
2025-12-22 19:44:24 +11:00
parent bdd36a92c7
commit 632dedcf57
9 changed files with 53 additions and 590 deletions

View File

@@ -1,108 +0,0 @@
===============================================================================
AUTO-DEPLOY SETUP - Fix Database Disconnection After Git Pull
===============================================================================
PROBLEM YOU'RE EXPERIENCING:
- Git auto-pulls new code to production
- Database stops connecting
- You have to manually run deploy.sh to fix it
SOLUTION:
Automatic service restart after every git pull!
===============================================================================
INSTALLATION (Run Once on Production Server)
===============================================================================
SSH into your production server and navigate to Connect-5 directory, then run:
bash setup-auto-deploy.sh
That's it! The script will:
✅ Install a git post-merge hook
✅ Detect your service manager (PM2/systemd/manual)
✅ Configure automatic restart after git pull
===============================================================================
HOW IT WORKS
===============================================================================
After installation, every time git pulls new code:
1. Git auto-pull happens (your existing automation)
2. Git triggers the post-merge hook automatically
3. Hook checks if package.json changed → runs npm install if needed
4. Hook restarts the Node.js service automatically
5. Database reconnects immediately
6. No manual intervention needed!
===============================================================================
WHAT'S INCLUDED
===============================================================================
📁 git-hooks/post-merge
- The hook script that runs after git pull
- Handles: npm install + service restart
- Works with: PM2, systemd, or manual process restart
📜 setup-auto-deploy.sh
- One-time setup script
- Copies hook to .git/hooks/
- Makes it executable
- Tests which service manager you're using
===============================================================================
QUICK SETUP (Copy/Paste This)
===============================================================================
On your production server:
cd /path/to/Connect-5
bash setup-auto-deploy.sh
Answer "y" when asked to test the hook.
===============================================================================
VERIFICATION
===============================================================================
After setup, test it:
1. Make a small change to README.md on your local machine
2. Git push from local
3. Wait for server to auto-pull (your existing setup)
4. SSH into server and check:
# Check if service restarted
pm2 logs connect5
# OR
sudo systemctl status connect5
# OR
tail -f server.log
5. You should see:
"🔄 Git Pull Detected - Running Auto-Deploy"
"✅ Auto-Deploy Complete!"
===============================================================================
NO MORE MANUAL DEPLOYS!
===============================================================================
Before: Git pulls → Database disconnects → You run deploy.sh manually
After: Git pulls → Hook runs → Service restarts → Database reconnects ✅
You'll never need to run deploy.sh manually again for database connection issues!
===============================================================================
ROLLBACK (If Needed)
===============================================================================
To disable auto-deploy:
rm .git/hooks/post-merge
To re-enable:
bash setup-auto-deploy.sh
===============================================================================

View File

@@ -337,6 +337,42 @@ sudo systemctl restart apache2
---
## 🔁 Auto-Restart & Auto-Deploy
### 1. Enable Auto-Start on Boot (Systemd)
To ensure your application starts automatically when the server reboots:
```bash
cd /path/to/Connect-5
sudo bash setup-auto-start.sh
```
This script will:
* Install `connect5.service` to systemd
* Configure the service to wait for PostgreSQL
* Enable it to start on boot
* Auto-restart the app if it crashes (10s delay)
### 2. Enable Auto-Deploy (Git Hooks)
To automatically restart the database and server every time you `git pull`:
```bash
cd /path/to/Connect-5
bash setup-auto-deploy.sh
```
This installs a git `post-merge` hook that:
* Detects when code is pulled
* Runs `npm install` (only if package.json changed)
* Restarts the `connect5` service
* Ensures the connection is refreshed properly
This prevents "Database Disconnected" errors after updates.
---
## Support
For issues:

View File

@@ -1,183 +0,0 @@
===============================================================================
PRODUCTION DEPLOYMENT INSTRUCTIONS - PostgreSQL Migration
===============================================================================
Git changes have been pushed. Since you have auto-pull set up, follow these
steps on your PRODUCTION SERVER to complete the migration:
===============================================================================
STEP 1: After Git Auto-Pull Completes
===============================================================================
SSH into your production server and navigate to the Connect-5 directory.
===============================================================================
STEP 2: Install New Dependencies
===============================================================================
npm install
This will:
- Remove @supabase/supabase-js
- Install pg (PostgreSQL driver)
===============================================================================
STEP 3: Create db.config.js with PostgreSQL Credentials
===============================================================================
IMPORTANT: You need to create db.config.js on the production server.
Option A - Using the example file:
-----------------------------------
cp db.config.example.js db.config.js
nano db.config.js
Then edit with your PostgreSQL credentials:
{
HOST: '202.171.184.108',
USER: 'postgres',
PASSWORD: 'X@gon2005!#$',
DB: 'connect5',
dialect: 'postgres',
pool: { max: 5, min: 0, acquire: 30000, idle: 10000 }
}
Option B - Quick create (copy/paste this entire block):
--------------------------------------------------------
cat > db.config.js << 'EOF'
module.exports = {
HOST: '202.171.184.108',
USER: 'postgres',
PASSWORD: 'X@gon2005!#$',
DB: 'connect5',
dialect: 'postgres',
pool: {
max: 5,
min: 0,
acquire: 30000,
idle: 10000
}
};
EOF
===============================================================================
STEP 4: Apply Database Schema (if not already done)
===============================================================================
Run the schema application script:
node apply-schema.js
Expected output:
✅ Schema applied successfully!
✅ Found 4 tables: active_sessions, game_moves, games, players
If you see errors about tables already existing, that's fine - skip this step.
===============================================================================
STEP 5: Restart the Node.js Service
===============================================================================
Depending on how you're running the server:
Option A - If using PM2:
------------------------
pm2 restart connect5
# OR
pm2 restart server.js
# OR
pm2 restart all
Option B - If using nohup:
--------------------------
pkill -f "node server.js"
sleep 2
nohup node server.js > server.log 2>&1 &
Option C - If using systemd service:
------------------------------------
sudo systemctl restart connect5
# OR
sudo systemctl restart connect5.service
Option D - Not sure what's running it?
--------------------------------------
# Check what's running
ps aux | grep "node server.js"
# Kill the process (replace PID with actual process ID)
kill -9 PID
# Start it again
nohup node server.js > server.log 2>&1 &
===============================================================================
STEP 6: Verify the Service is Running
===============================================================================
Check if the server started successfully:
# View the logs
tail -f server.log
Expected output:
🔄 Initializing PostgreSQL database schema...
✅ Database schema verified successfully
🌐 Server running on port 3000
📡 WebSocket server ready
🗄️ Database connected
# Test the API endpoint
curl http://localhost:3000/api/db-status
Expected response:
{
"connected": true,
"latency": 10,
"writeCapable": true,
"connectionType": "PostgreSQL Direct Connection",
"host": "202.171.184.108",
"database": "connect5"
}
===============================================================================
STEP 7: Test the Production URL
===============================================================================
Visit your production URL (e.g., https://connect5.beyondcloud.technology/)
Verify:
✅ Page loads correctly
✅ Status bar shows "Connected" in green
✅ Latency is displayed
✅ "Write: Enabled" shows in green
✅ Multiplayer functionality works
===============================================================================
SUMMARY OF SERVICES TO RESTART
===============================================================================
You need to restart:
✅ Node.js service (server.js) - This is the ONLY service that needs restarting
You DO NOT need to restart:
❌ Nginx/Apache (web server) - No changes to proxy config
❌ PostgreSQL - Database server continues running
❌ The production server itself
===============================================================================
TROUBLESHOOTING
===============================================================================
If the service won't start:
1. Check db.config.js exists and has correct credentials
2. Check logs: tail -f server.log
3. Test database connection: node apply-schema.js
4. Ensure PostgreSQL is accessible from production server
Common issues:
- "Cannot find module './db.config.js'" → Create db.config.js (Step 3)
- "Table 'players' does not exist" → Run apply-schema.js (Step 4)
- "ECONNREFUSED" → Check PostgreSQL firewall/network access
===============================================================================

View File

@@ -35,9 +35,11 @@ A beautiful, feature-rich implementation of the classic Connect-5 (Gomoku) game
### 🌐 Multiplayer Features
- **Player Lobby**: See all online players in real-time
- **Challenge System**: Send and receive game invitations
- **Surrender Option**: Forfeit games gracefully with confirmation
- **Rematch System**: Instantly challenge the same opponent again
- **Reliable Connections**: Auto-reconnect and state restoration
- **Player Statistics**: Track wins, losses, and draws
- **Auto-Login**: Username persistence across sessions
- **Session Management**: Automatic reconnection handling
- **Profanity Filter**: Safe and family-friendly usernames
### 🎲 Gameplay

View File

@@ -1,70 +0,0 @@
=================================================================
POSTGRESQL MIGRATION - FINAL SETUP STEP
=================================================================
✅ Code migration: COMPLETE
✅ Dependencies installed: COMPLETE
✅ Configuration file created: COMPLETE
⚠️ DATABASE SCHEMA: NEEDS TO BE APPLIED
=================================================================
NEXT STEP: Initialize PostgreSQL Database
=================================================================
You need to run the postgres-schema.sql file on your PostgreSQL server.
METHOD 1: If you have PostgreSQL client tools installed
--------------------------------------------------------
Run this command from PowerShell:
$env:PGPASSWORD='X@gon2005!#$'; psql -h 202.171.184.108 -U postgres -d connect5 -f postgres-schema.sql
METHOD 2: Using pgAdmin or another PostgreSQL GUI
--------------------------------------------------
1. Open pgAdmin or your PostgreSQL management tool
2. Connect to server: 202.171.184.108
3. Username: postgres
4. Password: X@gon2005!#$
5. Right-click on database 'connect5' (create if doesn't exist)
6. Select "Query Tool"
7. Open the file: postgres-schema.sql
8. Execute the entire script
9. You should see "Tables Created Successfully! table_count = 4"
METHOD 3: Copy/Paste SQL
-------------------------
If database 'connect5' doesn't exist, first run:
CREATE DATABASE connect5;
Then connect to connect5 and run the entire contents of:
postgres-schema.sql
=================================================================
VERIFY SCHEMA WAS APPLIED
=================================================================
After running the schema, verify with this query:
SELECT table_name
FROM information_schema.tables
WHERE table_schema = 'public'
AND table_name IN ('players', 'active_sessions', 'games', 'game_moves');
Expected: 4 tables listed
=================================================================
THEN START THE SERVER
=================================================================
Once the schema is applied:
npm start
The server should start successfully and show:
✅ Database schema verified successfully
🌐 Server running on port 3000
Then test at: http://localhost:3000
=================================================================

14
apply-prod-schema.sh Normal file
View File

@@ -0,0 +1,14 @@
#!/bin/bash
# Apply schema update to production database
# Use this if you are getting "function increment_wins does not exist" errors
# Setup
export PGHOST=202.171.184.108
export PGUSER=postgres
export PGPASSWORD=your_password_here
export PGDATABASE=connect5
echo "Applying schema..."
psql -f postgres-schema.sql
echo "Done!"

View File

@@ -1,60 +0,0 @@
// Quick script to apply postgres-schema.sql to the database
// Run with: node apply-schema.js
const fs = require('fs');
const { Pool } = require('pg');
const dbConfig = require('./db.config.js');
const pool = new Pool({
host: dbConfig.HOST,
user: dbConfig.USER,
password: dbConfig.PASSWORD,
database: dbConfig.DB,
port: 5432
});
async function applySchema() {
try {
console.log('📄 Reading postgres-schema.sql...');
const schema = fs.readFileSync('./postgres-schema.sql', 'utf8');
console.log('🔗 Connecting to PostgreSQL...');
console.log(` Host: ${dbConfig.HOST}`);
console.log(` Database: ${dbConfig.DB}`);
console.log('⚙️ Applying schema...');
await pool.query(schema);
console.log('✅ Schema applied successfully!');
// Verify tables were created
console.log('\n🔍 Verifying tables...');
const result = await pool.query(`
SELECT table_name
FROM information_schema.tables
WHERE table_schema = 'public'
AND table_name IN ('players', 'active_sessions', 'games', 'game_moves')
ORDER BY table_name;
`);
console.log(`✅ Found ${result.rows.length} tables:`);
result.rows.forEach(row => {
console.log(` - ${row.table_name}`);
});
if (result.rows.length === 4) {
console.log('\n🎉 Database setup complete! You can now run: npm start');
} else {
console.log('\n⚠ Warning: Expected 4 tables but found', result.rows.length);
}
} catch (error) {
console.error('❌ Error applying schema:', error.message);
console.error('\nDetails:', error);
process.exit(1);
} finally {
await pool.end();
}
}
applySchema();

View File

@@ -1,97 +0,0 @@
#!/bin/bash
# Add proxy rules to existing CloudSticks vhost config
echo "🔧 Adding proxy rules to existing app-connect5.conf"
echo "===================================================="
echo ""
GREEN='\033[0;32m'
NC='\033[0m'
if [ "$EUID" -ne 0 ]; then
echo "❌ Run with sudo"
exit 1
fi
CONFIG="/etc/nginx-cs/vhosts.d/app-connect5.conf"
echo "Step 1: Backing up existing config..."
cp "$CONFIG" "${CONFIG}.backup.$(date +%Y%m%d_%H%M%S)"
echo -e "${GREEN}✅ Backup created${NC}"
echo ""
echo "Step 2: Adding proxy rules..."
# Add proxy rules before the closing brace
sed -i '/^}$/i\
\
# Connect-5 API Proxy\
location /api {\
proxy_pass http://localhost:3000;\
proxy_http_version 1.1;\
proxy_set_header Upgrade $http_upgrade;\
proxy_set_header Connection '"'"'upgrade'"'"';\
proxy_set_header Host $host;\
proxy_cache_bypass $http_upgrade;\
proxy_set_header X-Real-IP $remote_addr;\
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;\
proxy_set_header X-Forwarded-Proto $scheme;\
}\
\
# Connect-5 Socket.io Proxy\
location /socket.io {\
proxy_pass http://localhost:3000;\
proxy_http_version 1.1;\
proxy_set_header Upgrade $http_upgrade;\
proxy_set_header Connection "upgrade";\
proxy_set_header Host $host;\
proxy_cache_bypass $http_upgrade;\
proxy_set_header X-Real-IP $remote_addr;\
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;\
proxy_set_header X-Forwarded-Proto $scheme;\
}' "$CONFIG"
echo -e "${GREEN}✅ Proxy rules added${NC}"
echo ""
echo "Step 3: Removing duplicate connect5-proxy.conf..."
rm -f /etc/nginx-cs/vhosts.d/connect5-proxy.conf
echo -e "${GREEN}✅ Removed duplicate${NC}"
echo ""
echo "Step 4: Restarting nginx-cs..."
systemctl restart nginx-cs
echo -e "${GREEN}✅ Nginx restarted${NC}"
echo ""
echo "Step 5: Checking Node.js..."
if ! pgrep -f "node server.js" > /dev/null; then
cd /home/github2/apps/app-connect5
nohup node server.js > server.log 2>&1 &
sleep 2
fi
echo -e "${GREEN}✅ Node.js running${NC}"
echo ""
echo "Step 6: Testing..."
sleep 3
LOCAL=$(curl -s -o /dev/null -w "%{http_code}" http://localhost:3000/api/db-status 2>/dev/null)
PROD=$(curl -s -o /dev/null -w "%{http_code}" https://connect5.beyondcloud.technology/api/db-status 2>/dev/null)
echo "Local: HTTP $LOCAL"
echo "Production: HTTP $PROD"
echo ""
if [ "$PROD" = "200" ]; then
echo -e "${GREEN}✅✅✅ SUCCESS! ✅✅✅${NC}"
echo ""
curl -s https://connect5.beyondcloud.technology/api/db-status | python3 -m json.tool 2>/dev/null
echo ""
echo "===================================================="
echo -e "${GREEN}🎉 PRODUCTION IS LIVE! 🎉${NC}"
echo "Visit: https://connect5.beyondcloud.technology/"
echo "===================================================="
else
echo "⚠️ Still HTTP $PROD - check logs"
fi

View File

@@ -1,71 +0,0 @@
// Surrender game
surrenderGame() {
if (!this.isMultiplayer || !this.currentGameId) {
this.showMessage('No active game to surrender', 'error');
return;
}
this.socket.emit('surrender', { gameId: this.currentGameId });
}
// Handle rematch request from opponent
handleRematchRequest(data) {
const notification = document.createElement('div');
notification.className = 'challenge-notification';
notification.innerHTML = `
<div class="challenge-content">
<h3>Rematch Request!</h3>
<p><strong>${data.from}</strong> wants a rematch</p>
<p>Board size: ${data.boardSize}×${data.boardSize}</p>
<div class="challenge-actions">
<button class="accept-btn" onclick="multiplayerClient.acceptRematch('${data.rematchId}')">
Accept
</button>
<button class="decline-btn" onclick="multiplayerClient.declineRematch('${data.rematchId}')">
Decline
</button>
</div>
</div>
`;
document.body.appendChild(notification);
setTimeout(() => notification.classList.add('active'), 10);
}
// Send rematch request
sendRematchRequest() {
if (!this.opponentId) {
this.showMessage('No opponent to challenge', 'error');
return;
}
this.socket.emit('send_rematch', {
opponentId: this.opponentId,
boardSize: this.selectedBoardSize
});
this.showMessage(`Rematch request sent to ${this.opponent}`, 'info');
document.getElementById('gameOverModal').classList.remove('active');
}
// Accept rematch
acceptRematch(rematchId) {
this.socket.emit('accept_rematch', { rematchId });
// Hide game over modal
document.getElementById('gameOverModal').classList.remove('active');
// Remove notification
const notifications = document.querySelectorAll('.challenge-notification');
notifications.forEach(n => n.remove());
}
// Decline rematch
declineRematch(rematchId) {
this.socket.emit('decline_rematch', { rematchId });
// Remove notification
const notifications = document.querySelectorAll('.challenge-notification');
notifications.forEach(n => n.remove());
}