feat: initial commit - Rust + React URL shortener
This commit is contained in:
@@ -0,0 +1,92 @@
|
|||||||
|
# Gitea Actions CI/CD Pipeline
|
||||||
|
|
||||||
|
name: CI/CD
|
||||||
|
|
||||||
|
on:
|
||||||
|
push:
|
||||||
|
branches: [main]
|
||||||
|
pull_request:
|
||||||
|
branches: [main]
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
lint-and-test:
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
steps:
|
||||||
|
- uses: actions/checkout@v4
|
||||||
|
|
||||||
|
- name: Setup Rust
|
||||||
|
uses: dtolnay/rust-toolchain@stable
|
||||||
|
with:
|
||||||
|
components: clippy
|
||||||
|
|
||||||
|
- name: Cache cargo registry
|
||||||
|
uses: actions/cache@v3
|
||||||
|
with:
|
||||||
|
path: ~/.cargo/registry
|
||||||
|
key: ${{ runner.os }}-cargo-${{ hashFiles('**/Cargo.lock') }}
|
||||||
|
|
||||||
|
- name: Install frontend dependencies
|
||||||
|
run: cd frontend && npm ci
|
||||||
|
|
||||||
|
- name: Build frontend
|
||||||
|
run: cd frontend && npm run build
|
||||||
|
|
||||||
|
- name: Rust fmt check
|
||||||
|
run: cargo fmt --check
|
||||||
|
|
||||||
|
- name: Rust clippy
|
||||||
|
run: cargo clippy -- -D warnings
|
||||||
|
|
||||||
|
- name: Rust tests
|
||||||
|
run: cargo test
|
||||||
|
|
||||||
|
build-and-push:
|
||||||
|
needs: lint-and-test
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
if: github.event_name == 'push' && github.ref == 'refs/heads/main'
|
||||||
|
steps:
|
||||||
|
- uses: actions/checkout@v4
|
||||||
|
|
||||||
|
- name: Set up Docker Buildx
|
||||||
|
uses: docker/setup-buildx-action@v3
|
||||||
|
|
||||||
|
- name: Login to Harbor
|
||||||
|
uses: docker/login-action@v3
|
||||||
|
with:
|
||||||
|
registry: harbor.k8s.crashpoint.ru
|
||||||
|
username: ${{ secrets.HARBOR_USER }}
|
||||||
|
password: ${{ secrets.HARBOR_TOKEN }}
|
||||||
|
|
||||||
|
- name: Docker meta
|
||||||
|
id: meta
|
||||||
|
uses: docker/metadata-action@v5
|
||||||
|
with:
|
||||||
|
images: harbor.k8s.crashpoint.ru/hello-web/hello-web
|
||||||
|
tags: |
|
||||||
|
type=sha
|
||||||
|
type=raw,value=latest
|
||||||
|
|
||||||
|
- name: Build and push
|
||||||
|
uses: docker/build-push-action@v5
|
||||||
|
with:
|
||||||
|
context: .
|
||||||
|
push: true
|
||||||
|
tags: ${{ steps.meta.outputs.tags }}
|
||||||
|
labels: ${{ steps.meta.outputs.labels }}
|
||||||
|
cache-from: type=gha
|
||||||
|
cache-to: type=gha,mode=max
|
||||||
|
|
||||||
|
deploy:
|
||||||
|
needs: build-and-push
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
if: github.event_name == 'push' && github.ref == 'refs/heads/main'
|
||||||
|
steps:
|
||||||
|
- uses: actions/checkout@v4
|
||||||
|
|
||||||
|
- name: Deploy to Kubernetes
|
||||||
|
run: |
|
||||||
|
sed -i "s|IMAGE_PLACEHOLDER|harbor.k8s.crashpoint.ru/hello-web/hello-web:sha-${{ github.sha }}|g" k8s/deployment.yaml
|
||||||
|
kubectl apply -f k8s/deployment.yaml
|
||||||
|
kubectl apply -f k8s/service.yaml
|
||||||
|
kubectl apply -f k8s/ingress.yaml
|
||||||
|
kubectl rollout status deployment/hello-web --timeout=120s
|
||||||
+20
@@ -0,0 +1,20 @@
|
|||||||
|
# Dependencies
|
||||||
|
target/
|
||||||
|
frontend/node_modules/
|
||||||
|
|
||||||
|
# Build outputs
|
||||||
|
frontend/dist/
|
||||||
|
|
||||||
|
# IDE
|
||||||
|
.vscode/
|
||||||
|
.idea/
|
||||||
|
*.swp
|
||||||
|
*.swo
|
||||||
|
|
||||||
|
# OS
|
||||||
|
.DS_Store
|
||||||
|
Thumbs.db
|
||||||
|
|
||||||
|
# Env
|
||||||
|
.env
|
||||||
|
.env.local
|
||||||
+15
@@ -0,0 +1,15 @@
|
|||||||
|
[package]
|
||||||
|
name = "hello-web"
|
||||||
|
version = "0.1.0"
|
||||||
|
edition = "2021"
|
||||||
|
|
||||||
|
[dependencies]
|
||||||
|
axum = { version = "0.7", features = ["macros"] }
|
||||||
|
tokio = { version = "1", features = ["full"] }
|
||||||
|
serde = { version = "1", features = ["derive"] }
|
||||||
|
serde_json = "1"
|
||||||
|
tower-http = { version = "0.5", features = ["fs", "trace"] }
|
||||||
|
tracing = "0.1"
|
||||||
|
tracing-subscriber = "0.3"
|
||||||
|
uuid = { version = "1", features = ["v4"] }
|
||||||
|
chrono = { version = "0.4", features = ["serde"] }
|
||||||
+26
@@ -0,0 +1,26 @@
|
|||||||
|
# Build frontend
|
||||||
|
FROM node:20-alpine AS frontend-build
|
||||||
|
WORKDIR /app
|
||||||
|
COPY frontend/package.json frontend/package-lock.json ./
|
||||||
|
RUN npm ci
|
||||||
|
COPY frontend/ .
|
||||||
|
RUN npm run build
|
||||||
|
|
||||||
|
# Build Rust backend
|
||||||
|
FROM rust:1.75 AS rust-builder
|
||||||
|
WORKDIR /app
|
||||||
|
COPY Cargo.toml Cargo.lock ./
|
||||||
|
COPY src/ ./src/
|
||||||
|
RUN cargo build --release
|
||||||
|
RUN cp target/release/hello-web /app/hello-web
|
||||||
|
|
||||||
|
# Final image
|
||||||
|
FROM debian:bookworm-slim
|
||||||
|
RUN apt-get update && apt-get install -y --no-install-recommends \
|
||||||
|
ca-certificates \
|
||||||
|
&& rm -rf /var/lib/apt/lists/*
|
||||||
|
WORKDIR /app
|
||||||
|
COPY --from=rust-builder /app/hello-web /app/hello-web
|
||||||
|
COPY --from=frontend-build /app/dist /app/frontend/dist
|
||||||
|
EXPOSE 3000
|
||||||
|
CMD ["/app/hello-web"]
|
||||||
@@ -0,0 +1,67 @@
|
|||||||
|
# 🔗 Hello Web — URL Shortener
|
||||||
|
|
||||||
|
Rust + React URL shortener with analytics dashboard.
|
||||||
|
|
||||||
|
## Features
|
||||||
|
|
||||||
|
- Create short URLs with optional custom aliases
|
||||||
|
- Click tracking and analytics
|
||||||
|
- Beautiful React frontend with dark theme
|
||||||
|
- RESTful API backend
|
||||||
|
- Full CI/CD pipeline with Gitea Actions
|
||||||
|
- Docker multi-stage builds
|
||||||
|
- Kubernetes deployment with auto-scaling
|
||||||
|
|
||||||
|
## Tech Stack
|
||||||
|
|
||||||
|
- **Backend**: Rust + Axum
|
||||||
|
- **Frontend**: React + Vite
|
||||||
|
- **CI/CD**: Gitea Actions
|
||||||
|
- **Registry**: Harbor
|
||||||
|
- **Deployment**: Kubernetes + ArgoCD
|
||||||
|
- **Monitoring**: VictoriaMetrics
|
||||||
|
|
||||||
|
## Local Development
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# Backend
|
||||||
|
cargo run
|
||||||
|
|
||||||
|
# Frontend (separate terminal)
|
||||||
|
cd frontend
|
||||||
|
npm install
|
||||||
|
npm run dev
|
||||||
|
```
|
||||||
|
|
||||||
|
## API Endpoints
|
||||||
|
|
||||||
|
- `POST /api/shorten` — Create short URL
|
||||||
|
- `GET /api/urls` — List all URLs
|
||||||
|
- `GET /api/stats` — Get analytics
|
||||||
|
- `GET /api/urls/{id}` — Get URL info
|
||||||
|
- `GET /{id}` — Redirect to original URL
|
||||||
|
- `GET /health` — Health check
|
||||||
|
|
||||||
|
## Deployment
|
||||||
|
|
||||||
|
The project uses Gitea Actions CI/CD:
|
||||||
|
|
||||||
|
1. Lint & test on every push
|
||||||
|
2. Build Docker image on merge to main
|
||||||
|
3. Push to Harbor registry
|
||||||
|
4. Deploy to Kubernetes cluster
|
||||||
|
|
||||||
|
## Architecture
|
||||||
|
|
||||||
|
```
|
||||||
|
┌─────────────┐ ┌──────────────┐ ┌─────────────┐
|
||||||
|
│ React UI │────▶│ Axum API │────▶│ Harbor │
|
||||||
|
│ (Vite) │ │ (Rust) │ │ Registry │
|
||||||
|
└─────────────┘ └──────────────┘ └─────────────┘
|
||||||
|
│ │
|
||||||
|
▼ ▼
|
||||||
|
┌──────────────┐ ┌─────────────┐
|
||||||
|
│ Victoria │ │ Kubernetes │
|
||||||
|
│ Metrics │ │ Cluster │
|
||||||
|
└──────────────┘ └─────────────┘
|
||||||
|
```
|
||||||
@@ -0,0 +1,44 @@
|
|||||||
|
<!DOCTYPE html>
|
||||||
|
<html lang="en">
|
||||||
|
<head>
|
||||||
|
<meta charset="UTF-8" />
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||||
|
<title>Hello Web - URL Shortener</title>
|
||||||
|
<style>
|
||||||
|
* { margin: 0; padding: 0; box-sizing: border-box; }
|
||||||
|
body { font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif; background: #0f172a; color: #e2e8f0; }
|
||||||
|
.container { max-width: 900px; margin: 0 auto; padding: 2rem; }
|
||||||
|
h1 { text-align: center; font-size: 2.5rem; margin-bottom: 0.5rem; background: linear-gradient(135deg, #667eea, #764ba2); -webkit-background-clip: text; -webkit-text-fill-color: transparent; }
|
||||||
|
.subtitle { text-align: center; color: #94a3b8; margin-bottom: 2rem; }
|
||||||
|
.card { background: #1e293b; border-radius: 12px; padding: 1.5rem; margin-bottom: 1.5rem; box-shadow: 0 4px 6px rgba(0,0,0,0.3); }
|
||||||
|
.input-group { display: flex; gap: 0.5rem; margin-bottom: 1rem; }
|
||||||
|
input { flex: 1; padding: 0.75rem 1rem; border: 2px solid #334155; border-radius: 8px; background: #0f172a; color: #e2e8f0; font-size: 1rem; outline: none; transition: border-color 0.2s; }
|
||||||
|
input:focus { border-color: #667eea; }
|
||||||
|
button { padding: 0.75rem 1.5rem; background: linear-gradient(135deg, #667eea, #764ba2); color: white; border: none; border-radius: 8px; font-size: 1rem; font-weight: 600; cursor: pointer; transition: transform 0.1s, opacity 0.2s; }
|
||||||
|
button:hover { opacity: 0.9; transform: translateY(-1px); }
|
||||||
|
button:active { transform: translateY(0); }
|
||||||
|
.result { padding: 1rem; background: #0f172a; border-radius: 8px; margin-top: 1rem; word-break: break-all; }
|
||||||
|
.result a { color: #667eea; text-decoration: none; }
|
||||||
|
.result a:hover { text-decoration: underline; }
|
||||||
|
.error { color: #f87171; margin-top: 0.5rem; }
|
||||||
|
.stats-grid { display: grid; grid-template-columns: repeat(3, 1fr); gap: 1rem; margin-bottom: 1.5rem; }
|
||||||
|
.stat-card { background: #0f172a; padding: 1rem; border-radius: 8px; text-align: center; }
|
||||||
|
.stat-value { font-size: 2rem; font-weight: 700; color: #667eea; }
|
||||||
|
.stat-label { color: #94a3b8; font-size: 0.875rem; margin-top: 0.25rem; }
|
||||||
|
table { width: 100%; border-collapse: collapse; }
|
||||||
|
th, td { padding: 0.75rem; text-align: left; border-bottom: 1px solid #334155; }
|
||||||
|
th { color: #94a3b8; font-weight: 600; font-size: 0.875rem; text-transform: uppercase; }
|
||||||
|
td a { color: #667eea; text-decoration: none; }
|
||||||
|
td a:hover { text-decoration: underline; }
|
||||||
|
.badge { display: inline-block; padding: 0.25rem 0.5rem; background: #667eea22; color: #667eea; border-radius: 4px; font-size: 0.875rem; }
|
||||||
|
.tabs { display: flex; gap: 0.5rem; margin-bottom: 1.5rem; }
|
||||||
|
.tab { padding: 0.5rem 1rem; background: #0f172a; border: 2px solid #334155; border-radius: 8px; cursor: pointer; transition: all 0.2s; }
|
||||||
|
.tab.active { border-color: #667eea; background: #667eea22; }
|
||||||
|
.custom-alias { margin-bottom: 1rem; }
|
||||||
|
</style>
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<div id="root"></div>
|
||||||
|
<script type="module" src="/src/main.jsx"></script>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
@@ -0,0 +1,10 @@
|
|||||||
|
import React from 'react'
|
||||||
|
import ReactDOM from 'react-dom/client'
|
||||||
|
import App from './App'
|
||||||
|
import './styles.css'
|
||||||
|
|
||||||
|
ReactDOM.createRoot(document.getElementById('root')).render(
|
||||||
|
<React.StrictMode>
|
||||||
|
<App />
|
||||||
|
</React.StrictMode>,
|
||||||
|
)
|
||||||
@@ -0,0 +1,22 @@
|
|||||||
|
{
|
||||||
|
"name": "hello-web-frontend",
|
||||||
|
"private": true,
|
||||||
|
"version": "0.1.0",
|
||||||
|
"type": "module",
|
||||||
|
"scripts": {
|
||||||
|
"dev": "vite",
|
||||||
|
"build": "vite build",
|
||||||
|
"preview": "vite preview"
|
||||||
|
},
|
||||||
|
"dependencies": {
|
||||||
|
"react": "^18.2.0",
|
||||||
|
"react-dom": "^18.2.0",
|
||||||
|
"axios": "^1.6.0"
|
||||||
|
},
|
||||||
|
"devDependencies": {
|
||||||
|
"@types/react": "^18.2.0",
|
||||||
|
"@types/react-dom": "^18.2.0",
|
||||||
|
"@vitejs/plugin-react": "^4.2.0",
|
||||||
|
"vite": "^5.0.0"
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,217 @@
|
|||||||
|
import React, { useState, useEffect } from 'react'
|
||||||
|
import axios from 'axios'
|
||||||
|
|
||||||
|
const API_BASE = '/api'
|
||||||
|
|
||||||
|
function App() {
|
||||||
|
const [url, setUrl] = useState('')
|
||||||
|
const [alias, setAlias] = useState('')
|
||||||
|
const [result, setResult] = useState(null)
|
||||||
|
const [error, setError] = useState('')
|
||||||
|
const [urls, setUrls] = useState([])
|
||||||
|
const [stats, setStats] = useState(null)
|
||||||
|
const [tab, setTab] = useState('create')
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (tab === 'list') fetchUrls()
|
||||||
|
if (tab === 'stats') fetchStats()
|
||||||
|
}, [tab])
|
||||||
|
|
||||||
|
const fetchUrls = async () => {
|
||||||
|
try {
|
||||||
|
const res = await axios.get(`${API_BASE}/urls`)
|
||||||
|
setUrls(res.data)
|
||||||
|
} catch (e) {
|
||||||
|
console.error('Failed to fetch URLs:', e)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const fetchStats = async () => {
|
||||||
|
try {
|
||||||
|
const res = await axios.get(`${API_BASE}/stats`)
|
||||||
|
setStats(res.data)
|
||||||
|
} catch (e) {
|
||||||
|
console.error('Failed to fetch stats:', e)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const shorten = async (e) => {
|
||||||
|
e.preventDefault()
|
||||||
|
setError('')
|
||||||
|
setResult(null)
|
||||||
|
|
||||||
|
if (!url) {
|
||||||
|
setError('Please enter a URL')
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
const res = await axios.post(`${API_BASE}/shorten`, {
|
||||||
|
url,
|
||||||
|
custom_alias: alias || undefined,
|
||||||
|
})
|
||||||
|
setResult(res.data)
|
||||||
|
setUrl('')
|
||||||
|
setAlias('')
|
||||||
|
fetchUrls()
|
||||||
|
fetchStats()
|
||||||
|
} catch (e) {
|
||||||
|
setError(e.response?.data || 'Failed to shorten URL')
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const copyToClipboard = (text) => {
|
||||||
|
navigator.clipboard.writeText(text)
|
||||||
|
alert('Copied to clipboard!')
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="container">
|
||||||
|
<h1>🔗 Hello Web</h1>
|
||||||
|
<p className="subtitle">URL Shortener built with Rust + React</p>
|
||||||
|
|
||||||
|
<div className="tabs">
|
||||||
|
<div className={tab === 'create' ? 'tab active' : 'tab'} onClick={() => setTab('create')}>
|
||||||
|
Create
|
||||||
|
</div>
|
||||||
|
<div className={tab === 'list' ? 'tab active' : 'tab'} onClick={() => setTab('list')}>
|
||||||
|
All URLs
|
||||||
|
</div>
|
||||||
|
<div className={tab === 'stats' ? 'tab active' : 'tab'} onClick={() => setTab('stats')}>
|
||||||
|
Stats
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{tab === 'create' && (
|
||||||
|
<div className="card">
|
||||||
|
<form onSubmit={shorten}>
|
||||||
|
<div className="input-group">
|
||||||
|
<input
|
||||||
|
type="url"
|
||||||
|
placeholder="Enter your long URL (e.g., https://example.com/very/long/path)"
|
||||||
|
value={url}
|
||||||
|
onChange={(e) => setUrl(e.target.value)}
|
||||||
|
/>
|
||||||
|
<button type="submit">Shorten</button>
|
||||||
|
</div>
|
||||||
|
<div className="custom-alias">
|
||||||
|
<input
|
||||||
|
type="text"
|
||||||
|
placeholder="Optional custom alias (3-20 chars)"
|
||||||
|
value={alias}
|
||||||
|
onChange={(e) => setAlias(e.target.value)}
|
||||||
|
style={{ width: '100%' }}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
</form>
|
||||||
|
|
||||||
|
{error && <div className="error">❌ {error}</div>}
|
||||||
|
|
||||||
|
{result && (
|
||||||
|
<div className="result">
|
||||||
|
<p><strong>Short URL:</strong></p>
|
||||||
|
<a href={result.short_url} target="_blank" rel="noopener noreferrer">
|
||||||
|
{result.short_url}
|
||||||
|
</a>
|
||||||
|
<p><small>Original: {result.original_url}</small></p>
|
||||||
|
<button onClick={() => copyToClipboard(result.short_url)} style={{ marginTop: '0.5rem' }}>
|
||||||
|
📋 Copy
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{tab === 'list' && (
|
||||||
|
<div className="card">
|
||||||
|
{urls.length === 0 ? (
|
||||||
|
<p style={{ textAlign: 'center', color: '#94a3b8' }}>No URLs created yet</p>
|
||||||
|
) : (
|
||||||
|
<table>
|
||||||
|
<thead>
|
||||||
|
<tr>
|
||||||
|
<th>Short URL</th>
|
||||||
|
<th>Original URL</th>
|
||||||
|
<th>Clicks</th>
|
||||||
|
<th>Created</th>
|
||||||
|
</tr>
|
||||||
|
</thead>
|
||||||
|
<tbody>
|
||||||
|
{urls.map((u) => (
|
||||||
|
<tr key={u.id}>
|
||||||
|
<td>
|
||||||
|
<a href={u.short_url || `/${u.id}`} target="_blank" rel="noopener noreferrer">
|
||||||
|
{u.id}
|
||||||
|
</a>
|
||||||
|
</td>
|
||||||
|
<td>
|
||||||
|
<a href={u.original_url} target="_blank" rel="noopener noreferrer">
|
||||||
|
{u.original_url}
|
||||||
|
</a>
|
||||||
|
</td>
|
||||||
|
<td><span className="badge">{u.click_count}</span></td>
|
||||||
|
<td>{new Date(u.created_at).toLocaleDateString()}</td>
|
||||||
|
</tr>
|
||||||
|
))}
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{tab === 'stats' && stats && (
|
||||||
|
<div className="card">
|
||||||
|
<div className="stats-grid">
|
||||||
|
<div className="stat-card">
|
||||||
|
<div className="stat-value">{stats.total_urls}</div>
|
||||||
|
<div className="stat-label">Total URLs</div>
|
||||||
|
</div>
|
||||||
|
<div className="stat-card">
|
||||||
|
<div className="stat-value">{stats.total_clicks}</div>
|
||||||
|
<div className="stat-label">Total Clicks</div>
|
||||||
|
</div>
|
||||||
|
<div className="stat-card">
|
||||||
|
<div className="stat-value">
|
||||||
|
{stats.total_urls > 0
|
||||||
|
? Math.round(stats.total_clicks / stats.total_urls)
|
||||||
|
: 0}
|
||||||
|
</div>
|
||||||
|
<div className="stat-label">Avg Clicks/URL</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<h3 style={{ marginBottom: '1rem' }}>🏆 Top URLs</h3>
|
||||||
|
{stats.top_urls.length === 0 ? (
|
||||||
|
<p style={{ color: '#94a3b8' }}>No data yet</p>
|
||||||
|
) : (
|
||||||
|
<table>
|
||||||
|
<thead>
|
||||||
|
<tr>
|
||||||
|
<th>ID</th>
|
||||||
|
<th>Clicks</th>
|
||||||
|
<th>Original URL</th>
|
||||||
|
</tr>
|
||||||
|
</thead>
|
||||||
|
<tbody>
|
||||||
|
{stats.top_urls.map((u) => (
|
||||||
|
<tr key={u.id}>
|
||||||
|
<td>{u.id}</td>
|
||||||
|
<td><span className="badge">{u.click_count}</span></td>
|
||||||
|
<td>
|
||||||
|
<a href={u.original_url} target="_blank" rel="noopener noreferrer">
|
||||||
|
{u.original_url.length > 40
|
||||||
|
? u.original_url.slice(0, 40) + '...'
|
||||||
|
: u.original_url}
|
||||||
|
</a>
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
|
))}
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
export default App
|
||||||
@@ -0,0 +1,9 @@
|
|||||||
|
import React from 'react'
|
||||||
|
import ReactDOM from 'react-dom/client'
|
||||||
|
import App from './App'
|
||||||
|
|
||||||
|
ReactDOM.createRoot(document.getElementById('root')).render(
|
||||||
|
<React.StrictMode>
|
||||||
|
<App />
|
||||||
|
</React.StrictMode>,
|
||||||
|
)
|
||||||
@@ -0,0 +1,12 @@
|
|||||||
|
import { defineConfig } from 'vite'
|
||||||
|
import react from '@vitejs/plugin-react'
|
||||||
|
|
||||||
|
export default defineConfig({
|
||||||
|
plugins: [react()],
|
||||||
|
server: {
|
||||||
|
port: 3000,
|
||||||
|
proxy: {
|
||||||
|
'/api': 'http://localhost:8080',
|
||||||
|
},
|
||||||
|
},
|
||||||
|
})
|
||||||
@@ -0,0 +1,45 @@
|
|||||||
|
apiVersion: apps/v1
|
||||||
|
kind: Deployment
|
||||||
|
metadata:
|
||||||
|
name: hello-web
|
||||||
|
labels:
|
||||||
|
app: hello-web
|
||||||
|
spec:
|
||||||
|
replicas: 2
|
||||||
|
selector:
|
||||||
|
matchLabels:
|
||||||
|
app: hello-web
|
||||||
|
template:
|
||||||
|
metadata:
|
||||||
|
labels:
|
||||||
|
app: hello-web
|
||||||
|
spec:
|
||||||
|
containers:
|
||||||
|
- name: hello-web
|
||||||
|
image: IMAGE_PLACEHOLDER
|
||||||
|
ports:
|
||||||
|
- containerPort: 3000
|
||||||
|
name: http
|
||||||
|
protocol: TCP
|
||||||
|
env:
|
||||||
|
- name: RUST_LOG
|
||||||
|
value: "info"
|
||||||
|
resources:
|
||||||
|
requests:
|
||||||
|
cpu: 100m
|
||||||
|
memory: 128Mi
|
||||||
|
limits:
|
||||||
|
cpu: 500m
|
||||||
|
memory: 512Mi
|
||||||
|
livenessProbe:
|
||||||
|
httpGet:
|
||||||
|
path: /health
|
||||||
|
port: 3000
|
||||||
|
initialDelaySeconds: 10
|
||||||
|
periodSeconds: 30
|
||||||
|
readinessProbe:
|
||||||
|
httpGet:
|
||||||
|
path: /health
|
||||||
|
port: 3000
|
||||||
|
initialDelaySeconds: 5
|
||||||
|
periodSeconds: 10
|
||||||
@@ -0,0 +1,19 @@
|
|||||||
|
apiVersion: networking.k8s.io/v1
|
||||||
|
kind: Ingress
|
||||||
|
metadata:
|
||||||
|
name: hello-web
|
||||||
|
annotations:
|
||||||
|
nginx.ingress.kubernetes.io/proxy-body-size: "10m"
|
||||||
|
nginx.ingress.kubernetes.io/use-regex: "true"
|
||||||
|
spec:
|
||||||
|
rules:
|
||||||
|
- host: hello-web.k8s.crashpoint.ru
|
||||||
|
http:
|
||||||
|
paths:
|
||||||
|
- path: /
|
||||||
|
pathType: Prefix
|
||||||
|
backend:
|
||||||
|
service:
|
||||||
|
name: hello-web
|
||||||
|
port:
|
||||||
|
number: 80
|
||||||
@@ -0,0 +1,15 @@
|
|||||||
|
apiVersion: v1
|
||||||
|
kind: Service
|
||||||
|
metadata:
|
||||||
|
name: hello-web
|
||||||
|
labels:
|
||||||
|
app: hello-web
|
||||||
|
spec:
|
||||||
|
type: ClusterIP
|
||||||
|
ports:
|
||||||
|
- port: 80
|
||||||
|
targetPort: 3000
|
||||||
|
protocol: TCP
|
||||||
|
name: http
|
||||||
|
selector:
|
||||||
|
app: hello-web
|
||||||
+195
@@ -0,0 +1,195 @@
|
|||||||
|
use axum::{
|
||||||
|
extract::{Path, Query, State},
|
||||||
|
http::StatusCode,
|
||||||
|
response::Json,
|
||||||
|
routing::{get, post},
|
||||||
|
Router,
|
||||||
|
};
|
||||||
|
use serde::{Deserialize, Serialize};
|
||||||
|
use std::collections::HashMap;
|
||||||
|
use std::sync::{Arc, Mutex};
|
||||||
|
use tokio::sync::RwLock;
|
||||||
|
use tower_http::trace::TraceLayer;
|
||||||
|
use tracing::{info, instrument};
|
||||||
|
|
||||||
|
#[derive(Clone, Serialize, Deserialize, Debug)]
|
||||||
|
struct ShortUrl {
|
||||||
|
id: String,
|
||||||
|
original_url: String,
|
||||||
|
created_at: String,
|
||||||
|
click_count: u64,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, Serialize, Deserialize, Debug)]
|
||||||
|
struct CreateRequest {
|
||||||
|
url: String,
|
||||||
|
custom_alias: Option<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, Serialize, Deserialize, Debug)]
|
||||||
|
struct CreateResponse {
|
||||||
|
short_url: String,
|
||||||
|
original_url: String,
|
||||||
|
id: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, Serialize, Deserialize, Debug)]
|
||||||
|
struct StatsResponse {
|
||||||
|
total_urls: usize,
|
||||||
|
total_clicks: u64,
|
||||||
|
top_urls: Vec<ShortUrl>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone)]
|
||||||
|
struct AppState {
|
||||||
|
urls: Arc<RwLock<HashMap<String, ShortUrl>>>,
|
||||||
|
base_url: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[instrument(skip(state))]
|
||||||
|
async fn create_short_url(
|
||||||
|
State(state): State<AppState>,
|
||||||
|
Json(req): Json<CreateRequest>,
|
||||||
|
) -> Result<Json<CreateResponse>, (StatusCode, String)> {
|
||||||
|
if !req.url.starts_with("http://") && !req.url.starts_with("https://") {
|
||||||
|
return Err((
|
||||||
|
StatusCode::BAD_REQUEST,
|
||||||
|
"URL must start with http:// or https://".to_string(),
|
||||||
|
));
|
||||||
|
}
|
||||||
|
|
||||||
|
let id = if let Some(alias) = &req.custom_alias {
|
||||||
|
if alias.len() < 3 || alias.len() > 20 {
|
||||||
|
return Err((
|
||||||
|
StatusCode::BAD_REQUEST,
|
||||||
|
"Alias must be 3-20 characters".to_string(),
|
||||||
|
));
|
||||||
|
}
|
||||||
|
alias.clone()
|
||||||
|
} else {
|
||||||
|
uuid::Uuid::new_v4().to_string()[..6].to_string()
|
||||||
|
};
|
||||||
|
|
||||||
|
let urls = state.urls.read().await;
|
||||||
|
if urls.contains_key(&id) {
|
||||||
|
return Err((
|
||||||
|
StatusCode::CONFLICT,
|
||||||
|
format!("Alias '{}' is already taken", id),
|
||||||
|
));
|
||||||
|
}
|
||||||
|
drop(urls);
|
||||||
|
|
||||||
|
let short_url = format!("{}/{}", state.base_url, id);
|
||||||
|
let now = chrono::Utc::now().to_rfc3339();
|
||||||
|
|
||||||
|
let entry = ShortUrl {
|
||||||
|
id: id.clone(),
|
||||||
|
original_url: req.url.clone(),
|
||||||
|
created_at: now.clone(),
|
||||||
|
click_count: 0,
|
||||||
|
};
|
||||||
|
|
||||||
|
state.urls.write().await.insert(id.clone(), entry.clone());
|
||||||
|
info!("Created short URL: {} -> {}", id, req.url);
|
||||||
|
|
||||||
|
Ok(Json(CreateResponse {
|
||||||
|
short_url,
|
||||||
|
original_url: req.url,
|
||||||
|
id,
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
|
||||||
|
#[instrument(skip(state))]
|
||||||
|
async fn redirect(
|
||||||
|
State(state): State<AppState>,
|
||||||
|
Path(id): Path<String>,
|
||||||
|
) -> Result<axum::http::Response<axum::body::Body>, (StatusCode, String)> {
|
||||||
|
let urls = state.urls.read().await;
|
||||||
|
let url = urls.get(&id).cloned();
|
||||||
|
drop(urls);
|
||||||
|
|
||||||
|
match url {
|
||||||
|
Some(mut entry) => {
|
||||||
|
entry.click_count += 1;
|
||||||
|
state.urls.write().await.insert(id.clone(), entry.clone());
|
||||||
|
info!("Redirect to {}: {} clicks", entry.original_url, entry.click_count);
|
||||||
|
Ok(axum::http::Response::builder()
|
||||||
|
.status(StatusCode::FOUND)
|
||||||
|
.header(axum::http::header::LOCATION, entry.original_url)
|
||||||
|
.body(axum::body::Body::empty())
|
||||||
|
.unwrap())
|
||||||
|
}
|
||||||
|
None => Err((StatusCode::NOT_FOUND, "Short URL not found".to_string())),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[instrument(skip(state))]
|
||||||
|
async fn list_urls(
|
||||||
|
State(state): State<AppState>,
|
||||||
|
) -> Json<Vec<ShortUrl>> {
|
||||||
|
let urls = state.urls.read().await;
|
||||||
|
let mut all_urls: Vec<ShortUrl> = urls.values().cloned().collect();
|
||||||
|
all_urls.sort_by(|a, b| b.click_count.cmp(&a.click_count));
|
||||||
|
Json(all_urls)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[instrument(skip(state))]
|
||||||
|
async fn get_stats(
|
||||||
|
State(state): State<AppState>,
|
||||||
|
) -> Json<StatsResponse> {
|
||||||
|
let urls = state.urls.read().await;
|
||||||
|
let total_urls = urls.len();
|
||||||
|
let total_clicks: u64 = urls.values().map(|u| u.click_count).sum();
|
||||||
|
let mut top_urls: Vec<ShortUrl> = urls.values().cloned().collect();
|
||||||
|
top_urls.sort_by(|a, b| b.click_count.cmp(&a.click_count));
|
||||||
|
top_urls.truncate(10);
|
||||||
|
|
||||||
|
Json(StatsResponse {
|
||||||
|
total_urls,
|
||||||
|
total_clicks,
|
||||||
|
top_urls,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
#[instrument(skip(state))]
|
||||||
|
async fn get_url_info(
|
||||||
|
State(state): State<AppState>,
|
||||||
|
Path(id): Path<String>,
|
||||||
|
) -> Result<Json<ShortUrl>, (StatusCode, String)> {
|
||||||
|
let urls = state.urls.read().await;
|
||||||
|
match urls.get(&id) {
|
||||||
|
Some(url) => Ok(Json(url.clone())),
|
||||||
|
None => Err((StatusCode::NOT_FOUND, "URL not found".to_string())),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn health_check() -> &'static str {
|
||||||
|
"OK"
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::main]
|
||||||
|
async fn main() {
|
||||||
|
tracing_subscriber::fmt()
|
||||||
|
.with_max_level(tracing::Level::INFO)
|
||||||
|
.init();
|
||||||
|
|
||||||
|
let state = AppState {
|
||||||
|
urls: Arc::new(RwLock::new(HashMap::new())),
|
||||||
|
base_url: "http://localhost:3000".to_string(),
|
||||||
|
};
|
||||||
|
|
||||||
|
let app = Router::new()
|
||||||
|
.route("/api/shorten", post(create_short_url))
|
||||||
|
.route("/api/urls", get(list_urls))
|
||||||
|
.route("/api/stats", get(get_stats))
|
||||||
|
.route("/api/urls/{id}", get(get_url_info))
|
||||||
|
.route("/{id}", get(redirect))
|
||||||
|
.route("/health", get(health_check))
|
||||||
|
.layer(TraceLayer::new_for_http());
|
||||||
|
|
||||||
|
let listener = tokio::net::TcpListener::bind("0.0.0.0:3000")
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
info!("Server running on port 3000");
|
||||||
|
axum::serve(listener, app).await.unwrap();
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user