feat(render+identity): daily render-limit — consume on submit, refund on admin-stop
Build backend images / build content-svc (push) Failing after 51s
Build backend images / build file-svc (push) Failing after 53s
Build backend images / build gateway (push) Failing after 1m1s
Build backend images / build identity-svc (push) Failing after 48s
Build backend images / build notification-svc (push) Failing after 42s
Build backend images / build render-svc (push) Failing after 47s
Build backend images / build studio-svc (push) Failing after 1m13s

Business rule: each user has a daily render limit. Admin-stop refunds the used
charge (not the user's fault); a user's own cancel does not.

- identity: ConsumeRenderChargeAsync / RefundRenderChargeAsync on DailyRemainRenderCount
  with lazy daily reset (mig 24: daily_renders_reset_at). Convention: max=0 ⇒ UNLIMITED,
  so existing 0/0 users keep rendering until an admin sets a real limit.
- identity InternalController (service-token): POST /v1/internal/render-charge/{consume,refund}
- render-svc: identityclient + on Create consume (block 429 when limit reached, fail-open
  on identity outage); on admin Stop refund the job owner; user /cancel unchanged
- compose: IDENTITY_URL for render-svc, ServiceToken for identity-svc

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
soroush.asadi
2026-06-03 02:18:00 +03:30
parent 7f7feabb85
commit 1f52f53cf7
9 changed files with 215 additions and 13 deletions
+4 -1
View File
@@ -8,6 +8,7 @@ import (
"github.com/flatrender/render-svc/internal/db"
"github.com/flatrender/render-svc/internal/handlers"
"github.com/flatrender/render-svc/internal/identityclient"
"github.com/flatrender/render-svc/internal/middleware"
"github.com/flatrender/render-svc/internal/notifier"
"github.com/gin-gonic/gin"
@@ -35,6 +36,7 @@ func main() {
minioBucket := getEnv("MINIO_BUCKET", "flatrender-exports")
minioTemplatesBucket := getEnv("MINIO_TEMPLATES_BUCKET", "flatrender-templates")
notificationURL := getEnv("NOTIFICATION_URL", "http://localhost:8080")
identityURL := getEnv("IDENTITY_URL", "")
serviceToken := getEnv("SERVICE_TOKEN", "internal-service-secret")
port := getEnv("PORT", "8080")
@@ -60,7 +62,8 @@ func main() {
// ── Store + handlers ──────────────────────────────────────────────────────
store := db.NewStore(pool)
notifyClient := notifier.New(notificationURL, serviceToken)
renderH := handlers.NewRenderHandler(store)
identityClient := identityclient.New(identityURL, serviceToken)
renderH := handlers.NewRenderHandler(store, identityClient)
snapH := handlers.NewSnapshotHandler(store)
exportH := handlers.NewExportHandler(store, mc, minioBucket)
nodeH := handlers.NewNodeHandler(store)
+12 -8
View File
@@ -597,22 +597,26 @@ func (s *Store) CancelJob(ctx context.Context, id, userID uuid.UUID) (bool, erro
return tag.RowsAffected() > 0, err
}
// StopJob cancels any in-progress job regardless of owner (admin action). Also
// frees the assigned node so it can pick up new work.
func (s *Store) StopJob(ctx context.Context, id uuid.UUID) (bool, error) {
tag, err := s.pool.Exec(ctx, `
// StopJob cancels any in-progress job regardless of owner (admin action), frees the
// assigned node, and returns the job's owner id so the caller can refund their charge.
func (s *Store) StopJob(ctx context.Context, id uuid.UUID) (bool, uuid.UUID, error) {
var ownerID uuid.UUID
err := s.pool.QueryRow(ctx, `
UPDATE render.render_jobs
SET step = 'Cancelled'::render_step, completed_at = NOW(), updated_at = NOW()
WHERE id = $1 AND step NOT IN ('Done','Failed','Cancelled')`,
id)
WHERE id = $1 AND step NOT IN ('Done','Failed','Cancelled')
RETURNING user_id`, id).Scan(&ownerID)
if err == pgx.ErrNoRows {
return false, uuid.Nil, nil
}
if err != nil {
return false, err
return false, uuid.Nil, err
}
// Release any node that was actively working this job.
_, _ = s.pool.Exec(ctx,
`UPDATE render.render_nodes SET status = 'Ready'::node_status, current_frame_job_id = NULL, updated_at = NOW()
WHERE current_frame_job_id IN (SELECT id FROM render.frame_jobs WHERE render_job_id = $1)`, id)
return tag.RowsAffected() > 0, err
return true, ownerID, nil
}
func (s *Store) GetJobProgress(ctx context.Context, id, userID uuid.UUID) (*models.RenderJob, error) {
+28 -4
View File
@@ -1,10 +1,12 @@
package handlers
import (
"log"
"net/http"
"strconv"
"github.com/flatrender/render-svc/internal/db"
"github.com/flatrender/render-svc/internal/identityclient"
"github.com/flatrender/render-svc/internal/middleware"
"github.com/flatrender/render-svc/internal/models"
"github.com/gin-gonic/gin"
@@ -12,11 +14,12 @@ import (
)
type RenderHandler struct {
store *db.Store
store *db.Store
identity *identityclient.Client
}
func NewRenderHandler(store *db.Store) *RenderHandler {
return &RenderHandler{store: store}
func NewRenderHandler(store *db.Store, identity *identityclient.Client) *RenderHandler {
return &RenderHandler{store: store, identity: identity}
}
// GET /v1/renders
@@ -61,8 +64,23 @@ func (h *RenderHandler) Create(c *gin.Context) {
c.JSON(http.StatusBadRequest, models.APIError{Code: "bad_request", Message: err.Error()})
return
}
// Daily render-limit: consume one render charge (0 max = unlimited).
allowed, err := h.identity.Consume(c.Request.Context(), userID)
if err != nil {
log.Printf("render-charge consume failed (allowing render): %v", err)
}
if !allowed {
c.JSON(http.StatusTooManyRequests, models.APIError{
Code: "daily_render_limit", Message: "سقف رندر روزانهٔ شما به پایان رسیده است.",
})
return
}
job, err := h.store.CreateJob(c.Request.Context(), userID, tenantID, &req)
if err != nil {
// Creation failed after consuming — return the charge.
_ = h.identity.Refund(c.Request.Context(), userID)
c.JSON(http.StatusInternalServerError, models.APIError{Code: "internal_error", Message: err.Error()})
return
}
@@ -138,11 +156,17 @@ func (h *RenderHandler) Stop(c *gin.Context) {
c.JSON(http.StatusBadRequest, models.APIError{Code: "bad_request", Message: "invalid job_id"})
return
}
stopped, err := h.store.StopJob(c.Request.Context(), jobID)
stopped, ownerID, err := h.store.StopJob(c.Request.Context(), jobID)
if err != nil {
c.JSON(http.StatusInternalServerError, models.APIError{Code: "internal_error", Message: err.Error()})
return
}
// Admin stop → refund the user's render charge (not their fault).
if stopped && ownerID != uuid.Nil {
if err := h.identity.Refund(c.Request.Context(), ownerID); err != nil {
log.Printf("render-charge refund failed for %s: %v", ownerID, err)
}
}
c.JSON(http.StatusOK, gin.H{"stopped": stopped})
}
@@ -0,0 +1,77 @@
// Package identityclient calls identity-svc's internal endpoints for render-charge
// consume/refund (service-to-service, shared service token).
package identityclient
import (
"bytes"
"context"
"encoding/json"
"fmt"
"net/http"
"time"
"github.com/google/uuid"
)
type Client struct {
baseURL string
token string
http *http.Client
}
func New(baseURL, token string) *Client {
return &Client{baseURL: baseURL, token: token, http: &http.Client{Timeout: 8 * time.Second}}
}
func (c *Client) configured() bool { return c.baseURL != "" }
type consumeResp struct {
Allowed bool `json:"allowed"`
Remaining int `json:"remaining"`
}
func (c *Client) post(ctx context.Context, path string, userID uuid.UUID) (*http.Response, error) {
body, _ := json.Marshal(map[string]string{"user_id": userID.String()})
req, err := http.NewRequestWithContext(ctx, http.MethodPost, c.baseURL+path, bytes.NewReader(body))
if err != nil {
return nil, err
}
req.Header.Set("Content-Type", "application/json")
req.Header.Set("X-Service-Token", c.token)
return c.http.Do(req)
}
// Consume decrements the user's daily render count. Returns whether the render is
// allowed. Fails OPEN (allowed=true) if identity is unreachable, to avoid blocking
// renders on a transient outage.
func (c *Client) Consume(ctx context.Context, userID uuid.UUID) (bool, error) {
if !c.configured() {
return true, nil
}
resp, err := c.post(ctx, "/v1/internal/render-charge/consume", userID)
if err != nil {
return true, err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return true, fmt.Errorf("consume status %d", resp.StatusCode)
}
var r consumeResp
if err := json.NewDecoder(resp.Body).Decode(&r); err != nil {
return true, err
}
return r.Allowed, nil
}
// Refund returns one render to the user's daily count (admin-stop only).
func (c *Client) Refund(ctx context.Context, userID uuid.UUID) error {
if !c.configured() {
return nil
}
resp, err := c.post(ctx, "/v1/internal/render-charge/refund", userID)
if err != nil {
return err
}
resp.Body.Close()
return nil
}