feat(canvas): 画布同步 - 新增操作事务、预演保存与并发恢复能力

This commit is contained in:
ddcat666
2026-10-11 22:19:20 +08:00
parent 6dedc5973c
commit 5f359f2b1d
63 changed files with 3235 additions and 6193 deletions

View File

@@ -0,0 +1,47 @@
package repository
import (
"errors"
"time"
"gorm.io/gorm"
"gorm.io/gorm/clause"
"yingce/backend/internal/model"
)
// LockCanvasMutation serializes all operations for an existing canvas, including
// deletion. On SQLite this first write also avoids a deferred read transaction
// trying to upgrade its stale snapshot to a write lock.
func (r *Repository) LockCanvasMutation(userID, canvasID string) error {
return r.db.Model(&model.CanvasProject{}).Where("id = ? AND user_id = ?", canvasID, userID).
UpdateColumn("revision", gorm.Expr("revision")).Error
}
func (r *Repository) CanvasMutationReceiptForUser(userID, canvasID, mutationID string) (*model.CanvasMutationReceipt, error) {
var receipt model.CanvasMutationReceipt
err := r.db.First(&receipt, "user_id = ? AND canvas_id = ? AND mutation_id = ?", userID, canvasID, mutationID).Error
return &receipt, err
}
func (r *Repository) TryCreateCanvasMutationReceipt(receipt *model.CanvasMutationReceipt) (bool, error) {
if receipt.CreatedAt.IsZero() {
receipt.CreatedAt = time.Now().UTC()
}
result := r.db.Clauses(clause.OnConflict{Columns: []clause.Column{{Name: "user_id"}, {Name: "canvas_id"}, {Name: "mutation_id"}}, DoNothing: true}).Create(receipt)
return result.RowsAffected == 1, result.Error
}
func (r *Repository) FinalizeCanvasMutationReceipt(receipt *model.CanvasMutationReceipt) error {
if receipt.ResultJSON == "" {
return errors.New("canvas mutation receipt requires a committed result")
}
result := r.db.Model(&model.CanvasMutationReceipt{}).Where("id = ? AND payload_digest = ?", receipt.ID, receipt.PayloadDigest).
Updates(map[string]any{"result_json": receipt.ResultJSON, "revision": receipt.Revision})
if result.Error != nil {
return result.Error
}
if result.RowsAffected != 1 {
return errors.New("canvas mutation receipt was not finalized")
}
return nil
}

View File

