Documentation
¶
Overview ¶
Package expr defines expressions and data types used by the DSL and the code generators. The expressions implement the Preparer, Validator, and Finalizer interfaces. The code generators use the finalized expressions to generate the final output.
The data types defined in the expr package are primitive types corresponding to scalar values (bool, string, integers, and numbers), array types which represent a collection of items, map types which represent maps of key/value pairs, and object types describing data structures with fields. The package also defines user types which can also be a result types. A result type is a user type used to describe response messages rendered using a view.
This file wires Loom's core expressions into the Meta DSL extension points.
The `dsl.Meta` and `dsl.RemoveMeta` helpers operate on the expression returned by `eval.Current()`. Most expressions that accept metadata store it in a `MetaExpr` field. By implementing the `MetaAdder` / `MetaDeleter` interfaces on those expressions, the DSL implementation stays small and does not need to enumerate all supported expression types.
Index ¶
- Constants
- Variables
- func CanonicalIdentifier(identifier string) string
- func CanonicalizeExample(att *AttributeExpr, example any) any
- func CreateTempFile(t *testing.T, content string) string
- func DerivedUnionTypeName(names []string) string
- func DerivedUnionVariantNames(types []DataType) []string
- func Equal(dt, dt2 DataType) bool
- func ExtractHTTPWildcards(path string) []string
- func Hash(dt DataType, ignoreFields, ignoreNames, ignoreTags bool) string
- func InlineJSONSchema(attr *AttributeExpr) ([]byte, error)
- func IsAlias(dt DataType) bool
- func IsArray(dt DataType) bool
- func IsMap(dt DataType) bool
- func IsObject(dt DataType) bool
- func IsPrimitive(dt DataType) bool
- func IsUnion(dt DataType) bool
- func NewLength(a *AttributeExpr, r *ExampleGenerator) int
- func PrepareValidateFinalize(root *RootExpr) error
- func QualifiedTypeName(t DataType) string
- func RemovePkgPath(attr *AttributeExpr)
- func ResetDSL(t *testing.T)
- func RunInvalidDSL(t *testing.T, dsl func()) error
- func TaggedAttribute(a *AttributeExpr, tag string) string
- func Title(s string) string
- func UnionVariantPublicName(dt DataType) string
- func UnionVariantTag(nat *NamedAttributeExpr) string
- func UniqueStableNames(bases, stableKeys []string, suffix func(base string, ordinal int) string) []string
- func WalkMappedAttr(ma *MappedAttributeExpr, it MappedAttributeWalker) error
- type APIExpr
- type Array
- type ArrayVal
- type AttributeExpr
- func (a *AttributeExpr) AddMeta(name string, vals ...string)
- func (a *AttributeExpr) AllRequired() []string
- func (a *AttributeExpr) Debug(prefix string)
- func (a *AttributeExpr) Delete(name string)
- func (a *AttributeExpr) DeleteMeta(name string)
- func (a *AttributeExpr) EvalName() string
- func (a *AttributeExpr) Example(r *ExampleGenerator) any
- func (a *AttributeExpr) ExtractUserExamples() []*ExampleExpr
- func (a *AttributeExpr) FieldTag() (tag string, found bool)
- func (a *AttributeExpr) Finalize()
- func (a *AttributeExpr) Find(name string) *AttributeExpr
- func (a *AttributeExpr) GetDefault(attName string) any
- func (a *AttributeExpr) HasDefaultValue(attName string) bool
- func (a *AttributeExpr) HasTag(tag string) bool
- func (a *AttributeExpr) HasTagPrefix(prefix string) bool
- func (a *AttributeExpr) Inherit(parent *AttributeExpr)
- func (a *AttributeExpr) IsPrimitivePointer(attName string, useDefault bool) bool
- func (a *AttributeExpr) IsRequired(attName string) bool
- func (a *AttributeExpr) IsRequiredNoDefault(attName string) bool
- func (*AttributeExpr) IsSupportedValidationFormat(vf ValidationFormat) bool
- func (a *AttributeExpr) Merge(other *AttributeExpr)
- func (a *AttributeExpr) Prepare()
- func (a *AttributeExpr) SetDefault(def any)
- func (a *AttributeExpr) Validate(ctx string, parent eval.Expression) *eval.ValidationErrors
- type CompositeExpr
- type ContactExpr
- type CookieSameSiteValue
- type DataType
- type DescriptionHolder
- type DeterministicRandomizer
- func (DeterministicRandomizer) ArrayLength() int
- func (DeterministicRandomizer) Bool() bool
- func (DeterministicRandomizer) Characters(n int) string
- func (DeterministicRandomizer) Email() string
- func (DeterministicRandomizer) Float32() float32
- func (DeterministicRandomizer) Float64() float64
- func (DeterministicRandomizer) Hostname() string
- func (DeterministicRandomizer) IPv4Address() net.IP
- func (DeterministicRandomizer) IPv6Address() net.IP
- func (DeterministicRandomizer) Int() int
- func (DeterministicRandomizer) Int32() int32
- func (DeterministicRandomizer) Int64() int64
- func (DeterministicRandomizer) Name() string
- func (DeterministicRandomizer) String() string
- func (DeterministicRandomizer) UInt() uint
- func (DeterministicRandomizer) UInt32() uint32
- func (DeterministicRandomizer) UInt64() uint64
- func (DeterministicRandomizer) URL() string
- func (DeterministicRandomizer) UUID() string
- type DocsExpr
- type ErrorExpr
- type ErrorRemedyExpr
- type ExampleExpr
- type ExampleGenerator
- type FakerRandomizer
- func (r *FakerRandomizer) ArrayLength() int
- func (r *FakerRandomizer) Bool() bool
- func (r *FakerRandomizer) Characters(n int) string
- func (r *FakerRandomizer) Email() string
- func (r *FakerRandomizer) Float32() float32
- func (r *FakerRandomizer) Float64() float64
- func (r *FakerRandomizer) Hostname() string
- func (r *FakerRandomizer) IPv4Address() net.IP
- func (r *FakerRandomizer) IPv6Address() net.IP
- func (r *FakerRandomizer) Int() int
- func (r *FakerRandomizer) Int32() int32
- func (r *FakerRandomizer) Int64() int64
- func (r *FakerRandomizer) Name() string
- func (r *FakerRandomizer) String() string
- func (r *FakerRandomizer) UInt() uint
- func (r *FakerRandomizer) UInt32() uint32
- func (r *FakerRandomizer) UInt64() uint64
- func (r *FakerRandomizer) URL() string
- func (r *FakerRandomizer) UUID() string
- type FlowExpr
- type FlowKind
- type GRPCEndpointExpr
- type GRPCErrorExpr
- type GRPCExpr
- type GRPCResponseExpr
- type GRPCServiceExpr
- func (svc *GRPCServiceExpr) Description() string
- func (svc *GRPCServiceExpr) Endpoint(name string) *GRPCEndpointExpr
- func (svc *GRPCServiceExpr) EndpointFor(name string, m *MethodExpr) *GRPCEndpointExpr
- func (svc *GRPCServiceExpr) Error(name string) *ErrorExpr
- func (svc *GRPCServiceExpr) EvalName() string
- func (svc *GRPCServiceExpr) GRPCError(name string) *GRPCErrorExpr
- func (svc *GRPCServiceExpr) Name() string
- func (svc *GRPCServiceExpr) Prepare()
- func (svc *GRPCServiceExpr) Validate() error
- type HTTPEndpointExpr
- func (e *HTTPEndpointExpr) AddMeta(name string, value ...string)
- func (e *HTTPEndpointExpr) DeleteMeta(name string)
- func (e *HTTPEndpointExpr) Description() string
- func (e *HTTPEndpointExpr) EvalName() string
- func (e *HTTPEndpointExpr) Finalize()
- func (e *HTTPEndpointExpr) HasAbsoluteRoutes() bool
- func (e *HTTPEndpointExpr) IsJSONRPC() bool
- func (e *HTTPEndpointExpr) Name() string
- func (e *HTTPEndpointExpr) PathParams() *MappedAttributeExpr
- func (e *HTTPEndpointExpr) Prepare()
- func (e *HTTPEndpointExpr) QueryParams() *MappedAttributeExpr
- func (e *HTTPEndpointExpr) Validate() error
- type HTTPErrorExpr
- type HTTPExpr
- type HTTPFileServerExpr
- type HTTPRedirectExpr
- type HTTPResponseCookieExpr
- type HTTPResponseExpr
- func (r *HTTPResponseExpr) AddCookie(cookie *HTTPResponseCookieExpr)
- func (r *HTTPResponseExpr) AddMeta(name string, value ...string)
- func (r *HTTPResponseExpr) CurrentCookie() *HTTPResponseCookieExpr
- func (r *HTTPResponseExpr) DeleteMeta(name string)
- func (r *HTTPResponseExpr) Dup() *HTTPResponseExpr
- func (r *HTTPResponseExpr) EvalName() string
- func (r *HTTPResponseExpr) Finalize(a *HTTPEndpointExpr, svcAtt *AttributeExpr)
- func (r *HTTPResponseExpr) Prepare()
- func (r *HTTPResponseExpr) Validate(e *HTTPEndpointExpr) *eval.ValidationErrors
- type HTTPResponseLinkExpr
- type HTTPSSEExpr
- type HTTPServiceExpr
- func (s *HTTPServiceExpr) AddMeta(name string, value ...string)
- func (svc *HTTPServiceExpr) CanonicalEndpoint() *HTTPEndpointExpr
- func (s *HTTPServiceExpr) DeleteMeta(name string)
- func (svc *HTTPServiceExpr) Description() string
- func (svc *HTTPServiceExpr) Endpoint(name string) *HTTPEndpointExpr
- func (svc *HTTPServiceExpr) EndpointFor(m *MethodExpr) *HTTPEndpointExpr
- func (svc *HTTPServiceExpr) Error(name string) *ErrorExpr
- func (svc *HTTPServiceExpr) EvalName() string
- func (svc *HTTPServiceExpr) Finalize()
- func (svc *HTTPServiceExpr) FullPaths() []string
- func (svc *HTTPServiceExpr) HTTPError(name string) *HTTPErrorExpr
- func (svc *HTTPServiceExpr) Name() string
- func (svc *HTTPServiceExpr) Parent() *HTTPServiceExpr
- func (svc *HTTPServiceExpr) Prepare()
- func (svc *HTTPServiceExpr) Validate() error
- type HostExpr
- func (h *HostExpr) AddMeta(name string, value ...string)
- func (h *HostExpr) Attribute() *AttributeExpr
- func (h *HostExpr) DeleteMeta(name string)
- func (h *HostExpr) EvalName() string
- func (h *HostExpr) Finalize()
- func (h *HostExpr) HasGRPCScheme() bool
- func (h *HostExpr) HasHTTPScheme() bool
- func (h *HostExpr) Schemes() []string
- func (h *HostExpr) URIString(u URIExpr) (string, error)
- func (h *HostExpr) Validate() error
- type InlineSchema
- type InterceptorExpr
- type JSONRPCExpr
- type Kind
- type LicenseExpr
- type Map
- type MapVal
- type MappedAttributeExpr
- func (ma *MappedAttributeExpr) Attribute() *AttributeExpr
- func (ma *MappedAttributeExpr) Delete(attName string)
- func (ma *MappedAttributeExpr) ElemName(keyName string) string
- func (ma *MappedAttributeExpr) FindKey(keyName string) (string, bool)
- func (ma *MappedAttributeExpr) IsEmpty() bool
- func (ma *MappedAttributeExpr) KeyName(elemName string) string
- func (ma *MappedAttributeExpr) Map(elemName, attName string)
- func (ma *MappedAttributeExpr) Merge(other *MappedAttributeExpr)
- func (ma *MappedAttributeExpr) Remap()
- type MappedAttributeWalker
- type MetaAdder
- type MetaDeleter
- type MetaExpr
- type MethodExpr
- func (m *MethodExpr) AddMeta(name string, value ...string)
- func (m *MethodExpr) DeleteMeta(name string)
- func (m *MethodExpr) Error(name string) *ErrorExpr
- func (m *MethodExpr) EvalName() string
- func (m *MethodExpr) Finalize()
- func (m *MethodExpr) HasMixedResults() bool
- func (m *MethodExpr) IsPayloadStreaming() bool
- func (m *MethodExpr) IsResultStreaming() bool
- func (m *MethodExpr) IsStreaming() bool
- func (m *MethodExpr) Prepare()
- func (m *MethodExpr) Validate() error
- type NamedAttributeExpr
- type Object
- func (o *Object) Attribute(name string) *AttributeExpr
- func (o *Object) Delete(n string)
- func (o *Object) Example(r *ExampleGenerator) any
- func (o *Object) Hash() string
- func (*Object) IsCompatible(val any) bool
- func (*Object) Kind() Kind
- func (o *Object) Merge(other *Object) *Object
- func (*Object) Name() string
- func (o *Object) Rename(n, m string)
- func (o *Object) Set(n string, att *AttributeExpr)
- type Primitive
- type Randomizer
- type ResultTypeExpr
- func (rt *ResultTypeExpr) Dup(att *AttributeExpr) UserType
- func (rt *ResultTypeExpr) Finalize()
- func (rt *ResultTypeExpr) HasMultipleViews() bool
- func (rt *ResultTypeExpr) ID() string
- func (*ResultTypeExpr) Kind() Kind
- func (rt *ResultTypeExpr) Name() string
- func (rt *ResultTypeExpr) View(name string) *ViewExpr
- func (rt *ResultTypeExpr) ViewHasAttribute(view, attr string) bool
- type ResultTypesRoot
- type RootExpr
- func (*RootExpr) DependsOn() []eval.Root
- func (r *RootExpr) Error(name string) *ErrorExpr
- func (*RootExpr) EvalName() string
- func (r *RootExpr) Finalize()
- func (*RootExpr) Packages() []string
- func (r *RootExpr) Service(name string) *ServiceExpr
- func (r *RootExpr) UserType(name string) UserType
- func (r *RootExpr) Validate() error
- func (r *RootExpr) WalkSets(walk eval.SetWalker)
- type RouteExpr
- func (r *RouteExpr) AddMeta(name string, value ...string)
- func (r *RouteExpr) DeleteMeta(name string)
- func (r *RouteExpr) EvalName() string
- func (r *RouteExpr) FullPaths() []string
- func (r *RouteExpr) IsAbsolute() bool
- func (r *RouteExpr) Params() []string
- func (r *RouteExpr) Validate() *eval.ValidationErrors
- type SchemeExpr
- type SchemeKind
- type ScopeExpr
- type SecurityExpr
- type SecurityHolder
- type ServerExpr
- type ServiceExpr
- func (s *ServiceExpr) AddMeta(name string, value ...string)
- func (s *ServiceExpr) DeleteMeta(name string)
- func (s *ServiceExpr) Error(name string) *ErrorExpr
- func (s *ServiceExpr) EvalName() string
- func (s *ServiceExpr) Finalize()
- func (s *ServiceExpr) Hash() string
- func (s *ServiceExpr) Method(n string) *MethodExpr
- func (s *ServiceExpr) Validate() error
- type SessionAuthExpr
- type SessionTransportExpr
- type SessionTransportKind
- type StreamKind
- type TimeoutHolder
- type TitleHolder
- type TypeMap
- type URIExpr
- type URLHolder
- type Union
- type UserType
- type UserTypeExpr
- func (u *UserTypeExpr) Attribute() *AttributeExpr
- func (u *UserTypeExpr) Dup(att *AttributeExpr) UserType
- func (u *UserTypeExpr) Example(r *ExampleGenerator) any
- func (u *UserTypeExpr) Hash() string
- func (u *UserTypeExpr) ID() string
- func (u *UserTypeExpr) IsCompatible(val any) bool
- func (*UserTypeExpr) Kind() Kind
- func (u *UserTypeExpr) Name() string
- func (u *UserTypeExpr) Rename(n string)
- func (u *UserTypeExpr) SetAttribute(att *AttributeExpr)
- type UserTypeRegistry
- type Val
- type ValidationExpr
- func (v *ValidationExpr) AddRequired(required ...string)
- func (v *ValidationExpr) Debug(title, prefix, indent string)
- func (v *ValidationExpr) Dup() *ValidationExpr
- func (v *ValidationExpr) HasRequiredOnly() bool
- func (v *ValidationExpr) Merge(other *ValidationExpr)
- func (v *ValidationExpr) RemoveRequired(required string)
- func (v *ValidationExpr) Validate(ctx string, parent eval.Expression) *eval.ValidationErrors
- type ValidationFormat
- type VersionHolder
- type ViewExpr
Constants ¶
const ( // FormatDate describes RFC3339 date values. FormatDate ValidationFormat = "date" // FormatDateTime describes RFC3339 date time values. FormatDateTime ValidationFormat = "date-time" // FormatUUID describes RFC4122 UUID values. FormatUUID = "uuid" // FormatEmail describes RFC5322 email addresses. FormatEmail = "email" // FormatHostname describes RFC1035 Internet hostnames. FormatHostname = "hostname" // FormatIPv4 describes RFC2373 IPv4 address values. FormatIPv4 = "ipv4" // FormatIPv6 describes RFC2373 IPv6 address values. FormatIPv6 = "ipv6" // FormatIP describes RFC2373 IPv4 or IPv6 address values. FormatIP = "ip" // FormatURI describes RFC3986 URI values. FormatURI = "uri" // FormatMAC describes IEEE 802 MAC-48, EUI-48 or EUI-64 MAC address values. FormatMAC = "mac" // FormatCIDR describes RFC4632 and RFC4291 CIDR notation IP address values. FormatCIDR = "cidr" // FormatRegexp describes regular expression syntax accepted by RE2. FormatRegexp = "regexp" // FormatJSON describes JSON text. FormatJSON = "json" // FormatRFC1123 describes RFC1123 date time values. FormatRFC1123 = "rfc1123" )
const ( StatusContinue = 100 // RFC 7231, 6.2.1 StatusSwitchingProtocols = 101 // RFC 7231, 6.2.2 StatusProcessing = 102 // RFC 2518, 10.1 StatusOK = 200 // RFC 7231, 6.3.1 StatusCreated = 201 // RFC 7231, 6.3.2 StatusAccepted = 202 // RFC 7231, 6.3.3 StatusNonAuthoritativeInfo = 203 // RFC 7231, 6.3.4 StatusNoContent = 204 // RFC 7231, 6.3.5 StatusResetContent = 205 // RFC 7231, 6.3.6 StatusPartialContent = 206 // RFC 7233, 4.1 StatusMultiStatus = 207 // RFC 4918, 11.1 StatusAlreadyReported = 208 // RFC 5842, 7.1 StatusIMUsed = 226 // RFC 3229, 10.4.1 StatusMultipleChoices = 300 // RFC 7231, 6.4.1 StatusMovedPermanently = 301 // RFC 7231, 6.4.2 StatusFound = 302 // RFC 7231, 6.4.3 StatusSeeOther = 303 // RFC 7231, 6.4.4 StatusNotModified = 304 // RFC 7232, 4.1 StatusUseProxy = 305 // RFC 7231, 6.4.5 StatusTemporaryRedirect = 307 // RFC 7231, 6.4.7 StatusPermanentRedirect = 308 // RFC 7538, 3 StatusBadRequest = 400 // RFC 7231, 6.5.1 StatusPaymentRequired = 402 // RFC 7231, 6.5.2 StatusForbidden = 403 // RFC 7231, 6.5.3 StatusNotFound = 404 // RFC 7231, 6.5.4 StatusMethodNotAllowed = 405 // RFC 7231, 6.5.5 StatusNotAcceptable = 406 // RFC 7231, 6.5.6 StatusProxyAuthRequired = 407 // RFC 7235, 3.2 StatusRequestTimeout = 408 // RFC 7231, 6.5.7 StatusConflict = 409 // RFC 7231, 6.5.8 StatusGone = 410 // RFC 7231, 6.5.9 StatusLengthRequired = 411 // RFC 7231, 6.5.10 StatusPreconditionFailed = 412 // RFC 7232, 4.2 StatusRequestEntityTooLarge = 413 // RFC 7231, 6.5.11 StatusRequestURITooLong = 414 // RFC 7231, 6.5.12 StatusUnsupportedMediaType = 415 // RFC 7231, 6.5.13 StatusRequestedRangeNotSatisfiable = 416 // RFC 7233, 4.4 StatusExpectationFailed = 417 // RFC 7231, 6.5.14 StatusTeapot = 418 // RFC 7168, 2.3.3 StatusUnprocessableEntity = 422 // RFC 4918, 11.2 StatusLocked = 423 // RFC 4918, 11.3 StatusFailedDependency = 424 // RFC 4918, 11.4 StatusUpgradeRequired = 426 // RFC 7231, 6.5.15 StatusPreconditionRequired = 428 // RFC 6585, 3 StatusTooManyRequests = 429 // RFC 6585, 4 StatusRequestHeaderFieldsTooLarge = 431 // RFC 6585, 5 StatusInternalServerError = 500 // RFC 7231, 6.6.1 StatusNotImplemented = 501 // RFC 7231, 6.6.2 StatusBadGateway = 502 // RFC 7231, 6.6.3 StatusGatewayTimeout = 504 // RFC 7231, 6.6.5 StatusHTTPVersionNotSupported = 505 // RFC 7231, 6.6.6 StatusVariantAlsoNegotiates = 506 // RFC 2295, 8.1 StatusInsufficientStorage = 507 // RFC 4918, 11.5 StatusLoopDetected = 508 // RFC 5842, 7.2 StatusNotExtended = 510 // RFC 2774, 7 StatusNetworkAuthenticationRequired = 511 // RFC 6585, 6 )
const ( RPCParseError = -32700 // JSON-RPC 2.0, 5.1 RPCInvalidRequest = -32600 RPCMethodNotFound = -32601 RPCInvalidParams = -32602 RPCInternalError = -32603 )
const ( // DefaultView is the name of the default result type view. DefaultView = "default" // ViewMetaKey is the key used to store the view name in the attribute meta. ViewMetaKey = "view" )
const ( // Boolean is the type for a JSON boolean. Boolean = Primitive(BooleanKind) // Int is the type for a signed integer. Int = Primitive(IntKind) // Int32 is the type for a signed 32-bit integer. Int32 = Primitive(Int32Kind) // Int64 is the type for a signed 64-bit integer. Int64 = Primitive(Int64Kind) // UInt is the type for an unsigned integer. UInt = Primitive(UIntKind) // UInt32 is the type for an unsigned 32-bit integer. UInt32 = Primitive(UInt32Kind) // UInt64 is the type for an unsigned 64-bit integer. UInt64 = Primitive(UInt64Kind) // Float32 is the type for a 32-bit floating number. Float32 = Primitive(Float32Kind) // Float64 is the type for a 64-bit floating number. Float64 = Primitive(Float64Kind) // String is the type for a JSON string. String = Primitive(StringKind) // Bytes is the type for binary data. Bytes = Primitive(BytesKind) // Any is the type for an arbitrary JSON value (any in Go). Any = Primitive(AnyKind) )
const DefaultProtoc = "protoc"
DefaultProtoc is the default command to be invoked for generating code from protobuf schemas.
Variables ¶
var ( // ErrorResultIdentifier is the result type identifier used for error // responses. ErrorResultIdentifier = "application/vnd.loom.error" // ProblemResultIdentifier is the standards-first result type identifier used // for RFC 9457-style problem responses. ProblemResultIdentifier = "application/problem+json" // ErrorResult is the built-in result type for error responses. ErrorResult = &ResultTypeExpr{ UserTypeExpr: &UserTypeExpr{ AttributeExpr: &AttributeExpr{ Type: errorResultType, Description: "Error response result type", Validation: &ValidationExpr{Required: []string{"name", "id", "message", "temporary", "timeout", "fault"}}, }, TypeName: "error", }, Identifier: ErrorResultIdentifier, Views: []*ViewExpr{errorResultView}, } // ProblemResult is the built-in result type for problem-document error // responses. ProblemResult = &ResultTypeExpr{ UserTypeExpr: &UserTypeExpr{ AttributeExpr: &AttributeExpr{ Type: problemResultType, Description: "Problem response result type", Validation: &ValidationExpr{Required: []string{"code", "title", "detail"}}, }, TypeName: "problem", }, Identifier: ProblemResultIdentifier, Views: []*ViewExpr{problemResultView}, } )
var Empty = &UserTypeExpr{ TypeName: "Empty", AttributeExpr: &AttributeExpr{ Description: "Empty represents empty values", Type: &Object{}, }, }
Empty represents empty values.
var GeneratedResultTypes = new(ResultTypesRoot)
GeneratedResultTypes records the generated result types and is a DSL root evaluated after Root.
var HTTPWildcardRegex = regexp.MustCompile(`/{\*?([a-zA-Z0-9_]+)}`)
HTTPWildcardRegex is the regular expression used to capture path parameters.
var Root = new(RootExpr)
Root is the root object built by the DSL.
Functions ¶
func CanonicalIdentifier ¶
CanonicalIdentifier returns the result type identifier sans suffix which is what the DSL uses to store and lookup result types.
func CanonicalizeExample ¶
func CanonicalizeExample(att *AttributeExpr, example any) any
CanonicalizeExample normalizes example values so Loom unions use their canonical discriminator/value JSON shape.
func CreateTempFile ¶
CreateTempFile creates a temporary file and writes the given content. It is used only for testing.
func DerivedUnionTypeName ¶
DerivedUnionTypeName returns the deterministic type name for a derived union given the already-derived variant names.
func DerivedUnionVariantNames ¶
DerivedUnionVariantNames returns deterministic discriminator names for the given union variant data types.
func Equal ¶
Equal compares the types recursively and returns true if they are equal. Two types are equal if:
- both types have the same kind
- array types have elements whose types are equal
- map types have keys and elements whose types are equal
- objects have the same attribute names and the attribute types are equal
Note: calling Equal is not equivalent to evaluating dt.Hash() == dt2.Hash() as the former may return true for two user types with different names and thus with different hash values.
func ExtractHTTPWildcards ¶
ExtractHTTPWildcards returns the names of the wildcards that appear in a HTTP path.
func Hash ¶
Hash returns a hash value for the given data type. Two types have the same hash if:
- both types have the same kind
- array types have elements whose types have the same hash
- map types have keys and elements whose types have the same hash
- user types have the same name if ignoreNames is false or ignoreFields is true
- user types have the same attribute names and the attribute types have the same hash if ignoreFields is false
- object attributes have the same "struct:field:xxx" tags if ignoreTags is false
func InlineJSONSchema ¶
func InlineJSONSchema(attr *AttributeExpr) ([]byte, error)
InlineJSONSchema returns a compact JSON Schema for the given Loom attribute. The schema is fully resolved and does not include $ref references.
func IsAlias ¶
IsAlias returns true if the data type is a user type backed by a primitive type (so call aliased type).
func IsPrimitive ¶
IsPrimitive returns true if the data type is a primitive type.
func NewLength ¶
func NewLength(a *AttributeExpr, r *ExampleGenerator) int
NewLength returns an int that validates the generator attribute length validations if any.
func PrepareValidateFinalize ¶
PrepareValidateFinalize runs prepare, validate, and finalize on the given root using an isolated evaluation context and temporary Root binding.
func QualifiedTypeName ¶
QualifiedTypeName returns the qualified type name for the given data type. The qualified type name includes the name of the type of the elements of array or map types. This is useful in reporting types in error messages, examples of qualified type names:
"array<string>" "map<string, string>" "map<string, array<int32>>"
func RemovePkgPath ¶
func RemovePkgPath(attr *AttributeExpr)
RemovePkgPath traverses the given data type and removes the "struct:pkg:path" metadata from all the user type attributes.
func ResetDSL ¶
ResetDSL resets the global expression state for testing and initializes a default API. This function should be called before running any DSL that modifies the global Root or GeneratedResultTypes variables.
Usage in tests:
func TestMyDSL(t *testing.T) {
// Option 1: Use expr.RunDSL which calls ResetDSL automatically
root := expr.RunDSL(t, func() {
Service("my-service", func() { /* ... */ })
})
// Option 2: Call ResetDSL manually when running DSL directly
expr.ResetDSL(t)
eval.Execute(myDSL, nil)
eval.RunDSL()
}
Note: RunDSL and RunInvalidDSL automatically call ResetDSL, so you only need to call it manually when executing DSL code directly.
func RunInvalidDSL ¶
RunInvalidDSL returns the error resulting from running the given DSL. It is used only in tests.
func TaggedAttribute ¶
func TaggedAttribute(a *AttributeExpr, tag string) string
TaggedAttribute returns the name of the child attribute of a with the given tag if a is an object.
func UnionVariantPublicName ¶
UnionVariantPublicName returns the stable public-facing name for the union variant data type.
func UnionVariantTag ¶
func UnionVariantTag(nat *NamedAttributeExpr) string
UnionVariantTag returns the wire discriminator value for a union branch. It prefers explicit metadata and falls back to the branch name.
func UniqueStableNames ¶
func UniqueStableNames(bases, stableKeys []string, suffix func(base string, ordinal int) string) []string
UniqueStableNames deduplicates base names using the corresponding stable keys to produce deterministic suffix assignment across runs.
func WalkMappedAttr ¶
func WalkMappedAttr(ma *MappedAttributeExpr, it MappedAttributeWalker) error
WalkMappedAttr iterates over the mapped attributes. It calls the given function giving each attribute as it iterates. WalkMappedAttr stops if there is no more attribute to iterate over or if the iterator function returns an error in which case it returns the error.
Types ¶
type APIExpr ¶
type APIExpr struct {
// DSLFunc contains the DSL used to initialize the expression.
eval.DSLFunc
// Name of API
Name string
// Title of API
Title string
// Description of API
Description string
// Version is the version of the API described by this DSL.
Version string
// Servers lists the API hosts.
Servers []*ServerExpr
// TermsOfService describes or links to the service terms of API.
TermsOfService string
// Contact provides the API users with contact information.
Contact *ContactExpr
// License describes the API license.
License *LicenseExpr
// Docs points to the API external documentation.
Docs *DocsExpr
// Meta is a list of key/value pairs.
Meta MetaExpr
// Requirements contains the security requirements that apply to
// all the API service methods. One requirement is composed of
// potentially multiple schemes. Incoming requests must validate
// at least one requirement to be authorized.
Requirements []*SecurityExpr
// SessionAuths contains the multi-transport session auth contracts that
// apply to all API service methods.
SessionAuths []*SessionAuthExpr
// ClientInterceptors is the list of API client interceptors.
ClientInterceptors []*InterceptorExpr
// ServerInterceptors is the list of API server interceptors.
ServerInterceptors []*InterceptorExpr
// HTTP contains the HTTP specific API level expressions.
HTTP *HTTPExpr
// GRPC contains the gRPC specific API level expressions.
GRPC *GRPCExpr
// JSONRPC contains the JSON-RPC specific API level expressions.
JSONRPC *JSONRPCExpr
// random generator used to build examples for the API types.
ExampleGenerator *ExampleGenerator
}
APIExpr contains the global properties for an API expression.
func NewAPIExpr ¶
NewAPIExpr initializes an API expression.
func (*APIExpr) DefaultServer ¶
func (a *APIExpr) DefaultServer() *ServerExpr
DefaultServer returns a server expression that describes a server which exposes all the services in the design and listens on localhost port 80 for HTTP requests and port 8080 for gRPC requests.
func (*APIExpr) DeleteMeta ¶
DeleteMeta removes a metadata entry from the API expression.
type Array ¶
type Array struct {
ElemType *AttributeExpr
NonNullableElems bool
}
Array is the type used to describe field arrays or repeated fields.
func (*Array) Example ¶
func (a *Array) Example(r *ExampleGenerator) any
Example generates a pseudo-random array value using the given random generator.
func (*Array) IsCompatible ¶
IsCompatible returns true if val is compatible with p.
type AttributeExpr ¶
type AttributeExpr struct {
// DSLFunc contains the DSL used to initialize the expression.
eval.DSLFunc
// Attribute type
Type DataType
// Base types if any
Bases []DataType
// Attribute reference types if any
References []DataType
// Optional description
Description string
// Docs points to external documentation
Docs *DocsExpr
// Optional validations
Validation *ValidationExpr
// Meta is a list of key/value pairs
Meta MetaExpr
// Optional member default value
DefaultValue any
// UserExample set in DSL or computed in Finalize
UserExamples []*ExampleExpr
// contains filtered or unexported fields
}
AttributeExpr defines an object field with optional description, default value and validations.
func DupAtt ¶
func DupAtt(att *AttributeExpr) *AttributeExpr
DupAtt creates a copy of the given attribute.
func UnionToObject ¶
func UnionToObject(att *AttributeExpr) *AttributeExpr
UnionToObject returns an object adequate to serialize the given union type in HTTP requests and responses. The object has two fields for the discriminator and value, with names determined by the union's Meta tags (defaulting to "Type" and "Value"). The discriminator field indicates the name of the union type, and the value field contains the JSON encoded union value.
func (*AttributeExpr) AddMeta ¶
func (a *AttributeExpr) AddMeta(name string, vals ...string)
AddMeta adds values to the meta field of the attribute.
func (*AttributeExpr) AllRequired ¶
func (a *AttributeExpr) AllRequired() []string
AllRequired returns the list of all required fields from the underlying object. This method recurses if the type is itself an attribute (i.e. a UserType, this happens with the Reference DSL for example).
func (*AttributeExpr) Debug ¶
func (a *AttributeExpr) Debug(prefix string)
Debug dumps the attribute to STDOUT in a Loom developer friendly way.
func (*AttributeExpr) Delete ¶
func (a *AttributeExpr) Delete(name string)
Delete removes an attribute with the given name. It does nothing if the attribute expression is not an object type.
func (*AttributeExpr) DeleteMeta ¶
func (a *AttributeExpr) DeleteMeta(name string)
DeleteMeta removes the metadata entry with the given name.
func (*AttributeExpr) EvalName ¶
func (a *AttributeExpr) EvalName() string
EvalName returns the name used by the DSL evaluation.
func (*AttributeExpr) Example ¶
func (a *AttributeExpr) Example(r *ExampleGenerator) any
Example returns the example set on the attribute at design time. If there isn't such a value then Example computes a random value for the attribute using the given random value producer.
func (*AttributeExpr) ExtractUserExamples ¶
func (a *AttributeExpr) ExtractUserExamples() []*ExampleExpr
ExtractUserExamples return the examples defined in the design directly on the attribute or on its type.
func (*AttributeExpr) FieldTag ¶
func (a *AttributeExpr) FieldTag() (tag string, found bool)
FieldTag returns the field tag if the attribute is a field.
func (*AttributeExpr) Finalize ¶
func (a *AttributeExpr) Finalize()
Finalize merges base and reference type attributes and finalizes the Type attribute.
func (*AttributeExpr) Find ¶
func (a *AttributeExpr) Find(name string) *AttributeExpr
Find finds a child attribute with the given name in the attribute and its bases and references. If the parent attribute is not an object, it returns nil.
func (*AttributeExpr) GetDefault ¶
func (a *AttributeExpr) GetDefault(attName string) any
GetDefault gets the default value for the child attribute with the given name. It returns nil if the child attribute with the given name does not exist or if the child attribute does not have a default value.
func (*AttributeExpr) HasDefaultValue ¶
func (a *AttributeExpr) HasDefaultValue(attName string) bool
HasDefaultValue returns true if the attribute with the given name has a default value.
func (*AttributeExpr) HasTag ¶
func (a *AttributeExpr) HasTag(tag string) bool
HasTag returns true if the attribute is an object that has an attribute with the given tag.
func (*AttributeExpr) HasTagPrefix ¶
func (a *AttributeExpr) HasTagPrefix(prefix string) bool
HasTagPrefix returns true if the attribute is an object that has an attribute with the given tag prefix.
func (*AttributeExpr) Inherit ¶
func (a *AttributeExpr) Inherit(parent *AttributeExpr)
Inherit merges the properties of existing target type attributes with the argument's. The algorithm is recursive so that child attributes are also merged.
func (*AttributeExpr) IsPrimitivePointer ¶
func (a *AttributeExpr) IsPrimitivePointer(attName string, useDefault bool) bool
IsPrimitivePointer returns true if the field generated for the given attribute should be a pointer to a primitive type. The receiver attribute must be an object.
If useDefault is true and the attribute has a default value then IsPrimitivePointer returns false. This makes it possible to differentiate between request types where attributes with default values should not be generated using a pointer value and response types where they should.
DefaultValue UseDefault Pointer (assuming all other conditions are true) Yes True False Yes False True No True True No False True
func (*AttributeExpr) IsRequired ¶
func (a *AttributeExpr) IsRequired(attName string) bool
IsRequired returns true if the given string matches the name of a required attribute, false otherwise. This method only applies to attributes of type Object.
func (*AttributeExpr) IsRequiredNoDefault ¶
func (a *AttributeExpr) IsRequiredNoDefault(attName string) bool
IsRequiredNoDefault returns true if the given string matches the name of a required attribute and the attribute has no default value, false otherwise. This method only applies to attributes of type Object.
func (*AttributeExpr) IsSupportedValidationFormat ¶
func (*AttributeExpr) IsSupportedValidationFormat(vf ValidationFormat) bool
IsSupportedValidationFormat checks if the validation format is supported by Loom.
func (*AttributeExpr) Merge ¶
func (a *AttributeExpr) Merge(other *AttributeExpr)
Merge merges other's attributes into a overriding attributes of a with attributes of other with identical names.
This only applies to attributes of type Object and Merge panics if the argument or the target is not of type Object.
func (*AttributeExpr) Prepare ¶
func (a *AttributeExpr) Prepare()
Prepare resolves any deferred named type references before validation.
func (*AttributeExpr) SetDefault ¶
func (a *AttributeExpr) SetDefault(def any)
SetDefault sets the default for the attribute. It also converts HashVal and ArrayVal to map and slice respectively.
func (*AttributeExpr) Validate ¶
func (a *AttributeExpr) Validate(ctx string, parent eval.Expression) *eval.ValidationErrors
Validate tests whether the attribute required fields exist. Since attributes are unaware of their context, additional context information can be provided to be used in error messages. The parent definition context is automatically added to error messages.
type CompositeExpr ¶
type CompositeExpr interface {
// Attribute returns the composite expression embedded attribute.
Attribute() *AttributeExpr
}
CompositeExpr defines a generic composite expression that contains an attribute. This makes it possible for plugins to use attributes in their own data structures.
type ContactExpr ¶
type ContactExpr struct {
// Name of the contact person/organization
Name string `json:"name,omitempty"`
// Email address of the contact person/organization
Email string `json:"email,omitempty"`
// URL pointing to the contact information
URL string `json:"url,omitempty"`
}
ContactExpr contains the API contact information.
func (*ContactExpr) EvalName ¶
func (c *ContactExpr) EvalName() string
EvalName is the qualified name of the expression.
type CookieSameSiteValue ¶
type CookieSameSiteValue string
CookieSameSiteValue is the type used to enumerate the possible cookie SameSite values.
const ( CookieSameSiteStrict CookieSameSiteValue = "strict" CookieSameSiteLax CookieSameSiteValue = "lax" CookieSameSiteNone CookieSameSiteValue = "none" CookieSameSiteDefault CookieSameSiteValue = "default" )
type DataType ¶
type DataType interface {
// Kind of data type, one of the Kind enum.
Kind() Kind
// Name returns the type name.
Name() string
// IsCompatible checks whether val has a Go type that is compatible with the data
// type.
IsCompatible(any) bool
// Example generates a pseudo-random value using the given random generator.
Example(*ExampleGenerator) any
// Hash returns a unique hash value for the instance of the type.
Hash() string
}
DataType is the common interface to all types.
type DescriptionHolder ¶
type DescriptionHolder interface {
SetDescription(string)
}
DescriptionHolder is an interface that allows expression types to receive a description. Types implementing this interface can use the Description() DSL function to set a description.
type DeterministicRandomizer ¶
type DeterministicRandomizer struct{}
DeterministicRandomizer returns hard-coded values, removing all randomness from example generation
func (DeterministicRandomizer) ArrayLength ¶
func (DeterministicRandomizer) ArrayLength() int
func (DeterministicRandomizer) Bool ¶
func (DeterministicRandomizer) Bool() bool
func (DeterministicRandomizer) Characters ¶
func (DeterministicRandomizer) Characters(n int) string
func (DeterministicRandomizer) Email ¶
func (DeterministicRandomizer) Email() string
func (DeterministicRandomizer) Float32 ¶
func (DeterministicRandomizer) Float32() float32
func (DeterministicRandomizer) Float64 ¶
func (DeterministicRandomizer) Float64() float64
func (DeterministicRandomizer) Hostname ¶
func (DeterministicRandomizer) Hostname() string
func (DeterministicRandomizer) IPv4Address ¶
func (DeterministicRandomizer) IPv4Address() net.IP
func (DeterministicRandomizer) IPv6Address ¶
func (DeterministicRandomizer) IPv6Address() net.IP
func (DeterministicRandomizer) Int ¶
func (DeterministicRandomizer) Int() int
func (DeterministicRandomizer) Int32 ¶
func (DeterministicRandomizer) Int32() int32
func (DeterministicRandomizer) Int64 ¶
func (DeterministicRandomizer) Int64() int64
func (DeterministicRandomizer) Name ¶
func (DeterministicRandomizer) Name() string
func (DeterministicRandomizer) String ¶
func (DeterministicRandomizer) String() string
func (DeterministicRandomizer) UInt ¶
func (DeterministicRandomizer) UInt() uint
func (DeterministicRandomizer) UInt32 ¶
func (DeterministicRandomizer) UInt32() uint32
func (DeterministicRandomizer) UInt64 ¶
func (DeterministicRandomizer) UInt64() uint64
func (DeterministicRandomizer) URL ¶
func (DeterministicRandomizer) URL() string
func (DeterministicRandomizer) UUID ¶
func (DeterministicRandomizer) UUID() string
type DocsExpr ¶
type DocsExpr struct {
// Description of documentation.
Description string `json:"description,omitempty"`
// URL to documentation.
URL string `json:"url,omitempty"`
}
DocsExpr points to external documentation.
type ErrorExpr ¶
type ErrorExpr struct {
// AttributeExpr is the underlying attribute.
*AttributeExpr
// Name is the unique name of the error.
Name string
// Remedy is the optional structured remediation guidance for the error.
Remedy *ErrorRemedyExpr
}
ErrorExpr defines an error response. It consists of a named attribute.
type ErrorRemedyExpr ¶
type ErrorRemedyExpr struct {
// Code is the stable remediation code consumers may use to classify the
// failure.
Code string
// SafeMessage is the safe, user-facing message to surface without leaking
// internal details.
SafeMessage string
// RetryHint is concise guidance on how to correct the request or retry the
// operation.
RetryHint string
}
ErrorRemedyExpr describes machine-consumable remediation guidance for an API error.
func (*ErrorRemedyExpr) EvalName ¶
func (*ErrorRemedyExpr) EvalName() string
EvalName returns the generic expression name used in validation errors.
func (*ErrorRemedyExpr) Validate ¶
func (r *ErrorRemedyExpr) Validate() *eval.ValidationErrors
Validate checks that a remedy, when declared, contains at least one field.
type ExampleExpr ¶
type ExampleExpr struct {
// Summary is the example short summary.
Summary string
// Description is an optional long description.
Description string
// Value is the example value.
Value any
}
ExampleExpr represents an example.
func (*ExampleExpr) EvalName ¶
func (a *ExampleExpr) EvalName() string
EvalName returns the name used by the DSL evaluation.
type ExampleGenerator ¶
type ExampleGenerator struct {
Randomizer
// contains filtered or unexported fields
}
func NewRandom ¶
func NewRandom(seed string) *ExampleGenerator
NewRandom returns a random value generator seeded from the given string value, using the faker library to generate random but realistic values.
func (*ExampleGenerator) HaveSeen ¶
func (r *ExampleGenerator) HaveSeen(typeID string, val *any)
HaveSeen stores the seen value in the randomizer, for reuse later
func (*ExampleGenerator) PreviouslySeen ¶
func (r *ExampleGenerator) PreviouslySeen(typeID string) (*any, bool)
PreviouslySeen returns the previously seen value for a given ID
type FakerRandomizer ¶
type FakerRandomizer struct {
Seed string
// contains filtered or unexported fields
}
FakerRandomizer implements the Random interface, using the Faker library.
func (*FakerRandomizer) ArrayLength ¶
func (r *FakerRandomizer) ArrayLength() int
func (*FakerRandomizer) Bool ¶
func (r *FakerRandomizer) Bool() bool
func (*FakerRandomizer) Characters ¶
func (r *FakerRandomizer) Characters(n int) string
func (*FakerRandomizer) Email ¶
func (r *FakerRandomizer) Email() string
func (*FakerRandomizer) Float32 ¶
func (r *FakerRandomizer) Float32() float32
func (*FakerRandomizer) Float64 ¶
func (r *FakerRandomizer) Float64() float64
func (*FakerRandomizer) Hostname ¶
func (r *FakerRandomizer) Hostname() string
func (*FakerRandomizer) IPv4Address ¶
func (r *FakerRandomizer) IPv4Address() net.IP
func (*FakerRandomizer) IPv6Address ¶
func (r *FakerRandomizer) IPv6Address() net.IP
func (*FakerRandomizer) Int ¶
func (r *FakerRandomizer) Int() int
func (*FakerRandomizer) Int32 ¶
func (r *FakerRandomizer) Int32() int32
func (*FakerRandomizer) Int64 ¶
func (r *FakerRandomizer) Int64() int64
func (*FakerRandomizer) Name ¶
func (r *FakerRandomizer) Name() string
func (*FakerRandomizer) String ¶
func (r *FakerRandomizer) String() string
func (*FakerRandomizer) UInt ¶
func (r *FakerRandomizer) UInt() uint
func (*FakerRandomizer) UInt32 ¶
func (r *FakerRandomizer) UInt32() uint32
func (*FakerRandomizer) UInt64 ¶
func (r *FakerRandomizer) UInt64() uint64
func (*FakerRandomizer) URL ¶
func (r *FakerRandomizer) URL() string
func (*FakerRandomizer) UUID ¶
func (r *FakerRandomizer) UUID() string
type FlowExpr ¶
type FlowExpr struct {
// Kind is the kind of flow.
Kind FlowKind
// AuthorizationURL to be used for implicit or authorizationCode
// flows.
AuthorizationURL string
// TokenURL to be used for password, clientCredentials or
// authorizationCode flows.
TokenURL string
// RefreshURL to be used for obtaining refresh token.
RefreshURL string
}
FlowExpr describes a specific OAuth2 flow.
func (*FlowExpr) Validate ¶
func (f *FlowExpr) Validate() *eval.ValidationErrors
Validate ensures that TokenURL and AuthorizationURL are valid URLs.
type FlowKind ¶
type FlowKind int
FlowKind is a type of OAuth2 flow.
const ( // AuthorizationCodeFlowKind identifies a OAuth2 authorization code // flow. AuthorizationCodeFlowKind FlowKind = iota + 1 // ImplicitFlowKind identifiers a OAuth2 implicit flow. ImplicitFlowKind // PasswordFlowKind identifies a Resource Owner Password flow. PasswordFlowKind // ClientCredentialsFlowKind identifies a OAuth Client Credentials flow. ClientCredentialsFlowKind )
type GRPCEndpointExpr ¶
type GRPCEndpointExpr struct {
eval.DSLFunc
// MethodExpr is the underlying method expression.
MethodExpr *MethodExpr
// Service is the parent service.
Service *GRPCServiceExpr
// Request is the message passed to the gRPC method.
Request *AttributeExpr
// StreamingRequest is the message passed to the gRPC method through a
// stream.
StreamingRequest *AttributeExpr
// Responses is the success gRPC response from the method.
Response *GRPCResponseExpr
// GRPCErrors is the list of all the possible error gRPC responses.
GRPCErrors []*GRPCErrorExpr
// Metadata is the metadata to be sent in a gRPC request.
Metadata *MappedAttributeExpr
// Requirements is the list of security requirements for the gRPC endpoint.
Requirements []*SecurityExpr
// Meta is a set of key/value pairs with semantic that is
// specific to each generator, see dsl.Meta.
Meta MetaExpr
}
GRPCEndpointExpr describes a gRPC endpoint. It embeds a MethodExpr and adds gRPC specific properties.
func (*GRPCEndpointExpr) Description ¶
func (e *GRPCEndpointExpr) Description() string
Description of gRPC endpoint
func (*GRPCEndpointExpr) EvalName ¶
func (e *GRPCEndpointExpr) EvalName() string
EvalName returns the generic expression name used in error messages.
func (*GRPCEndpointExpr) Finalize ¶
func (e *GRPCEndpointExpr) Finalize()
Finalize ensures the request and response attributes are initialized.
func (*GRPCEndpointExpr) Prepare ¶
func (e *GRPCEndpointExpr) Prepare()
Prepare initializes the Request and Response if nil.
func (*GRPCEndpointExpr) Validate ¶
func (e *GRPCEndpointExpr) Validate() error
Validate validates the endpoint expression by checking if the request and responses contains the "rpc:tag" in the meta. It also makes sure that there is only one response per status code.
type GRPCErrorExpr ¶
type GRPCErrorExpr struct {
// ErrorExpr is the underlying Loom design error expression.
*ErrorExpr
// Name of error to match it up with the appropriate ErrorExpr.
Name string
// Response is the corresponding gRPC response.
Response *GRPCResponseExpr
}
GRPCErrorExpr defines a gRPC error response including its name, status, and result type.
func (*GRPCErrorExpr) Dup ¶
func (e *GRPCErrorExpr) Dup() *GRPCErrorExpr
Dup creates a copy of the error expression.
func (*GRPCErrorExpr) EvalName ¶
func (e *GRPCErrorExpr) EvalName() string
EvalName returns the generic definition name used in error messages.
func (*GRPCErrorExpr) Finalize ¶
func (e *GRPCErrorExpr) Finalize(a *GRPCEndpointExpr)
Finalize looks up the corresponding method error expression.
func (*GRPCErrorExpr) Validate ¶
func (e *GRPCErrorExpr) Validate() *eval.ValidationErrors
Validate makes sure there is a error expression that matches the gRPC error expression.
type GRPCExpr ¶
type GRPCExpr struct {
// Services contains the gRPC services created by the DSL.
Services []*GRPCServiceExpr
// Errors lists the error gRPC error responses defined globally.
Errors []*GRPCErrorExpr
}
GRPCExpr contains the API level gRPC specific expressions.
func (*GRPCExpr) Service ¶
func (g *GRPCExpr) Service(name string) *GRPCServiceExpr
Service returns the service with the given name if any.
func (*GRPCExpr) ServiceFor ¶
func (g *GRPCExpr) ServiceFor(s *ServiceExpr) *GRPCServiceExpr
ServiceFor creates a new or returns the existing service definition for the given service.
type GRPCResponseExpr ¶
type GRPCResponseExpr struct {
// gRPC status code
StatusCode int
// Response description
Description string
// Response Message if any
Message *AttributeExpr
// Parent expression, one of EndpointExpr, ServiceExpr or
// RootExpr.
Parent eval.Expression
// Headers is the header metadata to be sent in the gRPC response.
Headers *MappedAttributeExpr
// Trailers is the trailer metadata to be sent in the gRPC response.
Trailers *MappedAttributeExpr
// Meta is a list of key/value pairs.
Meta MetaExpr
}
GRPCResponseExpr defines a gRPC response including its status code, result type, and metadata.
func (*GRPCResponseExpr) Dup ¶
func (r *GRPCResponseExpr) Dup() *GRPCResponseExpr
Dup creates a copy of the response expression.
func (*GRPCResponseExpr) EvalName ¶
func (r *GRPCResponseExpr) EvalName() string
EvalName returns the generic definition name used in error messages.
func (*GRPCResponseExpr) Finalize ¶
func (r *GRPCResponseExpr) Finalize(a *GRPCEndpointExpr, svcAtt *AttributeExpr)
Finalize ensures that the response message type is set. If Message DSL is used to set the response message then the message type is set by mapping the attributes to the method Result expression. If no response message set explicitly, the message is set from the method Result expression.
func (*GRPCResponseExpr) Prepare ¶
func (r *GRPCResponseExpr) Prepare()
Prepare makes sure the response message and metadata are initialized.
func (*GRPCResponseExpr) Validate ¶
func (r *GRPCResponseExpr) Validate(e *GRPCEndpointExpr) *eval.ValidationErrors
Validate checks that the response definition is consistent: its status is set and the result type definition if any is valid.
type GRPCServiceExpr ¶
type GRPCServiceExpr struct {
eval.DSLFunc
// ServiceExpr is the service expression that backs this service.
ServiceExpr *ServiceExpr
// Name of parent service if any
ParentName string
// ProtoPkg is the name of the generated protobuf package.
ProtoPkg string
// GRPCEndpoints is the list of service endpoints.
GRPCEndpoints []*GRPCEndpointExpr
// GRPCErrors lists gRPC errors that apply to all endpoints.
GRPCErrors []*GRPCErrorExpr
// Meta is a set of key/value pairs with semantic that is
// specific to each generator.
Meta MetaExpr
}
GRPCServiceExpr describes a gRPC service.
func (*GRPCServiceExpr) Description ¶
func (svc *GRPCServiceExpr) Description() string
Description of service (service)
func (*GRPCServiceExpr) Endpoint ¶
func (svc *GRPCServiceExpr) Endpoint(name string) *GRPCEndpointExpr
Endpoint returns the service endpoint with the given name or nil if there isn't one.
func (*GRPCServiceExpr) EndpointFor ¶
func (svc *GRPCServiceExpr) EndpointFor(name string, m *MethodExpr) *GRPCEndpointExpr
EndpointFor builds the endpoint for the given method.
func (*GRPCServiceExpr) Error ¶
func (svc *GRPCServiceExpr) Error(name string) *ErrorExpr
Error returns the error with the given name.
func (*GRPCServiceExpr) EvalName ¶
func (svc *GRPCServiceExpr) EvalName() string
EvalName returns the generic definition name used in error messages.
func (*GRPCServiceExpr) GRPCError ¶
func (svc *GRPCServiceExpr) GRPCError(name string) *GRPCErrorExpr
GRPCError returns the service gRPC error with given name if any.
func (*GRPCServiceExpr) Prepare ¶
func (svc *GRPCServiceExpr) Prepare()
Prepare initializes the error responses.
func (*GRPCServiceExpr) Validate ¶
func (svc *GRPCServiceExpr) Validate() error
Validate makes sure the service is valid.
type HTTPEndpointExpr ¶
type HTTPEndpointExpr struct {
eval.DSLFunc
// MethodExpr is the underlying method expression.
MethodExpr *MethodExpr
// Service is the parent service.
Service *HTTPServiceExpr
// Endpoint routes
Routes []*RouteExpr
// MapQueryParams - when not nil - indicates that the HTTP
// request query string parameters are used to build a map.
// - If the value is the empty string then the map is stored
// in the method payload (which must be of type Map)
// - If the value is a non-empty string then the map is
// stored in the payload attribute with the corresponding
// name (which must of be of type Map)
MapQueryParams *string
// Params defines the HTTP request path and query parameters.
Params *MappedAttributeExpr
// Headers defines the HTTP request headers.
Headers *MappedAttributeExpr
// Cookies defines the HTTP request cookies.
Cookies *MappedAttributeExpr
// Body describes the HTTP request body.
Body *AttributeExpr
// StreamingBody describes the body transferred through the websocket
// stream.
StreamingBody *AttributeExpr
// PayloadIDAttribute is the name of the JSON-RPC request ID
// payload attribute.
PayloadIDAttribute string
// ResultIDAttribute is the name of the JSON-RPC result ID
// result attribute.
ResultIDAttribute string
// SkipRequestBodyEncodeDecode indicates that the service method accepts
// a reader and that the client provides a reader to stream the request
// body.
SkipRequestBodyEncodeDecode bool
// SkipResponseBodyEncodeDecode indicates that the service method
// returns a reader and that the client accepts a reader to stream the
// response body.
SkipResponseBodyEncodeDecode bool
// Responses is the list of all the possible success HTTP
// responses.
Responses []*HTTPResponseExpr
// HTTPErrors is the list of all the possible error HTTP
// responses.
HTTPErrors []*HTTPErrorExpr
// Requirements contains the security requirements for the HTTP endpoint.
Requirements []*SecurityExpr
// MultipartRequest indicates that the request content type for
// the endpoint is a multipart type.
MultipartRequest bool
// FormRequest indicates that the request content type for
// the endpoint is application/x-www-form-urlencoded.
FormRequest bool
// OptionalRequestBody indicates that the endpoint accepts an empty
// request body in addition to a typed JSON request body.
OptionalRequestBody bool
// Redirect defines a redirect for the endpoint.
Redirect *HTTPRedirectExpr
// SSE defines the Server-Sent Events configuration for this endpoint if it's
// a streaming endpoint. If nil, the endpoint uses WebSockets by default or
// inherits the service-level SSE configuration if defined.
SSE *HTTPSSEExpr
// Meta is a set of key/value pairs with semantic that is
// specific to each generator, see dsl.Meta.
Meta MetaExpr
// contains filtered or unexported fields
}
HTTPEndpointExpr describes a HTTP endpoint. It embeds a MethodExpr and adds HTTP specific properties.
It defines both an HTTP endpoint and the shape of HTTP requests and responses made to that endpoint. The shape of requests is defined via "parameters", there are path parameters (i.e. portions of the URL that define parameter values), query string parameters and a payload parameter (request body).
func (*HTTPEndpointExpr) AddMeta ¶
func (e *HTTPEndpointExpr) AddMeta(name string, value ...string)
AddMeta appends metadata values to the HTTP endpoint expression.
func (*HTTPEndpointExpr) DeleteMeta ¶
func (e *HTTPEndpointExpr) DeleteMeta(name string)
DeleteMeta removes a metadata entry from the HTTP endpoint expression.
func (*HTTPEndpointExpr) Description ¶
func (e *HTTPEndpointExpr) Description() string
Description of HTTP endpoint
func (*HTTPEndpointExpr) EvalName ¶
func (e *HTTPEndpointExpr) EvalName() string
EvalName returns the generic expression name used in error messages.
func (*HTTPEndpointExpr) Finalize ¶
func (e *HTTPEndpointExpr) Finalize()
Finalize is run post DSL execution. It merges response definitions, creates implicit endpoint parameters and initializes querystring parameters. It also flattens the error responses and makes sure the error types are all user types so that the response encoding code can properly use the type to infer the response that it needs to build.
func (*HTTPEndpointExpr) HasAbsoluteRoutes ¶
func (e *HTTPEndpointExpr) HasAbsoluteRoutes() bool
HasAbsoluteRoutes returns true if all the endpoint routes are absolute.
func (*HTTPEndpointExpr) IsJSONRPC ¶
func (e *HTTPEndpointExpr) IsJSONRPC() bool
IsJSONRPC returns true if the endpoint is a JSON-RPC endpoint.
func (*HTTPEndpointExpr) PathParams ¶
func (e *HTTPEndpointExpr) PathParams() *MappedAttributeExpr
PathParams computes a mapped attribute containing the subset of e.Params that describe path parameters.
func (*HTTPEndpointExpr) Prepare ¶
func (e *HTTPEndpointExpr) Prepare()
Prepare computes the request path and query string parameters as well as the headers and body taking into account the inherited values from the service.
func (*HTTPEndpointExpr) QueryParams ¶
func (e *HTTPEndpointExpr) QueryParams() *MappedAttributeExpr
QueryParams computes a mapped attribute containing the subset of e.Params that describe query parameters.
func (*HTTPEndpointExpr) Validate ¶
func (e *HTTPEndpointExpr) Validate() error
Validate validates the endpoint expression.
type HTTPErrorExpr ¶
type HTTPErrorExpr struct {
// ErrorExpr is the underlying Loom design error expression.
*ErrorExpr
// Name of error, we need a separate copy of the name to match it
// up with the appropriate ErrorExpr.
Name string
// Response is the corresponding HTTP response.
Response *HTTPResponseExpr
}
HTTPErrorExpr defines a HTTP error response including its name, status, headers and result type.
func (*HTTPErrorExpr) Dup ¶
func (e *HTTPErrorExpr) Dup() *HTTPErrorExpr
Dup creates a copy of the error expression.
func (*HTTPErrorExpr) EvalName ¶
func (e *HTTPErrorExpr) EvalName() string
EvalName returns the generic definition name used in error messages.
func (*HTTPErrorExpr) Finalize ¶
func (e *HTTPErrorExpr) Finalize(a *HTTPEndpointExpr)
Finalize looks up the corresponding method error expression.
func (*HTTPErrorExpr) Validate ¶
func (e *HTTPErrorExpr) Validate() *eval.ValidationErrors
Validate makes sure there is a error expression that matches the HTTP error expression.
type HTTPExpr ¶
type HTTPExpr struct {
// Path is the common request path prefix to all the service
// HTTP endpoints.
Path string
// Params defines the HTTP request path and query parameters
// common to all the API endpoints.
Params *MappedAttributeExpr
// Headers defines the HTTP request headers common to to all
// the API endpoints.
Headers *MappedAttributeExpr
// Cookies defines the HTTP request cookies common to to all
// the API endpoints.
Cookies *MappedAttributeExpr
// Consumes lists the mime types supported by the API
// controllers.
Consumes []string
// Produces lists the mime types generated by the API
// controllers.
Produces []string
// Services contains the services created by the DSL.
Services []*HTTPServiceExpr
// Errors lists the error HTTP responses.
Errors []*HTTPErrorExpr
// SSE contains the Server-Sent Events configuration for all
// streaming endpoints in the API.
SSE *HTTPSSEExpr
}
HTTPExpr contains the API level HTTP specific expressions.
func (*HTTPExpr) Finalize ¶
func (h *HTTPExpr) Finalize()
Finalize initializes Consumes and Produces with defaults if not set.
func (*HTTPExpr) Service ¶
func (h *HTTPExpr) Service(name string) *HTTPServiceExpr
Service returns the service with the given name if any.
func (*HTTPExpr) ServiceFor ¶
func (h *HTTPExpr) ServiceFor(s *ServiceExpr, root *HTTPExpr) *HTTPServiceExpr
ServiceFor creates a new or returns the existing service definition for the given service.
type HTTPFileServerExpr ¶
type HTTPFileServerExpr struct {
// Service is the parent service.
Service *HTTPServiceExpr
// Description for docs
Description string
// Docs points to the service external documentation
Docs *DocsExpr
// FilePath is the file path to the static asset(s)
FilePath string
// RequestPaths is the list of HTTP paths that serve the assets.
RequestPaths []string
// Redirect defines a redirect for the endpoint.
Redirect *HTTPRedirectExpr
// Meta is a list of key/value pairs
Meta MetaExpr
}
HTTPFileServerExpr defines an endpoint that serves static assets through HTTP.
func (*HTTPFileServerExpr) AddMeta ¶
func (f *HTTPFileServerExpr) AddMeta(name string, value ...string)
AddMeta appends metadata values to the HTTP file server expression.
func (*HTTPFileServerExpr) DeleteMeta ¶
func (f *HTTPFileServerExpr) DeleteMeta(name string)
DeleteMeta removes a metadata entry from the HTTP file server expression.
func (*HTTPFileServerExpr) EvalName ¶
func (f *HTTPFileServerExpr) EvalName() string
EvalName returns the generic definition name used in error messages.
func (*HTTPFileServerExpr) Finalize ¶
func (f *HTTPFileServerExpr) Finalize()
Finalize normalizes the request path.
func (*HTTPFileServerExpr) IsDir ¶
func (f *HTTPFileServerExpr) IsDir() bool
IsDir returns true if the file server serves a directory, false otherwise.
type HTTPRedirectExpr ¶
type HTTPRedirectExpr struct {
// URL is the URL that is being redirected to.
URL string
// StatusCode is the HTTP status code.
StatusCode int
// Parent expression, one of HTTPEndpointExpr or HTTPFileServerExpr.
Parent eval.Expression
}
HTTPRedirectExpr defines an endpoint that replies to the request with a redirect.
func (*HTTPRedirectExpr) EvalName ¶
func (r *HTTPRedirectExpr) EvalName() string
EvalName returns the generic definition name used in error messages.
type HTTPResponseCookieExpr ¶
type HTTPResponseCookieExpr struct {
// MappedAttributeExpr contains the mapped result attribute for the cookie
// value.
*MappedAttributeExpr
// Path defines the cookie Path attribute.
Path string
// Domain defines the cookie Domain attribute.
Domain string
// MaxAge defines the cookie Max-Age attribute.
MaxAge string
// Secure indicates whether the cookie should include the Secure flag.
Secure bool
// HTTPOnly indicates whether the cookie should include the HttpOnly flag.
HTTPOnly bool
// SameSite defines the cookie SameSite attribute.
SameSite CookieSameSiteValue
}
HTTPResponseCookieExpr describes a single HTTP response cookie.
func NewHTTPResponseCookieExpr ¶
func NewHTTPResponseCookieExpr() *HTTPResponseCookieExpr
NewHTTPResponseCookieExpr creates an empty HTTP response cookie expression.
func (*HTTPResponseCookieExpr) Attribute ¶
func (c *HTTPResponseCookieExpr) Attribute() *AttributeExpr
Attribute returns the mapped cookie attribute.
func (*HTTPResponseCookieExpr) AttributeName ¶
func (c *HTTPResponseCookieExpr) AttributeName() string
AttributeName returns the mapped result attribute name.
func (*HTTPResponseCookieExpr) Dup ¶
func (c *HTTPResponseCookieExpr) Dup() *HTTPResponseCookieExpr
Dup creates a copy of the response cookie expression.
func (*HTTPResponseCookieExpr) HTTPName ¶
func (c *HTTPResponseCookieExpr) HTTPName() string
HTTPName returns the cookie name written on the wire.
func (*HTTPResponseCookieExpr) IsEmpty ¶
func (c *HTTPResponseCookieExpr) IsEmpty() bool
IsEmpty returns true if the cookie contains no mapped attribute.
type HTTPResponseExpr ¶
type HTTPResponseExpr struct {
// HTTP status
StatusCode int
// Response description
Description string
// Headers describe the HTTP response headers.
Headers *MappedAttributeExpr
// Cookies describe the HTTP response cookies.
Cookies []*HTTPResponseCookieExpr
// Response body if any
Body *AttributeExpr
// OpenAPIBody describes a documentation-only response body used by
// OpenAPI generation when runtime response encoding/decoding is skipped.
OpenAPIBody *AttributeExpr
// Response Content-Type header value
ContentType string
// Tag the value a field of the result must have for this
// response to be used.
Tag [2]string
// Parent expression, one of EndpointExpr, ServiceExpr or
// RootExpr.
Parent eval.Expression
// Meta is a list of key/value pairs
Meta MetaExpr
// Links describes the OpenAPI links emitted for this response.
Links []*HTTPResponseLinkExpr
// contains filtered or unexported fields
}
HTTPResponseExpr defines a HTTP response including its status code, headers and result type.
func (*HTTPResponseExpr) AddCookie ¶
func (r *HTTPResponseExpr) AddCookie(cookie *HTTPResponseCookieExpr)
AddCookie appends a response cookie to the response and marks it active for subsequent cookie attribute setters.
func (*HTTPResponseExpr) AddMeta ¶
func (r *HTTPResponseExpr) AddMeta(name string, value ...string)
AddMeta appends metadata values to the HTTP response expression.
func (*HTTPResponseExpr) CurrentCookie ¶
func (r *HTTPResponseExpr) CurrentCookie() *HTTPResponseCookieExpr
CurrentCookie returns the cookie currently configured by the DSL.
func (*HTTPResponseExpr) DeleteMeta ¶
func (r *HTTPResponseExpr) DeleteMeta(name string)
DeleteMeta removes a metadata entry from the HTTP response expression.
func (*HTTPResponseExpr) Dup ¶
func (r *HTTPResponseExpr) Dup() *HTTPResponseExpr
Dup creates a copy of the response expression.
func (*HTTPResponseExpr) EvalName ¶
func (r *HTTPResponseExpr) EvalName() string
EvalName returns the generic definition name used in error messages.
func (*HTTPResponseExpr) Finalize ¶
func (r *HTTPResponseExpr) Finalize(a *HTTPEndpointExpr, svcAtt *AttributeExpr)
Finalize sets the response result type from its type if the type is a result type and no result type is already specified.
func (*HTTPResponseExpr) Prepare ¶
func (r *HTTPResponseExpr) Prepare()
Prepare makes sure the response is initialized even if not done explicitly by
func (*HTTPResponseExpr) Validate ¶
func (r *HTTPResponseExpr) Validate(e *HTTPEndpointExpr) *eval.ValidationErrors
Validate checks that the response definition is consistent: its status is set and the result type definition if any is valid.
type HTTPResponseLinkExpr ¶
type HTTPResponseLinkExpr struct {
// Name is the published OpenAPI link key.
Name string
// Description is the optional human-readable link description.
Description string
// Operation is the target operation name. It may be either "method" for a
// method in the current service or "service.method" for an explicit target.
Operation string
// OperationRef is the explicit OpenAPI operationRef target.
OperationRef string
// Parameters maps target parameter names to OpenAPI runtime expressions.
Parameters map[string]string
// RequestBody is the optional OpenAPI runtime expression used to build the
// target request body.
RequestBody string
}
HTTPResponseLinkExpr describes an OpenAPI response link.
func (*HTTPResponseLinkExpr) EvalName ¶
func (l *HTTPResponseLinkExpr) EvalName() string
EvalName returns the generic definition name used in error messages.
func (*HTTPResponseLinkExpr) Validate ¶
func (l *HTTPResponseLinkExpr) Validate() *eval.ValidationErrors
Validate validates the response link definition.
type HTTPSSEExpr ¶
type HTTPSSEExpr struct {
// RequestIDField is the name of the attribute in the Payload type
// that provides the Last-Event-ID request header value.
// If empty, no Last-Event-ID request header is included in the request.
RequestIDField string
// DataField is the name of the attribute in the StreamingResult type
// that provides the data field for a Server-Sent Event.
// If empty, the entire StreamingResult is used as the data field.
DataField string
// IDField is the name of the attribute in the StreamingResult type
// that provides the id field for a Server-Sent Event.
// If empty, no id field is included in the event.
IDField string
// EventField is the name of the attribute in the StreamingResult type
// that provides the event field (event type) for a Server-Sent Event.
// If empty, no event field is included in the event.
EventField string
// RetryField is the name of the attribute in the StreamingResult type
// that provides the retry field for a Server-Sent Event.
// If empty, no retry field is included in the event.
RetryField string
}
HTTPSSEExpr describes a Server-Sent Events configuration for a HTTP endpoint. It defines how a streaming endpoint should use the Server-Sent Events protocol instead of WebSockets.
func (*HTTPSSEExpr) EvalName ¶
func (e *HTTPSSEExpr) EvalName() string
EvalName returns the generic expression name used in error messages.
func (*HTTPSSEExpr) Validate ¶
func (e *HTTPSSEExpr) Validate(method *MethodExpr) error
Validate validates the Server-Sent Events expression against a specific result type.
type HTTPServiceExpr ¶
type HTTPServiceExpr struct {
eval.DSLFunc
// Root is the root HTTP expression.
Root *HTTPExpr
// ServiceExpr is the service expression that backs this
// service.
ServiceExpr *ServiceExpr
// Common URL prefixes to all service endpoint HTTP requests
Paths []string
// Params defines the HTTP request path and query parameters
// common to all the service endpoints.
Params *MappedAttributeExpr
// Headers defines the HTTP request headers common to all the
// service endpoints.
Headers *MappedAttributeExpr
// Cookies defines the HTTP request cookies common to all the
// service endpoints.
Cookies *MappedAttributeExpr
// Name of parent service if any
ParentName string
// Endpoint with canonical service path
CanonicalEndpointName string
// HTTPEndpoints is the list of service endpoints.
HTTPEndpoints []*HTTPEndpointExpr
// HTTPErrors lists HTTP errors that apply to all endpoints.
HTTPErrors []*HTTPErrorExpr
// FileServers is the list of static asset serving endpoints
FileServers []*HTTPFileServerExpr
// SSE defines the Server-Sent Events configuration for all streaming endpoints
// in this service. If nil, streaming endpoints use WebSockets by default.
SSE *HTTPSSEExpr
// JSONRPCRoute is the route used for all JSON-RPC endpoints in this service.
// Only applicable to JSON-RPC services.
JSONRPCRoute *RouteExpr
// Meta is a set of key/value pairs with semantic that is
// specific to each generator.
Meta MetaExpr
}
HTTPServiceExpr describes a HTTP service. It defines both a result type and a set of endpoints that can be executed through HTTP requests. HTTPServiceExpr embeds a ServiceExpr and adds HTTP specific properties.
func NewJSONRPCHTTPService ¶
func NewJSONRPCHTTPService(service *ServiceExpr, routePath string) *HTTPServiceExpr
NewJSONRPCHTTPService builds an HTTP service expression for a synthesized JSON-RPC service. The returned service uses a single POST route for all methods and pre-initializes endpoint body and mapped attributes so transport analyzers can consume it directly.
func (*HTTPServiceExpr) AddMeta ¶
func (s *HTTPServiceExpr) AddMeta(name string, value ...string)
AddMeta appends metadata values to the HTTP service expression.
func (*HTTPServiceExpr) CanonicalEndpoint ¶
func (svc *HTTPServiceExpr) CanonicalEndpoint() *HTTPEndpointExpr
CanonicalEndpoint returns the canonical endpoint of the service if any. The canonical endpoint is used to compute hrefs to services.
func (*HTTPServiceExpr) DeleteMeta ¶
func (s *HTTPServiceExpr) DeleteMeta(name string)
DeleteMeta removes a metadata entry from the HTTP service expression.
func (*HTTPServiceExpr) Description ¶
func (svc *HTTPServiceExpr) Description() string
Description of service (service)
func (*HTTPServiceExpr) Endpoint ¶
func (svc *HTTPServiceExpr) Endpoint(name string) *HTTPEndpointExpr
Endpoint returns the service endpoint with the given name or nil if there isn't one.
func (*HTTPServiceExpr) EndpointFor ¶
func (svc *HTTPServiceExpr) EndpointFor(m *MethodExpr) *HTTPEndpointExpr
EndpointFor builds the endpoint for the given method.
func (*HTTPServiceExpr) Error ¶
func (svc *HTTPServiceExpr) Error(name string) *ErrorExpr
Error returns the error with the given name.
func (*HTTPServiceExpr) EvalName ¶
func (svc *HTTPServiceExpr) EvalName() string
EvalName returns the generic definition name used in error messages.
func (*HTTPServiceExpr) Finalize ¶
func (svc *HTTPServiceExpr) Finalize()
Finalize initializes the path if no path is set in design.
func (*HTTPServiceExpr) FullPaths ¶
func (svc *HTTPServiceExpr) FullPaths() []string
FullPaths computes the base paths to the service endpoints concatenating the API and parent service base paths as needed.
func (*HTTPServiceExpr) HTTPError ¶
func (svc *HTTPServiceExpr) HTTPError(name string) *HTTPErrorExpr
HTTPError returns the service HTTP error with given name if any.
func (*HTTPServiceExpr) Parent ¶
func (svc *HTTPServiceExpr) Parent() *HTTPServiceExpr
Parent returns the parent service if any, nil otherwise.
func (*HTTPServiceExpr) Prepare ¶
func (svc *HTTPServiceExpr) Prepare()
Prepare initializes the error responses.
func (*HTTPServiceExpr) Validate ¶
func (svc *HTTPServiceExpr) Validate() error
Validate makes sure the service is valid.
type HostExpr ¶
type HostExpr struct {
// Name of host
Name string
// Name of server that uses host.
ServerName string
// Description of host
Description string
// URIs to host if any, may contain parameter elements using
// the "{param}" syntax.
URIs []URIExpr
// Variables defines the URI variables if any.
Variables *AttributeExpr
// Meta is a set of key/value pairs.
Meta MetaExpr
}
HostExpr describes a server host.
func (*HostExpr) Attribute ¶
func (h *HostExpr) Attribute() *AttributeExpr
Attribute returns the variables attribute.
func (*HostExpr) DeleteMeta ¶
DeleteMeta removes a metadata entry from the host expression.
func (*HostExpr) HasGRPCScheme ¶
HasGRPCScheme returns true if at least one of the URIs in the host expression define "grpc" or "grpcs" scheme.
func (*HostExpr) HasHTTPScheme ¶
HasHTTPScheme returns true if at least one of the URIs in the host expression define "http" or "https" scheme.
func (*HostExpr) Schemes ¶
Schemes returns the list of transport schemes defined for the host. The possible values for the elements of the returned slice are "http", "https", "grpc" and "grpcs".
type InlineSchema ¶
type InlineSchema struct {
Type string `json:"type,omitempty"`
Description string `json:"description,omitempty"`
Examples []any `json:"examples,omitempty"`
Required []string `json:"required,omitempty"`
Properties map[string]*InlineSchema `json:"properties,omitempty"`
OneOf []*InlineSchema `json:"oneOf,omitempty"`
AnyOf []*InlineSchema `json:"anyOf,omitempty"`
Items *InlineSchema `json:"items,omitempty"`
AdditionalProperties any `json:"additionalProperties,omitempty"`
Enum []any `json:"enum,omitempty"`
Default any `json:"default,omitempty"`
Minimum *float64 `json:"minimum,omitempty"`
Maximum *float64 `json:"maximum,omitempty"`
MinLength *int `json:"minLength,omitempty"`
MaxLength *int `json:"maxLength,omitempty"`
Pattern string `json:"pattern,omitempty"`
Format string `json:"format,omitempty"`
MinItems *int `json:"minItems,omitempty"`
MaxItems *int `json:"maxItems,omitempty"`
}
InlineSchema represents a fully inlined JSON Schema document derived from a Loom attribute. It avoids $ref indirections so machine consumers can consume standalone payload and result contracts directly.
type InterceptorExpr ¶
type InterceptorExpr struct {
// Name is the name of the interceptor
Name string
// Description is the optional description of the interceptor
Description string
// ReadPayload lists the payload attribute names read by the interceptor
ReadPayload *AttributeExpr
// WritePayload lists the payload attribute names written by the interceptor
WritePayload *AttributeExpr
// ReadResult lists the result attribute names read by the interceptor
ReadResult *AttributeExpr
// WriteResult lists the result attribute names written by the interceptor
WriteResult *AttributeExpr
// ReadStreamingPayload lists the streaming payload attribute names read by the interceptor
ReadStreamingPayload *AttributeExpr
// WriteStreamingPayload lists the streaming payload attribute names written by the interceptor
WriteStreamingPayload *AttributeExpr
// ReadStreamingResult lists the streaming result attribute names read by the interceptor
ReadStreamingResult *AttributeExpr
// WriteStreamingResult lists the streaming result attribute names written by the interceptor
WriteStreamingResult *AttributeExpr
}
InterceptorExpr describes an interceptor definition in the design. Interceptors are used to inject user code into the request/response processing pipeline. There are four kinds of interceptors, in order of execution:
- client-side payload: executes after the payload is encoded and before the request is sent to the server
- server-side request: executes after the request is decoded and before the payload is sent to the service
- server-side result: executes after the service returns a result and before the response is encoded
- client-side response: executes after the response is decoded and before the result is sent to the client
func (*InterceptorExpr) EvalName ¶
func (i *InterceptorExpr) EvalName() string
EvalName returns the generic expression name used in error messages.
type JSONRPCExpr ¶
type JSONRPCExpr struct {
HTTPExpr
}
JSONRPCExpr contains the API level JSON-RPC specific expressions.
func (*JSONRPCExpr) EvalName ¶
func (*JSONRPCExpr) EvalName() string
EvalName returns the name printed in case of evaluation error.
func (*JSONRPCExpr) Prepare ¶
func (j *JSONRPCExpr) Prepare()
Prepare copies the HTTP API constructs over to the JSON-RPC API.
type Kind ¶
type Kind uint
A Kind defines the conceptual type that a DataType represents.
const ( // BooleanKind represents a boolean. BooleanKind Kind = iota + 1 // IntKind represents a signed integer. IntKind // Int32Kind represents a signed 32-bit integer. Int32Kind // Int64Kind represents a signed 64-bit integer. Int64Kind // UIntKind represents an unsigned integer. UIntKind // UInt32Kind represents an unsigned 32-bit integer. UInt32Kind // UInt64Kind represents an unsigned 64-bit integer. UInt64Kind // Float32Kind represents a 32-bit floating number. Float32Kind // Float64Kind represents a 64-bit floating number. Float64Kind // StringKind represents a string. StringKind // BytesKind represent a series of bytes (binary data). BytesKind // ArrayKind represents an array of types. ArrayKind // ObjectKind represents an object. ObjectKind // MapKind represents a dictionary. MapKind // UnionKind represents a union type. UnionKind // UserTypeKind represents a user defined type. UserTypeKind // ResultTypeKind represents a user defined result type. ResultTypeKind // AnyKind represents an unknown type. AnyKind )
type LicenseExpr ¶
type LicenseExpr struct {
// Name of license used for the API
Name string `json:"name,omitempty"`
// URL to the license used for the API
URL string `json:"url,omitempty"`
}
LicenseExpr contains the license information for the API.
func (*LicenseExpr) EvalName ¶
func (l *LicenseExpr) EvalName() string
EvalName is the qualified name of the expression.
type Map ¶
type Map struct {
KeyType *AttributeExpr
ElemType *AttributeExpr
}
Map is the type used to describe maps of fields.
func (*Map) Example ¶
func (m *Map) Example(r *ExampleGenerator) any
Example returns a random example value.
func (*Map) IsCompatible ¶
IsCompatible returns true if o describes the (Go) type of val.
type MappedAttributeExpr ¶
type MappedAttributeExpr struct {
*AttributeExpr
// contains filtered or unexported fields
}
MappedAttributeExpr is an attribute expression of type object that map the object keys to external names (e.g. HTTP header names).
func DupMappedAtt ¶
func DupMappedAtt(ma *MappedAttributeExpr) *MappedAttributeExpr
DupMappedAtt creates a deep copy of ma.
func NewEmptyMappedAttributeExpr ¶
func NewEmptyMappedAttributeExpr() *MappedAttributeExpr
NewEmptyMappedAttributeExpr creates an empty mapped attribute expression.
func NewMappedAttributeExpr ¶
func NewMappedAttributeExpr(att *AttributeExpr) *MappedAttributeExpr
NewMappedAttributeExpr instantiates a mapped attribute expression for the given attribute. The type of att must be Object.
func (*MappedAttributeExpr) Attribute ¶
func (ma *MappedAttributeExpr) Attribute() *AttributeExpr
Attribute returns the original attribute using "att:elem" format for the keys.
func (*MappedAttributeExpr) Delete ¶
func (ma *MappedAttributeExpr) Delete(attName string)
Delete removes a child attribute given its name.
func (*MappedAttributeExpr) ElemName ¶
func (ma *MappedAttributeExpr) ElemName(keyName string) string
ElemName returns the transport element name of the given object key. It returns keyName if it's a key of the mapped attribute object type. It panics if there is no mapping and keyName is not a key.
func (*MappedAttributeExpr) FindKey ¶
func (ma *MappedAttributeExpr) FindKey(keyName string) (string, bool)
FindKey finds the given key in the mapped attribute expression. If key is found, it returns the transport element name of the key and true. Otherwise, it returns an empty string and false.
func (*MappedAttributeExpr) IsEmpty ¶
func (ma *MappedAttributeExpr) IsEmpty() bool
IsEmpty returns true if the mapped attribute contains no key.
func (*MappedAttributeExpr) KeyName ¶
func (ma *MappedAttributeExpr) KeyName(elemName string) string
KeyName returns the object key of the given transport element name. It returns elemName if it's a key of the mapped attribute object type. It panics if there is no mapping and elemName is not a key.
func (*MappedAttributeExpr) Map ¶
func (ma *MappedAttributeExpr) Map(elemName, attName string)
Map records the element name of one of the child attributes. Map panics if attName is not the name of a child attribute.
func (*MappedAttributeExpr) Merge ¶
func (ma *MappedAttributeExpr) Merge(other *MappedAttributeExpr)
Merge merges other's attributes into a overriding attributes of a with attributes of other with identical names.
func (*MappedAttributeExpr) Remap ¶
func (ma *MappedAttributeExpr) Remap()
Remap recomputes the name mappings from the inner attribute. Use this if the underlying attribute is modified after the mapped attribute has been initially created.
type MappedAttributeWalker ¶
type MappedAttributeWalker func(name, elem string, a *AttributeExpr) error
MappedAttributeWalker is the type of functions given to WalkMappedAttr.
name is the name of the attribute elem the name of the corresponding transport element a is the corresponding attribute expression
type MetaAdder ¶
type MetaAdder interface {
// AddMeta appends the given values to the metadata entry identified by name.
AddMeta(name string, value ...string)
}
MetaAdder is implemented by expressions that can receive design-time metadata.
Loom's standard DSL helper `Meta(name, value...)` attaches metadata to the current expression. Most Loom core expressions store metadata directly in a `MetaExpr` field. Third-party DSLs (and plugins) may add new expression types that also want to support `Meta` without Loom needing to know about those concrete types.
An expression that implements MetaAdder opts into Loom's `Meta` DSL by providing an AddMeta implementation that:
- appends values to the existing entry for the given name, and
- preserves existing metadata for other names.
Callers should treat metadata keys and values as opaque strings; their interpretation is application-specific.
type MetaDeleter ¶
type MetaDeleter interface {
// DeleteMeta removes the metadata entry identified by name.
DeleteMeta(name string)
}
MetaDeleter is implemented by expressions that can remove design-time metadata.
Loom's standard DSL helper `RemoveMeta(name)` removes the metadata entry with the given name from the current expression.
Implementations should be a no-op when no metadata is present.
type MetaExpr ¶
MetaExpr is a set of key/value pairs
type MethodExpr ¶
type MethodExpr struct {
// DSLFunc contains the DSL used to initialize the expression.
eval.DSLFunc
// Name of method.
Name string
// Description of method for consumption by humans.
Description string
// Docs points to the method external documentation if any.
Docs *DocsExpr
// Payload attribute
Payload *AttributeExpr
// Result attribute
Result *AttributeExpr
// Errors lists the error responses.
Errors []*ErrorExpr
// Requirements contains the security requirements for the
// method. One requirement is composed of potentially multiple
// schemes. Incoming requests must validate at least one
// requirement to be authorized.
Requirements []*SecurityExpr
// SessionAuths contains the multi-transport session auth contracts that
// apply to the method.
SessionAuths []*SessionAuthExpr
// ClientInterceptors is the list of client interceptors.
ClientInterceptors []*InterceptorExpr
// ServerInterceptors is the list of server interceptors.
ServerInterceptors []*InterceptorExpr
// Service that owns method.
Service *ServiceExpr
// Meta is an arbitrary set of key/value pairs, see dsl.Meta
Meta MetaExpr
// Stream is the kind of stream (none, payload, result, or both)
// the method defines.
Stream StreamKind
// StreamingPayload is the payload sent across the stream.
StreamingPayload *AttributeExpr
// StreamingResult is the result sent across the stream when using SSE.
// When both Result and StreamingResult are defined with different types,
// the method supports content negotiation between standard HTTP responses
// (using Result) and SSE streams (using StreamingResult).
StreamingResult *AttributeExpr
}
MethodExpr defines a single method.
func (*MethodExpr) AddMeta ¶
func (m *MethodExpr) AddMeta(name string, value ...string)
AddMeta appends metadata values to the method expression.
func (*MethodExpr) DeleteMeta ¶
func (m *MethodExpr) DeleteMeta(name string)
DeleteMeta removes a metadata entry from the method expression.
func (*MethodExpr) Error ¶
func (m *MethodExpr) Error(name string) *ErrorExpr
Error returns the error with the given name. It looks up recursively in the endpoint then the service and finally the root expression.
func (*MethodExpr) EvalName ¶
func (m *MethodExpr) EvalName() string
EvalName returns the generic expression name used in error messages.
func (*MethodExpr) Finalize ¶
func (m *MethodExpr) Finalize()
Finalize makes sure the method payload and result types are set. It also projects the result if it is a result type and a view is explicitly set in the design or a result type having at most one view.
func (*MethodExpr) HasMixedResults ¶
func (m *MethodExpr) HasMixedResults() bool
HasMixedResults returns true if the method has both Result and StreamingResult defined with different types, indicating support for content negotiation.
func (*MethodExpr) IsPayloadStreaming ¶
func (m *MethodExpr) IsPayloadStreaming() bool
IsPayloadStreaming determines whether the method streams payload.
func (*MethodExpr) IsResultStreaming ¶
func (m *MethodExpr) IsResultStreaming() bool
IsResultStreaming determines whether the method streams payload.
func (*MethodExpr) IsStreaming ¶
func (m *MethodExpr) IsStreaming() bool
IsStreaming determines whether the method streams payload or result.
func (*MethodExpr) Prepare ¶
func (m *MethodExpr) Prepare()
Prepare makes sure the payload and result types are initialized (to the Empty type if nil) and merges the method interceptors with the API and service level interceptors.
func (*MethodExpr) Validate ¶
func (m *MethodExpr) Validate() error
Validate validates the method payloads, results, errors, security requirements, and interceptors.
type NamedAttributeExpr ¶
type NamedAttributeExpr struct {
// Name of attribute
Name string
// Attribute
Attribute *AttributeExpr
}
NamedAttributeExpr describes object attributes together with their names.
type Object ¶
type Object []*NamedAttributeExpr
Object is the type used to describe composite data structures. Note: not a map because order matters.
func (*Object) Attribute ¶
func (o *Object) Attribute(name string) *AttributeExpr
Attribute returns the attribute with the given name if any, nil otherwise.
func (*Object) Delete ¶
Delete creates a new object with the same named attributes as o but without the named attribute n if any.
func (*Object) Example ¶
func (o *Object) Example(r *ExampleGenerator) any
Example returns a random value of the object.
func (*Object) IsCompatible ¶
IsCompatible returns true if o describes the (Go) type of val.
func (*Object) Merge ¶
Merge creates a new object consisting of the named attributes of o appended with duplicates of the named attributes of other. Named attributes of o that have an identical name to named attributes of other get overridden.
func (*Object) Rename ¶
Rename changes the name of the named attribute n to m. Rename does nothing if o does not have an attribute named n.
func (*Object) Set ¶
func (o *Object) Set(n string, att *AttributeExpr)
Set replaces the object named attribute n if any - creates a new object by appending to the slice of named attributes otherwise. The resulting object is returned in both cases.
type Primitive ¶
type Primitive Kind
Primitive is the type for null, boolean, integer, number, string, and time.
func (Primitive) Example ¶
func (p Primitive) Example(r *ExampleGenerator) any
Example generates a pseudo-random primitive value using the given random generator.
func (Primitive) IsCompatible ¶
IsCompatible returns true if val is compatible with p.
type Randomizer ¶
type Randomizer interface {
// ArrayLength decides how long an example array will be
ArrayLength() int
// Int generates an integer example
Int() int
// Int32 generates an int32 example
Int32() int32
// Int64 generates an int64 example
Int64() int64
// String generates a string example
String() string
// Bool generates a bool example
Bool() bool
// Float32 generates a float32 example
Float32() float32
// Float64 generates a float64 example
Float64() float64
// UInt generates a uint example
UInt() uint
// UInt32 generates a uint example
UInt32() uint32
// UInt64 generates a uint example
UInt64() uint64
// Name generates a human name example
Name() string
// Email generates an example email address
Email() string
// Hostname generates an example hostname
Hostname() string
// IPv4Address generates an example IPv4 address
IPv4Address() net.IP
// IPv6Address generates an example IPv6 address
IPv6Address() net.IP
// URL generates an example URL
URL() string
// Characters generates a n-character string example
Characters(n int) string
// UUID generates a random v4 UUID
UUID() string
}
Randomizer generates consistent random values of different types given a seed.
The random values should be consistent in that given the same seed the same random values get generated.
Setting the randomizer to nil disables example generation.
func NewDeterministicRandomizer ¶
func NewDeterministicRandomizer() Randomizer
NewDeterministicRandomizer builds a Randomizer that will return hard-coded values, removing all randomness from example generation.
func NewFakerRandomizer ¶
func NewFakerRandomizer(seed string) Randomizer
NewFakerRandomizer creates a randomizer that uses the faker library to generate fake but reasonable values.
type ResultTypeExpr ¶
type ResultTypeExpr struct {
// A result type is a user type
*UserTypeExpr
// Identifier is the RFC 6838 result type media type identifier.
Identifier string
// ContentType identifies the value written to the response
// "Content-Type" header. Deprecated.
ContentType string
// Views list the supported views indexed by name.
Views []*ViewExpr
}
ResultTypeExpr is a user type which describes views used to render responses.
func GeneratedResultType ¶
func GeneratedResultType(id string) *ResultTypeExpr
GeneratedResultType returns the generated result type expression with the given id, nil if there isn't one.
func NewResultTypeExpr ¶
func NewResultTypeExpr(name, identifier string, fn func()) *ResultTypeExpr
NewResultTypeExpr creates a result type definition but does not execute the DSL.
func Project ¶
func Project(rt *ResultTypeExpr, view string) (*ResultTypeExpr, error)
Project creates a ResultTypeExpr containing the fields defined in the view expression of m named after the view argument.
The resulting result type defines a default view. The result type identifier is computed by adding a parameter called "view" to the original identifier. The value of the "view" parameter is the name of the view.
Project returns an error if the view does not exist for the given result type or any result type that makes up its attributes recursively. Note that individual attributes may use a different view. In this case Project uses that view and returns an error if it isn't defined on the attribute type.
func (*ResultTypeExpr) Dup ¶
func (rt *ResultTypeExpr) Dup(att *AttributeExpr) UserType
Dup creates a deep copy of the result type given a deep copy of its attribute.
func (*ResultTypeExpr) Finalize ¶
func (rt *ResultTypeExpr) Finalize()
Finalize builds the default view if not explicitly defined and finalizes the underlying UserTypeExpr.
func (*ResultTypeExpr) HasMultipleViews ¶
func (rt *ResultTypeExpr) HasMultipleViews() bool
HasMultipleViews returns true if the result type has more than one view.
func (*ResultTypeExpr) ID ¶
func (rt *ResultTypeExpr) ID() string
ID returns the identifier of the result type.
func (*ResultTypeExpr) Name ¶
func (rt *ResultTypeExpr) Name() string
Name returns the result type name.
func (*ResultTypeExpr) View ¶
func (rt *ResultTypeExpr) View(name string) *ViewExpr
View returns the view with the given name.
func (*ResultTypeExpr) ViewHasAttribute ¶
func (rt *ResultTypeExpr) ViewHasAttribute(view, attr string) bool
ViewHasAttribute returns true if the result type view has the given attribute.
type ResultTypesRoot ¶
type ResultTypesRoot []*ResultTypeExpr
ResultTypesRoot is a DSL root that records the result types generated by the DSL.
func (*ResultTypesRoot) Append ¶
func (r *ResultTypesRoot) Append(t *ResultTypeExpr)
Append adds the given type to the generated result types if not already added. It returns the type that was added or already present.
func (*ResultTypesRoot) DependsOn ¶
func (*ResultTypesRoot) DependsOn() []eval.Root
DependsOn ensures that Root executes first.
func (*ResultTypesRoot) EvalName ¶
func (*ResultTypesRoot) EvalName() string
EvalName is the name of the expression used by eval.
func (*ResultTypesRoot) Packages ¶
func (*ResultTypesRoot) Packages() []string
Packages returns the Go import path to this and the dsl packages.
func (*ResultTypesRoot) WalkSets ¶
func (r *ResultTypesRoot) WalkSets(w eval.SetWalker)
WalkSets returns the generated result types for evaluation.
type RootExpr ¶
type RootExpr struct {
// API contains the API expression built by the DSL.
API *APIExpr
// Services contains the list of services exposed by the API.
Services []*ServiceExpr
// Interceptors contains the list of interceptors.
Interceptors []*InterceptorExpr
// Errors contains the list of errors returned by all the API
// methods.
Errors []*ErrorExpr
// Types contains the user types described in the DSL.
Types []UserType
// ResultTypes contains the result types generated during DSL
// execution.
ResultTypes []*ResultTypeExpr
// Conversions list the user type to external type mappings.
Conversions []*TypeMap
// Creations list the external type to user type mappings.
Creations []*TypeMap
// Schemes list the registered security schemes.
Schemes []*SchemeExpr
// SessionAuths list the registered multi-transport session auth contracts.
SessionAuths []*SessionAuthExpr
}
RootExpr is the struct built by the DSL on process start.
func (*RootExpr) Finalize ¶
func (r *RootExpr) Finalize()
Finalize finalizes the server expressions.
func (*RootExpr) Service ¶
func (r *RootExpr) Service(name string) *ServiceExpr
Service returns the service with the given name.
func (*RootExpr) UserType ¶
UserType returns the user type expression with the given name if found, nil otherwise.
type RouteExpr ¶
type RouteExpr struct {
// Method is the HTTP method, e.g. "GET", "POST", etc.
Method string
// Path is the URL path e.g. "/tasks/{id}"
Path string
// Endpoint is the endpoint this route applies to.
Endpoint *HTTPEndpointExpr
// Meta is an arbitrary set of key/value pairs, see
// dsl.Meta
Meta MetaExpr
}
RouteExpr represents an endpoint route (HTTP endpoint).
func (*RouteExpr) DeleteMeta ¶
DeleteMeta removes a metadata entry from the route expression.
func (*RouteExpr) FullPaths ¶
FullPaths returns the endpoint full paths computed by concatenating the service base paths with the route specific path.
func (*RouteExpr) IsAbsolute ¶
IsAbsolute returns true if the endpoint path should not be concatenated to the service and API base paths.
func (*RouteExpr) Params ¶
Params returns all the route parameters across all the base paths. For example for the route "GET /foo/{fooID:foo_id}" Params returns []string{"fooID:foo_id"}.
func (*RouteExpr) Validate ¶
func (r *RouteExpr) Validate() *eval.ValidationErrors
Validate validates a route expression by ensuring that the route parameters can be inferred from the method payload and there is no duplicate parameters in an absolute route.
type SchemeExpr ¶
type SchemeExpr struct {
// Kind is the sort of security scheme this object represents.
Kind SchemeKind
// SchemeName is the name of the security scheme, e.g. "googAuth",
// "my_big_token", "jwt".
SchemeName string
// Description describes the security scheme e.g. "Google OAuth2"
Description string
// In determines the location of the API key, one of "header" or
// "query".
In string
// Name refers to a header or parameter name, based on In's
// value.
Name string
// Scopes lists the Basic, APIKey, JWT or OAuth2 scopes.
Scopes []*ScopeExpr
// Flows determine the oauth2 flows supported by this scheme.
Flows []*FlowExpr
// Meta is a list of key/value pairs
Meta MetaExpr
}
SchemeExpr defines a security scheme used to authenticate against the method being designed.
func DupScheme ¶
func DupScheme(sch *SchemeExpr) *SchemeExpr
DupScheme creates a copy of the given scheme expression.
func (*SchemeExpr) EvalName ¶
func (s *SchemeExpr) EvalName() string
EvalName returns the generic definition name used in error messages.
func (*SchemeExpr) Hash ¶
func (s *SchemeExpr) Hash() string
Hash returns a unique hash value for s.
func (*SchemeExpr) Validate ¶
func (s *SchemeExpr) Validate() *eval.ValidationErrors
Validate ensures that the method payload contains attributes required by the scheme.
type SchemeKind ¶
type SchemeKind int
SchemeKind is a type of security scheme.
const ( // OAuth2Kind identifies a "OAuth2" security scheme. OAuth2Kind SchemeKind = iota + 1 // BasicAuthKind means "basic" security scheme. BasicAuthKind // APIKeyKind means "apiKey" security scheme. APIKeyKind // JWTKind means an "JWT" security scheme, with support for // TokenPath and Scopes. JWTKind // NoKind means to have no security for this endpoint. NoKind )
func (SchemeKind) String ¶
func (k SchemeKind) String() string
type ScopeExpr ¶
type ScopeExpr struct {
// Name of the scope.
Name string
// Description is the description of the scope.
Description string
}
ScopeExpr defines a security scope.
type SecurityExpr ¶
type SecurityExpr struct {
// Schemes is the list of security schemes used for this
// requirement.
Schemes []*SchemeExpr
// Scopes list the required scopes if any.
Scopes []string
}
SecurityExpr defines a security requirement.
func DupRequirement ¶
func DupRequirement(req *SecurityExpr) *SecurityExpr
DupRequirement creates a copy of the given security requirement.
func (*SecurityExpr) EvalName ¶
func (s *SecurityExpr) EvalName() string
EvalName returns the generic definition name used in error messages.
type SecurityHolder ¶
type SecurityHolder interface {
AddSecurityRequirement(*SecurityExpr)
}
SecurityHolder is an interface that allows expression types to receive security requirements. Types implementing this interface can use the Security() DSL function to add security schemes.
type ServerExpr ¶
type ServerExpr struct {
// Name of server
Name string
// Description of server
Description string
// Services list the services hosted by the server.
Services []string
// Hosts list the server hosts.
Hosts []*HostExpr
// Meta is a set of key/value pairs.
Meta MetaExpr
}
ServerExpr contains a single API host information.
func (*ServerExpr) AddMeta ¶
func (s *ServerExpr) AddMeta(name string, value ...string)
AddMeta appends metadata values to the server expression.
func (*ServerExpr) DeleteMeta ¶
func (s *ServerExpr) DeleteMeta(name string)
DeleteMeta removes a metadata entry from the server expression.
func (*ServerExpr) EvalName ¶
func (s *ServerExpr) EvalName() string
EvalName is the qualified name of the expression.
func (*ServerExpr) Finalize ¶
func (s *ServerExpr) Finalize()
Finalize initializes the server services and/or host with default values if not set explicitly in the design.
func (*ServerExpr) Schemes ¶
func (s *ServerExpr) Schemes() []string
Schemes returns the list of transport schemes used by all the server endpoints. The possible values for the elements of the returned slice are "http", "https", "grpc" and "grpcs".
func (*ServerExpr) Validate ¶
func (s *ServerExpr) Validate() error
Validate validates the server and server hosts.
type ServiceExpr ¶
type ServiceExpr struct {
// DSLFunc contains the DSL used to initialize the expression.
eval.DSLFunc
// Name of service.
Name string
// Description of service used in documentation.
Description string
// Docs points to external documentation
Docs *DocsExpr
// Methods is the list of service methods.
Methods []*MethodExpr
// Errors list the errors common to all the service methods.
Errors []*ErrorExpr
// Requirements contains the security requirements that apply to
// all the service methods. One requirement is composed of
// potentially multiple schemes. Incoming requests must validate
// at least one requirement to be authorized.
Requirements []*SecurityExpr
// SessionAuths contains the multi-transport session auth contracts that
// apply to all service methods.
SessionAuths []*SessionAuthExpr
// ClientInterceptors is the list of client interceptors.
ClientInterceptors []*InterceptorExpr
// ServerInterceptors is the list of server interceptors.
ServerInterceptors []*InterceptorExpr
// Meta is a set of key/value pairs with semantic that is
// specific to each generator.
Meta MetaExpr
}
ServiceExpr describes a set of related methods.
func (*ServiceExpr) AddMeta ¶
func (s *ServiceExpr) AddMeta(name string, value ...string)
AddMeta appends metadata values to the service expression.
func (*ServiceExpr) DeleteMeta ¶
func (s *ServiceExpr) DeleteMeta(name string)
DeleteMeta removes a metadata entry from the service expression.
func (*ServiceExpr) Error ¶
func (s *ServiceExpr) Error(name string) *ErrorExpr
Error returns the error with the given name if any.
func (*ServiceExpr) EvalName ¶
func (s *ServiceExpr) EvalName() string
EvalName returns the generic expression name used in error messages.
func (*ServiceExpr) Finalize ¶
func (s *ServiceExpr) Finalize()
Finalize finalizes all the service methods and errors.
func (*ServiceExpr) Hash ¶
func (s *ServiceExpr) Hash() string
Hash returns a unique hash value for s.
func (*ServiceExpr) Method ¶
func (s *ServiceExpr) Method(n string) *MethodExpr
Method returns the method expression with the given name, nil if there isn't one.
func (*ServiceExpr) Validate ¶
func (s *ServiceExpr) Validate() error
Validate validates the service methods and errors.
type SessionAuthExpr ¶
type SessionAuthExpr struct {
// Name is the session auth contract name.
Name string
// Description describes the session auth contract.
Description string
// Transports lists the accepted auth transports.
Transports []*SessionTransportExpr
}
SessionAuthExpr defines a logical auth contract backed by one or more transport alternatives.
func (*SessionAuthExpr) EvalName ¶
func (s *SessionAuthExpr) EvalName() string
EvalName returns the generic definition name used in error messages.
func (*SessionAuthExpr) SetDescription ¶
func (s *SessionAuthExpr) SetDescription(d string)
SetDescription sets the session auth description.
func (*SessionAuthExpr) Validate ¶
func (s *SessionAuthExpr) Validate() *eval.ValidationErrors
Validate validates the session auth contract.
type SessionTransportExpr ¶
type SessionTransportExpr struct {
// Kind identifies the transport kind.
Kind SessionTransportKind
// Scheme is the underlying security scheme used by this transport.
Scheme *SchemeExpr
// FieldName is the payload field name associated with the transport.
FieldName string
// HTTPName is the inferred HTTP transport element name if any.
HTTPName string
// Description describes the transport.
Description string
}
SessionTransportExpr defines one accepted transport for a session auth contract.
func (*SessionTransportExpr) EvalName ¶
func (s *SessionTransportExpr) EvalName() string
EvalName returns the generic definition name used in error messages.
func (*SessionTransportExpr) SetDescription ¶
func (s *SessionTransportExpr) SetDescription(d string)
SetDescription sets the transport description.
func (*SessionTransportExpr) Validate ¶
func (s *SessionTransportExpr) Validate() *eval.ValidationErrors
Validate validates the session transport.
type SessionTransportKind ¶
type SessionTransportKind int
SessionTransportKind identifies the transport used by a session auth contract.
const ( // SessionBearerTransportKind identifies a bearer token transport. SessionBearerTransportKind SessionTransportKind = iota + 1 // SessionCookieTransportKind identifies a cookie transport. SessionCookieTransportKind )
func (SessionTransportKind) String ¶
func (k SessionTransportKind) String() string
type StreamKind ¶
type StreamKind int
StreamKind is a type denoting the kind of stream.
const ( // NoStreamKind represents no payload or result stream in method. NoStreamKind StreamKind = iota + 1 // ClientStreamKind represents client sends a streaming payload to // method. ClientStreamKind // ServerStreamKind represents server sends a streaming result from // method. ServerStreamKind // BidirectionalStreamKind represents client and server sending payload // and result respectively via a stream. BidirectionalStreamKind )
type TimeoutHolder ¶
TimeoutHolder is an interface that allows expression types to receive a timeout duration. Types implementing this interface can use the Timeout() DSL function to set a timeout.
type TitleHolder ¶
type TitleHolder interface {
SetTitle(string)
}
TitleHolder is an interface that allows expression types to receive a title. Types implementing this interface can use the Title() DSL function to set a title.
type TypeMap ¶
type TypeMap struct {
// User is the user type being converted or created.
User UserType
// External is an instance of the type being converted from or to.
External any
}
TypeMap defines a user to external type mapping.
type URIExpr ¶
type URIExpr string
URIExpr represents a parameterized URI.
type URLHolder ¶
type URLHolder interface {
SetURL(string)
}
URLHolder is an interface that allows expression types to receive a URL. Types implementing this interface can use the URL() DSL function to set a URL.
type Union ¶
type Union struct {
TypeName string
Values []*NamedAttributeExpr
// ExplicitTypeName is true when the union type name was set explicitly
// via DSL metadata and should not be recomputed from derived variants.
ExplicitTypeName bool
// TypeKey is the discriminator field name for JSON marshaling (defaults to "type")
TypeKey string
// ValueKey is the value field name for JSON marshaling (defaults to "value")
ValueKey string
}
Union is the type used to describe unions.
func (*Union) Example ¶
func (u *Union) Example(r *ExampleGenerator) any
Example returns a random example value.
func (*Union) GetTypeKey ¶
GetTypeKey returns the discriminator field name for JSON marshaling. Defaults to "type" if not explicitly set via Meta("oneof:type:field").
func (*Union) GetValueKey ¶
GetValueKey returns the value field name for JSON marshaling. Defaults to "value" if not explicitly set via Meta("oneof:value:field").
func (*Union) IsCompatible ¶
IsCompatible returns true if u describes the (Go) type of val.
type UserType ¶
type UserType interface {
DataType
eval.Expression
// Finalizes the underlying type.
eval.Finalizer
// Provides the underlying type and validations.
CompositeExpr
// ID returns the identifier for the user type.
ID() string
// Rename changes the type name to the given value.
Rename(string)
// SetAttribute updates the underlying attribute.
SetAttribute(*AttributeExpr)
// Dup makes a shallow copy of the type and assigns its
// attribute with att.
Dup(att *AttributeExpr) UserType
// Validate checks that the user type expression is consistent.
Validate(ctx string, parent eval.Expression) *eval.ValidationErrors
}
UserType is the interface implemented by all user type implementations. Plugins may leverage this interface to introduce their own types.
type UserTypeExpr ¶
type UserTypeExpr struct {
// The embedded attribute expression.
*AttributeExpr
// Name of type
TypeName string
// UID of type
UID string
}
UserTypeExpr describes user defined types. While a given design must ensure that the names are unique the code used to generate code can create multiple user types that share the same name (for example because generated in different packages). UID is always unique and makes it possible to avoid infinite recursions when traversing the data structures described by the attribute expression e.g. when computing example values.
func (*UserTypeExpr) Attribute ¶
func (u *UserTypeExpr) Attribute() *AttributeExpr
Attribute returns the embedded attribute.
func (*UserTypeExpr) Dup ¶
func (u *UserTypeExpr) Dup(att *AttributeExpr) UserType
Dup creates a deep copy of the user type given a deep copy of its attribute.
func (*UserTypeExpr) Example ¶
func (u *UserTypeExpr) Example(r *ExampleGenerator) any
Example produces an example for the user type which is JSON serialization compatible.
func (*UserTypeExpr) Hash ¶
func (u *UserTypeExpr) Hash() string
Hash returns a unique hash value for u.
func (*UserTypeExpr) ID ¶
func (u *UserTypeExpr) ID() string
ID returns the unique identifier for the user type.
func (*UserTypeExpr) IsCompatible ¶
func (u *UserTypeExpr) IsCompatible(val any) bool
IsCompatible returns true if u describes the (Go) type of val.
func (*UserTypeExpr) Rename ¶
func (u *UserTypeExpr) Rename(n string)
Rename changes the type name to the given value.
func (*UserTypeExpr) SetAttribute ¶
func (u *UserTypeExpr) SetAttribute(att *AttributeExpr)
SetAttribute sets the embedded attribute.
type UserTypeRegistry ¶
type UserTypeRegistry struct {
// contains filtered or unexported fields
}
UserTypeRegistry stores named temporary user types for synthesized expression trees and returns them in deterministic order.
func NewUserTypeRegistry ¶
func NewUserTypeRegistry() *UserTypeRegistry
NewUserTypeRegistry creates an empty registry for temporary named user types.
func (*UserTypeRegistry) Attribute ¶
func (r *UserTypeRegistry) Attribute(name string, builder func() *AttributeExpr) *AttributeExpr
Attribute returns an attribute that references the named user type.
func (*UserTypeRegistry) Collect ¶
func (r *UserTypeRegistry) Collect() []UserType
Collect returns all registered user types sorted by name.
func (*UserTypeRegistry) GetOrCreate ¶
func (r *UserTypeRegistry) GetOrCreate(name string, builder func() *AttributeExpr) *UserTypeExpr
GetOrCreate returns the named user type, creating it with builder on the first call only.
type ValidationExpr ¶
type ValidationExpr struct {
// Values represents an enum validation as described at
// http://json-schema.org/latest/json-schema-validation.html#anchor76.
Values []any
// Format represents a format validation as described at
// http://json-schema.org/latest/json-schema-validation.html#anchor104.
Format ValidationFormat
// PatternValidationExpr represents a pattern validation as
// described at
// http://json-schema.org/latest/json-schema-validation.html#anchor33
Pattern string
// ExclusiveMinimum represents an exclusiveMinimum value validation as described
// at
// http://json-schema.org/draft/2019-09/json-schema-validation.html#rfc.section.6.2.5.
ExclusiveMinimum *float64
// Minimum represents an minimum value validation as described
// at
// http://json-schema.org/latest/json-schema-validation.html#anchor21.
Minimum *float64
// Maximum represents a maximum value validation as described at
// http://json-schema.org/latest/json-schema-validation.html#anchor17.
Maximum *float64
// ExclusiveMaximum represents an exclusiveMaximum value validation as described
// at
// http://json-schema.org/draft/2019-09/json-schema-validation.html#rfc.section.6.2.3.
ExclusiveMaximum *float64
// MinLength represents an minimum length validation as
// described at
// http://json-schema.org/latest/json-schema-validation.html#anchor29.
MinLength *int
// MaxLength represents an maximum length validation as
// described at
// http://json-schema.org/latest/json-schema-validation.html#anchor26.
MaxLength *int
// Required list the required fields of object attributes as
// described at
// http://json-schema.org/latest/json-schema-validation.html#anchor61.
Required []string
}
ValidationExpr contains validation rules for an attribute.
func (*ValidationExpr) AddRequired ¶
func (v *ValidationExpr) AddRequired(required ...string)
AddRequired merges the required fields into v.
func (*ValidationExpr) Debug ¶
func (v *ValidationExpr) Debug(title, prefix, indent string)
Debug dumps the validation to STDOUT in a Loom developer friendly way.
func (*ValidationExpr) Dup ¶
func (v *ValidationExpr) Dup() *ValidationExpr
Dup makes a shallow dup of the validation.
func (*ValidationExpr) HasRequiredOnly ¶
func (v *ValidationExpr) HasRequiredOnly() bool
HasRequiredOnly returns true if the validation only has the Required field with a non-zero value.
func (*ValidationExpr) Merge ¶
func (v *ValidationExpr) Merge(other *ValidationExpr)
Merge merges other into v.
func (*ValidationExpr) RemoveRequired ¶
func (v *ValidationExpr) RemoveRequired(required string)
RemoveRequired removes the given field from the list of required fields.
func (*ValidationExpr) Validate ¶
func (v *ValidationExpr) Validate(ctx string, parent eval.Expression) *eval.ValidationErrors
Validate validates the validation expression.
type ValidationFormat ¶
type ValidationFormat string
ValidationFormat is the type used to enumerate the possible string formats.
type VersionHolder ¶
type VersionHolder interface {
SetVersion(string)
}
VersionHolder is an interface that allows expression types to receive a version. Types implementing this interface can use the Version() DSL function to set a version.
type ViewExpr ¶
type ViewExpr struct {
// Set of properties included in view
*AttributeExpr
// Name of view
Name string
// Parent result Type
Parent *ResultTypeExpr
}
ViewExpr defines which fields to render when building a response. The view is an object whose field names must match the names of the parent result type field names. The field definitions are inherited from the parent result type but may be overridden.
Source Files
¶
- api.go
- attribute.go
- docs.go
- dup.go
- error_remedy.go
- example.go
- example_canonicalization.go
- grpc.go
- grpc_endpoint.go
- grpc_error.go
- grpc_response.go
- grpc_service.go
- hasher.go
- helpers.go
- http.go
- http_body_types.go
- http_endpoint.go
- http_error.go
- http_file_server.go
- http_redirect.go
- http_response.go
- http_response_cookie.go
- http_response_link.go
- http_service.go
- http_sse.go
- init.go
- interceptor.go
- json_schema_inline.go
- jsonrpc.go
- jsonrpc_service_builder.go
- mapped_attribute.go
- meta.go
- meta_methods.go
- method.go
- random.go
- result_type.go
- result_types_root.go
- root.go
- root_runner.go
- security.go
- server.go
- service.go
- testing.go
- types.go
- union_naming.go
- user_type.go
- user_type_registry.go