Files
sless/terraform/provider/internal/client/client.go
T

423 lines
14 KiB
Go

// 2026-03-08
// client.go — HTTP-клиент для REST API sless оператора.
// Намеренно изолирован от terraform-plugin-framework — при переносе в nubes
// этот файл кладётся в internal/core/ без изменений.
// Все методы принимают ctx для правильной работы с таймаутами terraform.
package client
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"mime/multipart"
"net/http"
"os"
"path/filepath"
"time"
)
// Client — HTTP-клиент к sless operator REST API.
type Client struct {
httpClient *http.Client
endpoint string
token string
Namespace string // берётся из provider {}, пользователь не касается
}
// New создаёт клиент. endpoint — базовый URL оператора (без trailing slash).
func New(endpoint, token, namespace string) *Client {
return &Client{
httpClient: &http.Client{Timeout: 30 * time.Second},
endpoint: endpoint,
token: token,
Namespace: namespace,
}
}
// --- JSON-структуры (зеркало handler/functions.go и handler/triggers.go) ---
// FunctionRequest — тело POST/PUT /v1/namespaces/{ns}/functions[/{name}]
type FunctionRequest struct {
Name string `json:"name"`
Runtime string `json:"runtime"`
Entrypoint string `json:"entrypoint,omitempty"`
MemoryMB int32 `json:"memory_mb,omitempty"`
TimeoutSec int32 `json:"timeout_sec,omitempty"`
Env map[string]string `json:"env_vars,omitempty"`
}
// FunctionResponse — ответ GET /v1/namespaces/{ns}/functions/{name}
type FunctionResponse struct {
Name string `json:"name"`
Namespace string `json:"namespace"`
Runtime string `json:"runtime"`
Entrypoint string `json:"entrypoint"`
MemoryMB int32 `json:"memory_mb"`
TimeoutSec int32 `json:"timeout_sec"`
Env map[string]string `json:"env_vars"`
S3Bucket string `json:"s3_bucket"`
S3Key string `json:"s3_key"`
Phase string `json:"phase"`
ImageRef string `json:"image_ref"`
Message string `json:"message"`
}
// TriggerRequest — тело POST /v1/namespaces/{ns}/triggers
type TriggerRequest struct {
Name string `json:"name"`
Type string `json:"type"`
FunctionRef string `json:"function"`
Schedule string `json:"schedule,omitempty"`
// Enabled: nil = не передавать (по умолчанию true)
Enabled *bool `json:"enabled"`
}
// TriggerUpdateRequest — тело PATCH /v1/namespaces/{ns}/triggers/{name}
// Используем *bool чтобы различать nil (не передано) от false (явно выключен).
type TriggerUpdateRequest struct {
Enabled *bool `json:"enabled"`
}
// TriggerResponse — ответ GET /v1/namespaces/{ns}/triggers/{name}
type TriggerResponse struct {
Name string `json:"name"`
Namespace string `json:"namespace"`
Type string `json:"type"`
FunctionRef string `json:"function"`
Schedule string `json:"schedule"`
Enabled bool `json:"enabled"`
Active bool `json:"active"`
URL string `json:"url"`
Message string `json:"message"`
}
// --- Внутренний хелпер: выполнить JSON-запрос с Bearer-токеном ---
func (c *Client) doJSON(ctx context.Context, method, url string, body interface{}) (*http.Response, error) {
var bodyReader io.Reader
if body != nil {
data, err := json.Marshal(body)
if err != nil {
return nil, fmt.Errorf("marshal request: %w", err)
}
bodyReader = bytes.NewReader(data)
}
req, err := http.NewRequestWithContext(ctx, method, url, bodyReader)
if err != nil {
return nil, err
}
if body != nil {
req.Header.Set("Content-Type", "application/json")
}
req.Header.Set("Authorization", "Bearer "+c.token)
return c.httpClient.Do(req)
}
// --- Function CRUD ---
// CreateFunction — POST /v1/namespaces/{ns}/functions → 201
func (c *Client) CreateFunction(ctx context.Context, ns string, req FunctionRequest) (*FunctionResponse, error) {
url := fmt.Sprintf("%s/v1/namespaces/%s/functions", c.endpoint, ns)
resp, err := c.doJSON(ctx, http.MethodPost, url, req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusCreated {
body, _ := io.ReadAll(resp.Body)
return nil, fmt.Errorf("create function: status %d: %s", resp.StatusCode, body)
}
var fn FunctionResponse
return &fn, json.NewDecoder(resp.Body).Decode(&fn)
}
// GetFunction — GET /v1/namespaces/{ns}/functions/{name} → nil если 404
func (c *Client) GetFunction(ctx context.Context, ns, name string) (*FunctionResponse, error) {
url := fmt.Sprintf("%s/v1/namespaces/%s/functions/%s", c.endpoint, ns, name)
resp, err := c.doJSON(ctx, http.MethodGet, url, nil)
if err != nil {
return nil, err
}
defer resp.Body.Close()
if resp.StatusCode == http.StatusNotFound {
return nil, nil
}
if resp.StatusCode != http.StatusOK {
body, _ := io.ReadAll(resp.Body)
return nil, fmt.Errorf("get function: status %d: %s", resp.StatusCode, body)
}
var fn FunctionResponse
return &fn, json.NewDecoder(resp.Body).Decode(&fn)
}
// UpdateFunction — PUT /v1/namespaces/{ns}/functions/{name} → 200
func (c *Client) UpdateFunction(ctx context.Context, ns, name string, req FunctionRequest) (*FunctionResponse, error) {
url := fmt.Sprintf("%s/v1/namespaces/%s/functions/%s", c.endpoint, ns, name)
resp, err := c.doJSON(ctx, http.MethodPut, url, req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
body, _ := io.ReadAll(resp.Body)
return nil, fmt.Errorf("update function: status %d: %s", resp.StatusCode, body)
}
var fn FunctionResponse
return &fn, json.NewDecoder(resp.Body).Decode(&fn)
}
// DeleteFunction — DELETE /v1/namespaces/{ns}/functions/{name} → 204
func (c *Client) DeleteFunction(ctx context.Context, ns, name string) error {
url := fmt.Sprintf("%s/v1/namespaces/%s/functions/%s", c.endpoint, ns, name)
resp, err := c.doJSON(ctx, http.MethodDelete, url, nil)
if err != nil {
return err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusNoContent && resp.StatusCode != http.StatusNotFound {
body, _ := io.ReadAll(resp.Body)
return fmt.Errorf("delete function: status %d: %s", resp.StatusCode, body)
}
return nil
}
// UploadCode — POST /v1/namespaces/{ns}/functions/{name}/upload (multipart, field=code)
// После вызова оператор начинает kaniko-сборку образа.
func (c *Client) UploadCode(ctx context.Context, ns, name, zipPath string) error {
f, err := os.Open(zipPath)
if err != nil {
return fmt.Errorf("open zip %q: %w", zipPath, err)
}
defer f.Close()
var buf bytes.Buffer
mw := multipart.NewWriter(&buf)
fw, err := mw.CreateFormFile("code", filepath.Base(zipPath))
if err != nil {
return fmt.Errorf("create form file: %w", err)
}
if _, err := io.Copy(fw, f); err != nil {
return fmt.Errorf("copy zip: %w", err)
}
mw.Close()
url := fmt.Sprintf("%s/v1/namespaces/%s/functions/%s/upload", c.endpoint, ns, name)
req, err := http.NewRequestWithContext(ctx, http.MethodPost, url, &buf)
if err != nil {
return err
}
req.Header.Set("Content-Type", mw.FormDataContentType())
req.Header.Set("Authorization", "Bearer "+c.token)
resp, err := c.httpClient.Do(req)
if err != nil {
return err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
body, _ := io.ReadAll(resp.Body)
return fmt.Errorf("upload code: status %d: %s", resp.StatusCode, body)
}
return nil
}
// WaitReady опрашивает функцию каждые 5 секунд пока phase != Ready/Failed.
// Нужен после UploadCode — kaniko-сборка занимает ~1 минуту.
func (c *Client) WaitReady(ctx context.Context, ns, name string, timeout time.Duration) (*FunctionResponse, error) {
deadline := time.Now().Add(timeout)
for time.Now().Before(deadline) {
fn, err := c.GetFunction(ctx, ns, name)
if err != nil {
return nil, err
}
if fn == nil {
return nil, fmt.Errorf("function %s/%s not found while waiting", ns, name)
}
switch fn.Phase {
case "Ready":
return fn, nil
case "Failed":
return nil, fmt.Errorf("function build failed: %s", fn.Message)
}
select {
case <-ctx.Done():
return nil, ctx.Err()
case <-time.After(5 * time.Second):
}
}
return nil, fmt.Errorf("timeout waiting for function %s/%s to become Ready", ns, name)
}
// --- Trigger CRUD ---
// CreateTrigger — POST /v1/namespaces/{ns}/triggers → 201
func (c *Client) CreateTrigger(ctx context.Context, ns string, req TriggerRequest) (*TriggerResponse, error) {
url := fmt.Sprintf("%s/v1/namespaces/%s/triggers", c.endpoint, ns)
resp, err := c.doJSON(ctx, http.MethodPost, url, req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusCreated {
body, _ := io.ReadAll(resp.Body)
return nil, fmt.Errorf("create trigger: status %d: %s", resp.StatusCode, body)
}
var tr TriggerResponse
return &tr, json.NewDecoder(resp.Body).Decode(&tr)
}
// GetTrigger — GET /v1/namespaces/{ns}/triggers/{name} → nil если 404
func (c *Client) GetTrigger(ctx context.Context, ns, name string) (*TriggerResponse, error) {
url := fmt.Sprintf("%s/v1/namespaces/%s/triggers/%s", c.endpoint, ns, name)
resp, err := c.doJSON(ctx, http.MethodGet, url, nil)
if err != nil {
return nil, err
}
defer resp.Body.Close()
if resp.StatusCode == http.StatusNotFound {
return nil, nil
}
if resp.StatusCode != http.StatusOK {
body, _ := io.ReadAll(resp.Body)
return nil, fmt.Errorf("get trigger: status %d: %s", resp.StatusCode, body)
}
var tr TriggerResponse
return &tr, json.NewDecoder(resp.Body).Decode(&tr)
}
// DeleteTrigger — DELETE /v1/namespaces/{ns}/triggers/{name} → 204
func (c *Client) DeleteTrigger(ctx context.Context, ns, name string) error {
url := fmt.Sprintf("%s/v1/namespaces/%s/triggers/%s", c.endpoint, ns, name)
resp, err := c.doJSON(ctx, http.MethodDelete, url, nil)
if err != nil {
return err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusNoContent && resp.StatusCode != http.StatusNotFound {
body, _ := io.ReadAll(resp.Body)
return fmt.Errorf("delete trigger: status %d: %s", resp.StatusCode, body)
}
return nil
}
// UpdateTrigger — PATCH /v1/namespaces/{ns}/triggers/{name} → 200
// Позволяет изменить enabled без пересоздания триггера.
func (c *Client) UpdateTrigger(ctx context.Context, ns, name string, req TriggerUpdateRequest) (*TriggerResponse, error) {
url := fmt.Sprintf("%s/v1/namespaces/%s/triggers/%s", c.endpoint, ns, name)
resp, err := c.doJSON(ctx, http.MethodPatch, url, req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
body, _ := io.ReadAll(resp.Body)
return nil, fmt.Errorf("update trigger: status %d: %s", resp.StatusCode, body)
}
var tr TriggerResponse
return &tr, json.NewDecoder(resp.Body).Decode(&tr)
}
// --- Job CRUD ---
// JobRequest — тело POST /v1/namespaces/{ns}/jobs
type JobRequest struct {
Name string `json:"name"`
FunctionRef string `json:"function"`
EventJSON string `json:"event_json,omitempty"`
// RunID: 0 = создать без запуска, >0 = запустить
RunID int64 `json:"run_id"`
}
// JobResponse — ответ GET /v1/namespaces/{ns}/jobs/{name}
type JobResponse struct {
Name string `json:"name"`
Namespace string `json:"namespace"`
FunctionRef string `json:"function"`
EventJSON string `json:"event_json"`
RunID int64 `json:"run_id"`
Phase string `json:"phase"`
JobName string `json:"job_name"`
StartTime string `json:"start_time"`
CompletionTime string `json:"completion_time"`
Message string `json:"message"`
}
// CreateJob — POST /v1/namespaces/{ns}/jobs → 201
func (c *Client) CreateJob(ctx context.Context, ns string, req JobRequest) (*JobResponse, error) {
url := fmt.Sprintf("%s/v1/namespaces/%s/jobs", c.endpoint, ns)
resp, err := c.doJSON(ctx, http.MethodPost, url, req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusCreated {
body, _ := io.ReadAll(resp.Body)
return nil, fmt.Errorf("create job: status %d: %s", resp.StatusCode, body)
}
var j JobResponse
return &j, json.NewDecoder(resp.Body).Decode(&j)
}
// GetJob — GET /v1/namespaces/{ns}/jobs/{name} → nil если 404
func (c *Client) GetJob(ctx context.Context, ns, name string) (*JobResponse, error) {
url := fmt.Sprintf("%s/v1/namespaces/%s/jobs/%s", c.endpoint, ns, name)
resp, err := c.doJSON(ctx, http.MethodGet, url, nil)
if err != nil {
return nil, err
}
defer resp.Body.Close()
if resp.StatusCode == http.StatusNotFound {
return nil, nil
}
if resp.StatusCode != http.StatusOK {
body, _ := io.ReadAll(resp.Body)
return nil, fmt.Errorf("get job: status %d: %s", resp.StatusCode, body)
}
var j JobResponse
return &j, json.NewDecoder(resp.Body).Decode(&j)
}
// DeleteJob — DELETE /v1/namespaces/{ns}/jobs/{name} → 204
func (c *Client) DeleteJob(ctx context.Context, ns, name string) error {
url := fmt.Sprintf("%s/v1/namespaces/%s/jobs/%s", c.endpoint, ns, name)
resp, err := c.doJSON(ctx, http.MethodDelete, url, nil)
if err != nil {
return err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusNoContent && resp.StatusCode != http.StatusNotFound {
body, _ := io.ReadAll(resp.Body)
return fmt.Errorf("delete job: status %d: %s", resp.StatusCode, body)
}
return nil
}
// WaitJobDone опрашивает job каждые 5 секунд пока phase не Succeeded или Failed.
// Блокирует terraform apply до завершения джоба.
func (c *Client) WaitJobDone(ctx context.Context, ns, name string, timeout time.Duration) (*JobResponse, error) {
deadline := time.Now().Add(timeout)
for time.Now().Before(deadline) {
j, err := c.GetJob(ctx, ns, name)
if err != nil {
return nil, err
}
if j == nil {
return nil, fmt.Errorf("job %s/%s not found while waiting", ns, name)
}
switch j.Phase {
case "Succeeded":
return j, nil
case "Failed":
return nil, fmt.Errorf("job failed: %s", j.Message)
}
select {
case <-ctx.Done():
return nil, ctx.Err()
case <-time.After(5 * time.Second):
}
}
return nil, fmt.Errorf("timeout waiting for job %s/%s to complete", ns, name)
}