feat: add typed error message templates and stable replay snapshots

This commit is contained in:
2026-09-24 15:05:08 +08:00
parent 2041e7f661
commit 6e3f025aad
32 changed files with 1570 additions and 99 deletions

View File

@@ -4,20 +4,23 @@ import (
"context"
"crypto/rand"
"encoding/hex"
"encoding/json"
"errors"
apierrors "git.yuntuo.hk/k2safe/go-omni/errors"
"git.yuntuo.hk/k2safe/go-omni/httpx"
"git.yuntuo.hk/k2safe/go-omni/logx"
"net/http"
"strings"
"time"
apierrors "git.yuntuo.hk/k2safe/go-omni/errors"
"git.yuntuo.hk/k2safe/go-omni/httpx"
"git.yuntuo.hk/k2safe/go-omni/logx"
)
type StoredResponse struct {
Status int `json:"status"`
ErrorCode string `json:"errorCode,omitempty"`
Headers http.Header `json:"headers"`
Body []byte `json:"body"`
Status int `json:"status"`
ErrorCode string `json:"errorCode,omitempty"`
Failure *apierrors.Snapshot `json:"failure,omitempty"`
Headers http.Header `json:"headers"`
Body []byte `json:"body"`
}
type IdempotencyRecord struct {
Fingerprint string `json:"fingerprint"`
@@ -55,8 +58,10 @@ func (i *Idempotency) shared(c *httpx.Context, next httpx.Handler, id, fingerpri
response := record.Response
headers := response.Headers.Clone()
headers.Set("Idempotency-Replayed", "true")
if response.ErrorCode != "" {
c.RecordError(apierrors.New(response.Status, response.ErrorCode, ""))
if response.Failure != nil {
c.RecordFailure(response.Failure.ErrorValue())
} else if response.ErrorCode != "" {
c.RecordFailure(apierrors.New(response.Status, response.ErrorCode, ""))
}
return c.WriteResponse(response.Status, headers, response.Body)
}
@@ -89,13 +94,20 @@ func (i *Idempotency) shared(c *httpx.Context, next httpx.Handler, id, fingerpri
buffer.status = 200
}
if failure := child.Failure(); failure != nil {
c.RecordError(failure)
c.RecordFailure(failure)
}
var response *StoredResponse
if buffer.status < 500 && buffer.headers.Get("Set-Cookie") == "" && !strings.Contains(strings.ToLower(buffer.headers.Get("Cache-Control")), "no-store") {
response = &StoredResponse{Status: buffer.status, Headers: buffer.headers.Clone(), Body: append([]byte(nil), buffer.body.Bytes()...)}
if failure := child.Failure(); failure != nil {
response.ErrorCode = failure.Code
response.Failure = failure.Snapshot()
}
}
if response != nil && response.Failure != nil {
metadata, encodeErr := json.Marshal(response.Failure)
if encodeErr != nil || len(metadata) > i.config.MaxResponseBytes {
response = nil
}
}
if err = finish(response); err != nil {