Files
sless/examples/POSTGRES/code/go-counter-atomic/handler.go
T
Naeel b86ff3a62e feat(service): timeout_sec без дефолта; 0=нет таймаута; operator v0.1.48
- api/v1alpha1/service_types.go: убрать +kubebuilder:default=30
- invoke.go: TimeoutSec=0 → &http.Client{} (без таймаута)
- services.go: валидация timeout_sec < 0 || > 900 → HTTP 400
- service_resource.go: TF schema Optional (без Computed); 0 → Int64Null()
- deployments/k8s/operator.yaml: v0.1.47 → v0.1.48
- doc/: progress.md + api/design.md (модель Service) + decisions/log.md
- examples/POSTGRES/: bug_hunter.sh, chaos_marathon.sh, chaos_marathon.tf
2026-03-21 16:58:43 +03:00

56 lines
1.6 KiB
Go

// 2026-03-21 — go-counter-atomic: считает вызовы через atomic в памяти + пишет в PG.
// Тестирует: in-memory state между вызовами (Go pod остаётся живым), + PG INSERT на каждый вызов.
package handler
import (
"context"
"fmt"
"os"
"sync/atomic"
"time"
"github.com/jackc/pgx/v5/pgxpool"
)
// invocations считается между вызовами (пока pod жив).
var invocations int64
// Handle записывает факт вызова в PG и возвращает накопленный счётчик.
func Handle(event map[string]interface{}) interface{} {
n := atomic.AddInt64(&invocations, 1)
dsn := fmt.Sprintf(
"host=%s port=%s dbname=%s user=%s password=%s sslmode=%s",
os.Getenv("PGHOST"), envOrDefault("PGPORT", "5432"),
os.Getenv("PGDATABASE"), os.Getenv("PGUSER"),
os.Getenv("PGPASSWORD"), envOrDefault("PGSSLMODE", "require"),
)
pool, err := pgxpool.New(context.Background(), dsn)
if err != nil {
return map[string]interface{}{"invocation_n": n, "error": err.Error()}
}
defer pool.Close()
title := fmt.Sprintf("go-counter-invoke-%d-%d", n, time.Now().UnixMilli())
var id int64
err = pool.QueryRow(context.Background(),
"INSERT INTO terraform_demo_table (title) VALUES ($1) RETURNING id", title,
).Scan(&id)
if err != nil {
return map[string]interface{}{"invocation_n": n, "error": err.Error()}
}
return map[string]interface{}{
"invocation_n": n,
"inserted_id": id,
"title": title,
}
}
func envOrDefault(key, def string) string {
if v := os.Getenv(key); v != "" {
return v
}
return def
}