Merge develop into main

- Add complete multi-environment deployment pipeline
- Add auto-promotion workflow (dev → staging → prod)
- Add smoke tests using canonical Knative domains only
- Add all Kubernetes manifests for dev/staging/prod
- Resolve LICENSE conflict using develop branch version
This commit is contained in:
Greg
2025-06-30 23:13:30 -07:00
43 changed files with 4213 additions and 1 deletions

216
.github/workflows/auto-promote.yml vendored Normal file
View File

@@ -0,0 +1,216 @@
name: Auto-Promote Pipeline
on:
workflow_run:
workflows: ["Deploy to Development"]
types:
- completed
branches: [ main ]
jobs:
test-and-promote:
name: Test Dev and Auto-Promote
runs-on: ubuntu-latest
if: ${{ github.event.workflow_run.conclusion == 'success' }}
steps:
- name: Checkout repository
uses: actions/checkout@v4
- name: Wait for dev deployment to settle
run: |
echo "⏳ Waiting for dev deployment to fully settle..."
sleep 60
- name: Run comprehensive dev tests
run: |
echo "🧪 Running comprehensive tests on dev environment..."
# Test canonical domain first (primary test)
echo "Testing canonical domain: game-2048-dev.game-2048-dev.dev.wa.darknex.us"
canonical_response=$(curl -s -o /dev/null -w "%{http_code}" -L --max-time 30 https://game-2048-dev.game-2048-dev.dev.wa.darknex.us/)
if [ "$canonical_response" != "200" ]; then
echo "❌ Canonical domain returned HTTP $canonical_response"
exit 1
fi
echo "✅ Canonical domain accessible"
# Test SSL certificate on custom domain
echo "Testing SSL certificate on custom domain..."
cert_expiry=$(echo | openssl s_client -servername 2048-dev.wa.darknex.us -connect 2048-dev.wa.darknex.us:443 2>/dev/null | openssl x509 -noout -enddate | cut -d= -f2)
expiry_epoch=$(date -d "$cert_expiry" +%s)
current_epoch=$(date +%s)
days_until_expiry=$(( (expiry_epoch - current_epoch) / 86400 ))
if [ $days_until_expiry -lt 30 ]; then
echo "❌ SSL certificate expires in less than 30 days!"
exit 1
fi
echo "✅ SSL certificate valid for $days_until_expiry days"
# Test custom domain accessibility
echo "Testing custom domain accessibility..."
response_code=$(curl -s -o /dev/null -w "%{http_code}" -L --max-time 30 https://2048-dev.wa.darknex.us/)
if [ "$response_code" != "200" ]; then
echo "❌ Custom domain returned HTTP $response_code"
exit 1
fi
echo "✅ Custom domain accessible"
# Test content validation on canonical domain
echo "Testing content validation on canonical domain..."
content=$(curl -s -L --max-time 30 https://game-2048-dev.game-2048-dev.dev.wa.darknex.us/)
if ! echo "$content" | grep -q "2048"; then
echo "❌ Content missing 2048 title"
exit 1
fi
if ! echo "$content" | grep -q "HOW TO PLAY"; then
echo "❌ Content missing game instructions"
exit 1
fi
if ! echo "$content" | grep -q "style.css"; then
echo "❌ CSS file not referenced"
exit 1
fi
if ! echo "$content" | grep -q "script.js"; then
echo "❌ JavaScript file not referenced"
exit 1
fi
echo "✅ All content validation tests passed"
# Test performance on canonical domain
echo "Testing performance on canonical domain..."
response_time=$(curl -s -o /dev/null -w "%{time_total}" -L --max-time 30 https://game-2048-dev.game-2048-dev.dev.wa.darknex.us/)
if (( $(echo "$response_time > 10.0" | bc -l) )); then
echo "❌ Response time too slow: ${response_time}s"
exit 1
fi
echo "✅ Performance test passed: ${response_time}s"
- name: Auto-promote to staging
uses: actions/github-script@v7
with:
github-token: ${{ secrets.GITHUB_TOKEN }}
script: |
console.log('🚀 All dev tests passed! Auto-promoting to staging...');
const response = await github.rest.actions.createWorkflowDispatch({
owner: context.repo.owner,
repo: context.repo.repo,
workflow_id: 'deploy-staging.yml',
ref: 'main',
inputs: {
image_tag: 'latest'
}
});
console.log('✅ Staging deployment triggered');
return response;
- name: Create promotion summary
run: |
echo "## 🎯 Auto-Promotion Summary" >> $GITHUB_STEP_SUMMARY
echo "" >> $GITHUB_STEP_SUMMARY
echo "| Stage | Status | Action |" >> $GITHUB_STEP_SUMMARY
echo "|-------|--------|--------|" >> $GITHUB_STEP_SUMMARY
echo "| Dev Tests | ✅ Passed | Comprehensive validation completed |" >> $GITHUB_STEP_SUMMARY
echo "| Staging | 🚀 Triggered | Auto-promotion initiated |" >> $GITHUB_STEP_SUMMARY
echo "" >> $GITHUB_STEP_SUMMARY
echo "### 📋 Tests Performed" >> $GITHUB_STEP_SUMMARY
echo "- SSL certificate validation" >> $GITHUB_STEP_SUMMARY
echo "- Domain accessibility check" >> $GITHUB_STEP_SUMMARY
echo "- Content and functionality validation" >> $GITHUB_STEP_SUMMARY
echo "- Performance testing" >> $GITHUB_STEP_SUMMARY
echo "" >> $GITHUB_STEP_SUMMARY
echo "### 🔗 Next Steps" >> $GITHUB_STEP_SUMMARY
echo "- Monitor staging deployment progress" >> $GITHUB_STEP_SUMMARY
echo "- Staging tests will run automatically" >> $GITHUB_STEP_SUMMARY
echo "- Production promotion requires manual approval" >> $GITHUB_STEP_SUMMARY
promote-to-production:
name: Test Staging and Promote to Production
runs-on: ubuntu-latest
needs: test-and-promote
if: success()
environment: production-approval # This requires manual approval
steps:
- name: Checkout repository
uses: actions/checkout@v4
- name: Wait for staging deployment
run: |
echo "⏳ Waiting for staging deployment to complete..."
sleep 120 # Give staging time to deploy
- name: Test staging environment
run: |
echo "🧪 Running staging tests..."
# Test canonical staging domain first
echo "Testing canonical staging domain: game-2048-staging.game-2048-staging.staging.wa.darknex.us"
canonical_response=$(curl -s -o /dev/null -w "%{http_code}" -L --max-time 30 https://game-2048-staging.game-2048-staging.staging.wa.darknex.us/)
if [ "$canonical_response" != "200" ]; then
echo "❌ Staging canonical domain returned HTTP $canonical_response"
exit 1
fi
echo "✅ Staging canonical domain accessible"
# Test custom staging domain
echo "Testing custom staging domain: 2048-staging.wa.darknex.us"
response_code=$(curl -s -o /dev/null -w "%{http_code}" -L --max-time 30 https://2048-staging.wa.darknex.us/)
if [ "$response_code" != "200" ]; then
echo "❌ Staging custom domain returned HTTP $response_code"
exit 1
fi
echo "✅ Staging custom domain accessible"
# Test staging content on canonical domain
echo "Testing staging content..."
content=$(curl -s -L --max-time 30 https://game-2048-staging.game-2048-staging.staging.wa.darknex.us/)
if ! echo "$content" | grep -q "2048"; then
echo "❌ Staging content validation failed"
exit 1
fi
echo "✅ Staging content validation passed"
- name: Auto-promote to production
uses: actions/github-script@v7
with:
github-token: ${{ secrets.GITHUB_TOKEN }}
script: |
console.log('🎯 Staging tests passed! Promoting to production...');
const response = await github.rest.actions.createWorkflowDispatch({
owner: context.repo.owner,
repo: context.repo.repo,
workflow_id: 'deploy-prod.yml',
ref: 'main',
inputs: {
image_tag: 'latest',
confirmation: 'DEPLOY'
}
});
console.log('🚀 Production deployment triggered');
return response;
- name: Create final summary
run: |
echo "## 🎉 Full Pipeline Completion" >> $GITHUB_STEP_SUMMARY
echo "" >> $GITHUB_STEP_SUMMARY
echo "| Environment | Status | URL |" >> $GITHUB_STEP_SUMMARY
echo "|-------------|--------|-----|" >> $GITHUB_STEP_SUMMARY
echo "| Development | ✅ Tested & Live | https://2048-dev.wa.darknex.us |" >> $GITHUB_STEP_SUMMARY
echo "| Staging | ✅ Tested & Live | https://2048-staging.wa.darknex.us |" >> $GITHUB_STEP_SUMMARY
echo "| Production | 🚀 Deploying | https://2048.wa.darknex.us |" >> $GITHUB_STEP_SUMMARY
echo "" >> $GITHUB_STEP_SUMMARY
echo "### 🎮 Your 2048 Game is Live!" >> $GITHUB_STEP_SUMMARY
echo "All environments have been automatically tested and promoted successfully." >> $GITHUB_STEP_SUMMARY

64
.github/workflows/build-image.yml vendored Normal file
View File

@@ -0,0 +1,64 @@
name: Build and Push Container Image
on:
push:
branches: [ main ]
pull_request:
branches: [ main ]
env:
REGISTRY: ghcr.io
IMAGE_NAME: ghndrx/k8s-game-2048
jobs:
build:
runs-on: ubuntu-latest
permissions:
contents: read
packages: write
steps:
- name: Checkout repository
uses: actions/checkout@v4
- name: Log in to Container Registry
uses: docker/login-action@v3
with:
registry: ${{ env.REGISTRY }}
username: ${{ github.actor }}
password: ${{ secrets.GITHUB_TOKEN }}
- name: Extract metadata
id: meta
uses: docker/metadata-action@v5
with:
images: ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}
tags: |
type=ref,event=branch
type=ref,event=pr
type=sha,prefix={{branch}}-
type=raw,value=latest,enable={{is_default_branch}}
- name: Build and push container image
uses: docker/build-push-action@v5
with:
context: .
push: true
tags: ${{ steps.meta.outputs.tags }}
labels: ${{ steps.meta.outputs.labels }}
- name: Create build summary
run: |
echo "## 📦 Container Image Build Summary" >> $GITHUB_STEP_SUMMARY
echo "" >> $GITHUB_STEP_SUMMARY
echo "| Field | Value |" >> $GITHUB_STEP_SUMMARY
echo "|-------|-------|" >> $GITHUB_STEP_SUMMARY
echo "| Registry | ${{ env.REGISTRY }} |" >> $GITHUB_STEP_SUMMARY
echo "| Image | ${{ env.IMAGE_NAME }} |" >> $GITHUB_STEP_SUMMARY
echo "| Tags | $(echo '${{ steps.meta.outputs.tags }}' | tr '\n' ', ') |" >> $GITHUB_STEP_SUMMARY
echo "| Trigger | ${{ github.event_name }} |" >> $GITHUB_STEP_SUMMARY
echo "" >> $GITHUB_STEP_SUMMARY
echo "### Next Steps" >> $GITHUB_STEP_SUMMARY
echo "- 🧪 Development deployment will trigger automatically" >> $GITHUB_STEP_SUMMARY
echo "- 🎭 [Deploy to staging manually](https://github.com/${{ github.repository }}/actions/workflows/deploy-staging.yml)" >> $GITHUB_STEP_SUMMARY
echo "- 🚀 [Deploy to production manually](https://github.com/${{ github.repository }}/actions/workflows/deploy-prod.yml)" >> $GITHUB_STEP_SUMMARY

217
.github/workflows/deploy-dev.yml vendored Normal file
View File

@@ -0,0 +1,217 @@
name: Deploy to Development
on:
workflow_run:
workflows: ["Build and Push Container Image"]
types:
- completed
branches: [ main ]
push:
branches: [ main ]
workflow_dispatch:
inputs:
image_tag:
description: 'Image tag to deploy (default: latest)'
required: false
default: 'latest'
env:
REGISTRY: ghcr.io
IMAGE_NAME: ghndrx/k8s-game-2048
jobs:
deploy-dev:
name: Deploy to Development
runs-on: ubuntu-latest
if: ${{ github.event.workflow_run.conclusion == 'success' || github.event_name == 'workflow_dispatch' }}
environment: development
steps:
- name: Checkout repository
uses: actions/checkout@v4
- name: Set up kubectl
uses: azure/setup-kubectl@v3
with:
version: 'latest'
- name: Configure kubectl
run: |
mkdir -p ~/.kube
echo "${{ secrets.KUBECONFIG }}" | base64 -d > ~/.kube/config
chmod 600 ~/.kube/config
- name: Set image tag
run: |
IMAGE_TAG="${{ github.event.inputs.image_tag || 'latest' }}"
echo "IMAGE_TAG=$IMAGE_TAG" >> $GITHUB_ENV
echo "Deploying image: ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}:$IMAGE_TAG"
- name: Deploy to development
run: |
echo "🚀 Deploying to development environment..."
# Apply namespace
kubectl apply -f manifests/dev/namespace.yml
# Ensure GHCR secret exists
if kubectl get secret ghcr-secret -n default &>/dev/null; then
echo "🔐 Copying GHCR secret to dev namespace..."
kubectl get secret ghcr-secret -o yaml | \
sed 's/namespace: default/namespace: game-2048-dev/' | \
sed '/resourceVersion:/d' | \
sed '/uid:/d' | \
sed '/creationTimestamp:/d' | \
kubectl apply -f -
fi
# Update image in service and deploy
kubectl patch ksvc game-2048-dev -n game-2048-dev --type merge -p '{"spec":{"template":{"spec":{"containers":[{"image":"${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}:${{ env.IMAGE_TAG }}","imagePullPolicy":"Always"}]}}}}'
echo "⏳ Waiting for deployment to be ready..."
kubectl wait --for=condition=Ready ksvc/game-2048-dev -n game-2048-dev --timeout=300s || echo "⚠️ Service may still be starting"
- name: Verify deployment
run: |
echo "📊 Deployment status:"
kubectl get ksvc -n game-2048-dev
echo ""
echo "✅ Development deployment completed!"
echo "🌐 Available at: https://2048-dev.wa.darknex.us"
- name: Run smoke test
run: |
echo "🧪 Running smoke test..."
sleep 30
for i in {1..5}; do
echo "Attempt $i/5..."
# Test canonical domain first
if curl -s --max-time 30 https://game-2048-dev.game-2048-dev.dev.wa.darknex.us/ | grep -q "2048"; then
echo "✅ Canonical domain smoke test passed!"
break
# Fallback to custom domain
elif curl -s --max-time 30 https://2048-dev.wa.darknex.us/ | grep -q "2048"; then
echo "✅ Custom domain smoke test passed!"
break
elif [ $i -eq 5 ]; then
echo "⚠️ Smoke test failed after 5 attempts"
exit 1
else
echo "Retrying in 30 seconds..."
sleep 30
fi
done
uses: azure/setup-kubectl@v3
with:
version: 'v1.28.0'
- name: Configure kubectl
run: |
echo "${{ secrets.KUBECONFIG }}" | base64 -d > kubeconfig
export KUBECONFIG=kubeconfig
- name: Update image in manifests
run: |
sed -i "s|ghcr.io/ghndrx/k8s-game-2048:latest|${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}:${{ github.sha }}|g" manifests/dev/service.yml
- name: Deploy to development
run: |
export KUBECONFIG=kubeconfig
kubectl apply -f manifests/dev/
- name: Wait for deployment
run: |
export KUBECONFIG=kubeconfig
kubectl wait --for=condition=Ready ksvc/game-2048-dev -n game-2048-dev --timeout=300s
- name: Get service URL
id: get-url
run: |
export KUBECONFIG=kubeconfig
SERVICE_URL=$(kubectl get ksvc game-2048-dev -n game-2048-dev -o jsonpath='{.status.url}')
echo "service_url=$SERVICE_URL" >> $GITHUB_OUTPUT
echo "🚀 Development service deployed at: $SERVICE_URL"
- name: Set up Node.js for testing
uses: actions/setup-node@v4
with:
node-version: '18'
cache: 'npm'
cache-dependency-path: tests/package.json
- name: Install Playwright dependencies
run: |
cd tests
npm install
npx playwright install --with-deps
- name: Run Playwright tests
run: |
cd tests
BASE_URL=${{ steps.get-url.outputs.service_url }} npx playwright test
env:
CI: true
- name: Upload test results
uses: actions/upload-artifact@v4
if: always()
with:
name: playwright-results-dev-${{ github.sha }}-${{ github.run_number }}
path: |
tests/playwright-report/
tests/test-results/
retention-days: 30
- name: Upload screenshots
uses: actions/upload-artifact@v4
if: always()
with:
name: screenshots-dev-${{ github.sha }}-${{ github.run_number }}
path: tests/test-results/**/*.png
retention-days: 30
promote-to-staging:
needs: build-and-deploy
runs-on: ubuntu-latest
if: github.event_name == 'push' && github.ref == 'refs/heads/develop'
steps:
- name: Checkout repository
uses: actions/checkout@v4
with:
fetch-depth: 0
- name: Create Pull Request to Staging
uses: peter-evans/create-pull-request@v5
with:
token: ${{ secrets.GITHUB_TOKEN }}
push-to-fork: false
branch: auto-promote/dev-to-staging-${{ github.sha }}
base: staging
title: "🚀 Auto-promote: Deploy ${{ github.sha }} to staging"
body: |
## 🚀 Auto-promotion from Development
**Source**: `develop` branch
**Commit**: ${{ github.sha }}
**Triggered by**: @${{ github.actor }}
### ✅ Development Tests Passed
- Basic functionality tests
- Gameplay mechanics tests
- Visual regression tests
- Environment validation tests
### 🎯 Changes in this promotion:
${{ github.event.head_commit.message }}
This PR was automatically created after successful deployment and testing in the development environment.
**Development URL**: https://2048-dev.wa.darknex.us
**Will deploy to**: https://2048-staging.wa.darknex.us
labels: |
auto-promotion
staging
deploy

262
.github/workflows/deploy-prod.yml vendored Normal file
View File

@@ -0,0 +1,262 @@
name: Deploy to Production
on:
workflow_dispatch:
inputs:
image_tag:
description: 'Image tag to deploy (default: latest)'
required: false
default: 'latest'
confirmation:
description: 'Type "DEPLOY" to confirm production deployment'
required: true
env:
REGISTRY: ghcr.io
IMAGE_NAME: ghndrx/k8s-game-2048
jobs:
deploy-prod:
name: Deploy to Production
runs-on: ubuntu-latest
environment: production
if: ${{ github.event.inputs.confirmation == 'DEPLOY' }}
steps:
- name: Checkout repository
uses: actions/checkout@v4
- name: Set up kubectl
uses: azure/setup-kubectl@v3
with:
version: 'latest'
- name: Configure kubectl
run: |
mkdir -p ~/.kube
echo "${{ secrets.KUBECONFIG }}" | base64 -d > ~/.kube/config
chmod 600 ~/.kube/config
- name: Set image tag
run: |
IMAGE_TAG="${{ github.event.inputs.image_tag || 'latest' }}"
echo "IMAGE_TAG=$IMAGE_TAG" >> $GITHUB_ENV
echo "Deploying image: ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}:$IMAGE_TAG"
- name: Deploy to production
run: |
echo "🚀 Deploying to production environment..."
# Apply namespace
kubectl apply -f manifests/prod/namespace.yml
# Ensure GHCR secret exists
if kubectl get secret ghcr-secret -n default &>/dev/null; then
echo "🔐 Copying GHCR secret to prod namespace..."
kubectl get secret ghcr-secret -o yaml | \
sed 's/namespace: default/namespace: game-2048-prod/' | \
sed '/resourceVersion:/d' | \
sed '/uid:/d' | \
sed '/creationTimestamp:/d' | \
kubectl apply -f -
fi
# Update image in service and deploy
kubectl patch ksvc game-2048-prod -n game-2048-prod --type merge -p '{"spec":{"template":{"spec":{"containers":[{"image":"${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}:${{ env.IMAGE_TAG }}","imagePullPolicy":"Always"}]}}}}'
echo "⏳ Waiting for deployment to be ready..."
kubectl wait --for=condition=Ready ksvc/game-2048-prod -n game-2048-prod --timeout=300s || echo "⚠️ Service may still be starting"
- name: Verify deployment
run: |
echo "📊 Deployment status:"
kubectl get ksvc -n game-2048-prod
echo ""
echo "✅ Production deployment completed!"
echo "🌐 Available at: https://2048.wa.darknex.us"
- name: Run smoke test
run: |
echo "🧪 Running smoke test..."
sleep 30
for i in {1..5}; do
echo "Attempt $i/5..."
# Test canonical domain first
if curl -s --max-time 30 https://game-2048-prod.game-2048-prod.wa.darknex.us/ | grep -q "2048"; then
echo "✅ Canonical domain smoke test passed!"
break
# Fallback to custom domain
elif curl -s --max-time 30 https://2048.wa.darknex.us/ | grep -q "2048"; then
echo "✅ Custom domain smoke test passed!"
break
elif [ $i -eq 5 ]; then
echo "⚠️ Smoke test failed after 5 attempts"
exit 1
else
echo "Retrying in 30 seconds..."
sleep 30
fi
done
- name: Create production deployment summary
run: |
echo "## 🚀 Production Deployment Summary" >> $GITHUB_STEP_SUMMARY
echo "" >> $GITHUB_STEP_SUMMARY
echo "| Field | Value |" >> $GITHUB_STEP_SUMMARY
echo "|-------|-------|" >> $GITHUB_STEP_SUMMARY
echo "| Environment | **Production** |" >> $GITHUB_STEP_SUMMARY
echo "| Image | \`${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}:${{ env.IMAGE_TAG }}\` |" >> $GITHUB_STEP_SUMMARY
echo "| Domain | https://2048.wa.darknex.us |" >> $GITHUB_STEP_SUMMARY
echo "| Status | ✅ **LIVE** |" >> $GITHUB_STEP_SUMMARY
echo "" >> $GITHUB_STEP_SUMMARY
echo "### 🎉 Production is Live!" >> $GITHUB_STEP_SUMMARY
echo "- 🎮 [Play the game](https://2048.wa.darknex.us)" >> $GITHUB_STEP_SUMMARY
echo "- 🧪 [Run smoke tests](https://github.com/${{ github.repository }}/actions/workflows/smoke-test.yml)" >> $GITHUB_STEP_SUMMARY
- name: Log in to Container Registry
uses: docker/login-action@v3
with:
registry: ${{ env.REGISTRY }}
username: ${{ github.actor }}
password: ${{ secrets.GITHUB_TOKEN }}
- name: Extract metadata
id: meta
uses: docker/metadata-action@v5
with:
images: ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}
tags: |
type=ref,event=tag
type=semver,pattern={{version}}
type=semver,pattern={{major}}.{{minor}}
- name: Build and push Docker image
uses: docker/build-push-action@v5
with:
context: .
push: true
tags: ${{ steps.meta.outputs.tags }}
labels: ${{ steps.meta.outputs.labels }}
- name: Set up kubectl
uses: azure/setup-kubectl@v3
with:
version: 'v1.28.0'
- name: Configure kubectl
run: |
echo "${{ secrets.KUBECONFIG }}" | base64 -d > kubeconfig
export KUBECONFIG=kubeconfig
- name: Update image in manifests
run: |
TAG="${{ github.event.release.tag_name || github.event.inputs.tag }}"
sed -i "s|ghcr.io/ghndrx/k8s-game-2048:v1.0.0|${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}:${TAG}|g" manifests/prod/service.yml
- name: Deploy to production with blue-green strategy
run: |
export KUBECONFIG=kubeconfig
# Deploy new revision with 0% traffic
kubectl apply -f manifests/prod/
# Wait for new revision to be ready
kubectl wait --for=condition=Ready ksvc/game-2048-prod -n game-2048-prod --timeout=300s
# Get the latest revision name
LATEST_REVISION=$(kubectl get ksvc game-2048-prod -n game-2048-prod -o jsonpath='{.status.latestReadyRevisionName}')
# Gradually shift traffic (10%, 50%, 100%)
kubectl patch ksvc game-2048-prod -n game-2048-prod --type='merge' -p='{"spec":{"traffic":[{"revisionName":"'$LATEST_REVISION'","percent":10},{"latestRevision":false,"percent":90}]}}'
sleep 60
kubectl patch ksvc game-2048-prod -n game-2048-prod --type='merge' -p='{"spec":{"traffic":[{"revisionName":"'$LATEST_REVISION'","percent":50},{"latestRevision":false,"percent":50}]}}'
sleep 60
kubectl patch ksvc game-2048-prod -n game-2048-prod --type='merge' -p='{"spec":{"traffic":[{"latestRevision":true,"percent":100}]}}'
- name: Run production health checks
run: |
# Wait for traffic to stabilize
sleep 60
# Test the production URL
curl -f https://2048.wa.darknex.us/ || exit 1
# Additional health checks can be added here
- name: Get service URL
id: get-url
run: |
export KUBECONFIG=kubeconfig
SERVICE_URL=$(kubectl get ksvc game-2048-prod -n game-2048-prod -o jsonpath='{.status.url}')
echo "service_url=$SERVICE_URL" >> $GITHUB_OUTPUT
echo "🚀 Production service deployed at: $SERVICE_URL"
- name: Set up Node.js for testing
uses: actions/setup-node@v4
with:
node-version: '18'
cache: 'npm'
cache-dependency-path: tests/package.json
- name: Install Playwright dependencies
run: |
cd tests
npm install
npx playwright install --with-deps
- name: Run production smoke tests
run: |
cd tests
BASE_URL=${{ steps.get-url.outputs.service_url }} npx playwright test environment.spec.ts
env:
CI: true
- name: Run full test suite
run: |
cd tests
BASE_URL=${{ steps.get-url.outputs.service_url }} npx playwright test
env:
CI: true
- name: Upload production test results
uses: actions/upload-artifact@v4
if: always()
with:
name: playwright-results-production-${{ github.sha }}-${{ github.run_number }}
path: |
tests/playwright-report/
tests/test-results/
retention-days: 90
- name: Upload production screenshots
uses: actions/upload-artifact@v4
if: always()
with:
name: screenshots-production-${{ github.sha }}-${{ github.run_number }}
path: tests/test-results/**/*.png
retention-days: 90
- name: Production health validation
run: |
# Extended health checks for production
echo "🔍 Running production health checks..."
# Test main URL
curl -f https://2048.wa.darknex.us/ || exit 1
# Test health endpoint
curl -f https://2048.wa.darknex.us/health || exit 1
# Check response times
RESPONSE_TIME=$(curl -o /dev/null -s -w '%{time_total}' https://2048.wa.darknex.us/)
echo "Response time: ${RESPONSE_TIME}s"
# Fail if response time > 3 seconds
if (( $(echo "$RESPONSE_TIME > 3.0" | bc -l) )); then
echo "❌ Response time too slow: ${RESPONSE_TIME}s"
exit 1
fi
echo "✅ All production health checks passed!"

273
.github/workflows/deploy-staging.yml vendored Normal file
View File

@@ -0,0 +1,273 @@
name: Deploy to Staging
on:
workflow_dispatch:
inputs:
image_tag:
description: 'Image tag to deploy (default: latest)'
required: false
default: 'latest'
env:
REGISTRY: ghcr.io
IMAGE_NAME: ghndrx/k8s-game-2048
jobs:
deploy-staging:
name: Deploy to Staging
runs-on: ubuntu-latest
environment: staging
steps:
- name: Checkout repository
uses: actions/checkout@v4
- name: Set up kubectl
uses: azure/setup-kubectl@v3
with:
version: 'latest'
- name: Configure kubectl
run: |
mkdir -p ~/.kube
echo "${{ secrets.KUBECONFIG }}" | base64 -d > ~/.kube/config
chmod 600 ~/.kube/config
- name: Set image tag
run: |
IMAGE_TAG="${{ github.event.inputs.image_tag || 'latest' }}"
echo "IMAGE_TAG=$IMAGE_TAG" >> $GITHUB_ENV
echo "Deploying image: ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}:$IMAGE_TAG"
- name: Deploy to staging
run: |
echo "🚀 Deploying to staging environment..."
# Apply namespace
kubectl apply -f manifests/staging/namespace.yml
# Ensure GHCR secret exists
if kubectl get secret ghcr-secret -n default &>/dev/null; then
echo "🔐 Copying GHCR secret to staging namespace..."
kubectl get secret ghcr-secret -o yaml | \
sed 's/namespace: default/namespace: game-2048-staging/' | \
sed '/resourceVersion:/d' | \
sed '/uid:/d' | \
sed '/creationTimestamp:/d' | \
kubectl apply -f -
fi
# Update image in service and deploy
kubectl patch ksvc game-2048-staging -n game-2048-staging --type merge -p '{"spec":{"template":{"spec":{"containers":[{"image":"${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}:${{ env.IMAGE_TAG }}","imagePullPolicy":"Always"}]}}}}'
echo "⏳ Waiting for deployment to be ready..."
kubectl wait --for=condition=Ready ksvc/game-2048-staging -n game-2048-staging --timeout=300s || echo "⚠️ Service may still be starting"
- name: Verify deployment
run: |
echo "📊 Deployment status:"
kubectl get ksvc -n game-2048-staging
echo ""
echo "✅ Staging deployment completed!"
echo "🌐 Available at: https://2048-staging.wa.darknex.us"
- name: Run smoke test
run: |
echo "🧪 Running smoke test..."
sleep 30
for i in {1..5}; do
echo "Attempt $i/5..."
# Test canonical domain first
if curl -s --max-time 30 https://game-2048-staging.game-2048-staging.staging.wa.darknex.us/ | grep -q "2048"; then
echo "✅ Canonical domain smoke test passed!"
break
# Fallback to custom domain
elif curl -s --max-time 30 https://2048-staging.wa.darknex.us/ | grep -q "2048"; then
echo "✅ Custom domain smoke test passed!"
break
elif [ $i -eq 5 ]; then
echo "⚠️ Smoke test failed after 5 attempts"
exit 1
else
echo "Retrying in 30 seconds..."
sleep 30
fi
done
id: meta
uses: docker/metadata-action@v5
with:
images: ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}
tags: |
type=ref,event=branch
type=sha,prefix=staging-
- name: Build and push Docker image
uses: docker/build-push-action@v5
with:
context: .
push: true
tags: ${{ steps.meta.outputs.tags }}
labels: ${{ steps.meta.outputs.labels }}
- name: Set up kubectl
uses: azure/setup-kubectl@v3
with:
version: 'v1.28.0'
- name: Configure kubectl
run: |
echo "${{ secrets.KUBECONFIG }}" | base64 -d > kubeconfig
export KUBECONFIG=kubeconfig
- name: Update image in manifests
run: |
sed -i "s|ghcr.io/ghndrx/k8s-game-2048:staging|${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}:staging-${{ github.sha }}|g" manifests/staging/service.yml
- name: Deploy to staging
run: |
export KUBECONFIG=kubeconfig
kubectl apply -f manifests/staging/
- name: Wait for deployment
run: |
export KUBECONFIG=kubeconfig
kubectl wait --for=condition=Ready ksvc/game-2048-staging -n game-2048-staging --timeout=300s
- name: Run smoke tests
run: |
# Wait a bit for the service to be fully ready
sleep 30
# Test the staging URL
curl -f https://2048-staging.wa.darknex.us/ || exit 1
- name: Get service URL
id: get-url
run: |
export KUBECONFIG=kubeconfig
SERVICE_URL=$(kubectl get ksvc game-2048-staging -n game-2048-staging -o jsonpath='{.status.url}')
echo "service_url=$SERVICE_URL" >> $GITHUB_OUTPUT
echo "🚀 Staging service deployed at: $SERVICE_URL"
- name: Set up Node.js for testing
uses: actions/setup-node@v4
with:
node-version: '18'
cache: 'npm'
cache-dependency-path: tests/package.json
- name: Install Playwright dependencies
run: |
cd tests
npm install
npx playwright install --with-deps
- name: Run comprehensive Playwright tests
run: |
cd tests
BASE_URL=${{ steps.get-url.outputs.service_url }} npx playwright test
env:
CI: true
- name: Upload test results
uses: actions/upload-artifact@v4
if: always()
with:
name: playwright-results-staging-${{ github.sha }}-${{ github.run_number }}
path: |
tests/playwright-report/
tests/test-results/
retention-days: 30
- name: Upload screenshots
uses: actions/upload-artifact@v4
if: always()
with:
name: screenshots-staging-${{ github.sha }}-${{ github.run_number }}
path: tests/test-results/**/*.png
retention-days: 30
promote-to-master:
needs: build-and-deploy
runs-on: ubuntu-latest
if: github.event_name == 'push' && github.ref == 'refs/heads/staging'
steps:
- name: Checkout repository
uses: actions/checkout@v4
with:
fetch-depth: 0
- name: Create Pull Request to Master
uses: peter-evans/create-pull-request@v5
with:
token: ${{ secrets.GITHUB_TOKEN }}
push-to-fork: false
branch: auto-promote/staging-to-master-${{ github.sha }}
base: master
title: "🚀 Auto-promote: Deploy ${{ github.sha }} to production"
body: |
## 🚀 Auto-promotion from Staging
**Source**: `staging` branch
**Commit**: ${{ github.sha }}
**Triggered by**: @${{ github.actor }}
### ✅ Staging Tests Passed
- Basic functionality tests
- Gameplay mechanics tests
- Visual regression tests
- Environment validation tests
### 🎯 Changes in this promotion:
${{ github.event.head_commit.message }}
This PR was automatically created after successful deployment and testing in the staging environment.
**Staging URL**: https://2048-staging.wa.darknex.us
**Will deploy to**: https://2048.wa.darknex.us
⚠️ **Production Deployment** - Please review carefully before merging!
labels: |
auto-promotion
production
deploy
needs-review
- name: Create Pull Request to Master
uses: peter-evans/create-pull-request@v5
with:
token: ${{ secrets.GITHUB_TOKEN }}
push-to-fork: false
branch: auto-promote/staging-to-master-${{ github.sha }}
base: master
title: "🚀 Auto-promote: Deploy ${{ github.sha }} to production"
body: |
## 🚀 Auto-promotion from Staging
**Source**: `staging` branch
**Commit**: ${{ github.sha }}
**Triggered by**: @${{ github.actor }}
### ✅ Staging Tests Passed
- Basic functionality tests
- Gameplay mechanics tests
- Visual regression tests
- Environment validation tests
- Performance tests
### 🎯 Changes in this promotion:
${{ github.event.head_commit.message }}
This PR was automatically created after successful deployment and testing in the staging environment.
**Staging URL**: https://2048-staging.wa.darknex.us
**Will deploy to**: https://2048.wa.darknex.us
⚠️ **Production Deployment** - Please review carefully before merging!
labels: |
auto-promotion
production
deploy
needs-review

109
.github/workflows/pr-validation.yml vendored Normal file
View File

@@ -0,0 +1,109 @@
name: Pull Request Validation
on:
pull_request:
branches: [ develop, staging, master ]
env:
REGISTRY: ghcr.io
IMAGE_NAME: ghndrx/k8s-game-2048
jobs:
validate:
runs-on: ubuntu-latest
permissions:
contents: read
packages: write
pull-requests: write
steps:
- name: Checkout repository
uses: actions/checkout@v4
- name: Set up Node.js
uses: actions/setup-node@v4
with:
node-version: '18'
cache: 'npm'
cache-dependency-path: tests/package.json
- name: Install Playwright dependencies
run: |
cd tests
npm install
npx playwright install --with-deps
- name: Start local server
run: |
npm start &
sleep 5
curl -f http://localhost:8080/ || exit 1
env:
CI: true
- name: Run Playwright tests locally
run: |
cd tests
BASE_URL=http://localhost:8080 npx playwright test
env:
CI: true
- name: Build Docker image
uses: docker/build-push-action@v5
with:
context: .
push: false
tags: ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}:pr-${{ github.event.number }}
- name: Validate Kubernetes manifests
run: |
# Install kubeval for validation
curl -L https://github.com/instrumenta/kubeval/releases/latest/download/kubeval-linux-amd64.tar.gz | tar xz
sudo mv kubeval /usr/local/bin
# Validate all manifests
kubeval manifests/dev/*.yml
kubeval manifests/staging/*.yml
kubeval manifests/prod/*.yml
- name: Upload PR test results
uses: actions/upload-artifact@v4
if: always()
with:
name: pr-test-results-${{ github.event.number }}
path: |
tests/playwright-report/
tests/test-results/
retention-days: 7
- name: Comment PR with test results
uses: actions/github-script@v7
if: always()
with:
script: |
const { owner, repo } = context.repo;
const issue_number = context.payload.pull_request.number;
const comment = `## 🧪 PR Validation Results
**Tests Status**: ${{ job.status == 'success' && '✅ Passed' || '❌ Failed' }}
**Commit**: ${{ github.event.pull_request.head.sha }}
### Test Summary:
- ✅ Local server started successfully
- ✅ Playwright tests executed
- ✅ Docker image built
- ✅ Kubernetes manifests validated
### Artifacts:
- Test results and screenshots are available in the workflow artifacts
${{ job.status == 'success' && '🚀 Ready for merge!' || '⚠️ Please check the failed tests and fix issues before merging.' }}
`;
await github.rest.issues.createComment({
owner,
repo,
issue_number,
body: comment
});

231
.github/workflows/smoke-test.yml vendored Normal file
View File

@@ -0,0 +1,231 @@
name: Smoke Tests
on:
push:
branches: [ main, develop ]
pull_request:
branches: [ main ]
schedule:
# Run smoke tests every 6 hours
- cron: '0 */6 * * *'
workflow_dispatch:
inputs:
environment:
description: 'Environment to test (dev, staging, prod, all)'
required: false
default: 'all'
type: choice
options:
- all
- dev
- staging
- prod
jobs:
smoke-tests:
name: Smoke Tests
runs-on: ubuntu-latest
strategy:
fail-fast: false
matrix:
environment:
- ${{ github.event.inputs.environment == 'all' && 'dev' || github.event.inputs.environment || 'dev' }}
- ${{ github.event.inputs.environment == 'all' && 'staging' || '' }}
- ${{ github.event.inputs.environment == 'all' && 'prod' || '' }}
exclude:
- environment: ''
steps:
- name: Checkout code
uses: actions/checkout@v4
- name: Set environment variables
run: |
case "${{ matrix.environment }}" in
dev)
echo "CANONICAL_DOMAIN=game-2048-dev.game-2048-dev.dev.wa.darknex.us" >> $GITHUB_ENV
echo "ENV_NAME=development" >> $GITHUB_ENV
;;
staging)
echo "CANONICAL_DOMAIN=game-2048-staging.game-2048-staging.staging.wa.darknex.us" >> $GITHUB_ENV
echo "ENV_NAME=staging" >> $GITHUB_ENV
;;
prod)
echo "CANONICAL_DOMAIN=game-2048-prod.game-2048-prod.wa.darknex.us" >> $GITHUB_ENV
echo "ENV_NAME=production" >> $GITHUB_ENV
;;
esac
- name: Test Canonical Domain Accessibility
run: |
echo "🎯 Testing canonical Knative domain: ${{ env.CANONICAL_DOMAIN }}"
# Test HTTPS access to canonical domain
response_code=$(curl -s -o /dev/null -w "%{http_code}" -L --max-time 30 https://${{ env.CANONICAL_DOMAIN }}/)
echo "Canonical domain HTTP response code: $response_code"
if [ "$response_code" != "200" ]; then
echo "❌ Canonical domain ${{ env.CANONICAL_DOMAIN }} returned HTTP $response_code"
exit 1
else
echo "✅ Canonical domain ${{ env.CANONICAL_DOMAIN }} is accessible"
fi
- name: Test Content Validation
run: |
echo "📄 Testing content validation on canonical domain: ${{ env.CANONICAL_DOMAIN }}"
# Download the page content from canonical domain
content=$(curl -s -L --max-time 30 https://${{ env.CANONICAL_DOMAIN }}/)
# Check if it contains expected 2048 game elements
if echo "$content" | grep -q "2048"; then
echo "✅ Page contains '2048' title"
else
echo "❌ Page does not contain '2048' title"
exit 1
fi
if echo "$content" | grep -q "HOW TO PLAY"; then
echo "✅ Page contains game instructions"
else
echo "❌ Page does not contain game instructions"
exit 1
fi
if echo "$content" | grep -q "Environment.*${{ env.ENV_NAME }}"; then
echo "✅ Page shows correct environment: ${{ env.ENV_NAME }}"
else
echo "⚠️ Environment indicator not found or incorrect"
# Don't fail on this, just warn
fi
# Check if CSS and JS files are referenced
if echo "$content" | grep -q "style.css"; then
echo "✅ CSS file is referenced"
else
echo "❌ CSS file is not referenced"
exit 1
fi
if echo "$content" | grep -q "script.js"; then
echo "✅ JavaScript file is referenced"
else
echo "❌ JavaScript file is not referenced"
exit 1
fi
- name: Test Performance
run: |
echo "⚡ Testing performance for canonical domain: ${{ env.CANONICAL_DOMAIN }}"
# Measure response time on canonical domain
response_time=$(curl -s -o /dev/null -w "%{time_total}" -L --max-time 30 https://${{ env.CANONICAL_DOMAIN }}/)
echo "Canonical domain response time: ${response_time}s"
# Check if response time is reasonable (under 10 seconds)
if (( $(echo "$response_time < 10.0" | bc -l) )); then
echo "✅ Canonical domain response time is acceptable"
else
echo "⚠️ Canonical domain response time is slow: ${response_time}s"
fi
# Check content size
content_size=$(curl -s -L --max-time 30 https://${{ env.CANONICAL_DOMAIN }}/ | wc -c)
echo "Content size: $content_size bytes"
if [ $content_size -gt 1000 ]; then
echo "✅ Content size is reasonable"
else
echo "❌ Content size is too small: $content_size bytes"
exit 1
fi
test-canonical-domains:
name: Canonical Domain Infrastructure Tests
runs-on: ubuntu-latest
if: github.event.inputs.environment == 'all' || github.event.inputs.environment == '' || github.event_name != 'workflow_dispatch'
steps:
- name: Checkout code
uses: actions/checkout@v4
- name: Test Canonical Domain DNS Resolution
run: |
echo "🌐 Testing canonical domain DNS resolution"
canonical_domains=(
"game-2048-dev.game-2048-dev.dev.wa.darknex.us"
"game-2048-staging.game-2048-staging.staging.wa.darknex.us"
"game-2048-prod.game-2048-prod.wa.darknex.us"
)
for domain in "${canonical_domains[@]}"; do
echo "Testing DNS for canonical domain: $domain"
ip=$(dig +short $domain)
if [ -n "$ip" ]; then
echo "✅ $domain resolves to: $ip"
else
echo "❌ $domain does not resolve"
exit 1
fi
done
- name: Test Canonical Domain SSL Certificate Chain
run: |
echo "🔐 Testing SSL certificate chains for canonical domains"
canonical_domains=(
"game-2048-dev.game-2048-dev.dev.wa.darknex.us"
"game-2048-staging.game-2048-staging.staging.wa.darknex.us"
"game-2048-prod.game-2048-prod.wa.darknex.us"
)
for domain in "${canonical_domains[@]}"; do
echo "Testing SSL chain for canonical domain: $domain"
# Test certificate chain
chain_result=$(echo | openssl s_client -servername $domain -connect $domain:443 -verify_return_error 2>&1)
if echo "$chain_result" | grep -q "Verify return code: 0"; then
echo "✅ $domain has valid SSL certificate chain"
else
echo "❌ $domain has invalid SSL certificate chain"
echo "$chain_result"
exit 1
fi
done
summary:
name: Test Summary
runs-on: ubuntu-latest
needs: [smoke-tests, test-canonical-domains]
if: always()
steps:
- name: Check test results
run: |
if [ "${{ needs.smoke-tests.result }}" = "success" ] && [ "${{ needs.test-canonical-domains.result }}" = "success" ]; then
echo "✅ All tests passed successfully!"
echo "🎮 2048 game is working correctly across all environments using canonical Knative domains"
else
echo "❌ Some tests failed"
echo "Smoke tests: ${{ needs.smoke-tests.result }}"
echo "Canonical domain tests: ${{ needs.test-canonical-domains.result }}"
exit 1
fi
- name: Post summary
if: always()
run: |
echo "## Test Summary" >> $GITHUB_STEP_SUMMARY
echo "" >> $GITHUB_STEP_SUMMARY
echo "| Test Type | Status |" >> $GITHUB_STEP_SUMMARY
echo "|-----------|--------|" >> $GITHUB_STEP_SUMMARY
echo "| Smoke Tests | ${{ needs.smoke-tests.result == 'success' && '✅ Passed' || '❌ Failed' }} |" >> $GITHUB_STEP_SUMMARY
echo "| Canonical Domain Tests | ${{ needs.test-canonical-domains.result == 'success' && '✅ Passed' || '❌ Failed' }} |" >> $GITHUB_STEP_SUMMARY
echo "" >> $GITHUB_STEP_SUMMARY
echo "### Tested Canonical Domains" >> $GITHUB_STEP_SUMMARY
echo "- 🧪 Development: https://game-2048-dev.game-2048-dev.dev.wa.darknex.us" >> $GITHUB_STEP_SUMMARY
echo "- 🎭 Staging: https://game-2048-staging.game-2048-staging.staging.wa.darknex.us" >> $GITHUB_STEP_SUMMARY
echo "- 🚀 Production: https://game-2048-prod.game-2048-prod.wa.darknex.us" >> $GITHUB_STEP_SUMMARY

50
.gitignore vendored Normal file
View File

@@ -0,0 +1,50 @@
# Node.js
node_modules/
npm-debug.log*
yarn-debug.log*
yarn-error.log*
# Docker
.dockerignore
# Kubernetes
*.bak
# OS generated files
.DS_Store
.DS_Store?
._*
.Spotlight-V100
.Trashes
ehthumbs.db
Thumbs.db
# IDE
.vscode/
.idea/
*.swp
*.swo
# Environment files
.env
.env.local
.env.development.local
.env.test.local
.env.production.local
# Logs
logs
*.log
# Runtime data
pids
*.pid
*.seed
*.pid.lock
# Coverage directory used by tools like istanbul
coverage/
# Build outputs
dist/
build/

161
CONTRIBUTING.md Normal file
View File

@@ -0,0 +1,161 @@
# Contributing to K8s Game 2048
Thank you for considering contributing to this project! This guide will help you get started.
## Development Setup
1. **Clone the repository**
```bash
git clone https://github.com/your-username/k8s-game-2048.git
cd k8s-game-2048
```
2. **Local Development**
```bash
# Start local development server
npm start
# Or with Python
python3 -m http.server 8080 --directory src
```
3. **Build Docker Image**
```bash
npm run build
# Or
docker build -t k8s-game-2048 .
```
## Git Workflow
We use a GitFlow-inspired workflow:
- **`master`** - Production-ready code, deployed to production automatically
- **`staging`** - Staging branch, deployed to staging environment automatically
- **`develop`** - Development branch, deployed to dev environment automatically
- **`feature/*`** - Feature branches, create PR to develop
- **`hotfix/*`** - Hotfix branches, create PR to master
- **`release/*`** - Release branches for production deployment
### Branch Protection Rules
- **`master`**: Requires PR review, all checks must pass
- **`staging`**: Requires PR review, all checks must pass
- **`develop`**: Requires PR review, all checks must pass
## Deployment Environments
| Environment | Branch | Domain | Auto-Deploy |
|-------------|--------|---------|------------|
| Development | `develop` | `2048-dev.wa.darknex.us` | ✅ |
| Staging | `staging` | `2048-staging.wa.darknex.us` | ✅ |
| Production | `master` | `2048.wa.darknex.us` | ✅ |
## Making Changes
### For New Features
1. Create a feature branch from `develop`:
```bash
git checkout develop
git pull origin develop
git checkout -b feature/your-feature-name
```
2. Make your changes and commit:
```bash
git add .
git commit -m "feat: add your feature description"
```
3. Push and create a PR to `develop`:
```bash
git push origin feature/your-feature-name
```
### For Bug Fixes
1. Create a hotfix branch from `master`:
```bash
git checkout master
git pull origin master
git checkout -b hotfix/fix-description
```
2. Make your changes and create PR to `master`
## Commit Convention
We use [Conventional Commits](https://www.conventionalcommits.org/):
- `feat:` - New features
- `fix:` - Bug fixes
- `docs:` - Documentation changes
- `style:` - Code style changes (formatting, etc.)
- `refactor:` - Code refactoring
- `test:` - Adding or updating tests
- `chore:` - Maintenance tasks
## Testing
### Local Testing
```bash
# Test the game locally
npm start
open http://localhost:8080
```
### Kubernetes Testing
```bash
# Deploy to development environment
kubectl apply -f manifests/dev/
# Check deployment status
kubectl get ksvc -n game-2048-dev
# Test the deployed service
curl -f https://2048-dev.wa.darknex.us/
```
## Code Style
- Use 2 spaces for indentation
- Use meaningful variable and function names
- Add comments for complex logic
- Keep functions small and focused
## Pull Request Process
1. **Title**: Use conventional commit format
2. **Description**:
- What changes were made?
- Why were they made?
- How to test the changes?
3. **Testing**: Ensure all environments work correctly
4. **Documentation**: Update README if needed
## Release Process
1. Create a release branch from `master`:
```bash
git checkout master
git pull origin master
git checkout -b release/v1.1.0
```
2. Update version in `package.json`
3. Create PR to `master`
4. After merge, create a GitHub release with tag
5. Production deployment will trigger automatically
## Getting Help
- Open an issue for bugs or feature requests
- Start a discussion for questions
- Check existing issues before creating new ones
## Code of Conduct
Please note that this project is released with a Contributor Code of Conduct. By participating in this project you agree to abide by its terms.

17
Dockerfile Normal file
View File

@@ -0,0 +1,17 @@
FROM nginx:alpine
# Copy the 2048 game files
COPY src/ /usr/share/nginx/html/
# Copy custom nginx configuration
COPY nginx.conf /etc/nginx/conf.d/default.conf
# Expose port 8080 (Knative standard)
EXPOSE 8080
# Health check
HEALTHCHECK --interval=30s --timeout=3s --start-period=5s --retries=3 \
CMD curl -f http://localhost:8080/ || exit 1
# Run nginx
CMD ["nginx", "-g", "daemon off;"]

View File

@@ -1,6 +1,6 @@
MIT License
Copyright (c) 2025 Greg Hendrickson
Copyright (c) 2025 K8s Game 2048
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal

137
README.md Normal file
View File

@@ -0,0 +1,137 @@
# K8s Game 2048
A Kubernetes deployment of the classic 2048 game using Knative Serving with Istio service mesh and nginx ingress for SSL termination.
## Features
- **Knative Serving**: Serverless deployment with scale-to-zero capability
- **Istio Service Mesh**: Advanced traffic management and observability
- **nginx Ingress**: SSL termination and traffic routing
- **Multi-environment**: Development, Staging, and Production deployments
- **Custom Domains with SSL**: Environment-specific HTTPS domains
- **GitOps Workflow**: Complete CI/CD pipeline with GitHub Actions
## Environments
- **Development**: `https://2048-dev.wa.darknex.us`
- **Staging**: `https://2048-staging.wa.darknex.us`
- **Production**: `https://2048.wa.darknex.us`
## Architecture
```
┌─────────────┐ ┌─────────────┐ ┌─────────────┐ ┌─────────────┐
│ Internet │ │ nginx │ │ Istio │ │ Knative │
│ │───▶│ Ingress │───▶│ Gateway │───▶│ Service │
│ │ │ (SSL Term.) │ │ │ │ │
└─────────────┘ └─────────────┘ └─────────────┘ └─────────────┘
│ │
▼ ▼
┌─────────────┐ ┌─────────────┐
│ cert-manager│ │ 2048 Game │
│ Let's Encrypt│ │ Container │
└─────────────┘ └─────────────┘
```
## Quick Start
### Prerequisites
- Kubernetes cluster (1.21+) with k3s or similar
- Knative Serving installed
- Istio service mesh installed
- nginx ingress controller installed
- cert-manager for SSL certificates
- kubectl configured
- Domain DNS configured to point to your cluster IP
### Installation
1. Clone the repository:
```bash
git clone https://github.com/ghndrx/k8s-game-2048.git
cd k8s-game-2048
```
2. Deploy all environments:
```bash
./scripts/deploy.sh all
```
3. Or deploy a specific environment:
```bash
./scripts/deploy.sh dev # Development only
./scripts/deploy.sh staging # Staging only
./scripts/deploy.sh prod # Production only
```
3. Deploy to staging:
```bash
kubectl apply -f manifests/staging/
```
4. Deploy to production:
```bash
kubectl apply -f manifests/prod/
```
## Project Structure
```
k8s-game-2048/
├── README.md
├── Dockerfile
├── .github/
│ └── workflows/
│ ├── deploy-dev.yml
│ ├── deploy-staging.yml
│ └── deploy-prod.yml
├── manifests/
│ ├── dev/
│ │ ├── namespace.yml
│ │ ├── service.yml
│ │ └── domain-mapping.yml
│ ├── staging/
│ │ ├── namespace.yml
│ │ ├── service.yml
│ │ └── domain-mapping.yml
│ └── prod/
│ ├── namespace.yml
│ ├── service.yml
│ └── domain-mapping.yml
├── scripts/
│ ├── setup-knative.sh
│ ├── setup-kourier.sh
│ └── deploy.sh
└── src/
└── (2048 game files)
```
## Deployment
The application uses Knative Serving with the following features:
- **Scale to Zero**: Automatically scales down to 0 when not in use
- **Auto-scaling**: Scales up based on incoming requests
- **Blue-Green Deployments**: Safe deployment strategy with traffic splitting
- **Custom Domains**: Environment-specific domain mapping
## Monitoring
Each environment includes:
- Knative Service status monitoring
- Request metrics via Knative
- Custom domain health checks
## Contributing
1. Fork the repository
2. Create a feature branch (`git checkout -b feature/amazing-feature`)
3. Commit your changes (`git commit -m 'Add some amazing feature'`)
4. Push to the branch (`git push origin feature/amazing-feature`)
5. Open a Pull Request
## License
This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.

10
curl-format.txt Normal file
View File

@@ -0,0 +1,10 @@
time_namelookup: %{time_namelookup}\n
time_connect: %{time_connect}\n
time_appconnect: %{time_appconnect}\n
time_pretransfer: %{time_pretransfer}\n
time_redirect: %{time_redirect}\n
time_starttransfer: %{time_starttransfer}\n
----------\n
time_total: %{time_total}\n
response_code: %{response_code}\n
size_download: %{size_download}\n

154
docs/BRANCHING.md Normal file
View File

@@ -0,0 +1,154 @@
# Branch Strategy & Deployment Flow
## Branch Structure
```
master (production)
├── staging (staging environment)
└── develop (development environment)
├── feature/feature-name
├── feature/another-feature
└── hotfix/urgent-fix
```
## Deployment Flow
### 🟢 Development Environment
- **Branch**: `develop`
- **Domain**: `2048-dev.wa.darknex.us`
- **Trigger**: Push to `develop` branch
- **Auto-deploy**: ✅ Yes
- **Purpose**: Latest development features, may be unstable
### 🟡 Staging Environment
- **Branch**: `staging`
- **Domain**: `2048-staging.wa.darknex.us`
- **Trigger**: Push to `staging` branch
- **Auto-deploy**: ✅ Yes
- **Purpose**: Pre-production testing, stable features
### 🔴 Production Environment
- **Branch**: `master`
- **Domain**: `2048.wa.darknex.us`
- **Trigger**: Push to `master` branch OR GitHub Release
- **Auto-deploy**: ✅ Yes
- **Purpose**: Live production environment
## Workflow Examples
### Adding a New Feature
```bash
# 1. Start from develop
git checkout develop
git pull origin develop
# 2. Create feature branch
git checkout -b feature/awesome-new-feature
# 3. Make changes and commit
git add .
git commit -m "feat: add awesome new feature"
# 4. Push and create PR to develop
git push origin feature/awesome-new-feature
# Create PR: feature/awesome-new-feature → develop
```
### Promoting to Staging
```bash
# 1. Merge feature to develop (via PR)
# 2. Test in dev environment: 2048-dev.wa.darknex.us
# 3. Promote to staging
git checkout staging
git pull origin staging
git merge develop
git push origin staging
# 4. Test in staging: 2048-staging.wa.darknex.us
```
### Deploying to Production
```bash
# 1. After staging testing passes
git checkout master
git pull origin master
git merge staging
git push origin master
# 2. Optionally create a release tag
git tag -a v1.0.0 -m "Release version 1.0.0"
git push origin v1.0.0
# 3. Production deploys automatically: 2048.wa.darknex.us
```
### Hotfix Flow
```bash
# 1. Create hotfix from master
git checkout master
git pull origin master
git checkout -b hotfix/critical-bug-fix
# 2. Fix the issue
git add .
git commit -m "fix: resolve critical bug"
# 3. Push and create PR to master
git push origin hotfix/critical-bug-fix
# Create PR: hotfix/critical-bug-fix → master
# 4. After merge, also merge back to develop
git checkout develop
git merge master
git push origin develop
```
## CI/CD Pipeline
### Development Pipeline (`develop` branch)
1. ✅ Build Docker image
2. ✅ Push to GHCR with `develop-{sha}` tag
3. ✅ Deploy to dev namespace
4. ✅ Run basic health checks
### Staging Pipeline (`staging` branch)
1. ✅ Build Docker image
2. ✅ Push to GHCR with `staging-{sha}` tag
3. ✅ Deploy to staging namespace
4. ✅ Run smoke tests
5. ✅ Health check staging URL
### Production Pipeline (`master` branch)
1. ✅ Build Docker image
2. ✅ Push to GHCR with version tag
3. ✅ Blue-green deployment to production
4. ✅ Gradual traffic shifting (10% → 50% → 100%)
5. ✅ Production health checks
6. ✅ Rollback capability
## Environment Configuration
| Environment | Namespace | Min Scale | Max Scale | Scale Down Delay |
|-------------|-----------|-----------|-----------|------------------|
| Development | `game-2048-dev` | 0 | 10 | 30s |
| Staging | `game-2048-staging` | 0 | 20 | 60s |
| Production | `game-2048-prod` | 0 | 50 | 300s |
## Monitoring & Alerts
- **Development**: Basic logging, fast iteration
- **Staging**: Full monitoring, performance testing
- **Production**: Full observability, alerting, SLA monitoring
## Security
- All images are scanned for vulnerabilities
- Secrets managed via GitHub Secrets
- RBAC configured per namespace
- TLS termination at Kourier gateway
- Auto-TLS via cert-manager and Let's Encrypt

236
docs/SETUP.md Normal file
View File

@@ -0,0 +1,236 @@
# Knative & Kourier Setup Guide
This guide will help you set up Knative Serving with Kourier networking layer on your Kubernetes cluster.
## Prerequisites
- Kubernetes cluster (v1.21+)
- kubectl configured and working
- Cluster admin permissions
- LoadBalancer support (cloud provider or MetalLB)
## Quick Setup
Run the provided scripts in order:
```bash
# 1. Install Knative Serving
./scripts/setup-knative.sh
# 2. Install Kourier networking layer
./scripts/setup-kourier.sh
```
## Manual Setup
If you prefer to install manually:
### 1. Install Knative Serving
```bash
# Install CRDs
kubectl apply -f https://github.com/knative/serving/releases/download/knative-v1.12.0/serving-crds.yaml
# Install core components
kubectl apply -f https://github.com/knative/serving/releases/download/knative-v1.12.0/serving-core.yaml
# Install HPA autoscaler
kubectl apply -f https://github.com/knative/serving/releases/download/knative-v1.12.0/serving-hpa.yaml
```
### 2. Install Kourier
```bash
# Install Kourier
kubectl apply -f https://github.com/knative/net-kourier/releases/download/knative-v1.12.0/kourier.yaml
# Configure Knative to use Kourier
kubectl patch configmap/config-network \
--namespace knative-serving \
--type merge \
--patch '{"data":{"ingress-class":"kourier.ingress.networking.knative.dev"}}'
```
### 3. Configure Domain
```bash
# Set your custom domain
kubectl patch configmap/config-domain \
--namespace knative-serving \
--type merge \
--patch '{"data":{"wa.darknex.us":""}}'
```
### 4. Set up TLS (Optional but Recommended)
```bash
# Install cert-manager
kubectl apply -f https://github.com/cert-manager/cert-manager/releases/download/v1.13.0/cert-manager.yaml
# Install Knative cert-manager integration
kubectl apply -f https://github.com/knative/net-certmanager/releases/download/knative-v1.12.0/release.yaml
# Create Let's Encrypt ClusterIssuer
kubectl apply -f - <<EOF
apiVersion: cert-manager.io/v1
kind: ClusterIssuer
metadata:
name: letsencrypt-prod
spec:
acme:
server: https://acme-v02.api.letsencrypt.org/directory
email: admin@darknex.us
privateKeySecretRef:
name: letsencrypt-prod
solvers:
- http01:
ingress:
class: kourier.ingress.networking.knative.dev
EOF
# Configure Knative to use cert-manager
kubectl patch configmap/config-certmanager \
--namespace knative-serving \
--type merge \
--patch '{"data":{"issuerRef":"kind: ClusterIssuer\nname: letsencrypt-prod"}}'
# Enable auto-TLS
kubectl patch configmap/config-network \
--namespace knative-serving \
--type merge \
--patch '{"data":{"autoTLS":"Enabled","httpProtocol":"Redirected"}}'
```
## DNS Configuration
After installation, configure your DNS to point to the Kourier LoadBalancer:
1. **Get the LoadBalancer IP**:
```bash
kubectl get svc kourier -n kourier-system
```
2. **Create DNS records**:
```
2048-dev.wa.darknex.us -> LoadBalancer IP
2048-staging.wa.darknex.us -> LoadBalancer IP
2048.wa.darknex.us -> LoadBalancer IP
*.wa.darknex.us -> LoadBalancer IP (wildcard)
```
## Verification
Test your setup:
```bash
# Check Knative Serving
kubectl get pods -n knative-serving
# Check Kourier
kubectl get pods -n kourier-system
# Check cert-manager (if installed)
kubectl get pods -n cert-manager
# Deploy a test service
kubectl apply -f manifests/dev/
# Check service status
kubectl get ksvc -n game-2048-dev
```
## Troubleshooting
### Common Issues
1. **Pods stuck in Pending**:
- Check node resources: `kubectl describe nodes`
- Check PVC status: `kubectl get pvc -A`
2. **LoadBalancer IP not assigned**:
- Ensure your cluster supports LoadBalancer services
- For local clusters, consider using MetalLB
3. **TLS certificates not issued**:
- Check cert-manager logs: `kubectl logs -n cert-manager -l app=cert-manager`
- Verify DNS propagation: `dig 2048-dev.wa.darknex.us`
4. **Service not accessible**:
- Check Kourier gateway logs: `kubectl logs -n kourier-system -l app=3scale-kourier-gateway`
- Verify domain mapping: `kubectl get domainmapping -A`
### Useful Commands
```bash
# Check Knative service status
kubectl get ksvc -A
# Check revisions
kubectl get rev -A
# Check domain mappings
kubectl get domainmapping -A
# Check Kourier configuration
kubectl get svc kourier -n kourier-system -o yaml
# Check Knative configuration
kubectl get cm -n knative-serving
# Debug service logs
kubectl logs -n <namespace> -l serving.knative.dev/service=<service-name>
```
## Advanced Configuration
### Custom Autoscaling
```yaml
# Add to service annotations
autoscaling.knative.dev/minScale: "0"
autoscaling.knative.dev/maxScale: "100"
autoscaling.knative.dev/target: "70"
autoscaling.knative.dev/scaleDownDelay: "30s"
autoscaling.knative.dev/window: "60s"
```
### Traffic Splitting
```yaml
# In Knative Service spec
traffic:
- percent: 90
revisionName: myapp-00001
- percent: 10
revisionName: myapp-00002
```
### Custom Resource Limits
```yaml
# In container spec
resources:
requests:
cpu: 100m
memory: 128Mi
limits:
cpu: 1000m
memory: 512Mi
```
## Monitoring
Consider installing these additional tools:
- **Knative Monitoring**: `kubectl apply -f https://github.com/knative/serving/releases/download/knative-v1.12.0/monitoring.yaml`
- **Prometheus**: For metrics collection
- **Grafana**: For visualization
- **Jaeger**: For distributed tracing
## Next Steps
1. Deploy the 2048 game: `kubectl apply -f manifests/dev/`
2. Set up monitoring and alerting
3. Configure backup and disaster recovery
4. Implement proper RBAC policies
5. Set up GitOps with ArgoCD or Flux

View File

@@ -0,0 +1,7 @@
apiVersion: v1
kind: Namespace
metadata:
name: game-2048-dev
labels:
environment: development
app: game-2048

26
manifests/dev/service.yml Normal file
View File

@@ -0,0 +1,26 @@
apiVersion: serving.knative.dev/v1
kind: Service
metadata:
name: game-2048-dev
namespace: game-2048-dev
labels:
app: game-2048
environment: development
spec:
template:
metadata:
annotations:
autoscaling.knative.dev/minScale: "0"
autoscaling.knative.dev/maxScale: "10"
autoscaling.knative.dev/target: "100"
spec:
containers:
- image: ghcr.io/ghndrx/k8s-game-2048:latest
imagePullPolicy: Always
ports:
- containerPort: 80
env:
- name: ENVIRONMENT
value: "development"
imagePullSecrets:
- name: ghcr-secret

View File

@@ -0,0 +1,20 @@
apiVersion: networking.istio.io/v1beta1
kind: Gateway
metadata:
name: knative-ingress-gateway
namespace: knative-serving
labels:
app.kubernetes.io/component: net-istio
app.kubernetes.io/name: knative-serving
app.kubernetes.io/version: 1.12.0
networking.knative.dev/ingress-provider: istio
spec:
selector:
istio: ingressgateway
servers:
- hosts:
- '*'
port:
name: http
number: 80
protocol: HTTP

View File

@@ -0,0 +1,16 @@
apiVersion: v1
kind: ConfigMap
metadata:
name: config-domain
namespace: knative-serving
data:
dev.wa.darknex.us: |
selector:
environment: development
staging.wa.darknex.us: |
selector:
environment: staging
wa.darknex.us: |
selector:
environment: production
autocreate-cluster-domain-claims: "true"

View File

@@ -0,0 +1,40 @@
apiVersion: cert-manager.io/v1
kind: Certificate
metadata:
name: game-2048-dev-nginx-cert
namespace: default
spec:
secretName: game-2048-dev-nginx-tls
issuerRef:
name: letsencrypt-prod
kind: ClusterIssuer
dnsNames:
- "2048-dev.wa.darknex.us"
---
apiVersion: cert-manager.io/v1
kind: Certificate
metadata:
name: game-2048-staging-nginx-cert
namespace: default
spec:
secretName: game-2048-staging-nginx-tls
issuerRef:
name: letsencrypt-prod
kind: ClusterIssuer
dnsNames:
- "2048-staging.wa.darknex.us"
---
apiVersion: cert-manager.io/v1
kind: Certificate
metadata:
name: game-2048-prod-nginx-cert
namespace: default
spec:
secretName: game-2048-prod-nginx-tls
issuerRef:
name: letsencrypt-prod
kind: ClusterIssuer
dnsNames:
- "2048.wa.darknex.us"

View File

@@ -0,0 +1,119 @@
---
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
name: game-2048-dev-proxy
namespace: default
annotations:
nginx.ingress.kubernetes.io/ssl-redirect: "true"
nginx.ingress.kubernetes.io/force-ssl-redirect: "true"
cert-manager.io/cluster-issuer: "letsencrypt-prod"
nginx.ingress.kubernetes.io/backend-protocol: "HTTP"
nginx.ingress.kubernetes.io/configuration-snippet: |
proxy_set_header Host game-2048-dev.game-2048-dev.dev.wa.darknex.us;
spec:
ingressClassName: nginx
tls:
- hosts:
- 2048-dev.wa.darknex.us
secretName: game-2048-dev-nginx-tls
rules:
- host: 2048-dev.wa.darknex.us
http:
paths:
- path: /
pathType: Prefix
backend:
service:
name: istio-nodeport-service
port:
number: 80
---
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
name: game-2048-staging-proxy
namespace: default
annotations:
nginx.ingress.kubernetes.io/ssl-redirect: "true"
nginx.ingress.kubernetes.io/force-ssl-redirect: "true"
cert-manager.io/cluster-issuer: "letsencrypt-prod"
nginx.ingress.kubernetes.io/backend-protocol: "HTTP"
nginx.ingress.kubernetes.io/configuration-snippet: |
proxy_set_header Host game-2048-staging.game-2048-staging.staging.wa.darknex.us;
spec:
ingressClassName: nginx
tls:
- hosts:
- 2048-staging.wa.darknex.us
secretName: game-2048-staging-nginx-tls
rules:
- host: 2048-staging.wa.darknex.us
http:
paths:
- path: /
pathType: Prefix
backend:
service:
name: istio-nodeport-service
port:
number: 80
---
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
name: game-2048-prod-proxy
namespace: default
annotations:
nginx.ingress.kubernetes.io/ssl-redirect: "true"
nginx.ingress.kubernetes.io/force-ssl-redirect: "true"
cert-manager.io/cluster-issuer: "letsencrypt-prod"
nginx.ingress.kubernetes.io/backend-protocol: "HTTP"
nginx.ingress.kubernetes.io/configuration-snippet: |
proxy_set_header Host game-2048-prod.game-2048-prod.wa.darknex.us;
spec:
ingressClassName: nginx
tls:
- hosts:
- 2048.wa.darknex.us
secretName: game-2048-prod-nginx-tls
rules:
- host: 2048.wa.darknex.us
http:
paths:
- path: /
pathType: Prefix
backend:
service:
name: istio-nodeport-service
port:
number: 80
---
apiVersion: v1
kind: Service
metadata:
name: istio-nodeport-service
namespace: default
spec:
ports:
- name: http
port: 80
targetPort: 32135
protocol: TCP
clusterIP: None
---
apiVersion: v1
kind: Endpoints
metadata:
name: istio-nodeport-service
namespace: default
subsets:
- addresses:
- ip: 192.168.4.134 # Your k3s node IP
ports:
- name: http
port: 32135

View File

@@ -0,0 +1,7 @@
apiVersion: v1
kind: Namespace
metadata:
name: game-2048-prod
labels:
environment: production
app: game-2048

View File

@@ -0,0 +1,26 @@
apiVersion: serving.knative.dev/v1
kind: Service
metadata:
name: game-2048-prod
namespace: game-2048-prod
labels:
app: game-2048
environment: production
spec:
template:
metadata:
annotations:
autoscaling.knative.dev/minScale: "0"
autoscaling.knative.dev/maxScale: "10"
autoscaling.knative.dev/target: "100"
spec:
containers:
- image: ghcr.io/ghndrx/k8s-game-2048:latest
imagePullPolicy: Always
ports:
- containerPort: 80
env:
- name: ENVIRONMENT
value: "production"
imagePullSecrets:
- name: ghcr-secret

View File

@@ -0,0 +1,14 @@
apiVersion: cert-manager.io/v1
kind: ClusterIssuer
metadata:
name: letsencrypt-prod
spec:
acme:
server: https://acme-v02.api.letsencrypt.org/directory
email: admin@hndrx.co
privateKeySecretRef:
name: letsencrypt-prod
solvers:
- http01:
ingress:
class: nginx

View File

@@ -0,0 +1,7 @@
apiVersion: v1
kind: Namespace
metadata:
name: game-2048-staging
labels:
environment: staging
app: game-2048

View File

@@ -0,0 +1,26 @@
apiVersion: serving.knative.dev/v1
kind: Service
metadata:
name: game-2048-staging
namespace: game-2048-staging
labels:
app: game-2048
environment: staging
spec:
template:
metadata:
annotations:
autoscaling.knative.dev/minScale: "0"
autoscaling.knative.dev/maxScale: "10"
autoscaling.knative.dev/target: "100"
spec:
containers:
- image: ghcr.io/ghndrx/k8s-game-2048:latest
imagePullPolicy: Always
ports:
- containerPort: 80
env:
- name: ENVIRONMENT
value: "staging"
imagePullSecrets:
- name: ghcr-secret

38
nginx.conf Normal file
View File

@@ -0,0 +1,38 @@
server {
listen 8080;
server_name localhost;
root /usr/share/nginx/html;
index index.html index.htm;
# Gzip compression
gzip on;
gzip_vary on;
gzip_min_length 1024;
gzip_types text/plain text/css text/xml text/javascript application/javascript application/xml+rss application/json;
# Security headers
add_header X-Frame-Options "SAMEORIGIN" always;
add_header X-XSS-Protection "1; mode=block" always;
add_header X-Content-Type-Options "nosniff" always;
add_header Referrer-Policy "no-referrer-when-downgrade" always;
add_header Content-Security-Policy "default-src 'self' http: https: data: blob: 'unsafe-inline'" always;
# Cache static assets
location ~* \.(js|css|png|jpg|jpeg|gif|ico|svg)$ {
expires 1y;
add_header Cache-Control "public, immutable";
}
# Main location
location / {
try_files $uri $uri/ /index.html;
}
# Health check endpoint
location /health {
access_log off;
return 200 "healthy\n";
add_header Content-Type text/plain;
}
}

36
package.json Normal file
View File

@@ -0,0 +1,36 @@
{
"name": "k8s-game-2048",
"version": "1.0.0",
"description": "2048 game deployed on Kubernetes using Knative Serving with Kourier",
"main": "src/index.html",
"scripts": {
"start": "python3 -m http.server 8080 --directory src",
"build": "docker build -t k8s-game-2048 .",
"deploy:dev": "./scripts/deploy.sh dev",
"deploy:staging": "./scripts/deploy.sh staging",
"deploy:prod": "./scripts/deploy.sh prod",
"setup:knative": "./scripts/setup-knative.sh",
"setup:kourier": "./scripts/setup-kourier.sh"
},
"repository": {
"type": "git",
"url": "git+https://github.com/ghndrx/k8s-game-2048.git"
},
"keywords": [
"2048",
"game",
"kubernetes",
"knative",
"kourier",
"serverless",
"scale-to-zero"
],
"author": "Your Name",
"license": "MIT",
"bugs": {
"url": "https://github.com/ghndrx/k8s-game-2048/issues"
},
"homepage": "https://github.com/ghndrx/k8s-game-2048#readme",
"devDependencies": {},
"dependencies": {}
}

49
playwright.config.ts Normal file
View File

@@ -0,0 +1,49 @@
import { defineConfig, devices } from '@playwright/test';
export default defineConfig({
testDir: './tests',
fullyParallel: true,
forbidOnly: !!process.env.CI,
retries: process.env.CI ? 2 : 0,
workers: process.env.CI ? 1 : undefined,
reporter: [
['html'],
['json', { outputFile: 'test-results.json' }],
['junit', { outputFile: 'test-results.xml' }]
],
use: {
baseURL: process.env.BASE_URL || 'http://localhost:8080',
trace: 'on-first-retry',
screenshot: 'only-on-failure',
video: 'retain-on-failure',
},
projects: [
{
name: 'chromium',
use: { ...devices['Desktop Chrome'] },
},
{
name: 'firefox',
use: { ...devices['Desktop Firefox'] },
},
{
name: 'webkit',
use: { ...devices['Desktop Safari'] },
},
{
name: 'mobile-chrome',
use: { ...devices['Pixel 5'] },
},
{
name: 'mobile-safari',
use: { ...devices['iPhone 12'] },
},
],
webServer: process.env.CI ? undefined : {
command: 'npm start',
port: 8080,
reuseExistingServer: !process.env.CI,
},
});

101
scripts/deploy.sh Executable file
View File

@@ -0,0 +1,101 @@
#!/bin/bash
# Deployment script for 2048 game with Istio + nginx SSL setup
# Usage: ./deploy.sh [env] where env = dev|staging|prod|all
set -e
ENVIRONMENT=${1:-all}
REGISTRY="ghcr.io/ghndrx/k8s-game-2048"
echo "🚀 Deploying 2048 game with Istio + nginx SSL..."
echo "Environment: $ENVIRONMENT"
# Validate environment
case $ENVIRONMENT in
dev|staging|prod|all)
echo "✅ Valid environment: $ENVIRONMENT"
;;
*)
echo "❌ Invalid environment. Use: dev, staging, prod, or all"
exit 1
;;
esac
# Check dependencies
if ! command -v kubectl &> /dev/null; then
echo "❌ kubectl is not installed"
exit 1
fi
if ! kubectl cluster-info &> /dev/null; then
echo "❌ Cannot access Kubernetes cluster"
exit 1
fi
# Deploy function for a single environment
deploy_env() {
local env=$1
echo "📦 Deploying $env environment..."
# Apply namespace
kubectl apply -f manifests/$env/namespace.yml
# Ensure GHCR secret exists in the namespace
echo "🔐 Setting up GHCR secret for $env..."
if kubectl get secret ghcr-secret -n default &>/dev/null; then
kubectl get secret ghcr-secret -o yaml | \
sed "s/namespace: default/namespace: game-2048-$env/" | \
sed '/resourceVersion:/d' | \
sed '/uid:/d' | \
sed '/creationTimestamp:/d' | \
kubectl apply -f -
else
echo "⚠️ Warning: No GHCR secret found in default namespace"
fi
# Apply service
kubectl apply -f manifests/$env/service.yml
# Wait for service to be ready
echo "⏳ Waiting for $env service to be ready..."
kubectl wait --for=condition=Ready ksvc/game-2048-$env -n game-2048-$env --timeout=300s || echo "Warning: Service may still be starting"
}
# Deploy infrastructure (certificates, gateways, etc.)
echo "🏗️ Setting up infrastructure..."
kubectl apply -f manifests/ssl-certificate.yaml
kubectl apply -f manifests/nginx-certificate.yaml
kubectl apply -f manifests/knative-domain-config.yaml
kubectl apply -f manifests/istio-gateway.yaml
kubectl apply -f manifests/nginx-to-istio-proxy.yaml
# Deploy environments
if [ "$ENVIRONMENT" = "all" ]; then
deploy_env "dev"
deploy_env "staging"
deploy_env "prod"
else
deploy_env "$ENVIRONMENT"
fi
echo ""
echo "✅ Deployment completed!"
echo ""
echo "<22> Your 2048 game is available at:"
if [ "$ENVIRONMENT" = "all" ] || [ "$ENVIRONMENT" = "dev" ]; then
echo " Development: https://2048-dev.wa.darknex.us"
fi
if [ "$ENVIRONMENT" = "all" ] || [ "$ENVIRONMENT" = "staging" ]; then
echo " Staging: https://2048-staging.wa.darknex.us"
fi
if [ "$ENVIRONMENT" = "all" ] || [ "$ENVIRONMENT" = "prod" ]; then
echo " Production: https://2048.wa.darknex.us"
fi
echo ""
echo "🔧 Check status with:"
echo " kubectl get ksvc -A"
echo " kubectl get certificates -A"
echo " kubectl get ingress -A"
echo ""
echo "📝 Architecture: Internet → nginx (SSL) → Istio → Knative"

View File

@@ -0,0 +1,24 @@
#!/bin/bash
# Setup GitHub Environments for Protection Rules
# This script documents the manual steps needed in GitHub UI
echo "🔧 Setting up GitHub Environments for Auto-Promotion Pipeline"
echo ""
echo "📋 Manual Steps Required in GitHub Repository Settings:"
echo ""
echo "1. Go to Settings → Environments"
echo "2. Create 'production-approval' environment"
echo "3. Add required reviewers (yourself)"
echo "4. Set deployment protection rules"
echo ""
echo "Environment Configuration:"
echo "- Environment Name: production-approval"
echo "- Required Reviewers: Repository admins"
echo "- Wait Timer: 0 minutes (immediate on approval)"
echo "- Deployment Branches: main branch only"
echo ""
echo "This ensures production deployments require manual approval"
echo "while dev → staging promotion happens automatically on successful tests."
echo ""
echo "🔗 Navigate to: https://github.com/YOUR_USERNAME/k8s-game-2048/settings/environments"

58
scripts/setup-knative.sh Executable file
View File

@@ -0,0 +1,58 @@
#!/bin/bash
# Setup script for Knative Serving installation
# This script installs Knative Serving on a Kubernetes cluster
set -e
echo "🚀 Setting up Knative Serving..."
# Check if kubectl is available
if ! command -v kubectl &> /dev/null; then
echo "❌ kubectl is not installed. Please install kubectl first."
exit 1
fi
# Check if cluster is accessible
if ! kubectl cluster-info &> /dev/null; then
echo "❌ Cannot access Kubernetes cluster. Please check your kubeconfig."
exit 1
fi
# Install Knative Serving CRDs
echo "📦 Installing Knative Serving CRDs..."
kubectl apply -f https://github.com/knative/serving/releases/download/knative-v1.12.0/serving-crds.yaml
# Wait for CRDs to be established
echo "⏳ Waiting for CRDs to be established..."
kubectl wait --for condition=established --timeout=120s crd/configurations.serving.knative.dev
kubectl wait --for condition=established --timeout=120s crd/revisions.serving.knative.dev
kubectl wait --for condition=established --timeout=120s crd/routes.serving.knative.dev
kubectl wait --for condition=established --timeout=120s crd/services.serving.knative.dev
# Install Knative Serving core
echo "📦 Installing Knative Serving core..."
kubectl apply -f https://github.com/knative/serving/releases/download/knative-v1.12.0/serving-core.yaml
# Wait for Knative Serving to be ready
echo "⏳ Waiting for Knative Serving to be ready..."
kubectl wait --for=condition=Ready pod -l app=controller -n knative-serving --timeout=300s
kubectl wait --for=condition=Ready pod -l app=webhook -n knative-serving --timeout=300s
# Install Knative Serving HPA (Horizontal Pod Autoscaler)
echo "📦 Installing Knative Serving HPA..."
kubectl apply -f https://github.com/knative/serving/releases/download/knative-v1.12.0/serving-hpa.yaml
# Configure domain
echo "🌐 Configuring domain..."
kubectl patch configmap/config-domain \
--namespace knative-serving \
--type merge \
--patch '{"data":{"wa.darknex.us":""}}'
echo "✅ Knative Serving installation completed!"
echo ""
echo "Next steps:"
echo "1. Install Kourier as the networking layer: ./setup-kourier.sh"
echo "2. Configure DNS to point your domain to the Kourier LoadBalancer"
echo "3. Deploy your applications using the manifests in this repository"

109
scripts/setup-kourier.sh Executable file
View File

@@ -0,0 +1,109 @@
#!/bin/bash
# Setup script for Kourier networking layer
# This script installs Kourier as the Knative networking layer
set -e
echo "🚀 Setting up Kourier networking layer..."
# Check if kubectl is available
if ! command -v kubectl &> /dev/null; then
echo "❌ kubectl is not installed. Please install kubectl first."
exit 1
fi
# Check if cluster is accessible
if ! kubectl cluster-info &> /dev/null; then
echo "❌ Cannot access Kubernetes cluster. Please check your kubeconfig."
exit 1
fi
# Check if Knative Serving is installed
if ! kubectl get namespace knative-serving &> /dev/null; then
echo "❌ Knative Serving is not installed. Please run ./setup-knative.sh first."
exit 1
fi
# Install Kourier
echo "📦 Installing Kourier..."
kubectl apply -f https://github.com/knative/net-kourier/releases/download/knative-v1.12.0/kourier.yaml
# Wait for Kourier to be ready
echo "⏳ Waiting for Kourier to be ready..."
kubectl wait --for=condition=Ready pod -l app=3scale-kourier-gateway -n kourier-system --timeout=300s
# Configure Knative to use Kourier
echo "🔧 Configuring Knative to use Kourier..."
kubectl patch configmap/config-network \
--namespace knative-serving \
--type merge \
--patch '{"data":{"ingress-class":"kourier.ingress.networking.knative.dev"}}'
# Get the external IP of Kourier
echo "🔍 Getting Kourier LoadBalancer details..."
kubectl get svc kourier -n kourier-system
# Configure auto-TLS (optional)
echo "🔐 Configuring auto-TLS..."
kubectl patch configmap/config-network \
--namespace knative-serving \
--type merge \
--patch '{"data":{"autoTLS":"Enabled","httpProtocol":"Redirected"}}'
# Install cert-manager for TLS (optional but recommended)
echo "📦 Installing cert-manager for TLS..."
kubectl apply -f https://github.com/cert-manager/cert-manager/releases/download/v1.13.0/cert-manager.yaml
# Wait for cert-manager to be ready
echo "⏳ Waiting for cert-manager to be ready..."
kubectl wait --for=condition=Ready pod -l app=cert-manager -n cert-manager --timeout=300s
kubectl wait --for=condition=Ready pod -l app=cainjector -n cert-manager --timeout=300s
kubectl wait --for=condition=Ready pod -l app=webhook -n cert-manager --timeout=300s
# Install Knative cert-manager integration
echo "📦 Installing Knative cert-manager integration..."
kubectl apply -f https://github.com/knative/net-certmanager/releases/download/knative-v1.12.0/release.yaml
# Create ClusterIssuer for Let's Encrypt
echo "🔐 Creating Let's Encrypt ClusterIssuer..."
cat <<EOF | kubectl apply -f -
apiVersion: cert-manager.io/v1
kind: ClusterIssuer
metadata:
name: letsencrypt-prod
spec:
acme:
server: https://acme-v02.api.letsencrypt.org/directory
email: admin@darknex.us
privateKeySecretRef:
name: letsencrypt-prod
solvers:
- http01:
ingress:
class: kourier.ingress.networking.knative.dev
EOF
# Configure Knative to use the ClusterIssuer
echo "🔧 Configuring Knative to use cert-manager..."
kubectl patch configmap/config-certmanager \
--namespace knative-serving \
--type merge \
--patch '{"data":{"issuerRef":"kind: ClusterIssuer\nname: letsencrypt-prod"}}'
echo "✅ Kourier setup completed!"
echo ""
echo "🔍 Kourier LoadBalancer service details:"
kubectl get svc kourier -n kourier-system -o wide
echo ""
echo "📋 Next steps:"
echo "1. Configure your DNS to point the following domains to the LoadBalancer IP:"
echo " - 2048-dev.wa.darknex.us"
echo " - 2048-staging.wa.darknex.us"
echo " - 2048.wa.darknex.us"
echo " - *.wa.darknex.us (wildcard)"
echo ""
echo "2. Deploy your applications:"
echo " kubectl apply -f manifests/dev/"
echo " kubectl apply -f manifests/staging/"
echo " kubectl apply -f manifests/prod/"

0
scripts/setup-ssl.sh Executable file
View File

250
scripts/smoke-test.sh Normal file
View File

@@ -0,0 +1,250 @@
#!/bin/bash
# Smoke test script for 2048 game deployment
# Tests all environments and validates the complete flow
set -e
# Colors for output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color
# Test configuration
ENVIRONMENTS=("dev" "staging" "prod")
DOMAINS=("2048-dev.wa.darknex.us" "2048-staging.wa.darknex.us" "2048.wa.darknex.us")
CANONICAL_DOMAINS=("game-2048-dev.game-2048-dev.dev.wa.darknex.us" "game-2048-staging.game-2048-staging.staging.wa.darknex.us" "game-2048-prod.game-2048-prod.wa.darknex.us")
TIMEOUT=30
echo -e "${BLUE}🧪 Starting 2048 Game Smoke Tests${NC}"
echo "=================================="
# Function to test HTTP response
test_http_response() {
local url=$1
local expected_status=$2
local test_name=$3
echo -n " Testing $test_name... "
response=$(curl -s -w "%{http_code}" -o /tmp/response.html --max-time $TIMEOUT "$url" 2>/dev/null || echo "000")
if [ "$response" = "$expected_status" ]; then
echo -e "${GREEN}✅ PASS${NC} (HTTP $response)"
return 0
else
echo -e "${RED}❌ FAIL${NC} (HTTP $response, expected $expected_status)"
return 1
fi
}
# Function to test SSL certificate
test_ssl_cert() {
local domain=$1
echo -n " Testing SSL certificate for $domain... "
if echo | openssl s_client -servername "$domain" -connect "$domain:443" -verify_return_error &>/dev/null; then
echo -e "${GREEN}✅ VALID${NC}"
return 0
else
echo -e "${RED}❌ INVALID${NC}"
return 1
fi
}
# Function to test content
test_content() {
local url=$1
local expected_text=$2
local test_name=$3
echo -n " Testing $test_name content... "
if curl -s --max-time $TIMEOUT "$url" | grep -q "$expected_text"; then
echo -e "${GREEN}✅ FOUND${NC}"
return 0
else
echo -e "${RED}❌ NOT FOUND${NC}"
return 1
fi
}
# Function to test Kubernetes resources
test_k8s_resources() {
local env=$1
echo -e "${YELLOW}📋 Testing Kubernetes Resources for $env${NC}"
# Test namespace
echo -n " Checking namespace game-2048-$env... "
if kubectl get namespace "game-2048-$env" &>/dev/null; then
echo -e "${GREEN}✅ EXISTS${NC}"
else
echo -e "${RED}❌ MISSING${NC}"
return 1
fi
# Test Knative service
echo -n " Checking Knative service... "
if kubectl get ksvc "game-2048-$env" -n "game-2048-$env" &>/dev/null; then
local status=$(kubectl get ksvc "game-2048-$env" -n "game-2048-$env" -o jsonpath='{.status.conditions[?(@.type=="Ready")].status}')
if [ "$status" = "True" ]; then
echo -e "${GREEN}✅ READY${NC}"
else
echo -e "${YELLOW}⏳ NOT READY${NC} (Status: $status)"
fi
else
echo -e "${RED}❌ MISSING${NC}"
return 1
fi
# Test GHCR secret
echo -n " Checking GHCR secret... "
if kubectl get secret ghcr-secret -n "game-2048-$env" &>/dev/null; then
echo -e "${GREEN}✅ EXISTS${NC}"
else
echo -e "${RED}❌ MISSING${NC}"
return 1
fi
}
# Function to test ingress
test_ingress() {
echo -e "${YELLOW}🌐 Testing Ingress Configuration${NC}"
# Test nginx ingress controller
echo -n " Checking nginx ingress controller... "
if kubectl get pods -n ingress-nginx | grep -q "ingress-nginx-controller.*Running"; then
echo -e "${GREEN}✅ RUNNING${NC}"
else
echo -e "${RED}❌ NOT RUNNING${NC}"
return 1
fi
# Test Istio ingress gateway
echo -n " Checking Istio ingress gateway... "
if kubectl get pods -n istio-system | grep -q "istio-ingressgateway.*Running"; then
echo -e "${GREEN}✅ RUNNING${NC}"
else
echo -e "${RED}❌ NOT RUNNING${NC}"
return 1
fi
# Test cert-manager
echo -n " Checking cert-manager... "
if kubectl get pods -n cert-manager | grep -q "cert-manager.*Running"; then
echo -e "${GREEN}✅ RUNNING${NC}"
else
echo -e "${RED}❌ NOT RUNNING${NC}"
return 1
fi
}
# Function to test certificates
test_certificates() {
echo -e "${YELLOW}🔒 Testing SSL Certificates${NC}"
for i in "${!ENVIRONMENTS[@]}"; do
local env="${ENVIRONMENTS[$i]}"
local domain="${DOMAINS[$i]}"
echo -n " Checking certificate for $domain... "
local cert_status=$(kubectl get certificate "game-2048-$env-nginx-cert" -o jsonpath='{.status.conditions[?(@.type=="Ready")].status}' 2>/dev/null || echo "Unknown")
if [ "$cert_status" = "True" ]; then
echo -e "${GREEN}✅ READY${NC}"
test_ssl_cert "$domain"
else
echo -e "${RED}❌ NOT READY${NC} (Status: $cert_status)"
fi
done
}
# Main test execution
main() {
local total_tests=0
local passed_tests=0
# Test infrastructure
test_ingress
test_certificates
# Test each environment
for i in "${!ENVIRONMENTS[@]}"; do
local env="${ENVIRONMENTS[$i]}"
local domain="${DOMAINS[$i]}"
local canonical_domain="${CANONICAL_DOMAINS[$i]}"
echo ""
echo -e "${BLUE}🎮 Testing $env Environment${NC}"
echo "Domain: https://$domain"
echo "Canonical: https://$canonical_domain"
echo "----------------------------------------"
# Test Kubernetes resources
if test_k8s_resources "$env"; then
((total_tests++))
((passed_tests++))
else
((total_tests++))
fi
# Test custom domain accessibility
if test_http_response "https://$domain" "200\|301\|302" "custom domain"; then
((total_tests++))
((passed_tests++))
else
((total_tests++))
fi
# Test canonical domain accessibility
if test_http_response "https://$canonical_domain" "200" "canonical domain"; then
((total_tests++))
((passed_tests++))
else
((total_tests++))
fi
# Test content
if test_content "https://$canonical_domain" "2048" "game content"; then
((total_tests++))
((passed_tests++))
else
((total_tests++))
fi
# Test environment-specific content
local env_name=""
case $env in
"dev") env_name="development" ;;
"staging") env_name="staging" ;;
"prod") env_name="Production" ;;
esac
if test_content "https://$canonical_domain" "$env_name" "environment detection"; then
((total_tests++))
((passed_tests++))
else
((total_tests++))
fi
done
echo ""
echo "=================================="
echo -e "${BLUE}📊 Test Summary${NC}"
echo "Total Tests: $total_tests"
echo -e "Passed: ${GREEN}$passed_tests${NC}"
echo -e "Failed: ${RED}$((total_tests - passed_tests))${NC}"
if [ $passed_tests -eq $total_tests ]; then
echo -e "${GREEN}🎉 All tests passed!${NC}"
exit 0
else
echo -e "${RED}❌ Some tests failed${NC}"
exit 1
fi
}
# Run main function
main "$@"

82
src/index.html Normal file
View File

@@ -0,0 +1,82 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>2048 Game - Knative Edition</title>
<link rel="stylesheet" href="style.css">
<link rel="icon" type="image/png" href="favicon.png">
</head>
<body>
<div class="container">
<div class="header">
<h1>2048</h1>
<div class="environment-badge" id="env-badge"></div>
<div class="scores-container">
<div class="score-container">
<div class="score-title">SCORE</div>
<div class="score" id="score">0</div>
</div>
<div class="score-container">
<div class="score-title">BEST</div>
<div class="score" id="best">0</div>
</div>
</div>
</div>
<div class="above-game">
<p class="game-intro">
<strong>HOW TO PLAY:</strong> Use your <strong>arrow keys</strong> to move the tiles.
When two tiles with the same number touch, they <strong>merge into one!</strong>
</p>
<button class="restart-button" id="restart-button">New Game</button>
</div>
<div class="game-container">
<div class="game-message" id="game-message">
<p></p>
<div class="lower">
<button class="keep-playing-button" id="keep-playing-button">Keep going</button>
<button class="retry-button" id="retry-button">Try again</button>
</div>
</div>
<div class="grid-container">
<div class="grid-row">
<div class="grid-cell"></div>
<div class="grid-cell"></div>
<div class="grid-cell"></div>
<div class="grid-cell"></div>
</div>
<div class="grid-row">
<div class="grid-cell"></div>
<div class="grid-cell"></div>
<div class="grid-cell"></div>
<div class="grid-cell"></div>
</div>
<div class="grid-row">
<div class="grid-cell"></div>
<div class="grid-cell"></div>
<div class="grid-cell"></div>
<div class="grid-cell"></div>
</div>
<div class="grid-row">
<div class="grid-cell"></div>
<div class="grid-cell"></div>
<div class="grid-cell"></div>
<div class="grid-cell"></div>
</div>
</div>
<div class="tile-container" id="tile-container"></div>
</div>
<div class="game-explanation">
<p><strong>Knative Edition:</strong> This game is deployed using Knative Serving with scale-to-zero capabilities on Kubernetes!</p>
<p>Environment: <span id="environment">Production</span></p>
</div>
</div>
<script src="script.js"></script>
</body>
</html>

348
src/script.js Normal file
View File

@@ -0,0 +1,348 @@
// 2048 Game JavaScript - Knative Edition
class Game2048 {
constructor() {
this.grid = [];
this.score = 0;
this.best = localStorage.getItem('best2048') || 0;
this.gameWon = false;
this.gameOver = false;
this.keepPlaying = false;
this.init();
this.setupEventListeners();
this.setEnvironment();
}
init() {
this.grid = [
[0, 0, 0, 0],
[0, 0, 0, 0],
[0, 0, 0, 0],
[0, 0, 0, 0]
];
this.score = 0;
this.gameWon = false;
this.gameOver = false;
this.keepPlaying = false;
this.updateScore();
this.addRandomTile();
this.addRandomTile();
this.updateDisplay();
}
setEnvironment() {
const envElement = document.getElementById('environment');
const envBadge = document.getElementById('env-badge');
// Try to detect environment from hostname
const hostname = window.location.hostname;
let environment = 'production';
if (hostname.includes('dev')) {
environment = 'development';
} else if (hostname.includes('staging')) {
environment = 'staging';
}
envElement.textContent = environment.charAt(0).toUpperCase() + environment.slice(1);
envBadge.textContent = environment;
envBadge.className = `environment-badge ${environment}`;
}
setupEventListeners() {
document.addEventListener('keydown', (e) => this.handleKeyPress(e));
document.getElementById('restart-button').addEventListener('click', () => this.restart());
document.getElementById('keep-playing-button').addEventListener('click', () => this.keepPlayingGame());
document.getElementById('retry-button').addEventListener('click', () => this.restart());
// Touch/swipe support for mobile
let startX, startY;
document.addEventListener('touchstart', (e) => {
startX = e.touches[0].clientX;
startY = e.touches[0].clientY;
});
document.addEventListener('touchend', (e) => {
if (!startX || !startY) return;
const endX = e.changedTouches[0].clientX;
const endY = e.changedTouches[0].clientY;
const diffX = startX - endX;
const diffY = startY - endY;
if (Math.abs(diffX) > Math.abs(diffY)) {
if (diffX > 0) {
this.move('left');
} else {
this.move('right');
}
} else {
if (diffY > 0) {
this.move('up');
} else {
this.move('down');
}
}
});
}
handleKeyPress(e) {
if (this.gameOver && !this.keepPlaying) return;
switch (e.code) {
case 'ArrowUp':
e.preventDefault();
this.move('up');
break;
case 'ArrowDown':
e.preventDefault();
this.move('down');
break;
case 'ArrowLeft':
e.preventDefault();
this.move('left');
break;
case 'ArrowRight':
e.preventDefault();
this.move('right');
break;
}
}
move(direction) {
const previousGrid = this.grid.map(row => [...row]);
let moved = false;
switch (direction) {
case 'left':
moved = this.moveLeft();
break;
case 'right':
moved = this.moveRight();
break;
case 'up':
moved = this.moveUp();
break;
case 'down':
moved = this.moveDown();
break;
}
if (moved) {
this.addRandomTile();
this.updateDisplay();
this.checkGameState();
}
}
moveLeft() {
let moved = false;
for (let row = 0; row < 4; row++) {
const newRow = this.slideArray(this.grid[row]);
if (!this.arraysEqual(this.grid[row], newRow)) {
moved = true;
this.grid[row] = newRow;
}
}
return moved;
}
moveRight() {
let moved = false;
for (let row = 0; row < 4; row++) {
const reversed = [...this.grid[row]].reverse();
const newRow = this.slideArray(reversed).reverse();
if (!this.arraysEqual(this.grid[row], newRow)) {
moved = true;
this.grid[row] = newRow;
}
}
return moved;
}
moveUp() {
let moved = false;
for (let col = 0; col < 4; col++) {
const column = [this.grid[0][col], this.grid[1][col], this.grid[2][col], this.grid[3][col]];
const newColumn = this.slideArray(column);
if (!this.arraysEqual(column, newColumn)) {
moved = true;
for (let row = 0; row < 4; row++) {
this.grid[row][col] = newColumn[row];
}
}
}
return moved;
}
moveDown() {
let moved = false;
for (let col = 0; col < 4; col++) {
const column = [this.grid[0][col], this.grid[1][col], this.grid[2][col], this.grid[3][col]];
const reversed = [...column].reverse();
const newColumn = this.slideArray(reversed).reverse();
if (!this.arraysEqual(column, newColumn)) {
moved = true;
for (let row = 0; row < 4; row++) {
this.grid[row][col] = newColumn[row];
}
}
}
return moved;
}
slideArray(arr) {
const filtered = arr.filter(val => val !== 0);
const missing = 4 - filtered.length;
const zeros = Array(missing).fill(0);
const newArray = filtered.concat(zeros);
for (let i = 0; i < 3; i++) {
if (newArray[i] !== 0 && newArray[i] === newArray[i + 1]) {
newArray[i] *= 2;
newArray[i + 1] = 0;
this.score += newArray[i];
}
}
const filtered2 = newArray.filter(val => val !== 0);
const missing2 = 4 - filtered2.length;
const zeros2 = Array(missing2).fill(0);
return filtered2.concat(zeros2);
}
arraysEqual(a, b) {
return JSON.stringify(a) === JSON.stringify(b);
}
addRandomTile() {
const emptyCells = [];
for (let row = 0; row < 4; row++) {
for (let col = 0; col < 4; col++) {
if (this.grid[row][col] === 0) {
emptyCells.push({row, col});
}
}
}
if (emptyCells.length > 0) {
const randomCell = emptyCells[Math.floor(Math.random() * emptyCells.length)];
this.grid[randomCell.row][randomCell.col] = Math.random() < 0.9 ? 2 : 4;
}
}
updateDisplay() {
const container = document.getElementById('tile-container');
container.innerHTML = '';
for (let row = 0; row < 4; row++) {
for (let col = 0; col < 4; col++) {
if (this.grid[row][col] !== 0) {
const tile = document.createElement('div');
tile.className = `tile tile-${this.grid[row][col]}`;
tile.textContent = this.grid[row][col];
tile.style.left = `${col * 121.25}px`;
tile.style.top = `${row * 121.25}px`;
if (this.grid[row][col] > 2048) {
tile.className = 'tile tile-super';
}
container.appendChild(tile);
}
}
}
}
updateScore() {
document.getElementById('score').textContent = this.score;
if (this.score > this.best) {
this.best = this.score;
localStorage.setItem('best2048', this.best);
}
document.getElementById('best').textContent = this.best;
}
checkGameState() {
this.updateScore();
// Check for 2048 tile (game won)
if (!this.gameWon && !this.keepPlaying) {
for (let row = 0; row < 4; row++) {
for (let col = 0; col < 4; col++) {
if (this.grid[row][col] === 2048) {
this.gameWon = true;
this.showMessage('You Win!', 'game-won');
return;
}
}
}
}
// Check for game over
if (this.isGameOver()) {
this.gameOver = true;
this.showMessage('Game Over!', 'game-over');
}
}
isGameOver() {
// Check for empty cells
for (let row = 0; row < 4; row++) {
for (let col = 0; col < 4; col++) {
if (this.grid[row][col] === 0) {
return false;
}
}
}
// Check for possible merges
for (let row = 0; row < 4; row++) {
for (let col = 0; col < 4; col++) {
const current = this.grid[row][col];
if (
(row < 3 && current === this.grid[row + 1][col]) ||
(col < 3 && current === this.grid[row][col + 1])
) {
return false;
}
}
}
return true;
}
showMessage(text, className) {
const messageElement = document.getElementById('game-message');
messageElement.querySelector('p').textContent = text;
messageElement.className = `game-message ${className}`;
messageElement.style.display = 'block';
}
hideMessage() {
const messageElement = document.getElementById('game-message');
messageElement.style.display = 'none';
}
restart() {
this.hideMessage();
this.init();
}
keepPlayingGame() {
this.hideMessage();
this.keepPlaying = true;
}
}
// Initialize the game when the page loads
document.addEventListener('DOMContentLoaded', () => {
new Game2048();
});

382
src/style.css Normal file
View File

@@ -0,0 +1,382 @@
/* 2048 Game CSS - Knative Edition */
html, body {
margin: 0;
padding: 20px;
background: #faf8ef;
color: #776e65;
font-family: "Clear Sans", "Helvetica Neue", Arial, sans-serif;
font-size: 18px;
}
body {
margin: 80px 0;
}
.heading {
margin-bottom: 30px;
}
h1.title {
font-size: 80px;
font-weight: bold;
margin: 0;
display: inline-block;
}
.container {
width: 500px;
margin: 0 auto;
}
.header {
display: flex;
justify-content: space-between;
align-items: center;
margin-bottom: 20px;
}
.header h1 {
color: #776e65;
font-size: 80px;
font-weight: bold;
margin: 0;
}
.environment-badge {
padding: 8px 16px;
border-radius: 20px;
font-size: 12px;
font-weight: bold;
text-transform: uppercase;
color: white;
margin-left: 20px;
}
.environment-badge.development {
background: #ff6b6b;
}
.environment-badge.staging {
background: #ffa726;
}
.environment-badge.production {
background: #66bb6a;
}
.scores-container {
display: flex;
gap: 10px;
}
.score-container {
position: relative;
display: inline-block;
background: #bbada0;
padding: 10px 20px;
font-size: 25px;
height: 60px;
line-height: 47px;
font-weight: bold;
border-radius: 3px;
color: white;
text-align: center;
min-width: 80px;
}
.score-title {
position: absolute;
width: 100%;
top: 10px;
left: 0;
text-transform: uppercase;
font-size: 13px;
line-height: 13px;
text-align: center;
color: #eee4da;
}
.score {
font-size: 25px;
}
.above-game {
display: flex;
justify-content: space-between;
align-items: center;
margin-bottom: 20px;
}
.game-intro {
line-height: 1.65;
margin: 0;
flex: 1;
margin-right: 20px;
}
.restart-button {
display: inline-block;
background: #8f7a66;
border-radius: 3px;
padding: 0 20px;
text-decoration: none;
color: #f9f6f2;
height: 40px;
line-height: 42px;
border: none;
cursor: pointer;
font-size: 18px;
}
.restart-button:hover {
background: #9f8a76;
}
.game-container {
position: relative;
padding: 15px;
cursor: default;
user-select: none;
touch-action: none;
background: #bbada0;
border-radius: 10px;
width: 500px;
height: 500px;
box-sizing: border-box;
}
.game-message {
display: none;
position: absolute;
top: 0;
right: 0;
bottom: 0;
left: 0;
background: rgba(255, 255, 255, 0.73);
z-index: 100;
text-align: center;
border-radius: 10px;
}
.game-message p {
font-size: 60px;
font-weight: bold;
height: 60px;
line-height: 60px;
margin-top: 150px;
}
.game-message .lower {
display: block;
margin-top: 30px;
}
.game-message a {
display: inline-block;
background: #8f7a66;
border-radius: 3px;
padding: 0 20px;
text-decoration: none;
color: #f9f6f2;
height: 40px;
line-height: 42px;
margin-left: 9px;
}
.game-won {
background: rgba(237, 194, 46, 0.5);
color: #f9f6f2;
}
.game-won .game-message p {
color: #f9f6f2;
}
.game-over {
background: rgba(238, 228, 218, 0.73);
color: #776e65;
}
.game-over .game-message p {
color: #776e65;
}
.grid-container {
position: absolute;
z-index: 1;
}
.grid-row {
margin-bottom: 15px;
}
.grid-row:last-child {
margin-bottom: 0;
}
.grid-cell {
width: 106.25px;
height: 106.25px;
background: rgba(238, 228, 218, 0.35);
border-radius: 6px;
margin-right: 15px;
float: left;
}
.grid-cell:last-child {
margin-right: 0;
}
.tile-container {
position: absolute;
z-index: 2;
}
.tile {
width: 106.25px;
height: 106.25px;
background: #eee4da;
color: #776e65;
border-radius: 6px;
font-weight: bold;
text-align: center;
vertical-align: middle;
line-height: 106.25px;
font-size: 55px;
position: absolute;
transition: 0.15s ease-in-out;
transform-origin: center center;
}
.tile-2 { background: #eee4da; color: #776e65; }
.tile-4 { background: #ede0c8; color: #776e65; }
.tile-8 { color: #f9f6f2; background: #f2b179; }
.tile-16 { color: #f9f6f2; background: #f59563; }
.tile-32 { color: #f9f6f2; background: #f67c5f; }
.tile-64 { color: #f9f6f2; background: #f65e3b; }
.tile-128 { color: #f9f6f2; background: #edcf72; font-size: 45px; }
.tile-256 { color: #f9f6f2; background: #edcc61; font-size: 45px; }
.tile-512 { color: #f9f6f2; background: #edc850; font-size: 45px; }
.tile-1024 { color: #f9f6f2; background: #edc53f; font-size: 35px; }
.tile-2048 { color: #f9f6f2; background: #edc22e; font-size: 35px; }
.tile-super { color: #f9f6f2; background: #3c3a32; font-size: 30px; }
.tile-new {
animation: appear 200ms ease-in-out;
animation-fill-mode: backwards;
}
.tile-merged {
z-index: 20;
animation: pop 200ms ease-in-out;
animation-fill-mode: backwards;
}
@keyframes appear {
0% {
opacity: 0;
transform: scale(0);
}
100% {
opacity: 1;
transform: scale(1);
}
}
@keyframes pop {
0% {
transform: scale(0);
}
50% {
transform: scale(1.2);
}
100% {
transform: scale(1);
}
}
.game-explanation {
margin-top: 30px;
text-align: center;
color: #776e65;
}
.game-explanation p {
margin: 10px 0;
}
.keep-playing-button, .retry-button {
display: inline-block;
background: #8f7a66;
border-radius: 3px;
padding: 0 20px;
text-decoration: none;
color: #f9f6f2;
height: 40px;
line-height: 42px;
border: none;
cursor: pointer;
font-size: 18px;
margin: 0 5px;
}
.keep-playing-button:hover, .retry-button:hover {
background: #9f8a76;
}
/* Responsive design */
@media screen and (max-width: 520px) {
.container {
width: 280px;
margin: 0 auto;
}
.header h1 {
font-size: 50px;
}
.scores-container {
flex-direction: column;
gap: 5px;
}
.above-game {
flex-direction: column;
align-items: stretch;
gap: 15px;
}
.game-container {
width: 280px;
height: 280px;
padding: 10px;
}
.grid-cell {
width: 60px;
height: 60px;
margin-right: 10px;
margin-bottom: 10px;
}
.tile {
width: 60px;
height: 60px;
line-height: 60px;
font-size: 35px;
}
.tile-128, .tile-256, .tile-512 {
font-size: 25px;
}
.tile-1024, .tile-2048 {
font-size: 20px;
}
.tile-super {
font-size: 18px;
}
}

58
tests/basic.spec.ts Normal file
View File

@@ -0,0 +1,58 @@
import { test, expect } from '@playwright/test';
test.describe('2048 Game - Basic Functionality', () => {
test.beforeEach(async ({ page }) => {
await page.goto('/');
await page.waitForLoadState('networkidle');
});
test('should load the game successfully', async ({ page }) => {
// Check title
await expect(page).toHaveTitle(/2048/);
// Check main elements are present
await expect(page.locator('h1')).toContainText('2048');
await expect(page.locator('.game-container')).toBeVisible();
await expect(page.locator('.grid-container')).toBeVisible();
// Check score displays
await expect(page.locator('#score')).toBeVisible();
await expect(page.locator('#best')).toBeVisible();
});
test('should show environment badge', async ({ page }) => {
const envBadge = page.locator('#env-badge');
await expect(envBadge).toBeVisible();
// Should have one of the environment classes
const badgeClass = await envBadge.getAttribute('class');
expect(badgeClass).toMatch(/(development|staging|production)/);
});
test('should have initial tiles on game start', async ({ page }) => {
// Should have at least 2 tiles initially
const tiles = page.locator('.tile');
await expect(tiles).toHaveCount(2);
// Tiles should have values 2 or 4
const tileTexts = await tiles.allTextContents();
tileTexts.forEach(text => {
expect(['2', '4']).toContain(text);
});
});
test('should restart game when restart button is clicked', async ({ page }) => {
const restartButton = page.locator('#restart-button');
await expect(restartButton).toBeVisible();
// Click restart
await restartButton.click();
// Should have exactly 2 tiles after restart
const tiles = page.locator('.tile');
await expect(tiles).toHaveCount(2);
// Score should be reset to 0
await expect(page.locator('#score')).toHaveText('0');
});
});

75
tests/environment.spec.ts Normal file
View File

@@ -0,0 +1,75 @@
import { test, expect } from '@playwright/test';
test.describe('2048 Game - Environment Tests', () => {
test('should display correct environment in development', async ({ page }) => {
// This test will run when BASE_URL contains 'dev'
const baseUrl = process.env.BASE_URL || '';
test.skip(!baseUrl.includes('dev'), 'Development environment test');
await page.goto('/');
const envElement = page.locator('#environment');
await expect(envElement).toContainText('Development');
const envBadge = page.locator('#env-badge');
await expect(envBadge).toHaveClass(/development/);
});
test('should display correct environment in staging', async ({ page }) => {
const baseUrl = process.env.BASE_URL || '';
test.skip(!baseUrl.includes('staging'), 'Staging environment test');
await page.goto('/');
const envElement = page.locator('#environment');
await expect(envElement).toContainText('Staging');
const envBadge = page.locator('#env-badge');
await expect(envBadge).toHaveClass(/staging/);
});
test('should display correct environment in production', async ({ page }) => {
const baseUrl = process.env.BASE_URL || '';
test.skip(baseUrl.includes('dev') || baseUrl.includes('staging'), 'Production environment test');
await page.goto('/');
const envElement = page.locator('#environment');
await expect(envElement).toContainText('Production');
const envBadge = page.locator('#env-badge');
await expect(envBadge).toHaveClass(/production/);
});
test('should have working health endpoint', async ({ request }) => {
const response = await request.get('/health');
expect(response.status()).toBe(200);
const text = await response.text();
expect(text).toContain('healthy');
});
test('should load all assets successfully', async ({ page }) => {
const responses: any[] = [];
page.on('response', response => {
responses.push(response);
});
await page.goto('/');
await page.waitForLoadState('networkidle');
// Check that all resources loaded successfully
const failedResponses = responses.filter(response => response.status() >= 400);
expect(failedResponses.length).toBe(0);
});
test('should have correct security headers', async ({ request }) => {
const response = await request.get('/');
// Check for basic security headers
expect(response.headers()['x-frame-options']).toBeDefined();
expect(response.headers()['x-content-type-options']).toBeDefined();
expect(response.headers()['x-xss-protection']).toBeDefined();
});
});

83
tests/gameplay.spec.ts Normal file
View File

@@ -0,0 +1,83 @@
import { test, expect } from '@playwright/test';
test.describe('2048 Game - Gameplay Tests', () => {
test.beforeEach(async ({ page }) => {
await page.goto('/');
await page.waitForLoadState('networkidle');
});
test('should move tiles with arrow keys', async ({ page }) => {
// Get initial tile positions
const initialTiles = await page.locator('.tile').all();
const initialPositions = [];
for (const tile of initialTiles) {
const style = await tile.getAttribute('style');
initialPositions.push(style);
}
// Press arrow key to move tiles
await page.keyboard.press('ArrowRight');
await page.waitForTimeout(500); // Wait for animation
// Check that tiles moved or new tile appeared
const newTiles = await page.locator('.tile').all();
expect(newTiles.length).toBeGreaterThanOrEqual(2);
// At least one tile should have moved or new tile should appear
let tilesChanged = newTiles.length > initialTiles.length;
if (!tilesChanged) {
for (let i = 0; i < Math.min(newTiles.length, initialPositions.length); i++) {
const newStyle = await newTiles[i].getAttribute('style');
if (newStyle !== initialPositions[i]) {
tilesChanged = true;
break;
}
}
}
expect(tilesChanged).toBe(true);
});
test('should handle touch/swipe on mobile', async ({ page, isMobile }) => {
test.skip(!isMobile, 'Touch test only for mobile');
const gameContainer = page.locator('.game-container');
// Simulate swipe right
await gameContainer.touchStart([{ x: 100, y: 200 }]);
await gameContainer.touchEnd([{ x: 300, y: 200 }]);
await page.waitForTimeout(500);
// Should have tiles after swipe
const tiles = page.locator('.tile');
await expect(tiles).toHaveCount.atLeast(2);
});
test('should update score when tiles merge', async ({ page }) => {
// This test might need multiple moves to get mergeable tiles
// For now, just verify score element updates
const scoreElement = page.locator('#score');
const initialScore = await scoreElement.textContent();
// Try multiple moves to potentially trigger a merge
for (let i = 0; i < 10; i++) {
await page.keyboard.press('ArrowRight');
await page.waitForTimeout(200);
await page.keyboard.press('ArrowDown');
await page.waitForTimeout(200);
await page.keyboard.press('ArrowLeft');
await page.waitForTimeout(200);
await page.keyboard.press('ArrowUp');
await page.waitForTimeout(200);
const currentScore = await scoreElement.textContent();
if (currentScore !== initialScore) {
expect(parseInt(currentScore || '0')).toBeGreaterThan(parseInt(initialScore || '0'));
break;
}
}
});
});

14
tests/package.json Normal file
View File

@@ -0,0 +1,14 @@
{
"name": "playwright-tests",
"version": "1.0.0",
"description": "Playwright tests for 2048 game",
"scripts": {
"test": "playwright test",
"test:headed": "playwright test --headed",
"test:debug": "playwright test --debug",
"test:ui": "playwright test --ui"
},
"devDependencies": {
"@playwright/test": "^1.40.0"
}
}

60
tests/visual.spec.ts Normal file
View File

@@ -0,0 +1,60 @@
import { test, expect } from '@playwright/test';
test.describe('2048 Game - Visual Tests & Screenshots', () => {
test.beforeEach(async ({ page }) => {
await page.goto('/');
await page.waitForLoadState('networkidle');
});
test('should match initial game state screenshot', async ({ page }) => {
// Wait for game to fully load
await page.waitForSelector('.tile', { timeout: 5000 });
// Take screenshot of initial game state
await expect(page).toHaveScreenshot('initial-game-state.png', {
fullPage: true,
animations: 'disabled'
});
});
test('should match game container layout', async ({ page }) => {
const gameContainer = page.locator('.game-container');
await expect(gameContainer).toHaveScreenshot('game-container.png', {
animations: 'disabled'
});
});
test('should match header with scores', async ({ page }) => {
const header = page.locator('.header');
await expect(header).toHaveScreenshot('header-scores.png', {
animations: 'disabled'
});
});
test('should match environment badge', async ({ page }) => {
const envBadge = page.locator('#env-badge');
await expect(envBadge).toHaveScreenshot('environment-badge.png', {
animations: 'disabled'
});
});
test('should display correctly on mobile', async ({ page, isMobile }) => {
test.skip(!isMobile, 'Mobile test only');
await expect(page).toHaveScreenshot('mobile-game.png', {
fullPage: true,
animations: 'disabled'
});
});
test('should show game over state', async ({ page }) => {
// Try to fill the board quickly (this is a simplified approach)
// In a real scenario, we might need to manipulate the game state directly
// Take screenshot of current state for comparison
await expect(page).toHaveScreenshot('game-in-progress.png', {
fullPage: true,
animations: 'disabled'
});
});
});