56 lines
1.8 KiB
Go
56 lines
1.8 KiB
Go
package api
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
|
|
"go.opentelemetry.io/otel/attribute"
|
|
"go.opentelemetry.io/otel/metric"
|
|
|
|
"github.com/kanootoko/codevault/internal/db"
|
|
"github.com/kanootoko/codevault/internal/observability/metrics"
|
|
)
|
|
|
|
// StrictHandler implements StrictServerInterface.
|
|
type StrictHandler struct {
|
|
Secrets *db.SecretsRepository
|
|
Metrics metrics.ValueMetrics
|
|
}
|
|
|
|
func NewHandler(secrets *db.SecretsRepository, m metrics.ValueMetrics) *StrictHandler {
|
|
return &StrictHandler{Secrets: secrets, Metrics: m}
|
|
}
|
|
|
|
func (h *StrictHandler) GetValue(ctx context.Context, request GetValueRequestObject) (GetValueResponseObject, error) {
|
|
if request.Body == nil || request.Body.Code == "" {
|
|
return GetValue400Response{}, nil
|
|
}
|
|
|
|
value, err := h.Secrets.Get(ctx, request.Body.Code)
|
|
if errors.Is(err, db.ErrNotFound) {
|
|
h.Metrics.GetFailedTotal.Add(ctx, 1, metric.WithAttributes(attribute.String("reason", "not_found")))
|
|
return GetValue404Response{}, nil
|
|
}
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
h.Metrics.GetSuccessTotal.Add(ctx, 1, metric.WithAttributes(attribute.String("code", request.Body.Code)))
|
|
return GetValue200JSONResponse{Value: value}, nil
|
|
}
|
|
|
|
func (h *StrictHandler) SetValue(ctx context.Context, request SetValueRequestObject) (SetValueResponseObject, error) {
|
|
if request.Body == nil || request.Body.Code == "" || request.Body.Value == "" || len(request.Body.Value) > 10*1024*1024 {
|
|
h.Metrics.SetFailedTotal.Add(ctx, 1, metric.WithAttributes(attribute.String("reason", "bad_request")))
|
|
return SetValue400Response{}, nil
|
|
}
|
|
|
|
if err := h.Secrets.Set(ctx, request.Body.Code, request.Body.Value); err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
login, _ := LoginFromContext(ctx)
|
|
h.Metrics.SetSuccessTotal.Add(ctx, 1, metric.WithAttributes(attribute.String("user", login)))
|
|
return SetValue204Response{}, nil
|
|
}
|