package nsapi import ( "errors" "fmt" "regexp" "strings" computepb "buf.build/gen/go/namespace/cloud/protocolbuffers/go/proto/namespace/cloud/compute/v1beta" "google.golang.org/grpc/codes" "google.golang.org/grpc/status" ) // ExchangeReason says why namespace refused an oidc token type ExchangeReason uint8 const ( ExchangeUntrusted ExchangeReason = iota + 1 ExchangeWorkspaceNotFound ExchangeInvalid ) // ExchangeError is a refused Client.ExchangeOIDC type ExchangeError struct { Reason ExchangeReason err error } func (e *ExchangeError) Error() string { switch e.Reason { case ExchangeUntrusted: return fmt.Sprintf("The workspace rejected the run's ID token: %s", Said(e.err)) case ExchangeWorkspaceNotFound: return fmt.Sprintf("The workspace does not exist: %s", Said(e.err)) } return fmt.Sprintf("Namespace rejected the sign-in: %s", Said(e.err)) } func (e *ExchangeError) Unwrap() error { return e.err } // CapacityKind says which limit a workspace hit type CapacityKind uint8 const ( CapacityUnknown CapacityKind = iota CapacityCPUMemory CapacityInstanceCount ) // Resources is an amount of compute in a workspace type Resources struct { VCPU int32 MemoryMiB int32 Instances int32 } // CapacityError is a workspace with no room for an instance type CapacityError struct { Kind CapacityKind Requested, Used, Limit Resources Description string err error } func (e *CapacityError) Error() string { return "The workspace is out of capacity: " + e.Said() } func (e *CapacityError) Unwrap() error { return e.err } // Said gives namespace's own words for the error func (e *CapacityError) Said() string { if e.Description != "" { return sentence(e.Description) } return Said(e.err) } // Retryable reports if the instance can fit once others end, a request above // the limit never fits func (e *CapacityError) Retryable() bool { switch e.Kind { case CapacityCPUMemory: return e.Requested.VCPU <= e.Limit.VCPU && e.Requested.MemoryMiB <= e.Limit.MemoryMiB case CapacityInstanceCount: return e.Limit.Instances > 0 } return false } // UsageLimitError is a workspace that used all its compute minutes type UsageLimitError struct { UsedComputeUnitMinutes, LimitComputeUnitMinutes int64 err error } func (e *UsageLimitError) Error() string { return fmt.Sprintf("The workspace has used %d of its %d compute unit minutes.", e.UsedComputeUnitMinutes, e.LimitComputeUnitMinutes) } func (e *UsageLimitError) Unwrap() error { return e.err } // PlatformNotAllowedError is a workspace that does not allow the requested // os and arch type PlatformNotAllowedError struct { Requested string Allowed []string err error } func (e *PlatformNotAllowedError) Error() string { return fmt.Sprintf("The workspace doesn't allow `%s` machines, only %s.", e.Requested, strings.Join(e.Allowed, ", ")) } func (e *PlatformNotAllowedError) Unwrap() error { return e.err } // NoRegionError is a platform that no region can run for the workspace type NoRegionError struct { Platform string err error } func (e *NoRegionError) Error() string { return fmt.Sprintf("No region can run `%s` machines for the workspace.", e.Platform) } func (e *NoRegionError) Unwrap() error { return e.err } // InstanceFailedError is an instance that stopped before it was ready type InstanceFailedError struct { ID InstanceID Reasons []ShutdownReason } func (e *InstanceFailedError) Error() string { if len(e.Reasons) == 0 { return fmt.Sprintf("Instance `%s` failed.", e.ID) } msgs := make([]string, len(e.Reasons)) for i, r := range e.Reasons { msgs[i] = r.String() } return fmt.Sprintf("Instance `%s` failed: %s.", e.ID, strings.Join(msgs, "; ")) } // Container reports if the named container is one of the reasons func (e *InstanceFailedError) Container(name ContainerName) bool { for _, r := range e.Reasons { if r.Container == name { return true } } return false } func (r ShutdownReason) String() string { var parts []string if r.Container != "" { parts = append(parts, "container "+string(r.Container)) } if r.ContainerFailedReason != "" { parts = append(parts, r.ContainerFailedReason) } if r.Message != "" { parts = append(parts, r.Message) } if r.ErrorCode != 0 { parts = append(parts, fmt.Sprintf("code %d", r.ErrorCode)) } if len(parts) == 0 { return "no reason given" } return strings.Join(parts, ": ") } // ShapeNotOfferedError is a machine size that namespace does not offer // // namespace gives either the vcpu counts and memory sizes it offers, or a list // of whole sizes type ShapeNotOfferedError struct { VCPUs, MemoryGB []string Sizes []string err error } func (e *ShapeNotOfferedError) Error() string { return "Namespace doesn't offer the machine: " + Said(e.err) } func (e *ShapeNotOfferedError) Unwrap() error { return e.err } // BaseImageNotFoundError is a set of selectors that no base image matches type BaseImageNotFoundError struct{ err error } func (e *BaseImageNotFoundError) Error() string { return "Namespace has no base image for the machine: " + Said(e.err) } func (e *BaseImageNotFoundError) Unwrap() error { return e.err } // ImagePullError is a container image that namespace could not pull type ImagePullError struct{ err error } func (e *ImagePullError) Error() string { return "The image couldn't be pulled: " + Said(e.err) } func (e *ImagePullError) Unwrap() error { return e.err } var ( rangeShapes = regexp.MustCompile(`invalid cpu/mem .* expected in range \(\[([0-9 ]+)\] / \[([0-9 ]+)\]\)`) listShapes = regexp.MustCompile(`invalid cpu/mem .* expected one of ([0-9x, ]+)`) ) func shapeNotOffered(msg string, err error) (*ShapeNotOfferedError, bool) { if m := rangeShapes.FindStringSubmatch(msg); m != nil { return &ShapeNotOfferedError{VCPUs: strings.Fields(m[1]), MemoryGB: strings.Fields(m[2]), err: err}, true } if m := listShapes.FindStringSubmatch(msg); m != nil { return &ShapeNotOfferedError{Sizes: strings.FieldsFunc(m[1], func(r rune) bool { return r == ',' || r == ' ' }), err: err}, true } return nil, false } // Said gives the message of a grpc error as a sentence, without the code func Said(err error) string { msg := err.Error() var st interface{ GRPCStatus() *status.Status } if errors.As(err, &st) { msg = st.GRPCStatus().Message() } for strings.HasPrefix(msg, "rpc error: ") { _, rest, ok := strings.Cut(msg, "desc = ") if !ok { break } msg = rest } return sentence(msg) } func sentence(s string) string { s = strings.TrimSpace(s) if s == "" || strings.HasSuffix(s, ".") { return s } return s + "." } var exchangeRetry = []codes.Code{codes.Unavailable, codes.DeadlineExceeded, codes.Internal} // PermissionError is a token without a grant the call needs type PermissionError struct{ err error } func (e *PermissionError) Error() string { return fmt.Sprintf("The workspace token is missing a permission: %s", Said(e.err)) } func (e *PermissionError) Unwrap() error { return e.err } func computeError(err error) error { switch status.Code(err) { case codes.PermissionDenied, codes.Unauthenticated: return &PermissionError{err: err} } return err } func exchangeError(err error) error { switch status.Code(err) { case codes.Unauthenticated, codes.PermissionDenied: return &ExchangeError{Reason: ExchangeUntrusted, err: err} case codes.NotFound: return &ExchangeError{Reason: ExchangeWorkspaceNotFound, err: err} case codes.InvalidArgument, codes.FailedPrecondition: return &ExchangeError{Reason: ExchangeInvalid, err: err} } return err } func createError(err error) error { st, ok := status.FromError(err) if !ok { return err } for _, d := range st.Details() { switch d := d.(type) { case *computepb.ResourceLimitsError: return &CapacityError{ Kind: capacityKind(d.GetKind()), Requested: resources(d.GetRequested()), Used: resources(d.GetUsed()), Limit: resources(d.GetLimits()), Description: d.GetDescription(), err: err, } case *computepb.UsageLimitsError: return &UsageLimitError{ UsedComputeUnitMinutes: d.GetUsed().GetComputeUnitMinutes(), LimitComputeUnitMinutes: d.GetLimits().GetComputeUnitMinutes(), err: err, } case *computepb.PlatformNotAllowedError: return &PlatformNotAllowedError{Requested: d.GetRequestedPlatform(), Allowed: d.GetAllowedPlatforms(), err: err} case *computepb.NoEligibleRegionError: return &NoRegionError{Platform: d.GetRequestedPlatform(), err: err} } } msg := Said(err) switch { case st.Code() == codes.InvalidArgument: if e, ok := shapeNotOffered(msg, err); ok { return e } case st.Code() == codes.NotFound && strings.Contains(msg, "image not found"): return &BaseImageNotFoundError{err: err} case strings.Contains(msg, "failed to resolve image"): return &ImagePullError{err: err} } if st.Code() == codes.ResourceExhausted { return &CapacityError{Kind: CapacityUnknown, err: err} } return computeError(err) } func capacityKind(k computepb.ResourceLimitsError_LimitKind) CapacityKind { switch k { case computepb.ResourceLimitsError_CPU_MEMORY_LIMIT: return CapacityCPUMemory case computepb.ResourceLimitsError_INSTANCE_COUNT_LIMIT: return CapacityInstanceCount } return CapacityUnknown } func resources(r *computepb.ResourceLimitsError_Resource) Resources { return Resources{VCPU: r.GetVirtualCpu(), MemoryMiB: r.GetMemoryMegabytes(), Instances: r.GetInstanceCount()} }