feat: billing layer v1.3.86 — PostgreSQL statistics

- internal/billing: Store interface + pgStore (pgx/v5 pool) + NoopStore
- factory.go: NewStore() from BILLING_DSN env var (NoopStore fallback)
- Server.billing: injected into Config, initialized in main
- handleInvokeFunction: record invocation (TriggerConsole)
- invokeInternalFunction: record invocation (TriggerHTTP)
- handleCreateFunction: record event_type=create
- handleCloneFunction: record event_type=clone
- handleDeleteFunction: record event_type=delete
- table: invocations (namespace, function_name, trigger_type, duration_ms, status_code...)
- BILLING_DSN added to console.yaml
- pgx/v5 added to go.mod/go.sum
This commit is contained in:
“Naeel”
2026-05-10 08:26:42 +04:00
parent 11c90bac9e
commit aaa1b9a82d
15 changed files with 327 additions and 6 deletions
+11
View File
@@ -19,6 +19,7 @@ import (
"strings"
"time"
"fission-console/internal/billing"
"fission-console/internal/fission"
"fission-console/internal/runtime"
@@ -241,6 +242,16 @@ func (s *Server) handleCloneFunction(w http.ResponseWriter, r *http.Request, src
return
}
s.billing.RecordInvocation(billing.Invocation{
Namespace: ns,
FunctionName: req.NewName,
TriggerType: billing.TriggerEvent,
StartedAt: now,
StatusCode: http.StatusCreated,
RecordedBy: "console",
EventType: "clone",
})
writeAnyJSON(w, http.StatusCreated, map[string]any{
"name": req.NewName,
"cloned_from": srcName,
+11
View File
@@ -22,6 +22,7 @@ import (
"strings"
"time"
"fission-console/internal/billing"
"fission-console/internal/fission"
"fission-console/internal/model"
"fission-console/internal/runtime"
@@ -275,6 +276,16 @@ func (s *Server) handleCreateFunction(w http.ResponseWriter, r *http.Request) {
return
}
s.billing.RecordInvocation(billing.Invocation{
Namespace: ns,
FunctionName: req.Name,
TriggerType: billing.TriggerEvent,
StartedAt: now,
StatusCode: http.StatusCreated,
RecordedBy: "console",
EventType: "create",
})
writeAnyJSON(w, http.StatusCreated, map[string]any{
"name": req.Name,
"package": pkgName,
+11
View File
@@ -21,6 +21,7 @@ import (
"strings"
"time"
"fission-console/internal/billing"
"fission-console/internal/fission"
corev1 "k8s.io/api/core/v1"
@@ -228,6 +229,16 @@ func (s *Server) handleDeleteFunction(w http.ResponseWriter, r *http.Request, na
// (reconciler NS удалён — за FISSION_RESOURCE_NAMESPACES теперь отвечает Layer 1 NSWatcher)
s.billing.RecordInvocation(billing.Invocation{
Namespace: ns,
FunctionName: name,
TriggerType: billing.TriggerEvent,
StartedAt: time.Now(),
StatusCode: http.StatusOK,
RecordedBy: "console",
EventType: "delete",
})
writeAnyJSON(w, http.StatusOK, map[string]any{"deleted": true, "name": name, "package": pkgName})
}
+37 -2
View File
@@ -22,6 +22,7 @@ import (
"strings"
"time"
"fission-console/internal/billing"
"fission-console/internal/fission"
apierrors "k8s.io/apimachinery/pkg/api/errors"
@@ -202,9 +203,26 @@ func (s *Server) handleInvokeFunction(w http.ResponseWriter, r *http.Request, na
defer resp.Body.Close()
respBody, _ := io.ReadAll(resp.Body)
durationMS := time.Since(start).Milliseconds()
s.billing.RecordInvocation(billing.Invocation{
Namespace: ns,
FunctionName: name,
TriggerType: billing.TriggerConsole,
Route: invokeURL,
HTTPMethod: invokeMethod,
StartedAt: start,
DurationMS: durationMS,
StatusCode: resp.StatusCode,
RequestBytes: int64(len(bodyBytes)),
ResponseBytes: int64(len(respBody)),
RecordedBy: "console",
EventType: "invoke",
})
writeAnyJSON(w, http.StatusOK, map[string]any{
"status": resp.StatusCode,
"latency_ms": time.Since(start).Milliseconds(),
"latency_ms": durationMS,
"response_raw": string(respBody),
})
}
@@ -311,9 +329,26 @@ func (s *Server) invokeInternalFunction(w http.ResponseWriter, r *http.Request,
defer resp.Body.Close()
respBody, _ := io.ReadAll(resp.Body)
durationMS := time.Since(start).Milliseconds()
s.billing.RecordInvocation(billing.Invocation{
Namespace: namespace,
FunctionName: functionName,
TriggerType: billing.TriggerHTTP,
Route: extraPath,
HTTPMethod: r.Method,
StartedAt: start,
DurationMS: durationMS,
StatusCode: resp.StatusCode,
RequestBytes: int64(len(bodyBytes)),
ResponseBytes: int64(len(respBody)),
RecordedBy: "console",
EventType: "invoke",
})
writeAnyJSON(w, http.StatusOK, map[string]any{
"status": resp.StatusCode,
"latency_ms": time.Since(start).Milliseconds(),
"latency_ms": durationMS,
"response_raw": string(respBody),
})
}
+6
View File
@@ -13,6 +13,7 @@ import (
"time"
"fission-console/internal/auth"
"fission-console/internal/billing"
"fission-console/internal/cloud"
"fission-console/internal/fission"
"fission-console/ui"
@@ -59,6 +60,9 @@ type Server struct {
// nsManager управляет жизненным циклом пользовательских namespace-ов.
nsManager *cloud.NSManager
// billing — слой записи статистики вызовов. NoopStore если BILLING_DSN не задан.
billing billing.Store
}
// Config содержит все параметры для создания Server.
@@ -76,6 +80,7 @@ type Config struct {
Authenticator auth.Authenticator // слой аутентификации
LLMUrl string
LLMKey string
Billing billing.Store // слой статистики (NoopStore если не задан)
}
// NewServer создаёт и настраивает HTTP Server со всеми зависимостями.
@@ -96,6 +101,7 @@ func NewServer(cfg Config) *Server {
llmURL: cfg.LLMUrl,
llmKey: cfg.LLMKey,
nsManager: cloud.NewNSManager(cfg.Dyn),
billing: cfg.Billing,
}
}
+42
View File
@@ -0,0 +1,42 @@
// Package billing — слой записи статистики вызовов функций.
//
// Независим от типа БД: снаружи виден только интерфейс Store.
// Если BILLING_DSN не задан — работает NoopStore (тихо, не крашит).
package billing
import "time"
// TriggerType описывает источник вызова.
const (
TriggerHTTP = "http" // вызов через /fn/... снаружи
TriggerCron = "cron" // вызов по расписанию
TriggerConsole = "console" // вызов через кнопку «Вызов» в UI
TriggerEvent = "event" // lifecycle: create/delete/clone/update
)
// Invocation — одна запись о вызове или событии функции.
type Invocation struct {
Namespace string // пользовательский namespace (= пользователь)
FunctionName string // имя функции
TriggerType string // TriggerHTTP / TriggerCron / TriggerConsole / TriggerEvent
Route string // HTTP маршрут (/abc123/my-func), пусто для event
HTTPMethod string // GET/POST/... пусто для event
StartedAt time.Time // время начала
DurationMS int64 // длительность в миллисекундах (0 для event)
StatusCode int // HTTP статус ответа (0 для event)
ColdStart bool // true = первый вызов после создания/простоя
RequestBytes int64 // размер тела запроса
ResponseBytes int64 // размер тела ответа
ErrorMsg string // сообщение об ошибке, пусто если успех
RecordedBy string // "console" | "router"
EventType string // для TriggerEvent: "create" | "delete" | "clone" | "update" | "invoke"
}
// Store — интерфейс записи статистики.
// Реализации: pgStore (PostgreSQL через pgx), NoopStore (заглушка).
type Store interface {
// RecordInvocation записывает одно событие асинхронно (fire-and-forget).
RecordInvocation(inv Invocation)
// Close освобождает ресурсы (пул соединений и т.д.).
Close()
}
+23
View File
@@ -0,0 +1,23 @@
package billing
import (
"context"
"log"
"os"
)
// NewStore создаёт Store из переменной окружения BILLING_DSN.
// Если DSN пустой — возвращает NoopStore (статистика отключена, сервер работает нормально).
func NewStore() Store {
dsn := os.Getenv("BILLING_DSN")
if dsn == "" {
log.Printf("billing: BILLING_DSN not set, statistics disabled")
return NoopStore{}
}
store, err := NewPostgresStore(context.Background(), dsn)
if err != nil {
log.Printf("billing: failed to connect to PostgreSQL: %v — statistics disabled", err)
return NoopStore{}
}
return store
}
+8
View File
@@ -0,0 +1,8 @@
package billing
// NoopStore — заглушка Store, которая тихо игнорирует все записи.
// Используется когда BILLING_DSN не задан.
type NoopStore struct{}
func (NoopStore) RecordInvocation(_ Invocation) {}
func (NoopStore) Close() {}
+90
View File
@@ -0,0 +1,90 @@
package billing
import (
"context"
"log"
"time"
"github.com/jackc/pgx/v5/pgxpool"
)
// pgStore — реализация Store поверх PostgreSQL через pgx connection pool.
type pgStore struct {
pool *pgxpool.Pool
}
// NewPostgresStore создаёт Store с пулом соединений к PostgreSQL.
// dsn — строка вида postgres://user:pass@host:5432/dbname
// При ошибке подключения — возвращает ошибку, вызывающий код решает как реагировать.
func NewPostgresStore(ctx context.Context, dsn string) (Store, error) {
cfg, err := pgxpool.ParseConfig(dsn)
if err != nil {
return nil, err
}
cfg.MaxConns = 4
cfg.MinConns = 1
cfg.MaxConnIdleTime = 5 * time.Minute
pool, err := pgxpool.NewWithConfig(ctx, cfg)
if err != nil {
return nil, err
}
// Проверяем живость соединения
if err := pool.Ping(ctx); err != nil {
pool.Close()
return nil, err
}
log.Printf("billing: connected to PostgreSQL")
return &pgStore{pool: pool}, nil
}
// RecordInvocation вставляет запись асинхронно — не блокирует основной поток.
func (s *pgStore) RecordInvocation(inv Invocation) {
go func() {
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
_, err := s.pool.Exec(ctx, `
INSERT INTO invocations (
namespace, function_name, trigger_type, route, http_method,
started_at, duration_ms, status_code, cold_start,
request_bytes, response_bytes, error_msg, recorded_by, event_type
) VALUES (
$1,$2,$3,$4,$5,
$6,$7,$8,$9,
$10,$11,$12,$13,$14
)`,
inv.Namespace,
inv.FunctionName,
inv.TriggerType,
inv.Route,
inv.HTTPMethod,
inv.StartedAt,
inv.DurationMS,
inv.StatusCode,
inv.ColdStart,
inv.RequestBytes,
inv.ResponseBytes,
nullIfEmpty(inv.ErrorMsg),
inv.RecordedBy,
nullIfEmpty(inv.EventType),
)
if err != nil {
log.Printf("billing: insert invocation: %v", err)
}
}()
}
// Close закрывает пул соединений.
func (s *pgStore) Close() {
s.pool.Close()
log.Printf("billing: connection pool closed")
}
// nullIfEmpty возвращает nil для пустой строки (SQL NULL вместо пустой строки).
func nullIfEmpty(s string) interface{} {
if s == "" {
return nil
}
return s
}