@@ -55,6 +55,14 @@ func (r *Repository) WithContext(ctx context.Context) *Repository {
return &Repository{db: r.db.WithContext(ctx)}
}
// Transaction exposes a repository scoped to one database transaction. Domain
// services use it when a canvas mutation and its receipt must commit together.
func (r *Repository) Transaction(fn func(*Repository) error) error {
return r.db.Transaction(func(tx *gorm.DB) error {
return fn(New(tx))
})
}
func (r *Repository) Dialect() string {
return r.db.Dialector.Name()
}
@@ -95,6 +103,26 @@ func (r *Repository) UserStorageUsage(userID string) (UserStorageUsage, error) {
return usage, err
}
// UserStructuredStorageUsage reads only the counters and payload bytes used by
// asset/canvas structured-data quotas. Keeping task and API-log accounting out of
// this path avoids scanning unrelated large history rows on every canvas write.
func (r *Repository) UserStructuredStorageUsage(userID string) (UserStorageUsage, error) {
var usage UserStorageUsage
query := `
SELECT
(SELECT COUNT(*) FROM assets WHERE user_id = ?) AS asset_count,
(SELECT COALESCE(SUM(length(CAST(COALESCE(payload_json, '') AS BLOB))), 0) FROM assets WHERE user_id = ?) AS asset_bytes,
(SELECT COUNT(*) FROM canvas_projects WHERE user_id = ?) AS canvas_count,
(SELECT COALESCE(SUM(length(CAST(COALESCE(payload_json, '') AS BLOB))), 0) FROM canvas_projects WHERE user_id = ?) AS canvas_bytes
`
if r.Dialect() == "postgres" {
query = strings.ReplaceAll(query, "length(CAST(COALESCE(", "octet_length(COALESCE(")
query = strings.ReplaceAll(query, ", '') AS BLOB))", ", ''))")
}
err := r.db.Raw(query, userID, userID, userID, userID).Scan(&usage).Error
return usage, err
}
// Create 是低层兼容入口;业务写路径应优先使用带领域约束的显式方法。
func (r *Repository) Create(value any) error {
return r.db.Create(value).Error

View File

@@ -0,0 +1,89 @@
package repository
import (
"errors"
"path/filepath"
"testing"
"yingce/backend/internal/model"
"gorm.io/driver/sqlite"
"gorm.io/gorm"
"gorm.io/gorm/logger"
)
func TestUserStructuredStorageUsage(t *testing.T) {
db, err := gorm.Open(sqlite.Open(filepath.Join(t.TempDir(), "quota.db")), &gorm.Config{Logger: logger.Default.LogMode(logger.Silent)})
if err != nil {
t.Fatal(err)
}
sqlDB, err := db.DB()
if err != nil {
t.Fatal(err)
}
sqlDB.SetMaxOpenConns(1)
t.Cleanup(func() { _ = sqlDB.Close() })
// History tables are deliberately absent: canvas quota must not read them.
if err := db.AutoMigrate(&model.Asset{}, &model.CanvasProject{}); err != nil {
t.Fatal(err)
}
repo := New(db)
assetPayload := `{"title":"素材 🎬"}`
canvasPayload := `{"title":"画布","nodes":[]}`
assets := []model.Asset{
{ID: "asset", UserID: "owner", PayloadJSON: assetPayload},
{ID: "empty", UserID: "owner"},
{ID: "null", UserID: "owner"},
{ID: "foreign-asset", UserID: "other", PayloadJSON: assetPayload},
}
canvases := []model.CanvasProject{
{ID: "canvas", UserID: "owner", PayloadJSON: canvasPayload},
{ID: "foreign-canvas", UserID: "other", PayloadJSON: canvasPayload},
}
if err := db.Create(&assets).Error; err != nil {
t.Fatal(err)
}
if err := db.Model(&model.Asset{}).Where("id = ?", "null").UpdateColumn("payload_json", nil).Error; err != nil {
t.Fatal(err)
}
if err := db.Create(&canvases).Error; err != nil {
t.Fatal(err)
}
want := UserStorageUsage{AssetCount: 3, AssetBytes: int64(len(assetPayload)), CanvasCount: 1, CanvasBytes: int64(len(canvasPayload))}
assertUsage := func(repo *Repository, userID string, expected UserStorageUsage) {
t.Helper()
got, err := repo.UserStructuredStorageUsage(userID)
if err != nil {
t.Fatal(err)
}
if got != expected {
t.Fatalf("usage for %s = %+v, want %+v", userID, got, expected)
}
}
assertUsage(repo, "owner", want)
assertUsage(repo, "missing", UserStorageUsage{})
assertUsage(repo, "other", UserStorageUsage{AssetCount: 1, AssetBytes: int64(len(assetPayload)), CanvasCount: 1, CanvasBytes: int64(len(canvasPayload))})
rollback := errors.New("rollback quota probe")
err = repo.Transaction(func(tx *Repository) error {
project := model.CanvasProject{ID: "uncommitted", UserID: "owner", PayloadJSON: canvasPayload}
if err := tx.UpsertCanvasProject(&project); err != nil {
return err
}
inside := want
inside.CanvasCount++
inside.CanvasBytes += int64(len(canvasPayload))
assertUsage(tx, "owner", inside)
return rollback
})
if !errors.Is(err, rollback) {
t.Fatalf("transaction error = %v", err)
}
assertUsage(repo, "owner", want)
if err := db.Migrator().DropTable(&model.Asset{}); err != nil {
t.Fatal(err)
}
if _, err := repo.UserStructuredStorageUsage("owner"); err == nil {
t.Fatal("database error must not become zero usage")
}
}