-
+
source
A simple pastebin you can use from your terminal
Usage
diff --git a/tbin.go b/tbin.go
index c361a66..0450a42 100644
--- a/tbin.go
+++ b/tbin.go
@@ -1,20 +1,29 @@
package main
import (
+ "context"
"crypto/sha256"
"errors"
"flag"
"fmt"
"io"
- "log"
+ "log/slog"
"net"
"net/http"
"os"
+ "os/signal"
"path/filepath"
"strconv"
"strings"
+ "sync"
+ "sync/atomic"
+ "syscall"
"time"
"unicode/utf8"
+
+ "github.com/prometheus/client_golang/prometheus"
+ "github.com/prometheus/client_golang/prometheus/promhttp"
+ "golang.org/x/time/rate"
)
var (
@@ -30,82 +39,266 @@ var (
ttl = flag.Int("ttl", 48, "Time-to-live in hours for the snippets")
verbose = flag.Bool("verbose", false, "Verbose output")
plaintext = flag.Bool("plaintext", false, "Only allow plaintext snippets")
+ maxConns = flag.Int("max-conns", 100, "Maximum concurrent TCP connections")
+ rateLimit = flag.Int("rate-limit", 10, "Max requests per second per IP (0 to disable)")
+ metricsAddr = flag.String("metrics-addr", "", "Prometheus metrics listen address (empty to disable)")
)
+var (
+ logger *slog.Logger
+ connSem chan struct{}
+ activeConns atomic.Int64
+ wg sync.WaitGroup
+ purgeMu sync.Mutex
+
+ metricPastesTotal prometheus.Counter
+ metricPastesBytes prometheus.Counter
+ metricHTTPRequests *prometheus.CounterVec
+ metricTCPConnections prometheus.Counter
+ metricActiveConns prometheus.Gauge
+ metricPurgeRuns prometheus.Counter
+ metricPurgeFilesTotal *prometheus.CounterVec
+ metricRemovesTotal prometheus.Counter
+)
+
+const maxIPLimiterEntries = 10000
+
+type ipLimiter struct {
+ mu sync.Mutex
+ limiters map[string]*rate.Limiter
+ limit rate.Limit
+ burst int
+}
+
+func newIPLimiter(limit rate.Limit, burst int) *ipLimiter {
+ il := &ipLimiter{
+ limiters: make(map[string]*rate.Limiter),
+ limit: limit,
+ burst: burst,
+ }
+ go il.cleanup()
+ return il
+}
+
+func (il *ipLimiter) get(ip string) *rate.Limiter {
+ il.mu.Lock()
+ defer il.mu.Unlock()
+ l, ok := il.limiters[ip]
+ if !ok {
+ if len(il.limiters) >= maxIPLimiterEntries {
+ for k, v := range il.limiters {
+ if v.Tokens() == float64(il.burst) {
+ delete(il.limiters, k)
+ break
+ }
+ }
+ }
+ if len(il.limiters) >= maxIPLimiterEntries {
+ return rate.NewLimiter(rate.Limit(0), 0)
+ }
+ l = rate.NewLimiter(il.limit, il.burst)
+ il.limiters[ip] = l
+ }
+ return l
+}
+
+func (il *ipLimiter) cleanup() {
+ ticker := time.NewTicker(10 * time.Minute)
+ defer ticker.Stop()
+ for range ticker.C {
+ il.mu.Lock()
+ for ip, l := range il.limiters {
+ if l.Tokens() == float64(il.burst) {
+ delete(il.limiters, ip)
+ }
+ }
+ il.mu.Unlock()
+ }
+}
+
+var (
+ httpIPLimiter *ipLimiter
+ tcpIPLimiter *ipLimiter
+)
+
+func initMetrics() {
+ metricPastesTotal = prometheus.NewCounter(prometheus.CounterOpts{
+ Name: "tbin_pastes_total",
+ Help: "Total number of pastes created",
+ })
+ metricPastesBytes = prometheus.NewCounter(prometheus.CounterOpts{
+ Name: "tbin_pastes_bytes_total",
+ Help: "Total bytes of pastes created",
+ })
+ metricHTTPRequests = prometheus.NewCounterVec(prometheus.CounterOpts{
+ Name: "tbin_http_requests_total",
+ Help: "Total HTTP requests by method, endpoint, and status",
+ }, []string{"method", "endpoint", "status"})
+ metricTCPConnections = prometheus.NewCounter(prometheus.CounterOpts{
+ Name: "tbin_tcp_connections_total",
+ Help: "Total TCP connections accepted",
+ })
+ metricActiveConns = prometheus.NewGauge(prometheus.GaugeOpts{
+ Name: "tbin_tcp_active_connections",
+ Help: "Current active TCP connections",
+ })
+ metricPurgeRuns = prometheus.NewCounter(prometheus.CounterOpts{
+ Name: "tbin_purge_runs_total",
+ Help: "Total purge operations executed",
+ })
+ metricPurgeFilesTotal = prometheus.NewCounterVec(prometheus.CounterOpts{
+ Name: "tbin_purge_files_total",
+ Help: "Files processed during purge by result",
+ }, []string{"result"})
+ metricRemovesTotal = prometheus.NewCounter(prometheus.CounterOpts{
+ Name: "tbin_removes_total",
+ Help: "Total manual remove requests",
+ })
+
+ prometheus.MustRegister(
+ metricPastesTotal,
+ metricPastesBytes,
+ metricHTTPRequests,
+ metricTCPConnections,
+ metricActiveConns,
+ metricPurgeRuns,
+ metricPurgeFilesTotal,
+ metricRemovesTotal,
+ )
+}
+
func main() {
flag.Parse()
- // Validate and normalize configuration
+ logLevel := slog.LevelInfo
+ if *verbose {
+ logLevel = slog.LevelDebug
+ }
+ logger = slog.New(slog.NewTextHandler(os.Stderr, &slog.HandlerOptions{Level: logLevel}))
+ slog.SetDefault(logger)
+
+ initMetrics()
+
*buff *= 1024 * 1024
if *buff <= 0 {
- log.Fatal("Buffer size must be positive")
+ logger.Error("buffer size must be positive")
+ os.Exit(1)
}
if *chunkSize <= 0 {
- log.Fatal("Chunk size must be positive")
+ logger.Error("chunk size must be positive")
+ os.Exit(1)
}
if *connTimeout <= 0 {
- log.Fatal("Connection timeout must be positive")
+ logger.Error("connection timeout must be positive")
+ os.Exit(1)
}
if *readTimeout <= 0 {
- log.Fatal("Read timeout must be positive")
+ logger.Error("read timeout must be positive")
+ os.Exit(1)
}
if *ttl <= 0 {
- log.Fatal("TTL must be positive")
+ logger.Error("TTL must be positive")
+ os.Exit(1)
+ }
+
+ if *maxConns <= 0 {
+ logger.Error("max connections must be positive")
+ os.Exit(1)
}
if !strings.HasSuffix(*httpURL, "/") {
*httpURL += "/"
}
- // Validate and create data directory
if *dir == "" {
- log.Fatal("Data directory cannot be empty")
+ logger.Error("data directory cannot be empty")
+ os.Exit(1)
}
- // Use absolute path for data directory to prevent path traversal
absDir, err := filepath.Abs(*dir)
if err != nil {
- log.Fatalf("Error getting absolute path for data directory: %v", err)
+ logger.Error("error getting absolute path for data directory", "error", err)
+ os.Exit(1)
}
*dir = absDir
if err := os.MkdirAll(*dir, 0700); err != nil {
- log.Fatalf("Error creating data directory %s: %v", *dir, err)
+ logger.Error("error creating data directory", "dir", *dir, "error", err)
+ os.Exit(1)
}
- log.Printf("Starting tbin with data directory: %s", *dir)
- log.Printf("Buffer size: %d MB", *buff/1024/1024)
- log.Printf("TTL: %d hours", *ttl)
+ connSem = make(chan struct{}, *maxConns)
- go listenTCP()
- listenHTTP()
+ if *rateLimit > 0 {
+ httpIPLimiter = newIPLimiter(rate.Limit(*rateLimit), *rateLimit*2)
+ tcpIPLimiter = newIPLimiter(rate.Limit(*rateLimit), *rateLimit*2)
+ }
+
+ logger.Info("starting tbin",
+ "data_dir", *dir,
+ "buffer_mb", *buff/1024/1024,
+ "ttl_hours", *ttl,
+ "max_conns", *maxConns,
+ "rate_limit", *rateLimit,
+ )
+
+ ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
+ defer stop()
+
+ go listenTCP(ctx)
+
+ if *metricsAddr != "" {
+ go listenMetrics(ctx)
+ }
+
+ listenHTTP(ctx)
+
+ wg.Wait()
+ logger.Info("shutdown complete")
}
-func listenTCP() {
+func listenTCP(ctx context.Context) {
l, err := net.Listen("tcp", *connHost+":"+*connPort)
if err != nil {
- log.Fatalf("Error listening: %v", err)
+ logger.Error("error listening TCP", "error", err)
+ os.Exit(1)
}
defer l.Close()
- log.Printf("Listening on %s:%s for TCP connections", *connHost, *connPort)
+
+ go func() {
+ <-ctx.Done()
+ l.Close()
+ }()
+
+ logger.Info("listening for TCP connections", "addr", *connHost+":"+*connPort)
for {
conn, err := l.Accept()
if err != nil {
- log.Printf("Error accepting: %v", err)
- continue
+ select {
+ case <-ctx.Done():
+ return
+ default:
+ logger.Error("error accepting TCP connection", "error", err)
+ continue
+ }
}
- go handleTCP(conn)
+ metricTCPConnections.Inc()
+ wg.Add(1)
+ go func() {
+ defer wg.Done()
+ handleTCP(conn)
+ }()
}
}
-func listenHTTP() {
- // Set up security headers middleware
- http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
- // Security headers
+func listenHTTP(ctx context.Context) {
+ mux := http.NewServeMux()
+
+ mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("X-Content-Type-Options", "nosniff")
w.Header().Set("X-Frame-Options", "DENY")
w.Header().Set("X-XSS-Protection", "1; mode=block")
@@ -115,96 +308,250 @@ func listenHTTP() {
handleHTTP(w, r)
})
- log.Printf("Listening on %s:%s for HTTP connections", *connHost, *httpPort)
- err := http.ListenAndServe(*connHost+":"+*httpPort, nil)
- if err != nil {
- log.Fatalf("Error listening: %v", err)
+ mux.HandleFunc("/health", func(w http.ResponseWriter, r *http.Request) {
+ w.Header().Set("Content-Type", "application/json")
+ w.Write([]byte(`{"status":"ok"}`))
+ })
+
+ server := &http.Server{
+ Addr: *connHost + ":" + *httpPort,
+ Handler: mux,
+ ReadTimeout: 10 * time.Second,
+ WriteTimeout: 30 * time.Second,
+ IdleTimeout: 60 * time.Second,
}
+
+ go func() {
+ <-ctx.Done()
+ shutdownCtx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
+ defer cancel()
+ server.Shutdown(shutdownCtx)
+ }()
+
+ logger.Info("listening for HTTP connections", "addr", *connHost+":"+*httpPort)
+ if err := server.ListenAndServe(); err != nil && err != http.ErrServerClosed {
+ logger.Error("error listening HTTP", "error", err)
+ os.Exit(1)
+ }
+}
+
+func listenMetrics(ctx context.Context) {
+ mux := http.NewServeMux()
+ mux.Handle("/metrics", promhttp.Handler())
+
+ server := &http.Server{
+ Addr: *metricsAddr,
+ Handler: mux,
+ ReadTimeout: 5 * time.Second,
+ WriteTimeout: 10 * time.Second,
+ IdleTimeout: 30 * time.Second,
+ }
+
+ go func() {
+ <-ctx.Done()
+ shutdownCtx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
+ defer cancel()
+ server.Shutdown(shutdownCtx)
+ }()
+
+ logger.Info("listening for metrics", "addr", *metricsAddr)
+ if err := server.ListenAndServe(); err != nil && err != http.ErrServerClosed {
+ logger.Error("error listening metrics", "error", err)
+ }
+}
+
+func getRemoteIP(addr string) string {
+ host, _, err := net.SplitHostPort(addr)
+ if err != nil {
+ return addr
+ }
+ return host
+}
+
+func isLocalhost(addr string) bool {
+ host := getRemoteIP(addr)
+ return host == "127.0.0.1" || host == "::1" || host == "localhost"
}
func handleHTTP(w http.ResponseWriter, r *http.Request) {
if *verbose {
- log.Printf("HTTP %s %s %s", r.RemoteAddr, r.Method, r.URL.Path)
+ logger.Debug("http request", "remote", r.RemoteAddr, "method", r.Method, "path", r.URL.Path)
+ }
+
+ if httpIPLimiter != nil {
+ ip := getRemoteIP(r.RemoteAddr)
+ if !httpIPLimiter.get(ip).Allow() {
+ metricHTTPRequests.WithLabelValues(r.Method, "rate_limited", "429").Inc()
+ http.Error(w, "Too many requests", http.StatusTooManyRequests)
+ return
+ }
}
- // Security: Prevent path traversal attacks
id := strings.TrimPrefix(r.URL.Path, "/")
if strings.Contains(id, "..") || strings.Contains(id, "/") {
+ metricHTTPRequests.WithLabelValues(r.Method, "invalid_path", "400").Inc()
http.Error(w, "Invalid path", http.StatusBadRequest)
return
}
switch r.Method {
case "POST":
+ r.Body = http.MaxBytesReader(w, r.Body, int64(*buff)+1024)
+
switch id {
case "paste":
+ if err := r.ParseForm(); err != nil {
+ var maxErr *http.MaxBytesError
+ if errors.As(err, &maxErr) {
+ metricHTTPRequests.WithLabelValues(r.Method, "paste", "413").Inc()
+ http.Error(w, "Data too large", http.StatusRequestEntityTooLarge)
+ } else {
+ metricHTTPRequests.WithLabelValues(r.Method, "paste", "400").Inc()
+ http.Error(w, "Invalid form data", http.StatusBadRequest)
+ }
+ return
+ }
data := r.FormValue("paste")
if data == "" {
+ metricHTTPRequests.WithLabelValues(r.Method, "paste", "400").Inc()
http.Error(w, "Empty data", http.StatusBadRequest)
return
}
if len(data) > *buff {
+ metricHTTPRequests.WithLabelValues(r.Method, "paste", "413").Inc()
http.Error(w, "Data too large", http.StatusRequestEntityTooLarge)
return
}
- id = handleData([]byte(data))
- if id == "" {
+ newID := handleData([]byte(data))
+ if newID == "" {
+ metricHTTPRequests.WithLabelValues(r.Method, "paste", "500").Inc()
http.Error(w, "Error generating file", http.StatusInternalServerError)
return
}
- http.Redirect(w, r, "/"+id, http.StatusSeeOther)
+ metricHTTPRequests.WithLabelValues(r.Method, "paste", "303").Inc()
+ http.Redirect(w, r, "/"+newID, http.StatusSeeOther)
case "remove":
- id = r.FormValue("remove")
- if id != "" {
- go handleRemove(id)
+ if err := r.ParseForm(); err != nil {
+ var maxErr *http.MaxBytesError
+ if errors.As(err, &maxErr) {
+ metricHTTPRequests.WithLabelValues(r.Method, "remove", "413").Inc()
+ http.Error(w, "Data too large", http.StatusRequestEntityTooLarge)
+ } else {
+ metricHTTPRequests.WithLabelValues(r.Method, "remove", "400").Inc()
+ http.Error(w, "Invalid form data", http.StatusBadRequest)
+ }
+ return
}
+ removeID := r.FormValue("remove")
+ if removeID != "" {
+ metricRemovesTotal.Inc()
+ wg.Add(1)
+ go func() {
+ defer wg.Done()
+ handleRemove(removeID)
+ }()
+ }
+ metricHTTPRequests.WithLabelValues(r.Method, "remove", "303").Inc()
http.Redirect(w, r, "/", http.StatusSeeOther)
+ default:
+ metricHTTPRequests.WithLabelValues(r.Method, "not_found", "404").Inc()
+ http.Error(w, "Not found", http.StatusNotFound)
}
case "GET":
switch {
case id == "":
- id = "index.html"
- w.Header().Set("Content-Type", "text/html")
+ w.Header().Set("Content-Type", "text/html; charset=utf-8")
+ w.Header().Set("Cache-Control", "public, max-age=3600")
+ serveFile(w, "index.html")
+ metricHTTPRequests.WithLabelValues(r.Method, "index", "200").Inc()
case strings.HasPrefix(id, "favicon"):
- id = "favicon.png"
w.Header().Set("Content-Type", "image/png")
+ w.Header().Set("Cache-Control", "public, max-age=86400")
+ serveFile(w, "favicon.png")
+ metricHTTPRequests.WithLabelValues(r.Method, "favicon", "200").Inc()
case id == "example":
w.Header().Set("Content-Type", "text/plain; charset=utf-8")
w.Write([]byte("Hello there\n"))
+ metricHTTPRequests.WithLabelValues(r.Method, "example", "200").Inc()
return
case id == "purge":
- // Security: Only allow purge from localhost or add authentication
- if r.RemoteAddr != "[::1]:" && !strings.HasPrefix(r.RemoteAddr, "127.0.0.1:") {
- log.Printf("Unauthorized purge attempt from %s", r.RemoteAddr)
+ if !isLocalhost(r.RemoteAddr) {
+ logger.Warn("unauthorized purge attempt", "remote", r.RemoteAddr)
+ metricHTTPRequests.WithLabelValues(r.Method, "purge", "401").Inc()
http.Error(w, "Unauthorized", http.StatusUnauthorized)
return
}
- log.Printf("Purge requested from %s", r.RemoteAddr)
- go handlePurge()
+ logger.Info("purge requested", "remote", r.RemoteAddr)
+ metricHTTPRequests.WithLabelValues(r.Method, "purge", "200").Inc()
+ wg.Add(1)
+ go func() {
+ defer wg.Done()
+ handlePurge()
+ }()
w.Header().Set("Content-Type", "text/plain; charset=utf-8")
w.Write([]byte("OK\n"))
return
default:
w.Header().Set("Content-Type", "text/plain; charset=utf-8")
w.Header().Set("X-Robots-Tag", "noindex,nofollow")
- id = *dir + "/" + id + ".txt"
+ filename := filepath.Join(*dir, id+".txt")
+ f, err := os.Open(filename)
+ if err != nil {
+ metricHTTPRequests.WithLabelValues(r.Method, "paste", "404").Inc()
+ http.Error(w, "Not found", http.StatusNotFound)
+ return
+ }
+ defer f.Close()
+ metricHTTPRequests.WithLabelValues(r.Method, "paste", "200").Inc()
+ io.CopyN(w, f, int64(*buff))
}
- f, err := os.Open(id)
- if err != nil {
- http.Error(w, "Not found", http.StatusNotFound)
- return
- }
- defer f.Close()
- io.CopyN(w, f, int64(*buff))
+ default:
+ metricHTTPRequests.WithLabelValues(r.Method, "method_not_allowed", "405").Inc()
+ http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
}
}
-func handleTCP(conn net.Conn) {
- defer conn.Close()
+func serveFile(w http.ResponseWriter, name string) {
+ f, err := os.Open(name)
+ if err != nil {
+ http.Error(w, "Not found", http.StatusNotFound)
+ return
+ }
+ defer f.Close()
+ io.Copy(w, f)
+}
- // Rate limiting: limit concurrent connections per IP
+func handleTCP(conn net.Conn) {
remoteAddr := conn.RemoteAddr().String()
- log.Printf("TCP %s connection", remoteAddr)
+
+ select {
+ case connSem <- struct{}{}:
+ defer func() { <-connSem }()
+ default:
+ logger.Warn("max connections reached, rejecting", "remote", remoteAddr)
+ conn.Write([]byte("Error: server busy, try again later\n"))
+ conn.Close()
+ return
+ }
+
+ active := activeConns.Add(1)
+ metricActiveConns.Set(float64(active))
+ defer func() {
+ activeConns.Add(-1)
+ metricActiveConns.Set(float64(activeConns.Load()))
+ conn.Close()
+ }()
+
+ if tcpIPLimiter != nil {
+ ip := getRemoteIP(remoteAddr)
+ if !tcpIPLimiter.get(ip).Allow() {
+ logger.Warn("rate limit exceeded", "remote", remoteAddr)
+ conn.Write([]byte("Error: rate limit exceeded, slow down\n"))
+ return
+ }
+ }
+
+ logger.Debug("tcp connection", "remote", remoteAddr)
buf := make([]byte, *chunkSize)
var data []byte
@@ -216,7 +563,7 @@ func handleTCP(conn net.Conn) {
n, err := conn.Read(buf)
if err != nil {
if err != io.EOF {
- log.Printf("Error reading from %s: %v", remoteAddr, err)
+ logger.Debug("error reading from tcp", "remote", remoteAddr, "error", err)
}
break
}
@@ -224,7 +571,7 @@ func handleTCP(conn net.Conn) {
dataLen += n
if dataLen >= *buff {
- log.Printf("Buffer limit exceeded from %s: %d bytes", remoteAddr, dataLen)
+ logger.Warn("buffer limit exceeded", "remote", remoteAddr, "bytes", dataLen)
conn.Write([]byte("Warning: " + strconv.Itoa(*buff/1024/1024) + "MB limit exceeded\n"))
break
}
@@ -233,15 +580,14 @@ func handleTCP(conn net.Conn) {
}
if dataLen == 0 {
- log.Printf("No data received from %s", remoteAddr)
+ logger.Debug("no data received", "remote", remoteAddr)
conn.Write([]byte("Error: no data received\n"))
return
}
if *plaintext {
- err := checkData(data)
- if err != nil {
- log.Printf("Invalid data from %s: %v", remoteAddr, err)
+ if err := checkData(data); err != nil {
+ logger.Warn("invalid data", "remote", remoteAddr, "error", err)
conn.Write([]byte("Error: " + err.Error() + "\n"))
return
}
@@ -249,12 +595,12 @@ func handleTCP(conn net.Conn) {
id := handleData(data)
if id == "" {
- log.Printf("Error generating file for %s", remoteAddr)
+ logger.Error("error generating file", "remote", remoteAddr)
conn.Write([]byte("Error generating file\n"))
return
}
- log.Printf("TCP %s %d %s.txt", remoteAddr, dataLen, id)
+ logger.Info("tcp paste created", "remote", remoteAddr, "bytes", dataLen, "id", id)
conn.Write([]byte(*httpURL + id + "\n"))
time.Sleep(100 * time.Millisecond)
}
@@ -264,7 +610,6 @@ func checkData(data []byte) error {
return errors.New("only plain text data is allowed")
}
- // Additional validation: check for control characters (except newline)
for _, b := range data {
if b < 32 && b != '\n' && b != '\t' && b != '\r' {
return errors.New("control characters are not allowed")
@@ -278,43 +623,42 @@ func handleData(data []byte) string {
var id string
for l := 6; l <= 16; l++ {
id = generateId(data, l)
- if _, err := os.Stat(*dir + "/" + id + ".txt"); os.IsNotExist(err) {
+ if _, err := os.Stat(filepath.Join(*dir, id+".txt")); os.IsNotExist(err) {
break
}
id = ""
}
if id == "" {
- log.Println("Error no available id found")
+ logger.Error("no available id found")
return ""
}
- // Validate ID format
if !isAlphanumeric(id) {
- log.Printf("Error invalid ID format: %s", id)
+ logger.Error("invalid ID format", "id", id)
return ""
}
- filename := *dir + "/" + id + ".txt"
- f, err := os.Create(filename)
+ filename := filepath.Join(*dir, id+".txt")
+ f, err := os.OpenFile(filename, os.O_CREATE|os.O_WRONLY|os.O_EXCL, 0600)
if err != nil {
- log.Printf("Error creating file %s: %v", filename, err)
+ logger.Error("error creating file", "file", filename, "error", err)
return ""
}
defer f.Close()
- // Ensure data ends with newline
if len(data) > 0 && data[len(data)-1] != '\n' {
data = append(data, '\n')
}
- _, err = f.Write(data)
- if err != nil {
- log.Printf("Error writing to file %s: %v", filename, err)
- // Try to clean up the empty file
+ if _, err := f.Write(data); err != nil {
+ logger.Error("error writing to file", "file", filename, "error", err)
os.Remove(filename)
return ""
}
+ metricPastesTotal.Inc()
+ metricPastesBytes.Add(float64(len(data)))
+
return id
}
@@ -337,41 +681,46 @@ func isAlphanumeric(id string) bool {
}
func handleRemove(id string) {
- // Extract ID from URL or direct input
- id = strings.TrimPrefix(strings.Split(id, "/")[len(strings.Split(id, "/"))-1], "/")
+ parts := strings.Split(id, "/")
+ id = strings.TrimPrefix(parts[len(parts)-1], "/")
- // Validate ID format
if id == "" || len(id) > 16 || !isAlphanumeric(id) {
- log.Printf("Error invalid id to remove: %s", id)
+ logger.Warn("invalid id to remove", "id", id)
return
}
- filename := *dir + "/" + id + ".txt"
+ filename := filepath.Join(*dir, id+".txt")
- // Check if file exists before attempting to remove
if _, err := os.Stat(filename); os.IsNotExist(err) {
- log.Printf("File not found for removal: %s", filename)
+ logger.Debug("file not found for removal", "file", filename)
return
}
- err := os.Remove(filename)
- if err != nil {
- log.Printf("Error removing file %s: %v", filename, err)
+ if err := os.Remove(filename); err != nil {
+ logger.Error("error removing file", "file", filename, "error", err)
} else {
- log.Printf("File removed: %s", filename)
+ logger.Info("file removed", "file", filename)
}
}
func handlePurge() {
+ if !purgeMu.TryLock() {
+ logger.Debug("purge already running, skipping")
+ return
+ }
+ defer purgeMu.Unlock()
+
+ metricPurgeRuns.Inc()
+ logger.Info("purge started")
+
files, err := os.ReadDir(*dir)
if err != nil {
- log.Printf("Error reading data directory: %v", err)
+ logger.Error("error reading data directory", "error", err)
+ metricPurgeFilesTotal.WithLabelValues("error").Inc()
return
}
- var filesRemoved int
- var filesSkipped int
- var errorsEncountered int
+ var filesRemoved, filesSkipped, errorsEncountered int
for _, file := range files {
if file.IsDir() {
@@ -379,7 +728,6 @@ func handlePurge() {
continue
}
- // Only process .txt files
if !strings.HasSuffix(file.Name(), ".txt") {
filesSkipped++
continue
@@ -387,23 +735,29 @@ func handlePurge() {
info, err := file.Info()
if err != nil {
- log.Printf("Error getting file info for %s: %v", file.Name(), err)
+ logger.Error("error getting file info", "file", file.Name(), "error", err)
errorsEncountered++
+ metricPurgeFilesTotal.WithLabelValues("error").Inc()
continue
}
if time.Since(info.ModTime()) > time.Duration(*ttl)*time.Hour {
- filename := *dir + "/" + file.Name()
- err = os.Remove(filename)
- if err != nil {
- log.Printf("Error removing file %s: %v", filename, err)
+ filename := filepath.Join(*dir, file.Name())
+ if err := os.Remove(filename); err != nil {
+ logger.Error("error removing file", "file", filename, "error", err)
errorsEncountered++
+ metricPurgeFilesTotal.WithLabelValues("error").Inc()
} else {
filesRemoved++
- log.Printf("File removed: %s", filename)
+ logger.Debug("file removed", "file", filename)
+ metricPurgeFilesTotal.WithLabelValues("removed").Inc()
}
}
}
- log.Printf("Purge done: %d files removed, %d files skipped, %d errors", filesRemoved, filesSkipped, errorsEncountered)
+ logger.Info("purge done",
+ "removed", filesRemoved,
+ "skipped", filesSkipped,
+ "errors", errorsEncountered,
+ )
}