14 KiB
14 KiB
Geliştirme ve Dağıtım Kılavuzu
Yakıt Takip Sistemi geliştirme ortamı kurulumu, test süreçleri ve prodüksiyon dağıtımı hakkında kapsamlı rehber.
📋 İçerlik
- Geliştirme Ortamı Kurulumu
- Geliştirme Süreci
- Test Stratejisi
- Prodüksiyon Dağıtımı
- İzleme ve Bakım
- Sorun Giderme
🛠️ Geliştirme Ortamı Kurulumu
Gereksinimler
- Node.js: 16.x veya üzeri
- npm: 7.x veya üzeri
- Git: Son sürüm
- Editör: VS Code (önerilen)
- Tarayıcı: Chrome/Firefox (geliştirme araçları)
Adım 1: Sistemi Kurun
Node.js Kurulumu
# macOS (Homebrew)
brew install node
# Ubuntu/Debian
curl -fsSL https://deb.nodesource.com/setup_18.x | sudo -E bash -
sudo apt-get install -y nodejs
# Windows
# https://nodejs.org/en/download/ adresinden indirin
VS Code ve Eklentiler
# Önerilen VS Code eklentileri
- Svelte for VS Code
- SQLite
- Thunder Client (API testing)
- GitLens
- Prettier
- ESLint
Adım 2: Projeyi Kurun
# 1. Repoyu klonlayın
git clone <repository-url>
cd ytp
# 2. Ana proje bağımlılıklarını yükleyin
npm install
# 3. Frontend bağımlılıklarını yükleyin
cd client
npm install
cd ..
# 4. Veritabanını başlatın
npm run prepare:db
# 5. Ortam değişkenlerini yapılandırın
cp .env.example .env
Adım 3: Ortam Değişkenleri
.env Dosyası
# Sunucu ayarları
PORT=5005
NODE_ENV=development
# Veritabanı ayarları
DB_PATH=./data/app.db
# Session ayarları
SESSION_SECRET=your-secret-key-here
SESSION_TIMEOUT=24h
# CORS ayarları
CORS_ORIGIN=http://localhost:5173
# Log seviyesi
LOG_LEVEL=debug
Adım 4: Geliştirme Sunucusunu Başlatın
# Geliştirme modunda başlatma (hem backend hem frontend)
npm run dev
# Sadece backend sunucusu
npm run start:server
# Sadece frontend (ayrı terminal)
cd client && npm run dev
Adım 5: Doğrulama
# Sunucu çalışıyor mu?
curl http://localhost:5005/api/session
# Frontend çalışıyor mu?
# Tarayıcıda http://localhost:5173 açın
🔄 Geliştirme Süreci
Git Workflow
Branch Stratejisi
main # Prodüksiyon branch'i
├── develop # Geliştirme branch'i
├── feature/* # Yeni özellikler
├── bugfix/* # Hata düzeltmeleri
└── hotfix/* # Acil düzeltmeler
Commit Mesajları
# Format
<type>(<scope>): <description>
# Örnekler
feat(auth): add JWT token refresh mechanism
fix(api): handle null vehicle_id gracefully
docs(readme): update installation instructions
refactor(db): optimize fuel_slip queries
Geliştirme Akışı
# 1. Yeni feature branch oluştur
git checkout -b feature/fuel-slip-pdf
# 2. Geliştirme yap
# ... kod değişiklikleri
# 3. Değişiklikleri commit et
git add .
git commit -m "feat(fuel): add PDF generation for fuel slips"
# 4. Branch'e push et
git push origin feature/fuel-slip-pdf
# 5. Pull Request oluştur
# GitHub/GitLab üzerinden PR oluştur
# 6. Review ve merge
# Code review sonrası develop branch'ine merge
# 7. Geliştirme sunucusunu güncelle
git checkout develop
git pull origin develop
Kod Kalitesi
ESLint Yapılandırması
// .eslintrc.json
{
"extends": ["eslint:recommended"],
"env": {
"node": true,
"es2021": true
},
"rules": {
"no-console": "warn",
"no-unused-vars": "error",
"prefer-const": "error"
}
}
Prettier Yapılandırması
// .prettierrc
{
"semi": true,
"trailingComma": "es5",
"singleQuote": true,
"printWidth": 80,
"tabWidth": 2
}
Test Stratejisi
Test Türleri
- Unit Tests: Fonksiyon ve bileşen testleri
- Integration Tests: API endpoint testleri
- E2E Tests: Kullanıcı senaryoları
- Manual Tests: Manuel QA süreçleri
Test Tools
# Test framework'leri
npm install --save-dev jest supertest
npm install --save-dev @testing-library/svelte
npm install --save-dev playwright
Örnek Testler
// tests/api.test.js
const request = require('supertest');
const app = require('../server/index');
describe('Authentication', () => {
test('POST /api/auth/login with valid credentials', async () => {
const response = await request(app)
.post('/api/auth/login')
.send({ username: 'admin', password: 'Admin!123' })
.expect(200);
expect(response.body).toHaveProperty('token');
expect(response.body.user.role).toBe('admin');
});
});
🚀 Prodüksiyon Dağıtımı
Dağıtım Seçenekleri
1. Docker Dağıtımı (Önerilen)
Dockerfile
# Multi-stage build
FROM node:18-alpine AS builder
# Build stage
WORKDIR /app
COPY package*.json ./
RUN npm ci --only=production
COPY . .
WORKDIR /app/client
RUN npm ci
RUN npm run build
# Production stage
FROM node:18-alpine AS production
WORKDIR /app
COPY --from=builder /app/package*.json ./
COPY --from=builder /app/node_modules ./node_modules
COPY --from=builder /app/server ./server
COPY --from=builder /app/client/dist ./client/dist
COPY --from=builder /app/data ./data
EXPOSE 5005
CMD ["node", "server/index.js"]
docker-compose.yml
version: '3.8'
services:
ytp-app:
build: .
ports:
- "5005:5005"
environment:
- NODE_ENV=production
- PORT=5005
volumes:
- ./data:/app/data
- ./logs:/app/logs
restart: unless-stopped
nginx:
image: nginx:alpine
ports:
- "80:80"
- "443:443"
volumes:
- ./nginx.conf:/etc/nginx/nginx.conf
- ./ssl:/etc/nginx/ssl
depends_on:
- ytp-app
restart: unless-stopped
Docker Komutları
# Build ve çalıştırma
docker-compose up -d --build
# Logları izleme
docker-compose logs -f ytp-app
# Yeniden başlatma
docker-compose restart ytp-app
# Temizleme
docker-compose down -v
2. PM2 ile Dağıtım
PM2 Yapılandırması
// ecosystem.config.js
module.exports = {
apps: [{
name: 'ytp-app',
script: 'server/index.js',
instances: 'max',
exec_mode: 'cluster',
env: {
NODE_ENV: 'production',
PORT: 5005
},
error_file: './logs/err.log',
out_file: './logs/out.log',
log_file: './logs/combined.log',
time: true
}]
};
PM2 Komutları
# PM2 kurulumu
npm install -g pm2
# Uygulamayı başlatma
pm2 start ecosystem.config.js
# Durumunu kontrol etme
pm2 status
# Logları izleme
pm2 logs ytp-app
# Yeniden başlatma
pm2 restart ytp-app
# Sunucu yeniden başlatığında otomatik başlatma
pm2 startup
pm2 save
3. Systemd Service
Service Dosyası
# /etc/systemd/system/ytp.service
[Unit]
Description=Yakit Takip Sistemi
After=network.target
[Service]
Type=simple
User=www-data
WorkingDirectory=/var/www/ytp
ExecStart=/usr/bin/node server/index.js
Restart=always
RestartSec=10
Environment=NODE_ENV=production
Environment=PORT=5005
[Install]
WantedBy=multi-user.target
Systemd Komutları
# Service'i etkinleştirme
sudo systemctl enable ytp.service
# Service'i başlatma
sudo systemctl start ytp.service
# Durumunu kontrol etme
sudo systemctl status ytp.service
# Logları izleme
sudo journalctl -u ytp.service -f
Nginx Yapılandırması
nginx.conf
events {
worker_connections 1024;
}
http {
upstream ytp_backend {
server 127.0.0.1:5005;
}
server {
listen 80;
server_name your-domain.com;
# Frontend statik dosyaları
location / {
root /var/www/ytp/client/dist;
try_files $uri $uri/ /index.html;
# Cache headers
location ~* \.(js|css|png|jpg|jpeg|gif|ico|svg)$ {
expires 1y;
add_header Cache-Control "public, immutable";
}
}
# API requests
location /api/ {
proxy_pass http://ytp_backend;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection 'upgrade';
proxy_set_header Host $host;
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;
proxy_cache_bypass $http_upgrade;
}
# WebSocket connections
location /socket.io/ {
proxy_pass http://ytp_backend;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
proxy_set_header Host $host;
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;
}
}
# HTTPS (SSL kuruluysa)
server {
listen 443 ssl http2;
server_name your-domain.com;
ssl_certificate /etc/nginx/ssl/cert.pem;
ssl_certificate_key /etc/nginx/ssl/key.pem;
ssl_protocols TLSv1.2 TLSv1.3;
ssl_ciphers HIGH:!aNULL:!MD5;
# Aynı proxy ayarları burada da geçerli
# ...
}
}
Prodüksiyon Kurulum Script'i
setup.sh
#!/bin/bash
# Prodüksiyon kurulum script'i
set -e
echo "🚀 YTP Prodüksiyon Kurulumu Başlatılıyor..."
# Sistem güncellemeleri
sudo apt update && sudo apt upgrade -y
# Node.js kurulumu
curl -fsSL https://deb.nodesource.com/setup_18.x | sudo -E bash -
sudo apt-get install -y nodejs
# PM2 kurulumu
sudo npm install -g pm2
# Nginx kurulumu
sudo apt install -y nginx
# Firewall ayarları
sudo ufw allow ssh
sudo ufw allow 'Nginx Full'
sudo ufw --force enable
# Proje kurulumu
sudo mkdir -p /var/www/ytp
sudo chown $USER:$USER /var/www/ytp
# Git ile projeyi çek
cd /var/www/ytp
git clone <repository-url> .
# Bağımlılıkları yükle
npm install
cd client && npm install && cd ..
# Veritabanını başlat
npm run prepare:db
# PM2 başlat
pm2 start ecosystem.config.js
pm2 startup
pm2 save
# Nginx yapılandırması
sudo cp nginx.conf /etc/nginx/sites-available/ytp
sudo ln -s /etc/nginx/sites-available/ytp /etc/nginx/sites-enabled/
sudo nginx -t && sudo systemctl reload nginx
echo "✅ Kurulum tamamlandı!"
echo "🌐 Uygulama: http://your-domain.com"
echo "📊 PM2 durumu: pm2 status"
echo "📋 Loglar: pm2 logs ytp-app"
📊 İzleme ve Bakım
Log Yönetimi
Log Yapılandırması
// server/logger.js
const winston = require('winston');
const logger = winston.createLogger({
level: process.env.LOG_LEVEL || 'info',
format: winston.format.combine(
winston.format.timestamp(),
winston.format.json()
),
transports: [
new winston.transports.File({ filename: 'logs/error.log', level: 'error' }),
new winston.transports.File({ filename: 'logs/combined.log' }),
new winston.transports.Console({
format: winston.format.simple()
})
]
});
module.exports = logger;
Log Rotasyon
# logrotate yapılandırması
# /etc/logrotate.d/ytp
/var/www/ytp/logs/*.log {
daily
missingok
rotate 52
compress
notifempty
create 644 www-data www-data
postrotate
pm2 reloadLogs
endscript
}
Performans İzleme
Metrics Collection
// server/metrics.js
const express = require('express');
const responseTime = require('response-time');
const app = express();
// Response time middleware
app.use(responseTime((req, res, time) => {
console.log(`${req.method} ${req.url} - ${time}ms`);
}));
// Health check endpoint
app.get('/health', (req, res) => {
res.json({
status: 'healthy',
timestamp: new Date().toISOString(),
uptime: process.uptime(),
memory: process.memoryUsage()
});
});
Backup Stratejisi
Database Backup Script
#!/bin/bash
# backup.sh
BACKUP_DIR="/var/backups/ytp"
DATE=$(date +%Y%m%d_%H%M%S)
DB_PATH="/var/www/ytp/data/app.db"
mkdir -p $BACKUP_DIR
# Veritabanı yedeği
sqlite3 $DB_PATH ".backup $BACKUP_DIR/app_backup_$DATE.db"
# Eski yedekleri temizle (30 gün)
find $BACKUP_DIR -name "app_backup_*.db" -mtime +30 -delete
echo "Backup completed: $BACKUP_DIR/app_backup_$DATE.db"
Cron Job
# Günlük backup (saat 02:00)
0 2 * * * /var/www/ytp/scripts/backup.sh
# Log rotation (haftalık)
0 3 * * 0 /usr/sbin/logrotate /etc/logrotate.d/ytp
# Sistem health check (5 dakikada bir)
*/5 * * * * curl -f http://localhost:5005/health || echo "Health check failed" | mail -s "YTP Alert" admin@domain.com
🔧 Sorun Giderme
Yaygın Sorunlar
1. Port Çakışması
# Port kullanan süreci bul
lsof -i :5005
# Süreci sonlandır
kill -9 <PID>
# Farklı port kullan
PORT=3000 npm start
2. Veritabanı Hataları
# Veritabanı dosyası izinleri
sudo chown www-data:www-data data/app.db
sudo chmod 664 data/app.db
# Veritabanı durumu
sqlite3 data/app.db ".tables"
sqlite3 data/app.db "SELECT COUNT(*) FROM fuel_slips;"
3. Memory Issues
# Memory kullanımı
free -h
ps aux --sort=-%mem | head
# Node.js memory limit
node --max-old-space-size=4096 server/index.js
4. Socket.IO Connection Issues
# WebSocket connection test
wscat -c ws://localhost:5005/socket.io/?EIO=4&transport=websocket
# Nginx log kontrolü
sudo tail -f /var/log/nginx/error.log
Debugging Tools
Node.js Debugging
# Debug mode
node --inspect server/index.js
# Chrome DevTools ile debugging
# chrome://inspect adresini açın
Network Debugging
# Port test
telnet localhost 5005
# SSL cert test
openssl s_client -connect your-domain.com:443
Performance Optimization
Database Optimization
-- Index ekleme
CREATE INDEX idx_fuel_slips_date ON fuel_slips(slip_date);
CREATE INDEX idx_fuel_slips_status ON fuel_slips(status);
-- Query optimization
EXPLAIN QUERY PLAN SELECT * FROM fuel_slips WHERE status = 'pending';
Frontend Optimization
// vite.config.js
export default {
build: {
rollupOptions: {
output: {
manualChunks: {
vendor: ['svelte'],
api: ['./src/api.js']
}
}
}
}
};
Not: Prodüksiyon dağıtımından önce mutlaka test ortamında tüm senaryoları doğrulayın.