Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
71 changes: 71 additions & 0 deletions pkg/capabilities/errors/error.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
package errors

import "fmt"

type ReportType int

const (
// LocalOnly The message in the error may contain sensitive node local information and should not be reported remotely.
// In addition the serialised string representation is prefixed with an identify that prevents the error
// from being accidentally or maliciously marked as remote reportable by manipulating the error string.
LocalOnly ReportType = 0

// RemoteReportable The message in the error is safe to report remotely between nodes.
RemoteReportable ReportType = 1

// ReportableUser The error is due to user error and is safe to report remotely between nodes.
ReportableUser ReportType = 2
)

type Error interface {
error

ReportType() ReportType
Code() ErrorCode
SerializeToString() string
SerializeToRemoteReportableString() string
}

type capabilityError struct {
err error
reportType ReportType
errorCode ErrorCode
}

func newError(err error, reportType ReportType, errorCode ErrorCode) Error {
return &capabilityError{
err: err,
reportType: reportType,
errorCode: errorCode,
}
}

// NewRemoteReportableError indicates that the wrapped error does not contain any node local confidential information
// and is safe to report to other nodes in the network.
func NewRemoteReportableError(err error, errorCode ErrorCode) Error {
return newError(err, RemoteReportable, errorCode)
}

// NewReportableUserError indicates that the wrapped error is due to user error and does not contain any node local confidential information
// and is safe to report to other nodes in the network.
func NewReportableUserError(err error, errorCode ErrorCode) Error {
return newError(err, ReportableUser, errorCode)
}

// NewLocalReportableError indicates that the wrapped error may contain node local confidential information
// that should not be reported to other nodes in the network. Only the error code and generic message will be reported remotely.
func NewLocalReportableError(err error, errorCode ErrorCode) Error {
return newError(err, LocalOnly, errorCode)
}

func (e *capabilityError) Error() string {
return fmt.Sprintf("[%d]%s:", e.errorCode, e.errorCode.String()) + " " + e.err.Error()
}

func (e *capabilityError) ReportType() ReportType {
return e.reportType
}

func (e *capabilityError) Code() ErrorCode {
return e.errorCode
}
167 changes: 167 additions & 0 deletions pkg/capabilities/errors/error_codes.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,167 @@
package errors

type ErrorCode uint32

// *** TODO ***
// Just use GRPC error codes? or use GRPC error codes as inspiration (as below) but customize
// to make them relevant to capabilities?, IMO latter is better as it gives the flexibility to add
// more capability specific error codes (e.g. ConsensusFailed) whilst removing those
// that are not relevant (e.g OK, Unknown,

const (
// Uncategorized indicates no appropriate error code available - the capability author should consider adding a
// code that fits better. If the error code does not exist on the receiving side, it will be treated as Uncategorized
// to ensure backwards compatibility.
Uncategorized ErrorCode = 0

// Cancelled indicates the operation was canceled (typically by the caller).
Cancelled ErrorCode = 1

// InvalidArgument indicates client specified an invalid argument.
// Note that this differs from FailedPrecondition. It indicates arguments
// that are problematic regardless of the state of the system
// (e.g., a malformed file name).
InvalidArgument ErrorCode = 2

// DeadlineExceeded means operation expired before completion.
DeadlineExceeded ErrorCode = 3

// NotFound means some requested entity (e.g., file or directory) was
// not found.
NotFound ErrorCode = 4

// AlreadyExists means an attempt to create an entity failed because one
// already exists.
AlreadyExists ErrorCode = 5

// PermissionDenied indicates the caller does not have permission to
// execute the specified operation. It must not be used for rejections
// caused by exhausting some resource (use ResourceExhausted
// instead for those errors). It must not be
// used if the caller cannot be identified (use Unauthenticated
// instead for those errors).
PermissionDenied ErrorCode = 6

// ResourceExhausted indicates some resource has been exhausted, perhaps
// a per-user quota, or perhaps the entire file system is out of space.
ResourceExhausted ErrorCode = 7

// FailedPrecondition indicates operation was rejected because the
// system is not in a state required for the operation's execution.
// For example, directory to be deleted may be non-empty, an rmdir
// operation is applied to a non-directory, etc.
//
// A litmus test that may help a service implementor in deciding
// between FailedPrecondition, Aborted, and Unavailable:
// (a) Use Unavailable if the client can retry just the failing call.
// (b) Use Aborted if the client should retry at a higher-level
// (e.g., restarting a read-modify-write sequence).
// (c) Use FailedPrecondition if the client should not retry until
// the system state has been explicitly fixed. E.g., if an "rmdir"
// fails because the directory is non-empty, FailedPrecondition
// should be returned since the client should not retry unless
// they have first fixed up the directory by deleting files from it.
// (d) Use FailedPrecondition if the client performs conditional
// REST Get/Update/Delete on a resource and the resource on the
// server does not match the condition. E.g., conflicting
// read-modify-write on the same resource.
FailedPrecondition ErrorCode = 8

// Aborted indicates the operation was aborted, typically due to a
// concurrency issue like sequencer check failures, transaction aborts,
// etc.
//
// See litmus test above for deciding between FailedPrecondition,
// Aborted, and Unavailable.
Aborted ErrorCode = 9

// OutOfRange means operation was attempted past the valid range.
// E.g., seeking or reading past end of file.
//
// Unlike InvalidArgument, this error indicates a problem that may
// be fixed if the system state changes. For example, a 32-bit file
// system will generate InvalidArgument if asked to read at an
// offset that is not in the range [0,2^32-1], but it will generate
// OutOfRange if asked to read from an offset past the current
// file size.
//
// There is a fair bit of overlap between FailedPrecondition and
// OutOfRange. We recommend using OutOfRange (the more specific
// error) when it applies so that callers who are iterating through
// a space can easily look for an OutOfRange error to detect when
// they are done.
//
// This error code will not be generated by the gRPC framework.
OutOfRange ErrorCode = 10

// Unimplemented indicates operation is not implemented or not
// supported/enabled in this service.
//
// This error code will be generated by the gRPC framework. Most
// commonly, you will see this error code when a method implementation
// is missing on the server. It can also be generated for unknown
// compression algorithms or a disagreement as to whether an RPC should
// be streaming.
Unimplemented ErrorCode = 11

// Internal errors. Means some invariants expected by underlying
// system has been broken. If you see one of these errors,
// something is very broken.
Internal ErrorCode = 12

// Unavailable indicates the service is currently unavailable.
// This is a most likely a transient condition and may be corrected
// by retrying with a backoff. Note that it is not always safe to retry
// non-idempotent operations.
//
// See litmus test above for deciding between FailedPrecondition,
// Aborted, and Unavailable.
Unavailable ErrorCode = 13

// DataLoss indicates unrecoverable data loss or corruption.
DataLoss ErrorCode = 14

// Unauthenticated indicates the request does not have valid
// authentication credentials for the operation.
Unauthenticated ErrorCode = 15

// ConsensusFailed indicates failure to reach consensus
ConsensusFailed ErrorCode = 16
)

