mirror of
https://github.com/seaweedfs/seaweedfs.git
synced 2026-12-06 02:57:37 +01:00
77 lines
2.0 KiB
Go
77 lines
2.0 KiB
Go
package answer
|
|
|
|
import (
|
|
"errors"
|
|
"fmt"
|
|
"io"
|
|
"net/http"
|
|
|
|
"google.golang.org/grpc/status"
|
|
)
|
|
|
|
// Present formats a recorded failure for an operator. It preserves the
|
|
// original typed status/details and error chain for protocol decisions.
|
|
func Present(err error, contract Contract) error {
|
|
if err == nil {
|
|
return nil
|
|
}
|
|
var prior *presentation
|
|
if errors.As(err, &prior) && prior.contract == contract {
|
|
return err
|
|
}
|
|
observed := EnsureEvidence(PossiblyAdmitted, err)
|
|
policy, check := PolicyOf(observed, contract)
|
|
if check != nil {
|
|
policy, fallback := Lookup(PossiblyAdmitted, ForContract(contract, Guard("unsupported_error_code")))
|
|
if fallback != nil {
|
|
policy, _ = Lookup(PossiblyAdmitted, Guard("unsupported_error_code"))
|
|
}
|
|
return &presentation{contract: contract, cause: fmt.Errorf("%w; %v", observed, check), policy: policy}
|
|
}
|
|
return &presentation{contract: contract, cause: observed, policy: policy}
|
|
}
|
|
|
|
type presentation struct {
|
|
contract Contract
|
|
cause error
|
|
policy Policy
|
|
}
|
|
|
|
func (p *presentation) Error() string {
|
|
return fmt.Sprintf("%s: %v; %s", p.policy.Code, p.cause, p.policy.Cure)
|
|
}
|
|
func (p *presentation) Unwrap() error { return p.cause }
|
|
func (p *presentation) GRPCStatus() *status.Status {
|
|
server, ok := status.FromError(p.cause)
|
|
if !ok {
|
|
return nil
|
|
}
|
|
return server
|
|
}
|
|
|
|
// DoForContract adds presentation after transport evidence exists. It does
|
|
// not turn HTTP statuses into errors: callers still own 404/409 state rules.
|
|
func DoForContract(client *http.Client, req *http.Request, phase Phase, contract Contract) (*http.Response, error) {
|
|
resp, err := DoHTTP(client, req, phase)
|
|
if err != nil {
|
|
return resp, Present(err, contract)
|
|
}
|
|
if resp != nil && resp.Body != nil {
|
|
resp.Body = &presentedBody{ReadCloser: resp.Body, contract: contract}
|
|
}
|
|
return resp, nil
|
|
}
|
|
|
|
type presentedBody struct {
|
|
io.ReadCloser
|
|
contract Contract
|
|
}
|
|
|
|
func (b *presentedBody) Read(p []byte) (int, error) {
|
|
n, err := b.ReadCloser.Read(p)
|
|
if err != nil && err != io.EOF {
|
|
err = Present(err, b.contract)
|
|
}
|
|
return n, err
|
|
}
|