Add backups, currencies and dashboard APIs, and scope access by guard_name.
Web users may only CRUD their own records, operators stay in assigned branches, and admin/manager/superadmin keep full access. Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
233
internal/backup/db/postgresql.go
Normal file
233
internal/backup/db/postgresql.go
Normal file
@@ -0,0 +1,233 @@
|
||||
package db
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"online-back/internal/backup"
|
||||
"online-back/pkg/client/postgresql"
|
||||
"online-back/pkg/logging"
|
||||
"online-back/pkg/repository/genericrepo"
|
||||
)
|
||||
|
||||
type repository struct {
|
||||
client postgresql.Client
|
||||
generic *genericrepo.Repository[backup.BackupDTO]
|
||||
logger *logging.Logger
|
||||
}
|
||||
|
||||
func NewRepository(client postgresql.Client, logger *logging.Logger) backup.Repository {
|
||||
return &repository{
|
||||
client: client,
|
||||
generic: genericrepo.New(client, "backups", backupColumnsSQL, scanBackup),
|
||||
logger: logger,
|
||||
}
|
||||
}
|
||||
|
||||
var backupColumns = []string{
|
||||
"id", "file_name", "size_bytes", "status", "error_message",
|
||||
"created_by", "created_at", "updated_at",
|
||||
}
|
||||
|
||||
var backupColumnsSQL = strings.Join(backupColumns, ", ")
|
||||
|
||||
const userDisplaySQL = `COALESCE(NULLIF(TRIM(CONCAT_WS(' ', u.first_name, u.last_name)), ''), NULLIF(u.name, ''), u.username, '')`
|
||||
|
||||
const backupFromClause = ` FROM backups b
|
||||
LEFT JOIN users u ON u.id = b.created_by`
|
||||
|
||||
var backupSelectColumns = prefixed("b", backupColumns) + `,
|
||||
` + userDisplaySQL + `, COALESCE(u.username, ''), COALESCE(u.phone, ''), COALESCE(u.email, '')`
|
||||
|
||||
func prefixed(alias string, cols []string) string {
|
||||
parts := make([]string, len(cols))
|
||||
for i, col := range cols {
|
||||
parts[i] = alias + "." + col
|
||||
}
|
||||
return strings.Join(parts, ", ")
|
||||
}
|
||||
|
||||
func (r *repository) List(ctx context.Context, filter backup.ListFilter) (backup.ListBackupDTO, error) {
|
||||
whereClause, args := buildListQuery(filter)
|
||||
|
||||
var count int64
|
||||
if err := r.client.QueryRow(ctx, `SELECT COUNT(*) FROM backups b`+whereClause, args...).Scan(&count); err != nil {
|
||||
return backup.ListBackupDTO{}, err
|
||||
}
|
||||
|
||||
offset := (filter.Page - 1) * filter.Limit
|
||||
limitPlaceholder := len(args) + 1
|
||||
offsetPlaceholder := len(args) + 2
|
||||
query := fmt.Sprintf(
|
||||
`SELECT %s%s%s ORDER BY b.created_at DESC, b.id DESC LIMIT $%d OFFSET $%d`,
|
||||
backupSelectColumns, backupFromClause, whereClause, limitPlaceholder, offsetPlaceholder,
|
||||
)
|
||||
|
||||
rows, err := r.client.Query(ctx, query, append(args, filter.Limit, offset)...)
|
||||
if err != nil {
|
||||
return backup.ListBackupDTO{}, err
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
var items []backup.BackupDTO
|
||||
for rows.Next() {
|
||||
item, err := scanBackupWithUser(rows)
|
||||
if err != nil {
|
||||
return backup.ListBackupDTO{}, err
|
||||
}
|
||||
items = append(items, item)
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return backup.ListBackupDTO{}, err
|
||||
}
|
||||
|
||||
return backup.ListBackupDTO{Count: count, Backups: items}, nil
|
||||
}
|
||||
|
||||
func buildListQuery(filter backup.ListFilter) (whereClause string, args []interface{}) {
|
||||
var conditions []string
|
||||
|
||||
if filter.Search != "" {
|
||||
args = append(args, likePattern(filter.Search))
|
||||
conditions = append(conditions, fmt.Sprintf(`b.file_name ILIKE $%d ESCAPE '\'`, len(args)))
|
||||
}
|
||||
|
||||
if filter.Status != nil {
|
||||
args = append(args, *filter.Status)
|
||||
conditions = append(conditions, fmt.Sprintf("b.status = $%d", len(args)))
|
||||
}
|
||||
|
||||
if len(conditions) == 0 {
|
||||
return "", args
|
||||
}
|
||||
return " WHERE " + strings.Join(conditions, " AND "), args
|
||||
}
|
||||
|
||||
func likePattern(term string) string {
|
||||
return "%" + escapeLike(term) + "%"
|
||||
}
|
||||
|
||||
func escapeLike(term string) string {
|
||||
term = strings.ReplaceAll(term, `\`, `\\`)
|
||||
term = strings.ReplaceAll(term, `%`, `\%`)
|
||||
term = strings.ReplaceAll(term, `_`, `\_`)
|
||||
return term
|
||||
}
|
||||
|
||||
func (r *repository) GetByID(ctx context.Context, id int64) (backup.BackupDTO, error) {
|
||||
query := `SELECT ` + backupSelectColumns + backupFromClause + ` WHERE b.id = $1`
|
||||
return scanBackupWithUser(r.client.QueryRow(ctx, query, id))
|
||||
}
|
||||
|
||||
func (r *repository) Create(ctx context.Context, dto backup.CreateBackupDTO) (backup.BackupDTO, error) {
|
||||
query := `
|
||||
WITH inserted AS (
|
||||
INSERT INTO backups (file_name, created_by)
|
||||
VALUES ($1, $2)
|
||||
RETURNING ` + backupColumnsSQL + `
|
||||
)
|
||||
SELECT ` + backupSelectColumns + `
|
||||
FROM inserted b
|
||||
LEFT JOIN users u ON u.id = b.created_by`
|
||||
|
||||
return scanBackupWithUser(r.client.QueryRow(ctx, query, dto.FileName, dto.CreatedBy))
|
||||
}
|
||||
|
||||
func (r *repository) Finish(ctx context.Context, id int64, sizeBytes int64, status string, errMsg *string) (backup.BackupDTO, error) {
|
||||
query := `
|
||||
WITH updated AS (
|
||||
UPDATE backups SET
|
||||
size_bytes = $1,
|
||||
status = $2,
|
||||
error_message = $3,
|
||||
updated_at = (CURRENT_TIMESTAMP AT TIME ZONE 'UTC')
|
||||
WHERE id = $4
|
||||
RETURNING ` + backupColumnsSQL + `
|
||||
)
|
||||
SELECT ` + backupSelectColumns + `
|
||||
FROM updated b
|
||||
LEFT JOIN users u ON u.id = b.created_by`
|
||||
|
||||
item, err := scanBackupWithUser(r.client.QueryRow(ctx, query, sizeBytes, status, errMsg, id))
|
||||
if err != nil {
|
||||
return backup.BackupDTO{}, err
|
||||
}
|
||||
return item, nil
|
||||
}
|
||||
|
||||
func (r *repository) Delete(ctx context.Context, id int64) error {
|
||||
return r.generic.Delete(ctx, id)
|
||||
}
|
||||
|
||||
func (r *repository) CountByFilePrefix(ctx context.Context, prefix string) (int64, error) {
|
||||
var count int64
|
||||
err := r.client.QueryRow(ctx,
|
||||
`SELECT COUNT(*) FROM backups WHERE file_name LIKE $1 ESCAPE '\'`,
|
||||
escapeLike(prefix)+"%",
|
||||
).Scan(&count)
|
||||
return count, err
|
||||
}
|
||||
|
||||
func scanBackup(row genericrepo.Scanner) (backup.BackupDTO, error) {
|
||||
return scanBackupRow(row, false)
|
||||
}
|
||||
|
||||
func scanBackupWithUser(row genericrepo.Scanner) (backup.BackupDTO, error) {
|
||||
return scanBackupRow(row, true)
|
||||
}
|
||||
|
||||
func scanBackupRow(row genericrepo.Scanner, withUser bool) (backup.BackupDTO, error) {
|
||||
var item backup.BackupDTO
|
||||
dest := []interface{}{
|
||||
&item.Id, &item.FileName, &item.SizeBytes, &item.Status, &item.ErrorMessage,
|
||||
&item.CreatedById, &item.CreatedAt, &item.UpdatedAt,
|
||||
}
|
||||
|
||||
var userName, userUsername, userPhone, userEmail string
|
||||
if withUser {
|
||||
dest = append(dest, &userName, &userUsername, &userPhone, &userEmail)
|
||||
}
|
||||
|
||||
if err := row.Scan(dest...); err != nil {
|
||||
return backup.BackupDTO{}, err
|
||||
}
|
||||
|
||||
item.Size = formatSize(item.SizeBytes)
|
||||
|
||||
if withUser {
|
||||
if item.CreatedById != nil {
|
||||
item.CreatedBy = &backup.UserInfo{
|
||||
Id: *item.CreatedById,
|
||||
Name: userName,
|
||||
Username: userUsername,
|
||||
Phone: userPhone,
|
||||
Email: userEmail,
|
||||
}
|
||||
} else {
|
||||
item.CreatedBy = &backup.UserInfo{Name: "System", Username: "system"}
|
||||
}
|
||||
}
|
||||
return item, nil
|
||||
}
|
||||
|
||||
func formatSize(bytes int64) string {
|
||||
const (
|
||||
kb = 1024
|
||||
mb = 1024 * 1024
|
||||
gb = 1024 * 1024 * 1024
|
||||
)
|
||||
switch {
|
||||
case bytes >= gb:
|
||||
return fmt.Sprintf("%.1f GB", float64(bytes)/float64(gb))
|
||||
case bytes >= mb:
|
||||
if bytes%mb == 0 {
|
||||
return fmt.Sprintf("%d MB", bytes/mb)
|
||||
}
|
||||
return fmt.Sprintf("%.1f MB", float64(bytes)/float64(mb))
|
||||
case bytes >= kb:
|
||||
return fmt.Sprintf("%d KB", bytes/kb)
|
||||
default:
|
||||
return fmt.Sprintf("%d B", bytes)
|
||||
}
|
||||
}
|
||||
41
internal/backup/dto.go
Normal file
41
internal/backup/dto.go
Normal file
@@ -0,0 +1,41 @@
|
||||
package backup
|
||||
|
||||
import "time"
|
||||
|
||||
type UserInfo struct {
|
||||
Id int64 `json:"id"`
|
||||
Name string `json:"name"`
|
||||
Username string `json:"username"`
|
||||
Phone string `json:"phone"`
|
||||
Email string `json:"email"`
|
||||
}
|
||||
|
||||
type BackupDTO struct {
|
||||
Id int64 `json:"id"`
|
||||
FileName string `json:"fileName"`
|
||||
SizeBytes int64 `json:"sizeBytes"`
|
||||
Size string `json:"size"`
|
||||
Status string `json:"status"`
|
||||
ErrorMessage *string `json:"errorMessage,omitempty"`
|
||||
CreatedById *int64 `json:"-"`
|
||||
CreatedBy *UserInfo `json:"createdBy,omitempty"`
|
||||
CreatedAt time.Time `json:"createdAt"`
|
||||
UpdatedAt time.Time `json:"updatedAt"`
|
||||
}
|
||||
|
||||
type CreateBackupDTO struct {
|
||||
FileName string
|
||||
CreatedBy *int64
|
||||
}
|
||||
|
||||
type ListFilter struct {
|
||||
Search string
|
||||
Status *string
|
||||
Page int
|
||||
Limit int
|
||||
}
|
||||
|
||||
type ListBackupDTO struct {
|
||||
Count int64 `json:"count"`
|
||||
Backups []BackupDTO `json:"backups"`
|
||||
}
|
||||
55
internal/backup/dump.go
Normal file
55
internal/backup/dump.go
Normal file
@@ -0,0 +1,55 @@
|
||||
package backup
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"os"
|
||||
"os/exec"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"online-back/internal/config"
|
||||
)
|
||||
|
||||
const dumpTimeout = 10 * time.Minute
|
||||
|
||||
type Dumper interface {
|
||||
Dump(ctx context.Context, destPath string) error
|
||||
}
|
||||
|
||||
type PgDumper struct {
|
||||
storage config.StorageConfig
|
||||
}
|
||||
|
||||
func NewPgDumper(storage config.StorageConfig) *PgDumper {
|
||||
return &PgDumper{storage: storage}
|
||||
}
|
||||
|
||||
func (d *PgDumper) Dump(ctx context.Context, destPath string) error {
|
||||
ctx, cancel := context.WithTimeout(ctx, dumpTimeout)
|
||||
defer cancel()
|
||||
|
||||
cmd := exec.CommandContext(ctx, "pg_dump",
|
||||
"-h", d.storage.Host,
|
||||
"-p", d.storage.Port,
|
||||
"-U", d.storage.Username,
|
||||
"-d", d.storage.Database,
|
||||
"--no-owner",
|
||||
"--no-acl",
|
||||
"-f", destPath,
|
||||
)
|
||||
cmd.Env = append(os.Environ(), "PGPASSWORD="+d.storage.Password)
|
||||
|
||||
out, err := cmd.CombinedOutput()
|
||||
if err != nil {
|
||||
msg := strings.TrimSpace(string(out))
|
||||
if msg == "" {
|
||||
msg = err.Error()
|
||||
}
|
||||
if len(msg) > 512 {
|
||||
msg = msg[:512]
|
||||
}
|
||||
return fmt.Errorf("pg_dump: %s", msg)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
203
internal/backup/handler.go
Normal file
203
internal/backup/handler.go
Normal file
@@ -0,0 +1,203 @@
|
||||
package backup
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"net/http"
|
||||
"os"
|
||||
|
||||
"online-back/internal/appresult"
|
||||
"online-back/internal/handlers"
|
||||
"online-back/pkg/logging"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/jackc/pgx/v4"
|
||||
)
|
||||
|
||||
const baseURL = "/backups"
|
||||
|
||||
type handler struct {
|
||||
logger *logging.Logger
|
||||
service *Service
|
||||
}
|
||||
|
||||
func NewHandler(logger *logging.Logger, service *Service) handlers.Handler {
|
||||
return &handler{logger: logger, service: service}
|
||||
}
|
||||
|
||||
func (h *handler) Register(router *gin.RouterGroup) {
|
||||
group := router.Group(baseURL, appresult.JwtTokenCheck())
|
||||
group.GET("", h.list)
|
||||
group.POST("", h.create)
|
||||
group.GET("/:id/download", h.download)
|
||||
group.GET("/:id", h.getByID)
|
||||
group.DELETE("/:id", h.delete)
|
||||
}
|
||||
|
||||
// list godoc
|
||||
// @Summary List backups
|
||||
// @Description Returns paginated SQL backup files
|
||||
// @Tags backups
|
||||
// @Produce json
|
||||
// @Security BearerAuth
|
||||
// @Param search query string false "Filter by file name"
|
||||
// @Param status query string false "Filter by status (pending, completed, failed)"
|
||||
// @Param page query int false "Page number" default(1)
|
||||
// @Param limit query int false "Items per page" default(10)
|
||||
// @Success 200 {object} appresult.AppSuccess
|
||||
// @Failure 400 {object} appresult.AppError
|
||||
// @Failure 500 {object} appresult.AppError
|
||||
// @Router /backups [get]
|
||||
func (h *handler) list(c *gin.Context) {
|
||||
filter, ok := parseListFilter(c)
|
||||
if !ok {
|
||||
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
|
||||
return
|
||||
}
|
||||
|
||||
result, err := h.service.List(c.Request.Context(), filter)
|
||||
if err != nil {
|
||||
h.logger.Errorf("list backups failed: %v", err)
|
||||
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, appresult.SuccessWithData(result))
|
||||
}
|
||||
|
||||
// getByID godoc
|
||||
// @Summary Get backup by ID
|
||||
// @Description Returns a single backup record
|
||||
// @Tags backups
|
||||
// @Produce json
|
||||
// @Security BearerAuth
|
||||
// @Param id path int true "Backup ID"
|
||||
// @Success 200 {object} appresult.AppSuccess
|
||||
// @Failure 400 {object} appresult.AppError
|
||||
// @Failure 404 {object} appresult.AppError
|
||||
// @Failure 500 {object} appresult.AppError
|
||||
// @Router /backups/{id} [get]
|
||||
func (h *handler) getByID(c *gin.Context) {
|
||||
id, ok := parseID(c.Param("id"))
|
||||
if !ok {
|
||||
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
|
||||
return
|
||||
}
|
||||
|
||||
item, err := h.service.GetByID(c.Request.Context(), id)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
c.JSON(http.StatusNotFound, appresult.ErrNotFound)
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
h.logger.Errorf("get backup failed: %v", err)
|
||||
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, appresult.SuccessWithData(item))
|
||||
}
|
||||
|
||||
// create godoc
|
||||
// @Summary Create SQL backup
|
||||
// @Description Runs pg_dump and stores the resulting .sql file
|
||||
// @Tags backups
|
||||
// @Produce json
|
||||
// @Security BearerAuth
|
||||
// @Success 201 {object} appresult.AppSuccess
|
||||
// @Failure 500 {object} appresult.AppError
|
||||
// @Router /backups [post]
|
||||
func (h *handler) create(c *gin.Context) {
|
||||
item, err := h.service.Create(c.Request.Context(), currentUserID(c))
|
||||
if err != nil {
|
||||
h.logger.Errorf("create backup failed: %v", err)
|
||||
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusCreated, appresult.SuccessWithData(item))
|
||||
}
|
||||
|
||||
// download godoc
|
||||
// @Summary Download backup SQL file
|
||||
// @Description Downloads the .sql dump for a completed backup
|
||||
// @Tags backups
|
||||
// @Produce application/sql
|
||||
// @Security BearerAuth
|
||||
// @Param id path int true "Backup ID"
|
||||
// @Success 200 {file} file
|
||||
// @Failure 400 {object} appresult.AppError
|
||||
// @Failure 404 {object} appresult.AppError
|
||||
// @Failure 500 {object} appresult.AppError
|
||||
// @Router /backups/{id}/download [get]
|
||||
func (h *handler) download(c *gin.Context) {
|
||||
id, ok := parseID(c.Param("id"))
|
||||
if !ok {
|
||||
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
|
||||
return
|
||||
}
|
||||
|
||||
item, path, err := h.service.FilePath(c.Request.Context(), id)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
c.JSON(http.StatusNotFound, appresult.ErrNotFound)
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
h.logger.Errorf("download backup failed: %v", err)
|
||||
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
|
||||
return
|
||||
}
|
||||
if item.Status != "completed" {
|
||||
c.JSON(http.StatusNotFound, appresult.ErrNotFound)
|
||||
return
|
||||
}
|
||||
if _, err := os.Stat(path); err != nil {
|
||||
c.JSON(http.StatusNotFound, appresult.ErrNotFound)
|
||||
return
|
||||
}
|
||||
|
||||
c.FileAttachment(path, item.FileName)
|
||||
}
|
||||
|
||||
// delete godoc
|
||||
// @Summary Delete backup
|
||||
// @Description Deletes a backup record and its SQL file
|
||||
// @Tags backups
|
||||
// @Produce json
|
||||
// @Security BearerAuth
|
||||
// @Param id path int true "Backup ID"
|
||||
// @Success 200 {object} appresult.AppSuccess
|
||||
// @Failure 400 {object} appresult.AppError
|
||||
// @Failure 404 {object} appresult.AppError
|
||||
// @Failure 500 {object} appresult.AppError
|
||||
// @Router /backups/{id} [delete]
|
||||
func (h *handler) delete(c *gin.Context) {
|
||||
id, ok := parseID(c.Param("id"))
|
||||
if !ok {
|
||||
c.JSON(http.StatusBadRequest, appresult.ErrMissingParam)
|
||||
return
|
||||
}
|
||||
|
||||
if err := h.service.Delete(c.Request.Context(), id); errors.Is(err, pgx.ErrNoRows) {
|
||||
c.JSON(http.StatusNotFound, appresult.ErrNotFound)
|
||||
return
|
||||
} else if err != nil {
|
||||
h.logger.Errorf("delete backup failed: %v", err)
|
||||
c.JSON(http.StatusInternalServerError, appresult.ErrInternalServer)
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, appresult.SuccessWithData("backup removed"))
|
||||
}
|
||||
|
||||
func parseListFilter(c *gin.Context) (ListFilter, bool) {
|
||||
page, limit, ok := parsePageLimit(c)
|
||||
if !ok {
|
||||
return ListFilter{}, false
|
||||
}
|
||||
filter := ListFilter{Page: page, Limit: limit, Search: queryValue(c, "search", "q")}
|
||||
|
||||
if raw := queryValue(c, "status"); raw != "" {
|
||||
filter.Status = &raw
|
||||
}
|
||||
return filter, true
|
||||
}
|
||||
81
internal/backup/http.go
Normal file
81
internal/backup/http.go
Normal file
@@ -0,0 +1,81 @@
|
||||
package backup
|
||||
|
||||
import (
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
const (
|
||||
defaultPage = 1
|
||||
defaultLimit = 10
|
||||
maxLimit = 100
|
||||
)
|
||||
|
||||
func parseID(raw string) (int64, bool) {
|
||||
id, err := strconv.ParseInt(raw, 10, 64)
|
||||
if err != nil || id <= 0 {
|
||||
return 0, false
|
||||
}
|
||||
return id, true
|
||||
}
|
||||
|
||||
func queryValue(c *gin.Context, keys ...string) string {
|
||||
for _, key := range keys {
|
||||
if raw := strings.TrimSpace(c.Query(key)); raw != "" && raw != "undefined" && raw != "null" {
|
||||
return raw
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func parsePageLimit(c *gin.Context) (page, limit int, ok bool) {
|
||||
page = defaultPage
|
||||
limit = defaultLimit
|
||||
|
||||
if raw := queryValue(c, "page"); raw != "" {
|
||||
p, err := strconv.Atoi(raw)
|
||||
if err != nil || p < 1 {
|
||||
return 0, 0, false
|
||||
}
|
||||
page = p
|
||||
}
|
||||
|
||||
if raw := queryValue(c, "limit"); raw != "" {
|
||||
l, err := strconv.Atoi(raw)
|
||||
if err != nil || l < 1 {
|
||||
return 0, 0, false
|
||||
}
|
||||
if l > maxLimit {
|
||||
l = maxLimit
|
||||
}
|
||||
limit = l
|
||||
}
|
||||
|
||||
return page, limit, true
|
||||
}
|
||||
|
||||
func currentUserID(c *gin.Context) *int64 {
|
||||
rawID, exists := c.Get("id")
|
||||
if !exists {
|
||||
return nil
|
||||
}
|
||||
switch id := rawID.(type) {
|
||||
case int64:
|
||||
if id > 0 {
|
||||
return &id
|
||||
}
|
||||
case int:
|
||||
if id > 0 {
|
||||
v := int64(id)
|
||||
return &v
|
||||
}
|
||||
case string:
|
||||
parsed, err := strconv.ParseInt(id, 10, 64)
|
||||
if err == nil && parsed > 0 {
|
||||
return &parsed
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
154
internal/backup/service.go
Normal file
154
internal/backup/service.go
Normal file
@@ -0,0 +1,154 @@
|
||||
package backup
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"time"
|
||||
"unicode"
|
||||
|
||||
"online-back/pkg/logging"
|
||||
)
|
||||
|
||||
type Service struct {
|
||||
repo Repository
|
||||
dumper Dumper
|
||||
dir string
|
||||
logger *logging.Logger
|
||||
}
|
||||
|
||||
func NewService(repo Repository, dumper Dumper, dir string, logger *logging.Logger) *Service {
|
||||
return &Service{repo: repo, dumper: dumper, dir: dir, logger: logger}
|
||||
}
|
||||
|
||||
func (s *Service) List(ctx context.Context, filter ListFilter) (ListBackupDTO, error) {
|
||||
return s.repo.List(ctx, filter)
|
||||
}
|
||||
|
||||
func (s *Service) GetByID(ctx context.Context, id int64) (BackupDTO, error) {
|
||||
return s.repo.GetByID(ctx, id)
|
||||
}
|
||||
|
||||
func (s *Service) Create(ctx context.Context, userID *int64) (BackupDTO, error) {
|
||||
if err := os.MkdirAll(s.dir, 0o750); err != nil {
|
||||
return BackupDTO{}, fmt.Errorf("create backup dir: %w", err)
|
||||
}
|
||||
|
||||
fileName, err := s.nextFileName(ctx)
|
||||
if err != nil {
|
||||
return BackupDTO{}, err
|
||||
}
|
||||
|
||||
item, err := s.repo.Create(ctx, CreateBackupDTO{FileName: fileName, CreatedBy: userID})
|
||||
if err != nil {
|
||||
return BackupDTO{}, err
|
||||
}
|
||||
|
||||
dest, err := s.absPath(fileName)
|
||||
if err != nil {
|
||||
_, _ = s.repo.Finish(ctx, item.Id, 0, "failed", errString(err))
|
||||
return BackupDTO{}, err
|
||||
}
|
||||
|
||||
if dumpErr := s.dumper.Dump(ctx, dest); dumpErr != nil {
|
||||
_ = os.Remove(dest)
|
||||
msg := dumpErr.Error()
|
||||
s.logger.Errorf("sql backup dump failed: %v", dumpErr)
|
||||
return s.repo.Finish(ctx, item.Id, 0, "failed", &msg)
|
||||
}
|
||||
|
||||
info, statErr := os.Stat(dest)
|
||||
if statErr != nil {
|
||||
_ = os.Remove(dest)
|
||||
msg := statErr.Error()
|
||||
return s.repo.Finish(ctx, item.Id, 0, "failed", &msg)
|
||||
}
|
||||
|
||||
return s.repo.Finish(ctx, item.Id, info.Size(), "completed", nil)
|
||||
}
|
||||
|
||||
func (s *Service) Delete(ctx context.Context, id int64) error {
|
||||
item, err := s.repo.GetByID(ctx, id)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if err := s.repo.Delete(ctx, id); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if path, pathErr := s.absPath(item.FileName); pathErr == nil {
|
||||
if rmErr := os.Remove(path); rmErr != nil && !os.IsNotExist(rmErr) {
|
||||
s.logger.Errorf("remove backup file %s: %v", item.FileName, rmErr)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *Service) FilePath(ctx context.Context, id int64) (BackupDTO, string, error) {
|
||||
item, err := s.repo.GetByID(ctx, id)
|
||||
if err != nil {
|
||||
return BackupDTO{}, "", err
|
||||
}
|
||||
path, err := s.absPath(item.FileName)
|
||||
if err != nil {
|
||||
return BackupDTO{}, "", err
|
||||
}
|
||||
return item, path, nil
|
||||
}
|
||||
|
||||
func (s *Service) nextFileName(ctx context.Context) (string, error) {
|
||||
day := time.Now().UTC().Format("2006_01_02")
|
||||
prefix := "backup_" + day + "_"
|
||||
n, err := s.repo.CountByFilePrefix(ctx, prefix)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return fmt.Sprintf("backup_%s_%02d.sql", day, n+1), nil
|
||||
}
|
||||
|
||||
func (s *Service) absPath(fileName string) (string, error) {
|
||||
if !validBackupFileName(fileName) {
|
||||
return "", fmt.Errorf("invalid backup file name")
|
||||
}
|
||||
|
||||
dir, err := filepath.Abs(s.dir)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
full, err := filepath.Abs(filepath.Join(dir, fileName))
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
sep := string(os.PathSeparator)
|
||||
if full != dir && !strings.HasPrefix(full, dir+sep) {
|
||||
return "", fmt.Errorf("invalid backup path")
|
||||
}
|
||||
return full, nil
|
||||
}
|
||||
|
||||
func validBackupFileName(name string) bool {
|
||||
if name == "" || name != filepath.Base(name) || strings.Contains(name, "..") {
|
||||
return false
|
||||
}
|
||||
if !strings.HasPrefix(name, "backup_") || !strings.HasSuffix(name, ".sql") {
|
||||
return false
|
||||
}
|
||||
for _, r := range name {
|
||||
if unicode.IsLetter(r) || unicode.IsDigit(r) || r == '_' || r == '.' {
|
||||
continue
|
||||
}
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
func errString(err error) *string {
|
||||
if err == nil {
|
||||
return nil
|
||||
}
|
||||
msg := err.Error()
|
||||
return &msg
|
||||
}
|
||||
24
internal/backup/service_test.go
Normal file
24
internal/backup/service_test.go
Normal file
@@ -0,0 +1,24 @@
|
||||
package backup
|
||||
|
||||
import "testing"
|
||||
|
||||
func TestValidBackupFileName(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
ok bool
|
||||
}{
|
||||
{"backup_2026_05_22_01.sql", true},
|
||||
{"backup_2026_08_29_12.sql", true},
|
||||
{"", false},
|
||||
{"../etc/passwd", false},
|
||||
{"backup_2026_05_22_01.sql/../../x", false},
|
||||
{"foo.sql", false},
|
||||
{"backup_2026_05_22_01.sql.exe", false},
|
||||
{"backup_2026_05_22_01.sql ", false},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
if got := validBackupFileName(tt.name); got != tt.ok {
|
||||
t.Errorf("validBackupFileName(%q) = %v, want %v", tt.name, got, tt.ok)
|
||||
}
|
||||
}
|
||||
}
|
||||
12
internal/backup/storage.go
Normal file
12
internal/backup/storage.go
Normal file
@@ -0,0 +1,12 @@
|
||||
package backup
|
||||
|
||||
import "context"
|
||||
|
||||
type Repository interface {
|
||||
List(ctx context.Context, filter ListFilter) (ListBackupDTO, error)
|
||||
GetByID(ctx context.Context, id int64) (BackupDTO, error)
|
||||
Create(ctx context.Context, dto CreateBackupDTO) (BackupDTO, error)
|
||||
Finish(ctx context.Context, id int64, sizeBytes int64, status string, errMsg *string) (BackupDTO, error)
|
||||
Delete(ctx context.Context, id int64) error
|
||||
CountByFilePrefix(ctx context.Context, prefix string) (int64, error)
|
||||
}
|
||||
Reference in New Issue
Block a user