feat: V2 microservices stack — backend services, gateway, JWT auth
Add full V2 architecture: identity, content, studio (.NET 10) and file, render, notification, gateway (Go) services with vendored deps, plus DB migrations, event/API contracts, and an init-db script. Wire the Next.js frontend to the gateway: server-side JWT auth routes (login/register/refresh/logout/me), gateway fetch helper, and session/ cookie/jwt helpers under src/lib. Containerize the stack via docker-compose.v2.yml and per-service Dockerfiles. Base images resolve through a Nexus mirror (Docker Hub) and MCR directly; npm/NuGet pull from Nexus groups. Self-host fonts via next/font/local to avoid Google Fonts (geo-blocked). Add CI workflow and ignore .env.v2, *.stackdump, and .NET bin/obj. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,783 @@
|
||||
package db
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/flatrender/render-svc/internal/models"
|
||||
"github.com/google/uuid"
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
)
|
||||
|
||||
type Store struct {
|
||||
pool *pgxpool.Pool
|
||||
}
|
||||
|
||||
func NewStore(pool *pgxpool.Pool) *Store {
|
||||
return &Store{pool: pool}
|
||||
}
|
||||
|
||||
// ── Nodes ────────────────────────────────────────────────────────────────────
|
||||
|
||||
func (s *Store) ListNodes(ctx context.Context, region, status string) ([]*models.RenderNode, error) {
|
||||
q := `SELECT id, name, region, node_ip::text, worker_port, public_endpoint,
|
||||
ram_gb, cpu_cores, gpu_model, storage_gb,
|
||||
current_ae_version::text, available_ae_versions, node_agent_version,
|
||||
node_kind::text, owner_user_id, owner_tenant_id,
|
||||
status::text, current_job_id, current_frame_job_id, job_started_at,
|
||||
last_heartbeat_at, last_cpu_pct, last_ram_available_mb, ae_running,
|
||||
lifetime_task_count, lifetime_crash_count, consecutive_failures,
|
||||
priority, is_active, accepts_new_jobs,
|
||||
last_maintenance_at, next_maintenance_at, maintenance_reason,
|
||||
cached_template_md5s, cache_used_gb, created_at, updated_at
|
||||
FROM render.render_nodes
|
||||
WHERE is_active = TRUE`
|
||||
args := pgx.NamedArgs{}
|
||||
if region != "" {
|
||||
q += " AND region = @region"
|
||||
args["region"] = region
|
||||
}
|
||||
if status != "" {
|
||||
q += " AND status::text = @status"
|
||||
args["status"] = status
|
||||
}
|
||||
q += " ORDER BY region, priority DESC"
|
||||
|
||||
rows, err := s.pool.Query(ctx, q, args)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
return scanNodes(rows)
|
||||
}
|
||||
|
||||
func (s *Store) GetNodeByID(ctx context.Context, id uuid.UUID) (*models.RenderNode, error) {
|
||||
rows, err := s.pool.Query(ctx, `
|
||||
SELECT id, name, region, node_ip::text, worker_port, public_endpoint,
|
||||
ram_gb, cpu_cores, gpu_model, storage_gb,
|
||||
current_ae_version::text, available_ae_versions, node_agent_version,
|
||||
node_kind::text, owner_user_id, owner_tenant_id,
|
||||
status::text, current_job_id, current_frame_job_id, job_started_at,
|
||||
last_heartbeat_at, last_cpu_pct, last_ram_available_mb, ae_running,
|
||||
lifetime_task_count, lifetime_crash_count, consecutive_failures,
|
||||
priority, is_active, accepts_new_jobs,
|
||||
last_maintenance_at, next_maintenance_at, maintenance_reason,
|
||||
cached_template_md5s, cache_used_gb, created_at, updated_at
|
||||
FROM render.render_nodes WHERE id = $1`, id)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
nodes, err := scanNodes(rows)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if len(nodes) == 0 {
|
||||
return nil, fmt.Errorf("node not found")
|
||||
}
|
||||
return nodes[0], nil
|
||||
}
|
||||
|
||||
func (s *Store) CreateNode(ctx context.Context, req *models.NodeCreateRequest) (*models.RenderNode, error) {
|
||||
kind := "Shared"
|
||||
if req.NodeKind != nil {
|
||||
kind = *req.NodeKind
|
||||
}
|
||||
priority := 100
|
||||
if req.Priority != nil {
|
||||
priority = *req.Priority
|
||||
}
|
||||
var id uuid.UUID
|
||||
err := s.pool.QueryRow(ctx, `
|
||||
INSERT INTO render.render_nodes
|
||||
(name, region, node_ip, worker_port, current_ae_version, ram_gb, cpu_cores,
|
||||
node_kind, owner_user_id, priority, status)
|
||||
VALUES ($1, $2, $3::inet, $4, $5::ae_version, $6, $7, $8::node_kind, $9, $10, 'Offline'::node_status)
|
||||
RETURNING id`,
|
||||
req.Name, req.Region, req.NodeIP, req.WorkerPort, req.CurrentAEVersion,
|
||||
req.RamGB, req.CPUCores, kind, req.OwnerUserID, priority,
|
||||
).Scan(&id)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return s.GetNodeByID(ctx, id)
|
||||
}
|
||||
|
||||
func (s *Store) PatchNode(ctx context.Context, id uuid.UUID, req *models.NodePatchRequest) (*models.RenderNode, error) {
|
||||
if req.Priority != nil {
|
||||
_, err := s.pool.Exec(ctx, `UPDATE render.render_nodes SET priority = $1, updated_at = NOW() WHERE id = $2`, *req.Priority, id)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
if req.IsActive != nil {
|
||||
_, err := s.pool.Exec(ctx, `UPDATE render.render_nodes SET is_active = $1, updated_at = NOW() WHERE id = $2`, *req.IsActive, id)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
if req.AcceptsNewJobs != nil {
|
||||
_, err := s.pool.Exec(ctx, `UPDATE render.render_nodes SET accepts_new_jobs = $1, updated_at = NOW() WHERE id = $2`, *req.AcceptsNewJobs, id)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
if req.NodeKind != nil {
|
||||
_, err := s.pool.Exec(ctx, `UPDATE render.render_nodes SET node_kind = $1::node_kind, updated_at = NOW() WHERE id = $2`, *req.NodeKind, id)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
if req.OwnerUserID != nil {
|
||||
_, err := s.pool.Exec(ctx, `UPDATE render.render_nodes SET owner_user_id = $1, updated_at = NOW() WHERE id = $2`, *req.OwnerUserID, id)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
if req.NextMaintenanceAt != nil {
|
||||
_, err := s.pool.Exec(ctx, `UPDATE render.render_nodes SET next_maintenance_at = $1, maintenance_reason = $2, updated_at = NOW() WHERE id = $3`, *req.NextMaintenanceAt, req.MaintenanceReason, id)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
return s.GetNodeByID(ctx, id)
|
||||
}
|
||||
|
||||
func (s *Store) UpdateNodeHeartbeat(ctx context.Context, nodeID uuid.UUID, req *models.NodeHeartbeatRequest) error {
|
||||
_, err := s.pool.Exec(ctx, `
|
||||
UPDATE render.render_nodes SET
|
||||
status = $1::node_status,
|
||||
last_heartbeat_at = NOW(),
|
||||
last_cpu_pct = $2,
|
||||
last_ram_available_mb = $3,
|
||||
ae_running = COALESCE($4, ae_running),
|
||||
current_job_id = $5,
|
||||
current_frame_job_id = $6,
|
||||
updated_at = NOW()
|
||||
WHERE id = $7`,
|
||||
req.Status, req.CPUPct, req.RAMAvailableMB, req.AERunning,
|
||||
req.CurrentJobID, nil, nodeID,
|
||||
)
|
||||
return err
|
||||
}
|
||||
|
||||
func (s *Store) UpdateNodeOnline(ctx context.Context, nodeID uuid.UUID, req *models.NodeOnlineRequest) error {
|
||||
_, err := s.pool.Exec(ctx, `
|
||||
UPDATE render.render_nodes SET
|
||||
status = 'Ready'::node_status,
|
||||
node_agent_version = $1,
|
||||
current_ae_version = $2::ae_version,
|
||||
available_ae_versions = $3,
|
||||
ram_gb = COALESCE($4, ram_gb),
|
||||
cpu_cores = COALESCE($5, cpu_cores),
|
||||
cache_used_gb = COALESCE($6, cache_used_gb),
|
||||
cached_template_md5s = $7,
|
||||
last_heartbeat_at = NOW(),
|
||||
updated_at = NOW()
|
||||
WHERE id = $8`,
|
||||
req.NodeAgentVersion, req.CurrentAEVersion, req.AvailableAEVersions,
|
||||
req.RamGB, req.CPUCores, req.CacheUsedGB, req.CachedTemplateMD5s, nodeID,
|
||||
)
|
||||
return err
|
||||
}
|
||||
|
||||
func (s *Store) ReleaseNode(ctx context.Context, nodeID uuid.UUID) error {
|
||||
_, err := s.pool.Exec(ctx, `
|
||||
UPDATE render.render_nodes SET
|
||||
status = 'Ready'::node_status,
|
||||
current_job_id = NULL,
|
||||
current_frame_job_id = NULL,
|
||||
job_started_at = NULL,
|
||||
updated_at = NOW()
|
||||
WHERE id = $1`, nodeID)
|
||||
return err
|
||||
}
|
||||
|
||||
func (s *Store) ListNodeHealthHistory(ctx context.Context, nodeID uuid.UUID, from, to time.Time) ([]*models.NodeHealthLog, error) {
|
||||
rows, err := s.pool.Query(ctx, `
|
||||
SELECT id, node_id, recorded_at, status::text, cpu_pct, ram_available_mb,
|
||||
ae_running, current_job_id, current_frame, cache_used_gb
|
||||
FROM render.node_health_logs
|
||||
WHERE node_id = $1 AND recorded_at BETWEEN $2 AND $3
|
||||
ORDER BY recorded_at DESC LIMIT 1000`, nodeID, from, to)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
var out []*models.NodeHealthLog
|
||||
for rows.Next() {
|
||||
h := &models.NodeHealthLog{}
|
||||
if err := rows.Scan(&h.ID, &h.NodeID, &h.RecordedAt, &h.Status,
|
||||
&h.CPUPct, &h.RAMAvailableMB, &h.AERunning, &h.CurrentJobID,
|
||||
&h.CurrentFrame, &h.CacheUsedGB); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out = append(out, h)
|
||||
}
|
||||
return out, rows.Err()
|
||||
}
|
||||
|
||||
func (s *Store) ListNodeCrashes(ctx context.Context, nodeID uuid.UUID) ([]*models.NodeCrash, error) {
|
||||
rows, err := s.pool.Query(ctx, `
|
||||
SELECT id, node_id, render_job_id, frame_job_id, crashed_at,
|
||||
last_known_frame, crash_signal, error_log, log_file_url,
|
||||
auto_recovered, recovery_action, recovered_at, created_at
|
||||
FROM render.node_crashes
|
||||
WHERE node_id = $1 ORDER BY crashed_at DESC LIMIT 100`, nodeID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
var out []*models.NodeCrash
|
||||
for rows.Next() {
|
||||
c := &models.NodeCrash{}
|
||||
if err := rows.Scan(&c.ID, &c.NodeID, &c.RenderJobID, &c.FrameJobID, &c.CrashedAt,
|
||||
&c.LastKnownFrame, &c.CrashSignal, &c.ErrorLog, &c.LogFileURL,
|
||||
&c.AutoRecovered, &c.RecoveryAction, &c.RecoveredAt, &c.CreatedAt); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out = append(out, c)
|
||||
}
|
||||
return out, rows.Err()
|
||||
}
|
||||
|
||||
func (s *Store) InsertCrash(ctx context.Context, nodeID, jobID uuid.UUID, req *models.CrashReportRequest) error {
|
||||
_, err := s.pool.Exec(ctx, `
|
||||
INSERT INTO render.node_crashes
|
||||
(node_id, render_job_id, frame_job_id, last_known_frame, crash_signal, error_log, log_file_url)
|
||||
VALUES ($1, $2, $3, $4, $5, $6, $7)`,
|
||||
nodeID, jobID, req.FrameJobID, req.LastKnownFrame, req.CrashSignal,
|
||||
req.ErrorLogTail, req.LogFileURL)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
// Increment crash counts
|
||||
_, err = s.pool.Exec(ctx, `
|
||||
UPDATE render.render_nodes SET
|
||||
lifetime_crash_count = lifetime_crash_count + 1,
|
||||
consecutive_failures = consecutive_failures + 1,
|
||||
updated_at = NOW()
|
||||
WHERE id = $1`, nodeID)
|
||||
return err
|
||||
}
|
||||
|
||||
func (s *Store) UpdateNodeCache(ctx context.Context, nodeID uuid.UUID, req *models.CacheUpdateRequest) error {
|
||||
switch req.Action {
|
||||
case "Downloaded":
|
||||
if req.ProjectID != nil && req.FileSizeBytes != nil {
|
||||
_, err := s.pool.Exec(ctx, `
|
||||
INSERT INTO render.node_template_cache (node_id, project_id, aep_file_md5, file_size_bytes, local_path)
|
||||
VALUES ($1, $2, $3, $4, '')
|
||||
ON CONFLICT (node_id, aep_file_md5) DO UPDATE SET
|
||||
last_used_at = NOW(), use_count = node_template_cache.use_count + 1`,
|
||||
nodeID, *req.ProjectID, req.AEPFileMD5, *req.FileSizeBytes)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
if req.CacheUsedGB != nil {
|
||||
_, _ = s.pool.Exec(ctx, `UPDATE render.render_nodes SET cache_used_gb = $1, updated_at = NOW() WHERE id = $2`, *req.CacheUsedGB, nodeID)
|
||||
}
|
||||
case "Evicted":
|
||||
_, err := s.pool.Exec(ctx, `DELETE FROM render.node_template_cache WHERE node_id = $1 AND aep_file_md5 = $2`, nodeID, req.AEPFileMD5)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if req.CacheUsedGB != nil {
|
||||
_, _ = s.pool.Exec(ctx, `UPDATE render.render_nodes SET cache_used_gb = $1, updated_at = NOW() WHERE id = $2`, *req.CacheUsedGB, nodeID)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// ── Render Jobs ───────────────────────────────────────────────────────────────
|
||||
|
||||
func (s *Store) ListJobs(ctx context.Context, userID uuid.UUID, status string, page, pageSize int) ([]*models.RenderJob, int64, error) {
|
||||
q := `SELECT id, tenant_id, user_id, saved_project_id, original_project_id,
|
||||
project_name, title, name, external_job_id, priority_queue::text, priority_score,
|
||||
step::text, render_progress, convert_progress, image_preview_b64,
|
||||
price_type::text, paid_price_minor, discount_code, support_flatrender,
|
||||
mode, quality::text, resolution, r_height, frame_rate, is_60_fps,
|
||||
duration_sec, export_duration_sec,
|
||||
has_music, has_sfx, has_voiceover, music_volume, sfx_volume, voiceover_volume,
|
||||
render_node_count, current_active_nodes, region, tell_me_when_done,
|
||||
retry_count, max_retries, repair_attempts, failed_message, failed_at_step::text,
|
||||
export_id, task_start_date, queued_at, started_at, completed_at, created_at, updated_at
|
||||
FROM render.render_jobs WHERE user_id = $1`
|
||||
args := []any{userID}
|
||||
argIdx := 2
|
||||
if status != "" {
|
||||
q += fmt.Sprintf(" AND step::text = $%d", argIdx)
|
||||
args = append(args, status)
|
||||
argIdx++
|
||||
}
|
||||
|
||||
var total int64
|
||||
countQ := `SELECT COUNT(*) FROM render.render_jobs WHERE user_id = $1`
|
||||
if status != "" {
|
||||
countQ += fmt.Sprintf(" AND step::text = $2")
|
||||
_ = s.pool.QueryRow(ctx, countQ, args...).Scan(&total)
|
||||
} else {
|
||||
_ = s.pool.QueryRow(ctx, countQ, userID).Scan(&total)
|
||||
}
|
||||
|
||||
q += fmt.Sprintf(" ORDER BY created_at DESC LIMIT $%d OFFSET $%d", argIdx, argIdx+1)
|
||||
args = append(args, pageSize, (page-1)*pageSize)
|
||||
|
||||
rows, err := s.pool.Query(ctx, q, args...)
|
||||
if err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
defer rows.Close()
|
||||
jobs, err := scanJobs(rows)
|
||||
return jobs, total, err
|
||||
}
|
||||
|
||||
func (s *Store) GetJobByID(ctx context.Context, id, userID uuid.UUID) (*models.RenderJob, error) {
|
||||
rows, err := s.pool.Query(ctx, `
|
||||
SELECT id, tenant_id, user_id, saved_project_id, original_project_id,
|
||||
project_name, title, name, external_job_id, priority_queue::text, priority_score,
|
||||
step::text, render_progress, convert_progress, image_preview_b64,
|
||||
price_type::text, paid_price_minor, discount_code, support_flatrender,
|
||||
mode, quality::text, resolution, r_height, frame_rate, is_60_fps,
|
||||
duration_sec, export_duration_sec,
|
||||
has_music, has_sfx, has_voiceover, music_volume, sfx_volume, voiceover_volume,
|
||||
render_node_count, current_active_nodes, region, tell_me_when_done,
|
||||
retry_count, max_retries, repair_attempts, failed_message, failed_at_step::text,
|
||||
export_id, task_start_date, queued_at, started_at, completed_at, created_at, updated_at
|
||||
FROM render.render_jobs WHERE id = $1 AND user_id = $2`, id, userID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
jobs, err := scanJobs(rows)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if len(jobs) == 0 {
|
||||
return nil, fmt.Errorf("job not found")
|
||||
}
|
||||
return jobs[0], nil
|
||||
}
|
||||
|
||||
func (s *Store) CreateJob(ctx context.Context, userID, tenantID uuid.UUID, req *models.RenderJobCreateRequest) (*models.RenderJob, error) {
|
||||
priceType := "Free"
|
||||
if req.PriceType != nil {
|
||||
priceType = *req.PriceType
|
||||
}
|
||||
frameRate := 30
|
||||
if req.FrameRate != nil {
|
||||
frameRate = *req.FrameRate
|
||||
}
|
||||
tellMe := true
|
||||
if req.TellMeWhenDone != nil {
|
||||
tellMe = *req.TellMeWhenDone
|
||||
}
|
||||
|
||||
var id uuid.UUID
|
||||
err := s.pool.QueryRow(ctx, `
|
||||
INSERT INTO render.render_jobs
|
||||
(tenant_id, user_id, saved_project_id, original_project_id,
|
||||
priority_queue, step, price_type, quality, resolution, r_height,
|
||||
frame_rate, is_60_fps, duration_sec, mode, tell_me_when_done, region)
|
||||
VALUES ($1, $2, $3, $3,
|
||||
'paid'::render_priority_queue, 'Queued'::render_step, $4::price_kind,
|
||||
$5::render_quality, $6, 1080, $7, COALESCE($8, FALSE),
|
||||
0, 'FIX', $9, $10)
|
||||
RETURNING id`,
|
||||
tenantID, userID, req.SavedProjectID, priceType,
|
||||
req.Quality, req.Resolution, frameRate, req.Is60FPS,
|
||||
tellMe, req.PreferredRegion,
|
||||
).Scan(&id)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return s.GetJobByID(ctx, id, userID)
|
||||
}
|
||||
|
||||
// CompleteJob marks a render job as Done. Returns the updated job so callers
|
||||
// can read user_id / tenant_id for downstream notifications.
|
||||
func (s *Store) CompleteJob(ctx context.Context, jobID uuid.UUID, exportID *uuid.UUID) (*models.RenderJob, error) {
|
||||
_, err := s.pool.Exec(ctx, `
|
||||
UPDATE render.render_jobs SET
|
||||
step = 'Done'::render_step,
|
||||
render_progress = 100,
|
||||
export_id = COALESCE($1, export_id),
|
||||
completed_at = NOW(),
|
||||
updated_at = NOW()
|
||||
WHERE id = $2
|
||||
AND step NOT IN ('Done'::render_step, 'Failed'::render_step, 'Cancelled'::render_step)`,
|
||||
exportID, jobID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return s.getJobByIDInternal(ctx, jobID)
|
||||
}
|
||||
|
||||
// FailJob marks a render job as Failed. Returns the updated job.
|
||||
func (s *Store) FailJob(ctx context.Context, jobID uuid.UUID, reason, atStep string) (*models.RenderJob, error) {
|
||||
_, err := s.pool.Exec(ctx, `
|
||||
UPDATE render.render_jobs SET
|
||||
step = 'Failed'::render_step,
|
||||
failed_message = $1,
|
||||
failed_at_step = $2::render_step,
|
||||
completed_at = NOW(),
|
||||
updated_at = NOW()
|
||||
WHERE id = $3
|
||||
AND step NOT IN ('Done'::render_step, 'Failed'::render_step, 'Cancelled'::render_step)`,
|
||||
reason, atStep, jobID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return s.getJobByIDInternal(ctx, jobID)
|
||||
}
|
||||
|
||||
// getJobByIDInternal retrieves a job by ID without an ownership check.
|
||||
// Used only for internal operations (node agent callbacks).
|
||||
func (s *Store) getJobByIDInternal(ctx context.Context, id uuid.UUID) (*models.RenderJob, error) {
|
||||
rows, err := s.pool.Query(ctx, `
|
||||
SELECT id, tenant_id, user_id, saved_project_id, original_project_id,
|
||||
project_name, title, name, external_job_id, priority_queue::text, priority_score,
|
||||
step::text, render_progress, convert_progress, image_preview_b64,
|
||||
price_type::text, paid_price_minor, discount_code, support_flatrender,
|
||||
mode, quality::text, resolution, r_height, frame_rate, is_60_fps,
|
||||
duration_sec, export_duration_sec,
|
||||
has_music, has_sfx, has_voiceover, music_volume, sfx_volume, voiceover_volume,
|
||||
render_node_count, current_active_nodes, region, tell_me_when_done,
|
||||
retry_count, max_retries, repair_attempts, failed_message, failed_at_step::text,
|
||||
export_id, task_start_date, queued_at, started_at, completed_at, created_at, updated_at
|
||||
FROM render.render_jobs WHERE id = $1`, id)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
jobs, err := scanJobs(rows)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if len(jobs) == 0 {
|
||||
return nil, fmt.Errorf("job %s not found", id)
|
||||
}
|
||||
return jobs[0], nil
|
||||
}
|
||||
|
||||
func (s *Store) CancelJob(ctx context.Context, id, userID uuid.UUID) (bool, error) {
|
||||
tag, err := s.pool.Exec(ctx, `
|
||||
UPDATE render.render_jobs
|
||||
SET step = 'Cancelled'::render_step, completed_at = NOW(), updated_at = NOW()
|
||||
WHERE id = $1 AND user_id = $2 AND step NOT IN ('Done','Failed','Cancelled')`,
|
||||
id, userID)
|
||||
return tag.RowsAffected() > 0, err
|
||||
}
|
||||
|
||||
func (s *Store) GetJobProgress(ctx context.Context, id, userID uuid.UUID) (*models.RenderJob, error) {
|
||||
return s.GetJobByID(ctx, id, userID)
|
||||
}
|
||||
|
||||
func (s *Store) ListFrameJobs(ctx context.Context, renderJobID uuid.UUID) ([]*models.FrameJob, error) {
|
||||
rows, err := s.pool.Query(ctx, `
|
||||
SELECT id, render_job_id, node_id, start_frame, end_frame, collect_frame_count,
|
||||
order_value, folder_name, convert_url, status::text, frames_rendered,
|
||||
frames_validated, attempt, last_error, output_mp4_url,
|
||||
assigned_at, started_at, last_progress_at, completed_at, created_at, updated_at
|
||||
FROM render.frame_jobs WHERE render_job_id = $1 ORDER BY order_value`, renderJobID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
return scanFrameJobs(rows)
|
||||
}
|
||||
|
||||
func (s *Store) UpdateFrameProgress(ctx context.Context, jobID uuid.UUID, req *models.FrameProgressRequest) error {
|
||||
_, err := s.pool.Exec(ctx, `
|
||||
UPDATE render.frame_jobs SET
|
||||
frames_rendered = frames_rendered + 1,
|
||||
last_progress_at = NOW(),
|
||||
status = CASE WHEN $1 IS NOT NULL THEN 'Validated'::frame_job_status ELSE status END,
|
||||
completed_at = $1,
|
||||
updated_at = NOW()
|
||||
WHERE id = $2`,
|
||||
req.CompletedAt, req.FrameJobID)
|
||||
return err
|
||||
}
|
||||
|
||||
// ── Snapshots ────────────────────────────────────────────────────────────────
|
||||
|
||||
func (s *Store) GetCachedSnapshot(ctx context.Context, projectID uuid.UUID, sceneKey string, frame int, hash string) (*models.Snapshot, error) {
|
||||
rows, err := s.pool.Query(ctx, `
|
||||
SELECT id, tenant_id, user_id, saved_project_id, scene_key, frame_number,
|
||||
inputs_hash, status, render_node_id, image_url, thumbnail_url,
|
||||
width, height, size_bytes, requested_at, completed_at, duration_ms,
|
||||
expires_at, error_message, created_at
|
||||
FROM render.snapshots
|
||||
WHERE saved_project_id = $1 AND scene_key = $2 AND frame_number = $3
|
||||
AND inputs_hash = $4 AND status = 'Done' AND expires_at > NOW()
|
||||
LIMIT 1`, projectID, sceneKey, frame, hash)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
snaps, err := scanSnapshots(rows)
|
||||
if err != nil || len(snaps) == 0 {
|
||||
return nil, err
|
||||
}
|
||||
return snaps[0], nil
|
||||
}
|
||||
|
||||
func (s *Store) CreateSnapshot(ctx context.Context, userID, tenantID uuid.UUID, req *models.SnapshotCreateRequest, hash string) (*models.Snapshot, error) {
|
||||
var id uuid.UUID
|
||||
err := s.pool.QueryRow(ctx, `
|
||||
INSERT INTO render.snapshots
|
||||
(tenant_id, user_id, saved_project_id, scene_key, frame_number, inputs_hash, status)
|
||||
VALUES ($1, $2, $3, $4, $5, $6, 'Pending')
|
||||
RETURNING id`,
|
||||
tenantID, userID, req.SavedProjectID, req.SceneKey, req.FrameNumber, hash,
|
||||
).Scan(&id)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return s.GetSnapshotByID(ctx, id)
|
||||
}
|
||||
|
||||
func (s *Store) GetSnapshotByID(ctx context.Context, id uuid.UUID) (*models.Snapshot, error) {
|
||||
rows, err := s.pool.Query(ctx, `
|
||||
SELECT id, tenant_id, user_id, saved_project_id, scene_key, frame_number,
|
||||
inputs_hash, status, render_node_id, image_url, thumbnail_url,
|
||||
width, height, size_bytes, requested_at, completed_at, duration_ms,
|
||||
expires_at, error_message, created_at
|
||||
FROM render.snapshots WHERE id = $1`, id)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
snaps, err := scanSnapshots(rows)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if len(snaps) == 0 {
|
||||
return nil, fmt.Errorf("snapshot not found")
|
||||
}
|
||||
return snaps[0], nil
|
||||
}
|
||||
|
||||
// ── Exports ──────────────────────────────────────────────────────────────────
|
||||
|
||||
func (s *Store) ListExports(ctx context.Context, userID uuid.UUID, page, pageSize int) ([]*models.Export, int64, error) {
|
||||
var total int64
|
||||
_ = s.pool.QueryRow(ctx,
|
||||
`SELECT COUNT(*) FROM render.exports WHERE user_id = $1 AND deleted_at IS NULL`, userID).Scan(&total)
|
||||
|
||||
rows, err := s.pool.Query(ctx, `
|
||||
SELECT id, tenant_id, user_id, saved_project_id, project_id, render_job_id,
|
||||
image, path, file_extension, file_type::text, render_quality::text,
|
||||
create_type::text, size_bytes, duration_sec, width, height,
|
||||
produce_date, auto_delete_date, delete_notified, created_at, deleted_at
|
||||
FROM render.exports WHERE user_id = $1 AND deleted_at IS NULL
|
||||
ORDER BY produce_date DESC LIMIT $2 OFFSET $3`,
|
||||
userID, pageSize, (page-1)*pageSize)
|
||||
if err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
defer rows.Close()
|
||||
exports, err := scanExports(rows)
|
||||
return exports, total, err
|
||||
}
|
||||
|
||||
func (s *Store) GetExportByID(ctx context.Context, id, userID uuid.UUID) (*models.Export, error) {
|
||||
rows, err := s.pool.Query(ctx, `
|
||||
SELECT id, tenant_id, user_id, saved_project_id, project_id, render_job_id,
|
||||
image, path, file_extension, file_type::text, render_quality::text,
|
||||
create_type::text, size_bytes, duration_sec, width, height,
|
||||
produce_date, auto_delete_date, delete_notified, created_at, deleted_at
|
||||
FROM render.exports WHERE id = $1 AND user_id = $2 AND deleted_at IS NULL`, id, userID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
exports, err := scanExports(rows)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if len(exports) == 0 {
|
||||
return nil, fmt.Errorf("export not found")
|
||||
}
|
||||
return exports[0], nil
|
||||
}
|
||||
|
||||
func (s *Store) ListExportFiles(ctx context.Context, exportID uuid.UUID) ([]*models.ExportFile, error) {
|
||||
rows, err := s.pool.Query(ctx, `
|
||||
SELECT id, export_id, user_id, name, thumbnail, path, size_bytes,
|
||||
file_type::text, width, height, sort, created_at
|
||||
FROM render.export_files WHERE export_id = $1 ORDER BY sort`, exportID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
var out []*models.ExportFile
|
||||
for rows.Next() {
|
||||
f := &models.ExportFile{}
|
||||
if err := rows.Scan(&f.ID, &f.ExportID, &f.UserID, &f.Name, &f.Thumbnail,
|
||||
&f.Path, &f.SizeBytes, &f.FileType, &f.Width, &f.Height, &f.Sort, &f.CreatedAt); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out = append(out, f)
|
||||
}
|
||||
return out, rows.Err()
|
||||
}
|
||||
|
||||
func (s *Store) SoftDeleteExport(ctx context.Context, id, userID uuid.UUID) error {
|
||||
tag, err := s.pool.Exec(ctx, `
|
||||
UPDATE render.exports SET deleted_at = NOW() WHERE id = $1 AND user_id = $2 AND deleted_at IS NULL`, id, userID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if tag.RowsAffected() == 0 {
|
||||
return fmt.Errorf("export not found")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *Store) ExtendExportDeleteDate(ctx context.Context, id, userID uuid.UUID, days int) (time.Time, error) {
|
||||
var newDate time.Time
|
||||
err := s.pool.QueryRow(ctx, `
|
||||
UPDATE render.exports SET auto_delete_date = auto_delete_date + ($1 || ' days')::interval
|
||||
WHERE id = $2 AND user_id = $3 AND deleted_at IS NULL
|
||||
RETURNING auto_delete_date`, days, id, userID).Scan(&newDate)
|
||||
return newDate, err
|
||||
}
|
||||
|
||||
// ── Node Updates ─────────────────────────────────────────────────────────────
|
||||
|
||||
func (s *Store) ListNodeUpdates(ctx context.Context) ([]*models.NodeUpdate, error) {
|
||||
rows, err := s.pool.Query(ctx, `
|
||||
SELECT id, update_file_name, update_number, description, target_ae_version::text,
|
||||
in_update_queue, rolled_out_to_node_ids, last_update_queue_date, create_date, created_at
|
||||
FROM render.node_updates ORDER BY update_number DESC`)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
var out []*models.NodeUpdate
|
||||
for rows.Next() {
|
||||
u := &models.NodeUpdate{}
|
||||
if err := rows.Scan(&u.ID, &u.UpdateFileName, &u.UpdateNumber, &u.Description,
|
||||
&u.TargetAEVersion, &u.InUpdateQueue, &u.RolledOutToNodeIDs,
|
||||
&u.LastUpdateQueueDate, &u.CreateDate, &u.CreatedAt); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out = append(out, u)
|
||||
}
|
||||
return out, rows.Err()
|
||||
}
|
||||
|
||||
func (s *Store) QueueUpdateRollout(ctx context.Context, updateID uuid.UUID, nodeIDs []uuid.UUID) error {
|
||||
_, err := s.pool.Exec(ctx, `
|
||||
UPDATE render.node_updates SET
|
||||
in_update_queue = TRUE,
|
||||
last_update_queue_date = NOW(),
|
||||
rolled_out_to_node_ids = rolled_out_to_node_ids || $1
|
||||
WHERE id = $2`, nodeIDs, updateID)
|
||||
return err
|
||||
}
|
||||
|
||||
// ── Scanners ─────────────────────────────────────────────────────────────────
|
||||
|
||||
func scanNodes(rows pgx.Rows) ([]*models.RenderNode, error) {
|
||||
var out []*models.RenderNode
|
||||
for rows.Next() {
|
||||
n := &models.RenderNode{}
|
||||
if err := rows.Scan(
|
||||
&n.ID, &n.Name, &n.Region, &n.NodeIP, &n.WorkerPort, &n.PublicEndpoint,
|
||||
&n.RamGB, &n.CPUCores, &n.GPUModel, &n.StorageGB,
|
||||
&n.CurrentAEVersion, &n.AvailableAEVersions, &n.NodeAgentVersion,
|
||||
&n.NodeKind, &n.OwnerUserID, &n.OwnerTenantID,
|
||||
&n.Status, &n.CurrentJobID, &n.CurrentFrameJobID, &n.JobStartedAt,
|
||||
&n.LastHeartbeatAt, &n.LastCPUPct, &n.LastRAMAvailableMB, &n.AERunning,
|
||||
&n.LifetimeTaskCount, &n.LifetimeCrashCount, &n.ConsecutiveFailures,
|
||||
&n.Priority, &n.IsActive, &n.AcceptsNewJobs,
|
||||
&n.LastMaintenanceAt, &n.NextMaintenanceAt, &n.MaintenanceReason,
|
||||
&n.CachedTemplateMD5s, &n.CacheUsedGB, &n.CreatedAt, &n.UpdatedAt,
|
||||
); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out = append(out, n)
|
||||
}
|
||||
return out, rows.Err()
|
||||
}
|
||||
|
||||
func scanJobs(rows pgx.Rows) ([]*models.RenderJob, error) {
|
||||
var out []*models.RenderJob
|
||||
for rows.Next() {
|
||||
j := &models.RenderJob{}
|
||||
if err := rows.Scan(
|
||||
&j.ID, &j.TenantID, &j.UserID, &j.SavedProjectID, &j.OriginalProjectID,
|
||||
&j.ProjectName, &j.Title, &j.Name, &j.ExternalJobID, &j.PriorityQueue, &j.PriorityScore,
|
||||
&j.Step, &j.RenderProgress, &j.ConvertProgress, &j.ImagePreviewB64,
|
||||
&j.PriceType, &j.PaidPriceMinor, &j.DiscountCode, &j.SupportFlatrender,
|
||||
&j.Mode, &j.Quality, &j.Resolution, &j.RHeight, &j.FrameRate, &j.Is60FPS,
|
||||
&j.DurationSec, &j.ExportDurationSec,
|
||||
&j.HasMusic, &j.HasSFX, &j.HasVoiceover, &j.MusicVolume, &j.SFXVolume, &j.VoiceoverVolume,
|
||||
&j.RenderNodeCount, &j.CurrentActiveNodes, &j.Region, &j.TellMeWhenDone,
|
||||
&j.RetryCount, &j.MaxRetries, &j.RepairAttempts, &j.FailedMessage, &j.FailedAtStep,
|
||||
&j.ExportID, &j.TaskStartDate, &j.QueuedAt, &j.StartedAt, &j.CompletedAt,
|
||||
&j.CreatedAt, &j.UpdatedAt,
|
||||
); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out = append(out, j)
|
||||
}
|
||||
return out, rows.Err()
|
||||
}
|
||||
|
||||
func scanFrameJobs(rows pgx.Rows) ([]*models.FrameJob, error) {
|
||||
var out []*models.FrameJob
|
||||
for rows.Next() {
|
||||
f := &models.FrameJob{}
|
||||
if err := rows.Scan(
|
||||
&f.ID, &f.RenderJobID, &f.NodeID, &f.StartFrame, &f.EndFrame, &f.CollectFrameCount,
|
||||
&f.OrderValue, &f.FolderName, &f.ConvertURL, &f.Status, &f.FramesRendered,
|
||||
&f.FramesValidated, &f.Attempt, &f.LastError, &f.OutputMP4URL,
|
||||
&f.AssignedAt, &f.StartedAt, &f.LastProgressAt, &f.CompletedAt, &f.CreatedAt, &f.UpdatedAt,
|
||||
); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out = append(out, f)
|
||||
}
|
||||
return out, rows.Err()
|
||||
}
|
||||
|
||||
func scanSnapshots(rows pgx.Rows) ([]*models.Snapshot, error) {
|
||||
var out []*models.Snapshot
|
||||
for rows.Next() {
|
||||
s := &models.Snapshot{}
|
||||
if err := rows.Scan(
|
||||
&s.ID, &s.TenantID, &s.UserID, &s.SavedProjectID, &s.SceneKey, &s.FrameNumber,
|
||||
&s.InputsHash, &s.Status, &s.RenderNodeID, &s.ImageURL, &s.ThumbnailURL,
|
||||
&s.Width, &s.Height, &s.SizeBytes, &s.RequestedAt, &s.CompletedAt,
|
||||
&s.DurationMS, &s.ExpiresAt, &s.ErrorMessage, &s.CreatedAt,
|
||||
); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out = append(out, s)
|
||||
}
|
||||
return out, rows.Err()
|
||||
}
|
||||
|
||||
func scanExports(rows pgx.Rows) ([]*models.Export, error) {
|
||||
var out []*models.Export
|
||||
for rows.Next() {
|
||||
e := &models.Export{}
|
||||
if err := rows.Scan(
|
||||
&e.ID, &e.TenantID, &e.UserID, &e.SavedProjectID, &e.ProjectID, &e.RenderJobID,
|
||||
&e.Image, &e.Path, &e.FileExtension, &e.FileType, &e.RenderQuality,
|
||||
&e.CreateType, &e.SizeBytes, &e.DurationSec, &e.Width, &e.Height,
|
||||
&e.ProduceDate, &e.AutoDeleteDate, &e.DeleteNotified, &e.CreatedAt, &e.DeletedAt,
|
||||
); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out = append(out, e)
|
||||
}
|
||||
return out, rows.Err()
|
||||
}
|
||||
@@ -0,0 +1,151 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"time"
|
||||
|
||||
"github.com/flatrender/render-svc/internal/db"
|
||||
"github.com/flatrender/render-svc/internal/middleware"
|
||||
"github.com/flatrender/render-svc/internal/models"
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/google/uuid"
|
||||
"github.com/minio/minio-go/v7"
|
||||
)
|
||||
|
||||
type ExportHandler struct {
|
||||
store *db.Store
|
||||
minio *minio.Client
|
||||
bucket string
|
||||
}
|
||||
|
||||
func NewExportHandler(store *db.Store, mc *minio.Client, bucket string) *ExportHandler {
|
||||
return &ExportHandler{store: store, minio: mc, bucket: bucket}
|
||||
}
|
||||
|
||||
// GET /v1/exports
|
||||
func (h *ExportHandler) List(c *gin.Context) {
|
||||
userID := middleware.GetUserID(c)
|
||||
page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
|
||||
if page < 1 {
|
||||
page = 1
|
||||
}
|
||||
exports, total, err := h.store.ListExports(c.Request.Context(), userID, page, 20)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, models.APIError{Code: "internal_error", Message: err.Error()})
|
||||
return
|
||||
}
|
||||
if exports == nil {
|
||||
exports = []*models.Export{}
|
||||
}
|
||||
c.JSON(http.StatusOK, models.PagedResponse[*models.Export]{
|
||||
Data: exports,
|
||||
Meta: models.PaginationMeta{
|
||||
Page: page,
|
||||
PageSize: 20,
|
||||
Total: total,
|
||||
HasMore: int64(page*20) < total,
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
// GET /v1/exports/:export_id
|
||||
func (h *ExportHandler) Get(c *gin.Context) {
|
||||
userID := middleware.GetUserID(c)
|
||||
exportID, err := uuid.Parse(c.Param("export_id"))
|
||||
if err != nil {
|
||||
c.JSON(http.StatusBadRequest, models.APIError{Code: "bad_request", Message: "invalid export_id"})
|
||||
return
|
||||
}
|
||||
exp, err := h.store.GetExportByID(c.Request.Context(), exportID, userID)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusNotFound, models.APIError{Code: "not_found", Message: err.Error()})
|
||||
return
|
||||
}
|
||||
files, _ := h.store.ListExportFiles(c.Request.Context(), exportID)
|
||||
if files == nil {
|
||||
files = []*models.ExportFile{}
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"id": exp.ID,
|
||||
"saved_project_id": exp.SavedProjectID,
|
||||
"path": exp.Path,
|
||||
"image": exp.Image,
|
||||
"size_bytes": exp.SizeBytes,
|
||||
"duration_sec": exp.DurationSec,
|
||||
"width": exp.Width,
|
||||
"height": exp.Height,
|
||||
"file_extension": exp.FileExtension,
|
||||
"file_type": exp.FileType,
|
||||
"render_quality": exp.RenderQuality,
|
||||
"create_type": exp.CreateType,
|
||||
"produce_date": exp.ProduceDate,
|
||||
"auto_delete_date": exp.AutoDeleteDate,
|
||||
"files": files,
|
||||
})
|
||||
}
|
||||
|
||||
// DELETE /v1/exports/:export_id
|
||||
func (h *ExportHandler) Delete(c *gin.Context) {
|
||||
userID := middleware.GetUserID(c)
|
||||
exportID, err := uuid.Parse(c.Param("export_id"))
|
||||
if err != nil {
|
||||
c.JSON(http.StatusBadRequest, models.APIError{Code: "bad_request", Message: "invalid export_id"})
|
||||
return
|
||||
}
|
||||
if err := h.store.SoftDeleteExport(c.Request.Context(), exportID, userID); err != nil {
|
||||
c.JSON(http.StatusNotFound, models.APIError{Code: "not_found", Message: err.Error()})
|
||||
return
|
||||
}
|
||||
c.Status(http.StatusNoContent)
|
||||
}
|
||||
|
||||
// POST /v1/exports/:export_id/extend
|
||||
func (h *ExportHandler) Extend(c *gin.Context) {
|
||||
userID := middleware.GetUserID(c)
|
||||
exportID, err := uuid.Parse(c.Param("export_id"))
|
||||
if err != nil {
|
||||
c.JSON(http.StatusBadRequest, models.APIError{Code: "bad_request", Message: "invalid export_id"})
|
||||
return
|
||||
}
|
||||
var body struct {
|
||||
Days int `json:"days" binding:"required,min=1,max=365"`
|
||||
}
|
||||
if err := c.ShouldBindJSON(&body); err != nil {
|
||||
c.JSON(http.StatusBadRequest, models.APIError{Code: "bad_request", Message: err.Error()})
|
||||
return
|
||||
}
|
||||
newDate, err := h.store.ExtendExportDeleteDate(c.Request.Context(), exportID, userID, body.Days)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusNotFound, models.APIError{Code: "not_found", Message: err.Error()})
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{"new_auto_delete_date": newDate})
|
||||
}
|
||||
|
||||
// GET /v1/exports/:export_id/download-url
|
||||
func (h *ExportHandler) DownloadURL(c *gin.Context) {
|
||||
userID := middleware.GetUserID(c)
|
||||
exportID, err := uuid.Parse(c.Param("export_id"))
|
||||
if err != nil {
|
||||
c.JSON(http.StatusBadRequest, models.APIError{Code: "bad_request", Message: "invalid export_id"})
|
||||
return
|
||||
}
|
||||
exp, err := h.store.GetExportByID(c.Request.Context(), exportID, userID)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusNotFound, models.APIError{Code: "not_found", Message: err.Error()})
|
||||
return
|
||||
}
|
||||
// Generate presigned URL (15 min TTL)
|
||||
expiry := 15 * time.Minute
|
||||
url, err := h.minio.PresignedGetObject(context.Background(), h.bucket, exp.Path, expiry, nil)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, models.APIError{Code: "internal_error", Message: "could not generate download URL"})
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"url": url.String(),
|
||||
"expires_at": time.Now().Add(expiry),
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,218 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"github.com/flatrender/render-svc/internal/db"
|
||||
"github.com/flatrender/render-svc/internal/models"
|
||||
"github.com/flatrender/render-svc/internal/notifier"
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
type InternalHandler struct {
|
||||
store *db.Store
|
||||
notifier *notifier.Client // may be nil — notifications are best-effort
|
||||
}
|
||||
|
||||
func NewInternalHandler(store *db.Store, n *notifier.Client) *InternalHandler {
|
||||
return &InternalHandler{store: store, notifier: n}
|
||||
}
|
||||
|
||||
// completeRequest is the body for POST .../complete
|
||||
type completeRequest struct {
|
||||
ExportID *uuid.UUID `json:"export_id"`
|
||||
}
|
||||
|
||||
// failRequest is the body for POST .../fail
|
||||
type failRequest struct {
|
||||
Reason string `json:"reason" binding:"required"`
|
||||
AtStep string `json:"at_step"` // optional: which render step failed
|
||||
}
|
||||
|
||||
// POST /v1/internal/render/jobs/:job_id/complete
|
||||
func (h *InternalHandler) Complete(c *gin.Context) {
|
||||
jobID, err := uuid.Parse(c.Param("job_id"))
|
||||
if err != nil {
|
||||
c.JSON(http.StatusBadRequest, models.APIError{Code: "bad_request", Message: "invalid job_id"})
|
||||
return
|
||||
}
|
||||
var req completeRequest
|
||||
_ = c.ShouldBindJSON(&req) // export_id is optional
|
||||
|
||||
job, err := h.store.CompleteJob(c.Request.Context(), jobID, req.ExportID)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, models.APIError{Code: "internal_error", Message: err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
// Fire notification if the user requested it (tell_me_when_done)
|
||||
if h.notifier != nil && job.TellMeWhenDone {
|
||||
jobName := ""
|
||||
if job.Name != nil {
|
||||
jobName = *job.Name
|
||||
} else if job.Title != nil {
|
||||
jobName = *job.Title
|
||||
}
|
||||
h.notifier.NotifyRenderDone(c.Request.Context(),
|
||||
job.UserID, job.TenantID, job.ID, job.ExportID, jobName)
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, gin.H{"status": "done", "job_id": job.ID})
|
||||
}
|
||||
|
||||
// POST /v1/internal/render/jobs/:job_id/fail
|
||||
func (h *InternalHandler) Fail(c *gin.Context) {
|
||||
jobID, err := uuid.Parse(c.Param("job_id"))
|
||||
if err != nil {
|
||||
c.JSON(http.StatusBadRequest, models.APIError{Code: "bad_request", Message: "invalid job_id"})
|
||||
return
|
||||
}
|
||||
var req failRequest
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
c.JSON(http.StatusBadRequest, models.APIError{Code: "bad_request", Message: err.Error()})
|
||||
return
|
||||
}
|
||||
atStep := req.AtStep
|
||||
if atStep == "" {
|
||||
atStep = "Rendering"
|
||||
}
|
||||
|
||||
job, err := h.store.FailJob(c.Request.Context(), jobID, req.Reason, atStep)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, models.APIError{Code: "internal_error", Message: err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
// Notify user of failure
|
||||
if h.notifier != nil {
|
||||
jobName := ""
|
||||
if job.Name != nil {
|
||||
jobName = *job.Name
|
||||
} else if job.Title != nil {
|
||||
jobName = *job.Title
|
||||
}
|
||||
h.notifier.NotifyRenderFailed(c.Request.Context(),
|
||||
job.UserID, job.TenantID, job.ID, jobName, req.Reason)
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, gin.H{"status": "failed", "job_id": job.ID})
|
||||
}
|
||||
|
||||
// POST /v1/internal/nodes/:node_id/heartbeat
|
||||
func (h *InternalHandler) Heartbeat(c *gin.Context) {
|
||||
nodeID, err := uuid.Parse(c.Param("node_id"))
|
||||
if err != nil {
|
||||
c.JSON(http.StatusBadRequest, models.APIError{Code: "bad_request", Message: "invalid node_id"})
|
||||
return
|
||||
}
|
||||
var req models.NodeHeartbeatRequest
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
c.JSON(http.StatusBadRequest, models.APIError{Code: "bad_request", Message: err.Error()})
|
||||
return
|
||||
}
|
||||
req.NodeID = nodeID
|
||||
if err := h.store.UpdateNodeHeartbeat(c.Request.Context(), nodeID, &req); err != nil {
|
||||
c.JSON(http.StatusInternalServerError, models.APIError{Code: "internal_error", Message: err.Error()})
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"next_heartbeat_in_sec": 5,
|
||||
"pending_commands": []any{},
|
||||
})
|
||||
}
|
||||
|
||||
// POST /v1/internal/nodes/:node_id/online
|
||||
func (h *InternalHandler) Online(c *gin.Context) {
|
||||
nodeID, err := uuid.Parse(c.Param("node_id"))
|
||||
if err != nil {
|
||||
c.JSON(http.StatusBadRequest, models.APIError{Code: "bad_request", Message: "invalid node_id"})
|
||||
return
|
||||
}
|
||||
var req models.NodeOnlineRequest
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
c.JSON(http.StatusBadRequest, models.APIError{Code: "bad_request", Message: err.Error()})
|
||||
return
|
||||
}
|
||||
if err := h.store.UpdateNodeOnline(c.Request.Context(), nodeID, &req); err != nil {
|
||||
c.JSON(http.StatusInternalServerError, models.APIError{Code: "internal_error", Message: err.Error()})
|
||||
return
|
||||
}
|
||||
c.Status(http.StatusOK)
|
||||
}
|
||||
|
||||
// POST /v1/internal/render/jobs/:job_id/frames
|
||||
func (h *InternalHandler) FrameProgress(c *gin.Context) {
|
||||
jobID, err := uuid.Parse(c.Param("job_id"))
|
||||
if err != nil {
|
||||
c.JSON(http.StatusBadRequest, models.APIError{Code: "bad_request", Message: "invalid job_id"})
|
||||
return
|
||||
}
|
||||
var req models.FrameProgressRequest
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
c.JSON(http.StatusBadRequest, models.APIError{Code: "bad_request", Message: err.Error()})
|
||||
return
|
||||
}
|
||||
if err := h.store.UpdateFrameProgress(c.Request.Context(), jobID, &req); err != nil {
|
||||
c.JSON(http.StatusInternalServerError, models.APIError{Code: "internal_error", Message: err.Error()})
|
||||
return
|
||||
}
|
||||
c.Status(http.StatusNoContent)
|
||||
}
|
||||
|
||||
// POST /v1/internal/render/jobs/:job_id/crash
|
||||
func (h *InternalHandler) Crash(c *gin.Context) {
|
||||
jobID, err := uuid.Parse(c.Param("job_id"))
|
||||
if err != nil {
|
||||
c.JSON(http.StatusBadRequest, models.APIError{Code: "bad_request", Message: "invalid job_id"})
|
||||
return
|
||||
}
|
||||
var req models.CrashReportRequest
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
c.JSON(http.StatusBadRequest, models.APIError{Code: "bad_request", Message: err.Error()})
|
||||
return
|
||||
}
|
||||
if err := h.store.InsertCrash(c.Request.Context(), req.NodeID, jobID, &req); err != nil {
|
||||
c.JSON(http.StatusInternalServerError, models.APIError{Code: "internal_error", Message: err.Error()})
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"action_recommended": "ResetAndRestart",
|
||||
"reassigned_to_node_id": nil,
|
||||
})
|
||||
}
|
||||
|
||||
// POST /v1/internal/render/jobs/:job_id/replica-ready
|
||||
func (h *InternalHandler) ReplicaReady(c *gin.Context) {
|
||||
_, err := uuid.Parse(c.Param("job_id"))
|
||||
if err != nil {
|
||||
c.JSON(http.StatusBadRequest, models.APIError{Code: "bad_request", Message: "invalid job_id"})
|
||||
return
|
||||
}
|
||||
var req models.ReplicaReadyRequest
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
c.JSON(http.StatusBadRequest, models.APIError{Code: "bad_request", Message: err.Error()})
|
||||
return
|
||||
}
|
||||
// In production: update job step to TemplateCache → JsxGen, signal next pipeline phase
|
||||
c.Status(http.StatusNoContent)
|
||||
}
|
||||
|
||||
// POST /v1/internal/nodes/:node_id/cache-update
|
||||
func (h *InternalHandler) CacheUpdate(c *gin.Context) {
|
||||
nodeID, err := uuid.Parse(c.Param("node_id"))
|
||||
if err != nil {
|
||||
c.JSON(http.StatusBadRequest, models.APIError{Code: "bad_request", Message: "invalid node_id"})
|
||||
return
|
||||
}
|
||||
var req models.CacheUpdateRequest
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
c.JSON(http.StatusBadRequest, models.APIError{Code: "bad_request", Message: err.Error()})
|
||||
return
|
||||
}
|
||||
if err := h.store.UpdateNodeCache(c.Request.Context(), nodeID, &req); err != nil {
|
||||
c.JSON(http.StatusInternalServerError, models.APIError{Code: "internal_error", Message: err.Error()})
|
||||
return
|
||||
}
|
||||
c.Status(http.StatusNoContent)
|
||||
}
|
||||
@@ -0,0 +1,226 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
"github.com/flatrender/render-svc/internal/db"
|
||||
"github.com/flatrender/render-svc/internal/models"
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
type NodeHandler struct {
|
||||
store *db.Store
|
||||
}
|
||||
|
||||
func NewNodeHandler(store *db.Store) *NodeHandler {
|
||||
return &NodeHandler{store: store}
|
||||
}
|
||||
|
||||
// GET /v1/nodes
|
||||
func (h *NodeHandler) List(c *gin.Context) {
|
||||
region := c.Query("region")
|
||||
status := c.Query("status")
|
||||
nodes, err := h.store.ListNodes(c.Request.Context(), region, status)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, models.APIError{Code: "internal_error", Message: err.Error()})
|
||||
return
|
||||
}
|
||||
if nodes == nil {
|
||||
nodes = []*models.RenderNode{}
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{"data": nodes})
|
||||
}
|
||||
|
||||
// POST /v1/nodes
|
||||
func (h *NodeHandler) Create(c *gin.Context) {
|
||||
var req models.NodeCreateRequest
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
c.JSON(http.StatusBadRequest, models.APIError{Code: "bad_request", Message: err.Error()})
|
||||
return
|
||||
}
|
||||
node, err := h.store.CreateNode(c.Request.Context(), &req)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, models.APIError{Code: "internal_error", Message: err.Error()})
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusCreated, node)
|
||||
}
|
||||
|
||||
// GET /v1/nodes/:node_id
|
||||
func (h *NodeHandler) Get(c *gin.Context) {
|
||||
nodeID, err := uuid.Parse(c.Param("node_id"))
|
||||
if err != nil {
|
||||
c.JSON(http.StatusBadRequest, models.APIError{Code: "bad_request", Message: "invalid node_id"})
|
||||
return
|
||||
}
|
||||
node, err := h.store.GetNodeByID(c.Request.Context(), nodeID)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusNotFound, models.APIError{Code: "not_found", Message: err.Error()})
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, node)
|
||||
}
|
||||
|
||||
// PATCH /v1/nodes/:node_id
|
||||
func (h *NodeHandler) Patch(c *gin.Context) {
|
||||
nodeID, err := uuid.Parse(c.Param("node_id"))
|
||||
if err != nil {
|
||||
c.JSON(http.StatusBadRequest, models.APIError{Code: "bad_request", Message: "invalid node_id"})
|
||||
return
|
||||
}
|
||||
var req models.NodePatchRequest
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
c.JSON(http.StatusBadRequest, models.APIError{Code: "bad_request", Message: err.Error()})
|
||||
return
|
||||
}
|
||||
node, err := h.store.PatchNode(c.Request.Context(), nodeID, &req)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, models.APIError{Code: "internal_error", Message: err.Error()})
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, node)
|
||||
}
|
||||
|
||||
// POST /v1/nodes/:node_id/restart — Stub: in production this calls the node agent
|
||||
func (h *NodeHandler) Restart(c *gin.Context) {
|
||||
_, err := uuid.Parse(c.Param("node_id"))
|
||||
if err != nil {
|
||||
c.JSON(http.StatusBadRequest, models.APIError{Code: "bad_request", Message: "invalid node_id"})
|
||||
return
|
||||
}
|
||||
c.Status(http.StatusAccepted)
|
||||
}
|
||||
|
||||
// POST /v1/nodes/:node_id/release
|
||||
func (h *NodeHandler) Release(c *gin.Context) {
|
||||
nodeID, err := uuid.Parse(c.Param("node_id"))
|
||||
if err != nil {
|
||||
c.JSON(http.StatusBadRequest, models.APIError{Code: "bad_request", Message: "invalid node_id"})
|
||||
return
|
||||
}
|
||||
if err := h.store.ReleaseNode(c.Request.Context(), nodeID); err != nil {
|
||||
c.JSON(http.StatusInternalServerError, models.APIError{Code: "internal_error", Message: err.Error()})
|
||||
return
|
||||
}
|
||||
c.Status(http.StatusNoContent)
|
||||
}
|
||||
|
||||
// POST /v1/nodes/:node_id/close-ae — Stub: signals the node agent to kill AE process
|
||||
func (h *NodeHandler) CloseAE(c *gin.Context) {
|
||||
_, err := uuid.Parse(c.Param("node_id"))
|
||||
if err != nil {
|
||||
c.JSON(http.StatusBadRequest, models.APIError{Code: "bad_request", Message: "invalid node_id"})
|
||||
return
|
||||
}
|
||||
c.Status(http.StatusNoContent)
|
||||
}
|
||||
|
||||
// GET /v1/nodes/:node_id/health
|
||||
func (h *NodeHandler) Health(c *gin.Context) {
|
||||
nodeID, err := uuid.Parse(c.Param("node_id"))
|
||||
if err != nil {
|
||||
c.JSON(http.StatusBadRequest, models.APIError{Code: "bad_request", Message: "invalid node_id"})
|
||||
return
|
||||
}
|
||||
node, err := h.store.GetNodeByID(c.Request.Context(), nodeID)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusNotFound, models.APIError{Code: "not_found", Message: err.Error()})
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"node_id": node.ID,
|
||||
"recorded_at": node.LastHeartbeatAt,
|
||||
"status": node.Status,
|
||||
"cpu_pct": node.LastCPUPct,
|
||||
"ram_available_mb": node.LastRAMAvailableMB,
|
||||
"ae_running": node.AERunning,
|
||||
"current_job_id": node.CurrentJobID,
|
||||
"cache_used_gb": node.CacheUsedGB,
|
||||
})
|
||||
}
|
||||
|
||||
// GET /v1/nodes/:node_id/health/history
|
||||
func (h *NodeHandler) HealthHistory(c *gin.Context) {
|
||||
nodeID, err := uuid.Parse(c.Param("node_id"))
|
||||
if err != nil {
|
||||
c.JSON(http.StatusBadRequest, models.APIError{Code: "bad_request", Message: "invalid node_id"})
|
||||
return
|
||||
}
|
||||
fromStr := c.Query("from")
|
||||
toStr := c.Query("to")
|
||||
from := time.Now().Add(-24 * time.Hour)
|
||||
to := time.Now()
|
||||
if fromStr != "" {
|
||||
if t, err := time.Parse(time.RFC3339, fromStr); err == nil {
|
||||
from = t
|
||||
}
|
||||
}
|
||||
if toStr != "" {
|
||||
if t, err := time.Parse(time.RFC3339, toStr); err == nil {
|
||||
to = t
|
||||
}
|
||||
}
|
||||
logs, err := h.store.ListNodeHealthHistory(c.Request.Context(), nodeID, from, to)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, models.APIError{Code: "internal_error", Message: err.Error()})
|
||||
return
|
||||
}
|
||||
if logs == nil {
|
||||
logs = []*models.NodeHealthLog{}
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{"data": logs})
|
||||
}
|
||||
|
||||
// GET /v1/nodes/:node_id/crashes
|
||||
func (h *NodeHandler) Crashes(c *gin.Context) {
|
||||
nodeID, err := uuid.Parse(c.Param("node_id"))
|
||||
if err != nil {
|
||||
c.JSON(http.StatusBadRequest, models.APIError{Code: "bad_request", Message: "invalid node_id"})
|
||||
return
|
||||
}
|
||||
crashes, err := h.store.ListNodeCrashes(c.Request.Context(), nodeID)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, models.APIError{Code: "internal_error", Message: err.Error()})
|
||||
return
|
||||
}
|
||||
if crashes == nil {
|
||||
crashes = []*models.NodeCrash{}
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{"data": crashes})
|
||||
}
|
||||
|
||||
// GET /v1/node-updates
|
||||
func (h *NodeHandler) ListUpdates(c *gin.Context) {
|
||||
updates, err := h.store.ListNodeUpdates(c.Request.Context())
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, models.APIError{Code: "internal_error", Message: err.Error()})
|
||||
return
|
||||
}
|
||||
if updates == nil {
|
||||
updates = []*models.NodeUpdate{}
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{"data": updates})
|
||||
}
|
||||
|
||||
// POST /v1/node-updates/:update_id/rollout
|
||||
func (h *NodeHandler) Rollout(c *gin.Context) {
|
||||
updateID, err := uuid.Parse(c.Param("update_id"))
|
||||
if err != nil {
|
||||
c.JSON(http.StatusBadRequest, models.APIError{Code: "bad_request", Message: "invalid update_id"})
|
||||
return
|
||||
}
|
||||
var body struct {
|
||||
NodeIDs []uuid.UUID `json:"node_ids"`
|
||||
}
|
||||
if err := c.ShouldBindJSON(&body); err != nil {
|
||||
c.JSON(http.StatusBadRequest, models.APIError{Code: "bad_request", Message: err.Error()})
|
||||
return
|
||||
}
|
||||
if err := h.store.QueueUpdateRollout(c.Request.Context(), updateID, body.NodeIDs); err != nil {
|
||||
c.JSON(http.StatusInternalServerError, models.APIError{Code: "internal_error", Message: err.Error()})
|
||||
return
|
||||
}
|
||||
c.Status(http.StatusAccepted)
|
||||
}
|
||||
@@ -0,0 +1,193 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"strconv"
|
||||
|
||||
"github.com/flatrender/render-svc/internal/db"
|
||||
"github.com/flatrender/render-svc/internal/middleware"
|
||||
"github.com/flatrender/render-svc/internal/models"
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
type RenderHandler struct {
|
||||
store *db.Store
|
||||
}
|
||||
|
||||
func NewRenderHandler(store *db.Store) *RenderHandler {
|
||||
return &RenderHandler{store: store}
|
||||
}
|
||||
|
||||
// GET /v1/renders
|
||||
func (h *RenderHandler) List(c *gin.Context) {
|
||||
userID := middleware.GetUserID(c)
|
||||
status := c.Query("status")
|
||||
page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
|
||||
pageSize, _ := strconv.Atoi(c.DefaultQuery("page_size", "20"))
|
||||
if page < 1 {
|
||||
page = 1
|
||||
}
|
||||
if pageSize < 1 || pageSize > 100 {
|
||||
pageSize = 20
|
||||
}
|
||||
|
||||
jobs, total, err := h.store.ListJobs(c.Request.Context(), userID, status, page, pageSize)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, models.APIError{Code: "internal_error", Message: err.Error()})
|
||||
return
|
||||
}
|
||||
if jobs == nil {
|
||||
jobs = []*models.RenderJob{}
|
||||
}
|
||||
c.JSON(http.StatusOK, models.PagedResponse[*models.RenderJob]{
|
||||
Data: jobs,
|
||||
Meta: models.PaginationMeta{
|
||||
Page: page,
|
||||
PageSize: pageSize,
|
||||
Total: total,
|
||||
HasMore: int64(page*pageSize) < total,
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
// POST /v1/renders
|
||||
func (h *RenderHandler) Create(c *gin.Context) {
|
||||
userID := middleware.GetUserID(c)
|
||||
tenantID := middleware.GetTenantID(c)
|
||||
|
||||
var req models.RenderJobCreateRequest
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
c.JSON(http.StatusBadRequest, models.APIError{Code: "bad_request", Message: err.Error()})
|
||||
return
|
||||
}
|
||||
job, err := h.store.CreateJob(c.Request.Context(), userID, tenantID, &req)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, models.APIError{Code: "internal_error", Message: err.Error()})
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusCreated, job)
|
||||
}
|
||||
|
||||
// GET /v1/renders/:job_id
|
||||
func (h *RenderHandler) Get(c *gin.Context) {
|
||||
userID := middleware.GetUserID(c)
|
||||
jobID, err := uuid.Parse(c.Param("job_id"))
|
||||
if err != nil {
|
||||
c.JSON(http.StatusBadRequest, models.APIError{Code: "bad_request", Message: "invalid job_id"})
|
||||
return
|
||||
}
|
||||
job, err := h.store.GetJobByID(c.Request.Context(), jobID, userID)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusNotFound, models.APIError{Code: "not_found", Message: err.Error()})
|
||||
return
|
||||
}
|
||||
frames, _ := h.store.ListFrameJobs(c.Request.Context(), jobID)
|
||||
if frames == nil {
|
||||
frames = []*models.FrameJob{}
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"id": job.ID,
|
||||
"saved_project_id": job.SavedProjectID,
|
||||
"name": job.Name,
|
||||
"step": job.Step,
|
||||
"render_progress": job.RenderProgress,
|
||||
"priority_queue": job.PriorityQueue,
|
||||
"price_type": job.PriceType,
|
||||
"paid_price_minor": job.PaidPriceMinor,
|
||||
"quality": job.Quality,
|
||||
"resolution": job.Resolution,
|
||||
"frame_rate": job.FrameRate,
|
||||
"duration_sec": job.DurationSec,
|
||||
"has_voiceover": job.HasVoiceover,
|
||||
"image_preview_b64": job.ImagePreviewB64,
|
||||
"failed_message": job.FailedMessage,
|
||||
"export_id": job.ExportID,
|
||||
"queued_at": job.QueuedAt,
|
||||
"started_at": job.StartedAt,
|
||||
"completed_at": job.CompletedAt,
|
||||
"retry_count": job.RetryCount,
|
||||
"repair_attempts": job.RepairAttempts,
|
||||
"frame_jobs": frames,
|
||||
})
|
||||
}
|
||||
|
||||
// POST /v1/renders/:job_id/cancel
|
||||
func (h *RenderHandler) Cancel(c *gin.Context) {
|
||||
userID := middleware.GetUserID(c)
|
||||
jobID, err := uuid.Parse(c.Param("job_id"))
|
||||
if err != nil {
|
||||
c.JSON(http.StatusBadRequest, models.APIError{Code: "bad_request", Message: "invalid job_id"})
|
||||
return
|
||||
}
|
||||
cancelled, err := h.store.CancelJob(c.Request.Context(), jobID, userID)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, models.APIError{Code: "internal_error", Message: err.Error()})
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"cancelled": cancelled,
|
||||
"refund_amount_minor": 0,
|
||||
})
|
||||
}
|
||||
|
||||
// POST /v1/renders/:job_id/retry
|
||||
func (h *RenderHandler) Retry(c *gin.Context) {
|
||||
userID := middleware.GetUserID(c)
|
||||
tenantID := middleware.GetTenantID(c)
|
||||
jobID, err := uuid.Parse(c.Param("job_id"))
|
||||
if err != nil {
|
||||
c.JSON(http.StatusBadRequest, models.APIError{Code: "bad_request", Message: "invalid job_id"})
|
||||
return
|
||||
}
|
||||
original, err := h.store.GetJobByID(c.Request.Context(), jobID, userID)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusNotFound, models.APIError{Code: "not_found", Message: err.Error()})
|
||||
return
|
||||
}
|
||||
// Create a new job cloning the original config
|
||||
req := &models.RenderJobCreateRequest{
|
||||
SavedProjectID: original.SavedProjectID,
|
||||
Quality: original.Quality,
|
||||
Resolution: original.Resolution,
|
||||
FrameRate: &original.FrameRate,
|
||||
}
|
||||
newJob, err := h.store.CreateJob(c.Request.Context(), userID, tenantID, req)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, models.APIError{Code: "internal_error", Message: err.Error()})
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusCreated, newJob)
|
||||
}
|
||||
|
||||
// GET /v1/renders/:job_id/progress
|
||||
func (h *RenderHandler) Progress(c *gin.Context) {
|
||||
userID := middleware.GetUserID(c)
|
||||
jobID, err := uuid.Parse(c.Param("job_id"))
|
||||
if err != nil {
|
||||
c.JSON(http.StatusBadRequest, models.APIError{Code: "bad_request", Message: "invalid job_id"})
|
||||
return
|
||||
}
|
||||
job, err := h.store.GetJobByID(c.Request.Context(), jobID, userID)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusNotFound, models.APIError{Code: "not_found", Message: err.Error()})
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"job_id": job.ID,
|
||||
"step": job.Step,
|
||||
"progress": job.RenderProgress,
|
||||
"current_frame": nil,
|
||||
"total_frames": nil,
|
||||
"eta_seconds": nil,
|
||||
"preview_b64": job.ImagePreviewB64,
|
||||
"active_nodes": job.CurrentActiveNodes,
|
||||
"message": job.FailedMessage,
|
||||
})
|
||||
}
|
||||
|
||||
// GET /v1/renders/:job_id/logs
|
||||
func (h *RenderHandler) Logs(c *gin.Context) {
|
||||
// Logs are stored externally (MinIO/ELK). Return empty for now — node agents push logs elsewhere.
|
||||
c.JSON(http.StatusOK, gin.H{"logs": []any{}})
|
||||
}
|
||||
@@ -0,0 +1,80 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"crypto/sha256"
|
||||
"fmt"
|
||||
"net/http"
|
||||
|
||||
"github.com/flatrender/render-svc/internal/db"
|
||||
"github.com/flatrender/render-svc/internal/middleware"
|
||||
"github.com/flatrender/render-svc/internal/models"
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
type SnapshotHandler struct {
|
||||
store *db.Store
|
||||
}
|
||||
|
||||
func NewSnapshotHandler(store *db.Store) *SnapshotHandler {
|
||||
return &SnapshotHandler{store: store}
|
||||
}
|
||||
|
||||
// POST /v1/snapshots
|
||||
func (h *SnapshotHandler) Create(c *gin.Context) {
|
||||
userID := middleware.GetUserID(c)
|
||||
tenantID := middleware.GetTenantID(c)
|
||||
|
||||
var req models.SnapshotCreateRequest
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
c.JSON(http.StatusBadRequest, models.APIError{Code: "bad_request", Message: err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
// Deterministic cache key from inputs
|
||||
hash := fmt.Sprintf("%x", sha256.Sum256([]byte(
|
||||
fmt.Sprintf("%s:%s:%d", req.SavedProjectID, req.SceneKey, req.FrameNumber),
|
||||
)))
|
||||
|
||||
// Check cache first
|
||||
cached, err := h.store.GetCachedSnapshot(c.Request.Context(),
|
||||
req.SavedProjectID, req.SceneKey, req.FrameNumber, hash)
|
||||
if err == nil && cached != nil {
|
||||
c.JSON(http.StatusAccepted, gin.H{
|
||||
"snapshot_id": cached.ID,
|
||||
"status": "Cached",
|
||||
"image_url": cached.ImageURL,
|
||||
"thumbnail_url": cached.ThumbnailURL,
|
||||
"expires_at": cached.ExpiresAt,
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
snap, err := h.store.CreateSnapshot(c.Request.Context(), userID, tenantID, &req, hash)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, models.APIError{Code: "internal_error", Message: err.Error()})
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusAccepted, gin.H{
|
||||
"snapshot_id": snap.ID,
|
||||
"status": "Pending",
|
||||
"image_url": nil,
|
||||
"thumbnail_url": nil,
|
||||
"expires_at": snap.ExpiresAt,
|
||||
})
|
||||
}
|
||||
|
||||
// GET /v1/snapshots/:snapshot_id
|
||||
func (h *SnapshotHandler) Get(c *gin.Context) {
|
||||
snapID, err := uuid.Parse(c.Param("snapshot_id"))
|
||||
if err != nil {
|
||||
c.JSON(http.StatusBadRequest, models.APIError{Code: "bad_request", Message: "invalid snapshot_id"})
|
||||
return
|
||||
}
|
||||
snap, err := h.store.GetSnapshotByID(c.Request.Context(), snapID)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusNotFound, models.APIError{Code: "not_found", Message: err.Error()})
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, snap)
|
||||
}
|
||||
@@ -0,0 +1,105 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net/http"
|
||||
"strings"
|
||||
|
||||
"github.com/flatrender/render-svc/internal/models"
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/golang-jwt/jwt/v5"
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
const (
|
||||
CtxUserID = "user_id"
|
||||
CtxTenantID = "tenant_id"
|
||||
CtxIsAdmin = "is_admin"
|
||||
CtxRole = "role"
|
||||
)
|
||||
|
||||
func JWTAuth(secret string) gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
hdr := c.GetHeader("Authorization")
|
||||
if !strings.HasPrefix(hdr, "Bearer ") {
|
||||
c.AbortWithStatusJSON(http.StatusUnauthorized, models.APIError{Code: "unauthorized", Message: "missing bearer token"})
|
||||
return
|
||||
}
|
||||
tokenStr := hdr[7:]
|
||||
token, err := jwt.Parse(tokenStr, func(t *jwt.Token) (interface{}, error) {
|
||||
if _, ok := t.Method.(*jwt.SigningMethodHMAC); !ok {
|
||||
return nil, jwt.ErrSignatureInvalid
|
||||
}
|
||||
return []byte(secret), nil
|
||||
})
|
||||
if err != nil || !token.Valid {
|
||||
c.AbortWithStatusJSON(http.StatusUnauthorized, models.APIError{Code: "unauthorized", Message: "invalid token"})
|
||||
return
|
||||
}
|
||||
claims, ok := token.Claims.(jwt.MapClaims)
|
||||
if !ok {
|
||||
c.AbortWithStatusJSON(http.StatusUnauthorized, models.APIError{Code: "unauthorized", Message: "bad claims"})
|
||||
return
|
||||
}
|
||||
userID, _ := uuid.Parse(fmt.Sprintf("%v", claims["sub"]))
|
||||
tenantID, _ := uuid.Parse(fmt.Sprintf("%v", claims["tenant_id"]))
|
||||
isAdmin, _ := claims["is_admin"].(bool)
|
||||
role, _ := claims["role"].(string)
|
||||
|
||||
c.Set(CtxUserID, userID)
|
||||
c.Set(CtxTenantID, tenantID)
|
||||
c.Set(CtxIsAdmin, isAdmin)
|
||||
c.Set(CtxRole, role)
|
||||
c.Next()
|
||||
}
|
||||
}
|
||||
|
||||
func RequireAdmin() gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
isAdmin, _ := c.Get(CtxIsAdmin)
|
||||
b, _ := isAdmin.(bool)
|
||||
if !b {
|
||||
c.AbortWithStatusJSON(http.StatusForbidden, models.APIError{Code: "forbidden", Message: "admin required"})
|
||||
return
|
||||
}
|
||||
c.Next()
|
||||
}
|
||||
}
|
||||
|
||||
// RequireServiceRole allows callers presenting a token with role="Service"
|
||||
func RequireServiceRole() gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
role, _ := c.Get(CtxRole)
|
||||
isAdmin, _ := c.Get(CtxIsAdmin)
|
||||
b, _ := isAdmin.(bool)
|
||||
if role != "Service" && !b {
|
||||
c.AbortWithStatusJSON(http.StatusForbidden, models.APIError{Code: "forbidden", Message: "service role required"})
|
||||
return
|
||||
}
|
||||
c.Next()
|
||||
}
|
||||
}
|
||||
|
||||
// NodeHMAC verifies the X-Node-Signature header for node-agent calls
|
||||
func NodeHMAC(nodeSecret string) gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
sig := c.GetHeader("X-Node-Signature")
|
||||
if sig == "" || sig != nodeSecret {
|
||||
c.AbortWithStatusJSON(http.StatusUnauthorized, models.APIError{Code: "unauthorized", Message: "invalid node signature"})
|
||||
return
|
||||
}
|
||||
c.Next()
|
||||
}
|
||||
}
|
||||
|
||||
func GetUserID(c *gin.Context) uuid.UUID {
|
||||
v, _ := c.Get(CtxUserID)
|
||||
id, _ := v.(uuid.UUID)
|
||||
return id
|
||||
}
|
||||
|
||||
func GetTenantID(c *gin.Context) uuid.UUID {
|
||||
v, _ := c.Get(CtxTenantID)
|
||||
id, _ := v.(uuid.UUID)
|
||||
return id
|
||||
}
|
||||
@@ -0,0 +1,431 @@
|
||||
package models
|
||||
|
||||
import (
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
// ── Enums ────────────────────────────────────────────────────────────────────
|
||||
|
||||
const (
|
||||
// NodeStatus
|
||||
NodeStatusReady = "Ready"
|
||||
NodeStatusBusy = "Busy"
|
||||
NodeStatusOffline = "Offline"
|
||||
NodeStatusMaintenance = "Maintenance"
|
||||
NodeStatusCrashed = "Crashed"
|
||||
NodeStatusUpdating = "Updating"
|
||||
NodeStatusDisabled = "Disabled"
|
||||
|
||||
// NodeKind
|
||||
NodeKindShared = "Shared"
|
||||
NodeKindDedicated = "Dedicated"
|
||||
NodeKindSpot = "Spot"
|
||||
|
||||
// RenderStep
|
||||
StepQueued = "Queued"
|
||||
StepPreparing = "Preparing"
|
||||
StepTemplateCache = "TemplateCache"
|
||||
StepJsxGen = "JsxGen"
|
||||
StepMusic = "Music"
|
||||
StepRendering = "Rendering"
|
||||
StepValidating = "Validating"
|
||||
StepRepairing = "Repairing"
|
||||
StepOptimisation = "Optimisation"
|
||||
StepVideo = "Video"
|
||||
StepMixing = "Mixing"
|
||||
StepFinal = "Final"
|
||||
StepUploading = "Uploading"
|
||||
StepDone = "Done"
|
||||
StepFailed = "Failed"
|
||||
StepCancelled = "Cancelled"
|
||||
|
||||
// PriceKind
|
||||
PriceKindFree = "Free"
|
||||
PriceKindPreview = "Preview"
|
||||
PriceKindCash = "Cash"
|
||||
PriceKindPlan = "Plan"
|
||||
PriceKindSnapshot = "Snapshot"
|
||||
PriceKindReseller = "Reseller"
|
||||
|
||||
// RenderQuality
|
||||
QualityLow = "Low"
|
||||
QualityMedium = "Medium"
|
||||
QualityHigh = "High"
|
||||
QualityFull = "Full"
|
||||
QualityLossless = "Lossless"
|
||||
|
||||
// FrameJobStatus
|
||||
FrameJobPending = "Pending"
|
||||
FrameJobRendering = "Rendering"
|
||||
FrameJobValidated = "Validated"
|
||||
FrameJobRepairing = "Repairing"
|
||||
FrameJobConverting = "Converting"
|
||||
FrameJobDone = "Done"
|
||||
FrameJobFailed = "Failed"
|
||||
|
||||
// PriorityQueue
|
||||
QueueSnapshot = "snapshot"
|
||||
QueueVIP = "vip"
|
||||
QueuePaid = "paid"
|
||||
QueuePreview = "preview"
|
||||
QueueMockup = "mockup"
|
||||
QueueVoiceover = "voiceover"
|
||||
|
||||
// Export types
|
||||
ExportCreateRender = "Render"
|
||||
ExportCreateUpload = "Upload"
|
||||
ExportCreateSnapshot = "Snapshot"
|
||||
ExportCreateReupload = "Reupload"
|
||||
|
||||
ExportFileVideo = "Video"
|
||||
ExportFileImage = "Image"
|
||||
ExportFileAudio = "Audio"
|
||||
ExportFileGIF = "GIF"
|
||||
ExportFilePDF = "PDF"
|
||||
)
|
||||
|
||||
// ── Domain entities ──────────────────────────────────────────────────────────
|
||||
|
||||
type RenderNode struct {
|
||||
ID uuid.UUID `json:"id"`
|
||||
Name string `json:"name"`
|
||||
Region string `json:"region"`
|
||||
NodeIP string `json:"node_ip"`
|
||||
WorkerPort int `json:"worker_port"`
|
||||
PublicEndpoint *string `json:"public_endpoint,omitempty"`
|
||||
RamGB *int `json:"ram_gb,omitempty"`
|
||||
CPUCores *int `json:"cpu_cores,omitempty"`
|
||||
GPUModel *string `json:"gpu_model,omitempty"`
|
||||
StorageGB *int `json:"storage_gb,omitempty"`
|
||||
CurrentAEVersion string `json:"current_ae_version"`
|
||||
AvailableAEVersions []string `json:"available_ae_versions"`
|
||||
NodeAgentVersion *string `json:"node_agent_version,omitempty"`
|
||||
NodeKind string `json:"node_kind"`
|
||||
OwnerUserID *uuid.UUID `json:"owner_user_id,omitempty"`
|
||||
OwnerTenantID *uuid.UUID `json:"owner_tenant_id,omitempty"`
|
||||
Status string `json:"status"`
|
||||
CurrentJobID *uuid.UUID `json:"current_job_id,omitempty"`
|
||||
CurrentFrameJobID *uuid.UUID `json:"current_frame_job_id,omitempty"`
|
||||
JobStartedAt *time.Time `json:"job_started_at,omitempty"`
|
||||
LastHeartbeatAt *time.Time `json:"last_heartbeat_at,omitempty"`
|
||||
LastCPUPct *int `json:"last_cpu_pct,omitempty"`
|
||||
LastRAMAvailableMB *int `json:"last_ram_available_mb,omitempty"`
|
||||
AERunning bool `json:"ae_running"`
|
||||
LifetimeTaskCount int64 `json:"lifetime_task_count"`
|
||||
LifetimeCrashCount int `json:"lifetime_crash_count"`
|
||||
ConsecutiveFailures int `json:"consecutive_failures"`
|
||||
Priority int `json:"priority"`
|
||||
IsActive bool `json:"is_active"`
|
||||
AcceptsNewJobs bool `json:"accepts_new_jobs"`
|
||||
LastMaintenanceAt *time.Time `json:"last_maintenance_at,omitempty"`
|
||||
NextMaintenanceAt *time.Time `json:"next_maintenance_at,omitempty"`
|
||||
MaintenanceReason *string `json:"maintenance_reason,omitempty"`
|
||||
CachedTemplateMD5s []string `json:"cached_template_md5s"`
|
||||
CacheUsedGB int `json:"cache_used_gb"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
}
|
||||
|
||||
type RenderJob struct {
|
||||
ID uuid.UUID `json:"id"`
|
||||
TenantID uuid.UUID `json:"tenant_id"`
|
||||
UserID uuid.UUID `json:"user_id"`
|
||||
SavedProjectID uuid.UUID `json:"saved_project_id"`
|
||||
OriginalProjectID uuid.UUID `json:"original_project_id"`
|
||||
ProjectName *string `json:"project_name,omitempty"`
|
||||
Title *string `json:"title,omitempty"`
|
||||
Name *string `json:"name,omitempty"`
|
||||
ExternalJobID *string `json:"external_job_id,omitempty"`
|
||||
PriorityQueue string `json:"priority_queue"`
|
||||
PriorityScore int `json:"priority_score"`
|
||||
Step string `json:"step"`
|
||||
RenderProgress int `json:"render_progress"`
|
||||
ConvertProgress int `json:"convert_progress"`
|
||||
ImagePreviewB64 *string `json:"image_preview_b64,omitempty"`
|
||||
PriceType string `json:"price_type"`
|
||||
PaidPriceMinor int64 `json:"paid_price_minor"`
|
||||
DiscountCode *string `json:"discount_code,omitempty"`
|
||||
SupportFlatrender bool `json:"support_flatrender"`
|
||||
Mode string `json:"mode"`
|
||||
Quality string `json:"quality"`
|
||||
Resolution string `json:"resolution"`
|
||||
RHeight int `json:"r_height"`
|
||||
FrameRate int `json:"frame_rate"`
|
||||
Is60FPS bool `json:"is_60_fps"`
|
||||
DurationSec float64 `json:"duration_sec"`
|
||||
ExportDurationSec *float64 `json:"export_duration_sec,omitempty"`
|
||||
HasMusic bool `json:"has_music"`
|
||||
HasSFX bool `json:"has_sfx"`
|
||||
HasVoiceover bool `json:"has_voiceover"`
|
||||
MusicVolume *float64 `json:"music_volume,omitempty"`
|
||||
SFXVolume *float64 `json:"sfx_volume,omitempty"`
|
||||
VoiceoverVolume *float64 `json:"voiceover_volume,omitempty"`
|
||||
RenderNodeCount int `json:"render_node_count"`
|
||||
CurrentActiveNodes int `json:"current_active_nodes"`
|
||||
Region *string `json:"region,omitempty"`
|
||||
TellMeWhenDone bool `json:"tell_me_when_done"`
|
||||
RetryCount int `json:"retry_count"`
|
||||
MaxRetries int `json:"max_retries"`
|
||||
RepairAttempts int `json:"repair_attempts"`
|
||||
FailedMessage *string `json:"failed_message,omitempty"`
|
||||
FailedAtStep *string `json:"failed_at_step,omitempty"`
|
||||
ExportID *uuid.UUID `json:"export_id,omitempty"`
|
||||
TaskStartDate time.Time `json:"task_start_date"`
|
||||
QueuedAt time.Time `json:"queued_at"`
|
||||
StartedAt *time.Time `json:"started_at,omitempty"`
|
||||
CompletedAt *time.Time `json:"completed_at,omitempty"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
}
|
||||
|
||||
type FrameJob struct {
|
||||
ID uuid.UUID `json:"id"`
|
||||
RenderJobID uuid.UUID `json:"render_job_id"`
|
||||
NodeID uuid.UUID `json:"node_id"`
|
||||
StartFrame int `json:"start_frame"`
|
||||
EndFrame int `json:"end_frame"`
|
||||
CollectFrameCount int `json:"collect_frame_count"`
|
||||
OrderValue int `json:"order_value"`
|
||||
FolderName string `json:"folder_name"`
|
||||
ConvertURL *string `json:"convert_url,omitempty"`
|
||||
Status string `json:"status"`
|
||||
FramesRendered int `json:"frames_rendered"`
|
||||
FramesValidated int `json:"frames_validated"`
|
||||
Attempt int `json:"attempt"`
|
||||
LastError *string `json:"last_error,omitempty"`
|
||||
OutputMP4URL *string `json:"output_mp4_url,omitempty"`
|
||||
AssignedAt time.Time `json:"assigned_at"`
|
||||
StartedAt *time.Time `json:"started_at,omitempty"`
|
||||
LastProgressAt *time.Time `json:"last_progress_at,omitempty"`
|
||||
CompletedAt *time.Time `json:"completed_at,omitempty"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
}
|
||||
|
||||
type Snapshot struct {
|
||||
ID uuid.UUID `json:"id"`
|
||||
TenantID uuid.UUID `json:"tenant_id"`
|
||||
UserID uuid.UUID `json:"user_id"`
|
||||
SavedProjectID uuid.UUID `json:"saved_project_id"`
|
||||
SceneKey string `json:"scene_key"`
|
||||
FrameNumber int `json:"frame_number"`
|
||||
InputsHash string `json:"inputs_hash"`
|
||||
Status string `json:"status"`
|
||||
RenderNodeID *uuid.UUID `json:"render_node_id,omitempty"`
|
||||
ImageURL *string `json:"image_url,omitempty"`
|
||||
ThumbnailURL *string `json:"thumbnail_url,omitempty"`
|
||||
Width *int `json:"width,omitempty"`
|
||||
Height *int `json:"height,omitempty"`
|
||||
SizeBytes *int64 `json:"size_bytes,omitempty"`
|
||||
RequestedAt time.Time `json:"requested_at"`
|
||||
CompletedAt *time.Time `json:"completed_at,omitempty"`
|
||||
DurationMS *int `json:"duration_ms,omitempty"`
|
||||
ExpiresAt time.Time `json:"expires_at"`
|
||||
ErrorMessage *string `json:"error_message,omitempty"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
}
|
||||
|
||||
type Export struct {
|
||||
ID uuid.UUID `json:"id"`
|
||||
TenantID uuid.UUID `json:"tenant_id"`
|
||||
UserID uuid.UUID `json:"user_id"`
|
||||
SavedProjectID uuid.UUID `json:"saved_project_id"`
|
||||
ProjectID uuid.UUID `json:"project_id"`
|
||||
RenderJobID *uuid.UUID `json:"render_job_id,omitempty"`
|
||||
Image *string `json:"image,omitempty"`
|
||||
Path string `json:"path"`
|
||||
FileExtension string `json:"file_extension"`
|
||||
FileType string `json:"file_type"`
|
||||
RenderQuality string `json:"render_quality"`
|
||||
CreateType string `json:"create_type"`
|
||||
SizeBytes int64 `json:"size_bytes"`
|
||||
DurationSec *float64 `json:"duration_sec,omitempty"`
|
||||
Width *int `json:"width,omitempty"`
|
||||
Height *int `json:"height,omitempty"`
|
||||
ProduceDate time.Time `json:"produce_date"`
|
||||
AutoDeleteDate time.Time `json:"auto_delete_date"`
|
||||
DeleteNotified bool `json:"delete_notified"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
DeletedAt *time.Time `json:"deleted_at,omitempty"`
|
||||
}
|
||||
|
||||
type ExportFile struct {
|
||||
ID uuid.UUID `json:"id"`
|
||||
ExportID uuid.UUID `json:"export_id"`
|
||||
UserID uuid.UUID `json:"user_id"`
|
||||
Name *string `json:"name,omitempty"`
|
||||
Thumbnail *string `json:"thumbnail,omitempty"`
|
||||
Path string `json:"path"`
|
||||
SizeBytes int64 `json:"size_bytes"`
|
||||
FileType string `json:"file_type"`
|
||||
Width *int `json:"width,omitempty"`
|
||||
Height *int `json:"height,omitempty"`
|
||||
Sort int `json:"sort"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
}
|
||||
|
||||
type NodeHealthLog struct {
|
||||
ID int64 `json:"id"`
|
||||
NodeID uuid.UUID `json:"node_id"`
|
||||
RecordedAt time.Time `json:"recorded_at"`
|
||||
Status string `json:"status"`
|
||||
CPUPct *int `json:"cpu_pct,omitempty"`
|
||||
RAMAvailableMB *int `json:"ram_available_mb,omitempty"`
|
||||
AERunning *bool `json:"ae_running,omitempty"`
|
||||
CurrentJobID *uuid.UUID `json:"current_job_id,omitempty"`
|
||||
CurrentFrame *int `json:"current_frame,omitempty"`
|
||||
CacheUsedGB *int `json:"cache_used_gb,omitempty"`
|
||||
}
|
||||
|
||||
type NodeCrash struct {
|
||||
ID uuid.UUID `json:"id"`
|
||||
NodeID uuid.UUID `json:"node_id"`
|
||||
RenderJobID *uuid.UUID `json:"render_job_id,omitempty"`
|
||||
FrameJobID *uuid.UUID `json:"frame_job_id,omitempty"`
|
||||
CrashedAt time.Time `json:"crashed_at"`
|
||||
LastKnownFrame *int `json:"last_known_frame,omitempty"`
|
||||
CrashSignal *string `json:"crash_signal,omitempty"`
|
||||
ErrorLog *string `json:"error_log,omitempty"`
|
||||
LogFileURL *string `json:"log_file_url,omitempty"`
|
||||
AutoRecovered bool `json:"auto_recovered"`
|
||||
RecoveryAction *string `json:"recovery_action,omitempty"`
|
||||
RecoveredAt *time.Time `json:"recovered_at,omitempty"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
}
|
||||
|
||||
type NodeUpdate struct {
|
||||
ID uuid.UUID `json:"id"`
|
||||
UpdateFileName string `json:"update_file_name"`
|
||||
UpdateNumber int `json:"update_number"`
|
||||
Description *string `json:"description,omitempty"`
|
||||
TargetAEVersion *string `json:"target_ae_version,omitempty"`
|
||||
InUpdateQueue bool `json:"in_update_queue"`
|
||||
RolledOutToNodeIDs []uuid.UUID `json:"rolled_out_to_node_ids"`
|
||||
LastUpdateQueueDate *time.Time `json:"last_update_queue_date,omitempty"`
|
||||
CreateDate time.Time `json:"create_date"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
}
|
||||
|
||||
// ── Request / Response types ─────────────────────────────────────────────────
|
||||
|
||||
type PagedResponse[T any] struct {
|
||||
Data []T `json:"data"`
|
||||
Meta PaginationMeta `json:"meta"`
|
||||
}
|
||||
|
||||
type PaginationMeta struct {
|
||||
Page int `json:"page"`
|
||||
PageSize int `json:"page_size"`
|
||||
Total int64 `json:"total"`
|
||||
HasMore bool `json:"has_more"`
|
||||
}
|
||||
|
||||
type RenderJobCreateRequest struct {
|
||||
SavedProjectID uuid.UUID `json:"saved_project_id" binding:"required"`
|
||||
Quality string `json:"quality" binding:"required"`
|
||||
Resolution string `json:"resolution" binding:"required"`
|
||||
FrameRate *int `json:"frame_rate"`
|
||||
Is60FPS *bool `json:"is_60_fps"`
|
||||
PriceType *string `json:"price_type"`
|
||||
DiscountCode *string `json:"discount_code"`
|
||||
SupportFlatrender *bool `json:"support_flatrender"`
|
||||
TellMeWhenDone *bool `json:"tell_me_when_done"`
|
||||
PreferredRegion *string `json:"preferred_region"`
|
||||
}
|
||||
|
||||
type SnapshotCreateRequest struct {
|
||||
SavedProjectID uuid.UUID `json:"saved_project_id" binding:"required"`
|
||||
SceneKey string `json:"scene_key" binding:"required"`
|
||||
FrameNumber int `json:"frame_number" binding:"min=0"`
|
||||
}
|
||||
|
||||
type NodeCreateRequest struct {
|
||||
Name string `json:"name" binding:"required"`
|
||||
Region string `json:"region" binding:"required"`
|
||||
NodeIP string `json:"node_ip" binding:"required"`
|
||||
WorkerPort int `json:"worker_port" binding:"required"`
|
||||
CurrentAEVersion string `json:"current_ae_version" binding:"required"`
|
||||
RamGB *int `json:"ram_gb"`
|
||||
CPUCores *int `json:"cpu_cores"`
|
||||
NodeKind *string `json:"node_kind"`
|
||||
OwnerUserID *uuid.UUID `json:"owner_user_id"`
|
||||
Priority *int `json:"priority"`
|
||||
}
|
||||
|
||||
type NodePatchRequest struct {
|
||||
Priority *int `json:"priority"`
|
||||
IsActive *bool `json:"is_active"`
|
||||
AcceptsNewJobs *bool `json:"accepts_new_jobs"`
|
||||
NodeKind *string `json:"node_kind"`
|
||||
OwnerUserID *uuid.UUID `json:"owner_user_id"`
|
||||
NextMaintenanceAt *time.Time `json:"next_maintenance_at"`
|
||||
MaintenanceReason *string `json:"maintenance_reason"`
|
||||
}
|
||||
|
||||
type NodeHeartbeatRequest struct {
|
||||
NodeID uuid.UUID `json:"node_id"`
|
||||
Status string `json:"status"`
|
||||
CPUPct *int `json:"cpu_pct"`
|
||||
RAMAvailableMB *int `json:"ram_available_mb"`
|
||||
AERunning *bool `json:"ae_running"`
|
||||
CurrentJobID *uuid.UUID `json:"current_job_id"`
|
||||
CurrentFrame *int `json:"current_frame"`
|
||||
CacheUsedGB *int `json:"cache_used_gb"`
|
||||
}
|
||||
|
||||
type NodeOnlineRequest struct {
|
||||
NodeAgentVersion string `json:"node_agent_version"`
|
||||
CurrentAEVersion string `json:"current_ae_version"`
|
||||
AvailableAEVersions []string `json:"available_ae_versions"`
|
||||
RamGB *int `json:"ram_gb"`
|
||||
CPUCores *int `json:"cpu_cores"`
|
||||
CacheUsedGB *int `json:"cache_used_gb"`
|
||||
CachedTemplateMD5s []string `json:"cached_template_md5s"`
|
||||
}
|
||||
|
||||
type FrameProgressRequest struct {
|
||||
FrameJobID uuid.UUID `json:"frame_job_id" binding:"required"`
|
||||
FrameNumber int `json:"frame_number"`
|
||||
FileSizeBytes *int64 `json:"file_size_bytes"`
|
||||
CompletedAt *time.Time `json:"completed_at"`
|
||||
}
|
||||
|
||||
type CrashReportRequest struct {
|
||||
NodeID uuid.UUID `json:"node_id" binding:"required"`
|
||||
FrameJobID *uuid.UUID `json:"frame_job_id"`
|
||||
LastKnownFrame *int `json:"last_known_frame"`
|
||||
CrashSignal *string `json:"crash_signal"`
|
||||
AEVersion *string `json:"ae_version"`
|
||||
ErrorLogTail *string `json:"error_log_tail"`
|
||||
LogFileURL *string `json:"log_file_url"`
|
||||
}
|
||||
|
||||
type CacheUpdateRequest struct {
|
||||
Action string `json:"action" binding:"required"`
|
||||
ProjectID *uuid.UUID `json:"project_id"`
|
||||
AEPFileMD5 string `json:"aep_file_md5" binding:"required"`
|
||||
FileSizeBytes *int64 `json:"file_size_bytes"`
|
||||
CacheUsedGB *int `json:"cache_used_gb"`
|
||||
ErrorMessage *string `json:"error_message"`
|
||||
}
|
||||
|
||||
type ReplicaReadyRequest struct {
|
||||
NodeID uuid.UUID `json:"node_id" binding:"required"`
|
||||
ReplicaPath string `json:"replica_path" binding:"required"`
|
||||
ReplicaMD5 *string `json:"replica_md5"`
|
||||
}
|
||||
|
||||
type APIError struct {
|
||||
Code string `json:"code"`
|
||||
Message string `json:"message"`
|
||||
}
|
||||
|
||||
// Claims carries JWT payload
|
||||
type Claims struct {
|
||||
UserID uuid.UUID `json:"sub"`
|
||||
TenantID uuid.UUID `json:"tenant_id"`
|
||||
IsAdmin bool `json:"is_admin"`
|
||||
Role string `json:"role"`
|
||||
}
|
||||
@@ -0,0 +1,135 @@
|
||||
// Package notifier provides a lightweight HTTP client for the notification
|
||||
// service. All methods are fire-and-forget: errors are logged but never
|
||||
// propagate to the caller, so a notification failure never breaks a render
|
||||
// flow.
|
||||
package notifier
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"log"
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
// Client sends notifications to the internal notification service endpoint.
|
||||
type Client struct {
|
||||
baseURL string
|
||||
serviceToken string
|
||||
http *http.Client
|
||||
}
|
||||
|
||||
// New returns a Client pointing at baseURL (e.g. "http://notification-svc:8080")
|
||||
// and authenticating with serviceToken.
|
||||
func New(baseURL, serviceToken string) *Client {
|
||||
return &Client{
|
||||
baseURL: baseURL,
|
||||
serviceToken: serviceToken,
|
||||
http: &http.Client{Timeout: 5 * time.Second},
|
||||
}
|
||||
}
|
||||
|
||||
// createNotificationReq mirrors the notification service's CreateNotificationRequest.
|
||||
type createNotificationReq struct {
|
||||
UserID uuid.UUID `json:"user_id"`
|
||||
TenantID uuid.UUID `json:"tenant_id"`
|
||||
NotificationType string `json:"notification_type"`
|
||||
Priority string `json:"priority"`
|
||||
Title string `json:"title"`
|
||||
Message string `json:"message"`
|
||||
RenderJobID *uuid.UUID `json:"render_job_id,omitempty"`
|
||||
ExportID *uuid.UUID `json:"export_id,omitempty"`
|
||||
ActionURL *string `json:"action_url,omitempty"`
|
||||
ActionText *string `json:"action_text,omitempty"`
|
||||
Channels []string `json:"channels"`
|
||||
}
|
||||
|
||||
// send posts a notification to the service. Returns an error for caller
|
||||
// awareness, but callers are expected to ignore it.
|
||||
func (c *Client) send(ctx context.Context, req createNotificationReq) error {
|
||||
body, err := json.Marshal(req)
|
||||
if err != nil {
|
||||
return fmt.Errorf("notifier marshal: %w", err)
|
||||
}
|
||||
httpReq, err := http.NewRequestWithContext(ctx, http.MethodPost,
|
||||
c.baseURL+"/v1/internal/notifications", bytes.NewReader(body))
|
||||
if err != nil {
|
||||
return fmt.Errorf("notifier new request: %w", err)
|
||||
}
|
||||
httpReq.Header.Set("Content-Type", "application/json")
|
||||
httpReq.Header.Set("Authorization", "Bearer "+c.serviceToken)
|
||||
|
||||
resp, err := c.http.Do(httpReq)
|
||||
if err != nil {
|
||||
return fmt.Errorf("notifier send: %w", err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
if resp.StatusCode >= 400 {
|
||||
return fmt.Errorf("notifier: status %d", resp.StatusCode)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// NotifyRenderDone fires a RenderCompleted notification. Never blocks the
|
||||
// caller — errors are only logged.
|
||||
func (c *Client) NotifyRenderDone(
|
||||
ctx context.Context,
|
||||
userID, tenantID, jobID uuid.UUID,
|
||||
exportID *uuid.UUID,
|
||||
jobName string,
|
||||
) {
|
||||
actionURL := "/dashboard/renders/" + jobID.String()
|
||||
actionText := "مشاهده فایل"
|
||||
req := createNotificationReq{
|
||||
UserID: userID,
|
||||
TenantID: tenantID,
|
||||
NotificationType: "RenderCompleted",
|
||||
Priority: "High",
|
||||
Title: "رندر تکمیل شد 🎉",
|
||||
Message: fmt.Sprintf("پروژه «%s» با موفقیت رندر شد و آماده دانلود است.", jobName),
|
||||
RenderJobID: &jobID,
|
||||
ExportID: exportID,
|
||||
ActionURL: &actionURL,
|
||||
ActionText: &actionText,
|
||||
Channels: []string{"InApp"},
|
||||
}
|
||||
if err := c.send(ctx, req); err != nil {
|
||||
log.Printf("[notifier] RenderDone job=%s err=%v", jobID, err)
|
||||
}
|
||||
}
|
||||
|
||||
// NotifyRenderFailed fires a RenderFailed notification. Never blocks the
|
||||
// caller — errors are only logged.
|
||||
func (c *Client) NotifyRenderFailed(
|
||||
ctx context.Context,
|
||||
userID, tenantID, jobID uuid.UUID,
|
||||
jobName, reason string,
|
||||
) {
|
||||
actionURL := "/dashboard/renders/" + jobID.String()
|
||||
actionText := "جزئیات"
|
||||
var msg string
|
||||
if reason != "" {
|
||||
msg = fmt.Sprintf("رندر پروژه «%s» با خطا مواجه شد: %s", jobName, reason)
|
||||
} else {
|
||||
msg = fmt.Sprintf("رندر پروژه «%s» با خطا مواجه شد. لطفاً دوباره تلاش کنید.", jobName)
|
||||
}
|
||||
req := createNotificationReq{
|
||||
UserID: userID,
|
||||
TenantID: tenantID,
|
||||
NotificationType: "RenderFailed",
|
||||
Priority: "High",
|
||||
Title: "خطا در رندر",
|
||||
Message: msg,
|
||||
RenderJobID: &jobID,
|
||||
ActionURL: &actionURL,
|
||||
ActionText: &actionText,
|
||||
Channels: []string{"InApp"},
|
||||
}
|
||||
if err := c.send(ctx, req); err != nil {
|
||||
log.Printf("[notifier] RenderFailed job=%s err=%v", jobID, err)
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user