// String returns the string representation of the ErrorCode.
func (e ErrorCode) String() string {
if s, ok := errorCodeToString[e]; ok {
return s
}
return "Unknown"
}

var errorCodeToString = map[ErrorCode]string{
Uncategorized: "Uncategorized",
Cancelled: "Cancelled",
InvalidArgument: "InvalidArgument",
DeadlineExceeded: "DeadlineExceeded",
NotFound: "NotFound",
AlreadyExists: "AlreadyExists",
PermissionDenied: "PermissionDenied",
ResourceExhausted: "ResourceExhausted",
FailedPrecondition: "FailedPrecondition",
Aborted: "Aborted",
OutOfRange: "OutOfRange",
Unimplemented: "Unimplemented",
Internal: "Internal",
Unavailable: "Unavailable",
DataLoss: "DataLoss",
Unauthenticated: "Unauthenticated",
ConsensusFailed: "ConsensusFailed",
}

// ErrorCodeFromInt returns the ErrorCode for a given int, or Uncategorized if not found.
func ErrorCodeFromInt(i uint32) ErrorCode {
code := ErrorCode(i)
if _, ok := errorCodeToString[code]; ok {
return code
}
return Uncategorized
}
83 changes: 83 additions & 0 deletions pkg/capabilities/errors/error_serialization.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
package errors

import (
"errors"
"strconv"
"strings"
)

const remoteReportableErrorIdentifier = "RemoteReportableError:"

const reportableUserErrorIdentifier = remoteReportableErrorIdentifier + "UserError:"

const localReportableErrorIdentifier = "LocalReportableError:"

const errorCodeIdentifier = "ErrorCode="

func PrePendLocalReportableErrorIdentifier(errorMessage string) string {
return localReportableErrorIdentifier + errorMessage
}

// GetErrorCode Returns the error code and removes it from the message if present.
func GetErrorCode(message string) (ErrorCode, string) {
if strings.HasPrefix(message, errorCodeIdentifier) {
rest := message[len(errorCodeIdentifier):]
colonIdx := strings.Index(rest, ":")
if colonIdx != -1 {
codeStr := rest[:colonIdx]
code, err := strconv.ParseUint(codeStr, 10, 32)
if err == nil {
return ErrorCodeFromInt(uint32(code)), rest[colonIdx+1:]
}
}
}
return Uncategorized, message
}

func DeserializeErrorFromString(errorMsg string) Error {
// Order is important here as reportable user errors also have the remote reportable error identifier.
if strings.HasPrefix(errorMsg, reportableUserErrorIdentifier) {
errorMsg = strings.TrimPrefix(errorMsg, reportableUserErrorIdentifier)
errorCode, msg := GetErrorCode(errorMsg)
return NewReportableUserError(errors.New(msg), errorCode)
}

if strings.HasPrefix(errorMsg, remoteReportableErrorIdentifier) {
msg := strings.TrimPrefix(errorMsg, remoteReportableErrorIdentifier)
errorCode, msg := GetErrorCode(msg)
return NewRemoteReportableError(errors.New(msg), errorCode)
}

if strings.HasPrefix(errorMsg, localReportableErrorIdentifier) {
msg := strings.TrimPrefix(errorMsg, localReportableErrorIdentifier)
errorCode, msg := GetErrorCode(msg)
return NewLocalReportableError(errors.New(msg), errorCode)
}

// Default to local reportable error if no identifier is found.
errorCode, errorMsg := GetErrorCode(errorMsg)
return NewLocalReportableError(errors.New(errorMsg), errorCode)
}

func (e *capabilityError) SerializeToString() string {
var prefix string
switch e.ReportType() {
case RemoteReportable:
prefix = remoteReportableErrorIdentifier
case ReportableUser:
prefix = reportableUserErrorIdentifier
case LocalOnly:
prefix = localReportableErrorIdentifier
}

return prefix + errorCodeIdentifier + strconv.Itoa(int(e.Code())) + ":" + e.err.Error()
}

func (e *capabilityError) SerializeToRemoteReportableString() string {
switch e.ReportType() {
case RemoteReportable, ReportableUser:
return e.SerializeToString()
}

return localReportableErrorIdentifier + errorCodeIdentifier + strconv.Itoa(int(e.Code())) + ": failed to execute capability - error message is not remotely reportable"
}
Loading
Loading