code

package
v0.40.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: May 14, 2024 License: Apache-2.0 Imports: 13 Imported by: 1

Documentation

Overview

Package holds higher-level abstractions on top of OpenAPI that are used to generate code via text/template for Databricks SDK in different languages.

Index

Constants

This section is empty.

Variables

View Source
var ErrSkipThisFile = errors.New("skip generating this file")
View Source
var HIDDEN_HEADERS = map[string]struct{}{
	"X-Databricks-GCP-SA-Access-Token": {},
}

The following headers should not be added added to the generated structs

View Source
var HelperFuncs = template.FuncMap{
	"notLast": func(idx int, a interface{}) bool {
		return idx+1 != reflect.ValueOf(a).Len()
	},
	"contains": strings.Contains,
	"lower":    strings.ToLower,
	"lowerFirst": func(s string) string {
		return strings.ToLower(s[0:1]) + s[1:]
	},
	"trimPrefix": func(right, left string) string {
		return strings.TrimPrefix(left, right)
	},
	"trimSuffix": func(right, left string) string {
		return strings.TrimSuffix(left, right)
	},
	"replaceAll": func(from, to, str string) string {
		return strings.ReplaceAll(str, from, to)
	},
	"without": func(left, right string) string {
		return strings.ReplaceAll(right, left, "")
	},
	"skipThisFile": func() error {

		panic(ErrSkipThisFile)
	},
	"alphanumOnly": func(in []*Field) (out []*Field) {
		for _, v := range in {
			if !alphanumRE.MatchString(v.Name) {
				continue
			}
			out = append(out, v)
		}
		return out
	},
	"list": func(l ...any) []any {
		return l
	},
	"in": func(haystack []any, needle string) bool {
		for _, v := range haystack {
			if needle == fmt.Sprint(v) {
				return true
			}
		}
		return false
	},
	"dict": func(args ...any) map[string]any {
		if len(args)%2 != 0 {
			panic("number of arguments to dict is not even")
		}
		result := map[string]any{}
		for i := 0; i < len(args); i += 2 {
			k := fmt.Sprint(args[i])
			v := args[i+1]
			result[k] = v
		}
		return result
	},
	"getOrDefault": func(dict map[string]any, key string, def any) any {
		v, ok := dict[key]
		if ok {
			return v
		}
		return def
	},
	"fmt": fmt.Sprintf,
	"concat": func(v ...string) string {
		return strings.Join(v, "")
	},
}
View Source
var SUPPORTED_HEADER_TYPES = map[string]struct{}{
	"string":  {},
	"integer": {},
}

When adding a new type, implement it in all SDKs GO: httpclient/response.go#injectHeaders

Functions

This section is empty.

Types

type Batch

type Batch struct {
	// contains filtered or unexported fields
}

func NewFromFile

func NewFromFile(ctx context.Context, name string) (*Batch, error)

NewFromFile loads OpenAPI specification from file

func NewFromSpec added in v0.13.0

func NewFromSpec(ctx context.Context, spec *openapi.Specification) (*Batch, error)

NewFromSpec converts OpenAPI spec to intermediate representation

func (*Batch) ErrorCodeMapping added in v0.26.0

func (b *Batch) ErrorCodeMapping() (rules []ErrorMappingRule)

func (*Batch) ErrorOverrides added in v0.38.0

func (b *Batch) ErrorOverrides() []ErrorOverride

func (*Batch) ErrorStatusCodeMapping added in v0.26.0

func (b *Batch) ErrorStatusCodeMapping() (rules []ErrorMappingRule)

func (*Batch) ExceptionTypes added in v0.26.0

func (b *Batch) ExceptionTypes() []*ExceptionType

func (*Batch) FullName

func (b *Batch) FullName() string

func (*Batch) Packages

func (b *Batch) Packages() (pkgs []*Package)

Packages returns sorted slice of packages

func (*Batch) Services

func (b *Batch) Services() (services []*Service)

Pkgs returns sorted slice of packages

func (*Batch) ServicesSortedByParent added in v0.34.0

func (b *Batch) ServicesSortedByParent() (services []*Service)

func (*Batch) TransientErrorRegexes added in v0.39.0

func (b *Batch) TransientErrorRegexes() (res []string)

func (*Batch) Types

func (b *Batch) Types() (types []*Entity)

Pkgs returns sorted slice of packages

type Binding

type Binding struct {
	// Polling method request field
	PollField *Field

	// Wrapped method either response or request body field
	Bind *Field

	// Is wrapped method response used?
	IsResponseBind bool
}

Binding connects fields in generated code across multiple requests

type Entity

type Entity struct {
	Named
	Package *Package

	ArrayValue   *Entity
	MapValue     *Entity
	IsInt        bool
	IsInt64      bool
	IsFloat64    bool
	IsBool       bool
	IsString     bool
	IsByteStream bool

	// this field does not have a concrete type
	IsAny bool

	// this field is computed on the platform side
	IsComputed bool

	// if entity has required fields, this is the order of them
	RequiredOrder []string

	// Schema references the OpenAPI schema this entity was created from.
	Schema *openapi.Schema
	// contains filtered or unexported fields
}

Entity represents a Type

func (*Entity) CamelName

func (e *Entity) CamelName() string

CamelName overrides parent implementation by appending List suffix for unnamed list types

func (*Entity) Enum

func (e *Entity) Enum() (enum []EnumEntry)

Enum returns all entries for enum entities

func (*Entity) Field

func (e *Entity) Field(name string) *Field

Field gets field representation by name or nil

func (*Entity) Fields

func (e *Entity) Fields() (fields []*Field)

Fields returns sorted slice of field representations

func (*Entity) FullName

func (e *Entity) FullName() string

FullName includes package name and untransformed name of the entity

func (*Entity) GetUnderlyingFields added in v0.13.0

func (e *Entity) GetUnderlyingFields(path []string) ([]*Field, error)

Given a list of field names, return the list of *Field objects which result from following the path of fields in the entity.

func (*Entity) HasByteStreamField added in v0.34.0

func (e *Entity) HasByteStreamField() bool

HasByteStreamField returns true if any of the fields is a ByteStream

func (*Entity) HasHeaderField added in v0.32.0

func (e *Entity) HasHeaderField() bool

HasHeaderField returns true if any of the fields is from header

func (*Entity) HasJsonField added in v0.2.0

func (e *Entity) HasJsonField() bool

HasJsonField returns true if any of the fields is in the body

func (*Entity) HasQueryField added in v0.2.0

func (e *Entity) HasQueryField() bool

HasQueryField returns true if any of the fields is from query

func (*Entity) HasRequiredPathFields added in v0.24.0

func (e *Entity) HasRequiredPathFields() bool

func (*Entity) HasRequiredRequestBodyFields added in v0.24.0

func (e *Entity) HasRequiredRequestBodyFields() bool

func (*Entity) IsAllRequiredFieldsPrimitive added in v0.10.0

func (e *Entity) IsAllRequiredFieldsPrimitive() bool

func (*Entity) IsBasicGoLangType added in v0.23.0

func (e *Entity) IsBasicGoLangType() bool

Whether this entity represents a basic GoLang type

func (*Entity) IsEmpty

func (e *Entity) IsEmpty() bool

func (*Entity) IsExternal

func (e *Entity) IsExternal() bool

IsExternal returns true if entity is declared in external package and has to be imported from it

func (*Entity) IsMap added in v0.30.1

func (e *Entity) IsMap() bool

func (*Entity) IsNumber

func (e *Entity) IsNumber() bool

IsNumber returns true if field is numeric

func (*Entity) IsObject

func (e *Entity) IsObject() bool

IsObject returns true if entity is an object. We determine this by checking if it is any other type of structure.

func (*Entity) IsOnlyPrimitiveFields added in v0.2.0

func (e *Entity) IsOnlyPrimitiveFields() bool

func (*Entity) IsPrimitive added in v0.2.0

func (e *Entity) IsPrimitive() bool

func (*Entity) IsPrivatePreview added in v0.10.0

func (e *Entity) IsPrivatePreview() bool

IsPrivatePreview flags object being in private preview.

func (*Entity) IsPublicPreview added in v0.10.0

func (e *Entity) IsPublicPreview() bool

IsPublicPreview flags object being in public preview.

func (*Entity) IsReferred added in v0.13.0

func (e *Entity) IsReferred() bool

func (*Entity) IsRequest added in v0.13.0

func (e *Entity) IsRequest() bool

func (*Entity) IsResponse added in v0.13.0

func (e *Entity) IsResponse() bool

func (*Entity) NonRequiredFields added in v0.2.0

func (e *Entity) NonRequiredFields() (fields []*Field)

func (*Entity) PascalName

func (e *Entity) PascalName() string

PascalName overrides parent implementation by appending List suffix for unnamed list types

func (*Entity) RequiredFields added in v0.2.0

func (e *Entity) RequiredFields() (fields []*Field)

func (*Entity) RequiredPathFields added in v0.24.0

func (e *Entity) RequiredPathFields() (fields []*Field)

func (*Entity) RequiredRequestBodyFields added in v0.24.0

func (e *Entity) RequiredRequestBodyFields() (fields []*Field)

func (*Entity) ShouldIncludeForceSendFields added in v0.23.0

func (e *Entity) ShouldIncludeForceSendFields() bool

Whether the Entity contains a basic GoLang type which is not required

func (*Entity) Traverse added in v0.14.1

func (e *Entity) Traverse(fn func(*Entity))

type EnumEntry

type EnumEntry struct {
	Named
	Entity *Entity
	// SCIM API has schema specifiers
	Content string
}

type ErrorMappingRule added in v0.26.0

type ErrorMappingRule struct {
	Named
	StatusCode int
	ErrorCode  string
}

type ErrorOverride added in v0.38.0

type ErrorOverride struct {
	Name              string
	PathRegex         string
	Verb              string
	StatusCodeMatcher string
	ErrorCodeMatcher  string
	MessageMatcher    string
	OverrideErrorCode Named
}

type ExceptionType added in v0.26.0

type ExceptionType struct {
	Named
	StatusCode int
	Inherit    *Named
}

func (*ExceptionType) FullName added in v0.26.0

func (et *ExceptionType) FullName() string

type Field

type Field struct {
	Named
	Required           bool
	Entity             *Entity
	Of                 *Entity
	IsJson             bool
	IsPath             bool
	IsPathMultiSegment bool
	IsQuery            bool
	IsHeader           bool
	Schema             *openapi.Schema
}

Field of a Type (Entity)

func (*Field) IsOptionalObject

func (f *Field) IsOptionalObject() bool

func (*Field) IsPrivatePreview added in v0.10.0

func (f *Field) IsPrivatePreview() bool

IsPrivatePreview flags object being in private preview.

func (*Field) IsPublicPreview added in v0.10.0

func (f *Field) IsPublicPreview() bool

IsPublicPreview flags object being in public preview.

func (*Field) IsRequestBodyField added in v0.25.0

func (f *Field) IsRequestBodyField() bool

IsRequestBodyField indicates a field which can only be set as part of request body There are some fields, such as PipelineId for example, which can be both used in JSON and as path parameters. In code generation we handle path and request body parameters separately by making path parameters always required. Thus, we don't need to consider such fields as request body fields anymore.

func (*Field) Traverse added in v0.14.1

func (f *Field) Traverse(fn func(*Field))

Call the provided callback on this field and any nested fields in its entity, recursively.

type Method

type Method struct {
	Named
	Service *Service
	// HTTP method name
	Verb string
	// Full API Path, including /api/2.x prefix
	Path string
	// Slice of path params, e.g. permissions/{type}/{id}
	PathParts []PathPart
	// Request type representation
	Request *Entity
	// Response type representation
	Response *Entity

	// The style of the request, either "rpc" or "rest". See the documentation on
	// Operation for more details.
	PathStyle openapi.PathStyle

	// For list APIs, the path of fields in the response entity to follow to get
	// the resource ID.
	IdFieldPath []*Field

	// For list APIs, the path of fields in the response entity to follow to get
	// the user-friendly name of the resource.
	NameFieldPath []*Field

	// If not nil, the field in the request and reponse entities that should be
	// mapped to the request/response body.
	RequestBodyField  *Field
	ResponseBodyField *Field

	// Expected content type of the request and response
	FixedRequestHeaders map[string]string

	Operation *openapi.Operation
	// contains filtered or unexported fields
}

Method represents service RPC

func (*Method) AsFlat added in v0.16.0

func (m *Method) AsFlat() *Named

func (*Method) CanHaveResponseBody

func (m *Method) CanHaveResponseBody() bool

func (*Method) CanUseJson added in v0.24.0

func (m *Method) CanUseJson() bool

CanUseJson indicates whether the generated command supports --json flag. It happens when either method has to use JSON input or not all fields in request are primitives. Because such fields are not required, the command has not but should support JSON input.

func (*Method) CmdletName added in v0.16.0

func (m *Method) CmdletName(prefix string) string

func (*Method) GetByName

func (m *Method) GetByName() *Entity

GetByName returns entity from the same service with x-databricks-crud:read

func (*Method) HasIdentifierField added in v0.13.0

func (m *Method) HasIdentifierField() bool

func (*Method) HasNameField added in v0.13.0

func (m *Method) HasNameField() bool

func (*Method) HasRequiredPositionalArguments added in v0.30.0

func (m *Method) HasRequiredPositionalArguments() bool

func (*Method) IdentifierField added in v0.13.0

func (m *Method) IdentifierField() *Field

func (*Method) IsCrudCreate added in v0.10.0

func (m *Method) IsCrudCreate() bool

func (*Method) IsCrudRead added in v0.2.0

func (m *Method) IsCrudRead() bool

func (*Method) IsJsonOnly added in v0.10.1

func (m *Method) IsJsonOnly() bool

func (*Method) IsPrivatePreview added in v0.10.0

func (m *Method) IsPrivatePreview() bool

IsPrivatePreview flags object being in private preview.

func (*Method) IsPublicPreview added in v0.10.0

func (m *Method) IsPublicPreview() bool

IsPublicPreview flags object being in public preview.

func (*Method) IsRequestByteStream added in v0.18.0

func (m *Method) IsRequestByteStream() bool

func (*Method) IsResponseByteStream added in v0.18.0

func (m *Method) IsResponseByteStream() bool

func (*Method) MustUseJson added in v0.24.0

func (m *Method) MustUseJson() bool

MustUseJson indicates whether we have to use JSON input to set all required fields for request. If we can do so, it means we can only use JSON input passed via --json flag.

func (*Method) NamedIdMap

func (m *Method) NamedIdMap() *NamedIdMap

NamedIdMap returns name-to-id mapping retrieval definition for all entities of a type

func (*Method) NeedsOffsetDedupe added in v0.13.0

func (m *Method) NeedsOffsetDedupe() bool

func (*Method) Pagination

func (m *Method) Pagination() *Pagination

Pagination returns definition for possibly multi-request result iterator

func (*Method) RequiredPositionalArguments added in v0.30.0

func (m *Method) RequiredPositionalArguments() (fields []*Field)

func (*Method) ResponseHeaders added in v0.33.0

func (m *Method) ResponseHeaders() (headers []Field)

func (*Method) Shortcut

func (m *Method) Shortcut() *Shortcut

Shortcut creates definition from path params and single-field request entities

func (*Method) TitleVerb

func (m *Method) TitleVerb() string

func (*Method) Wait

func (m *Method) Wait() *Wait

Wait returns definition for long-running operation

type Named

type Named struct {
	Name        string
	Description string
}

Named holds common methods for identifying and describing things

func (*Named) AbbrName added in v0.2.0

func (n *Named) AbbrName() string

AbbrName returns `nlt` for `namesLikeThis`

func (*Named) CamelName

func (n *Named) CamelName() string

CamelName creates namesLikesThis

func (*Named) Comment

func (n *Named) Comment(prefix string, maxLen int) string

Comment formats description into language-specific comment multi-line strings

func (*Named) ConstantName

func (n *Named) ConstantName() string

ConstantName creates NAMES_LIKE_THIS

func (*Named) DescriptionWithoutSummary added in v0.2.0

func (n *Named) DescriptionWithoutSummary() string

func (*Named) HasComment

func (n *Named) HasComment() bool

func (*Named) IsNameReserved

func (n *Named) IsNameReserved() bool

func (*Named) KebabName

func (n *Named) KebabName() string

KebabName creates names-like-this

func (*Named) PascalName

func (n *Named) PascalName() string

PascalName creates NamesLikesThis

func (*Named) Singular

func (n *Named) Singular() *Named

func (*Named) SnakeName

func (n *Named) SnakeName() string

SnakeName creates names_like_this

func (*Named) Summary added in v0.2.0

func (n *Named) Summary() string

Summary gets the first sentence from the description. Always ends in a dot.

func (*Named) TitleName added in v0.1.1

func (n *Named) TitleName() string

TitleName creates Names Likes This

func (*Named) TrimPrefix added in v0.8.0

func (n *Named) TrimPrefix(prefix string) *Named

TrimPrefix returns *Named, but with a prefix trimmed from CamelName()

Example:

(&Named{Name: "AccountMetastoreAssigment"}).TrimPrefix("account").CamelName() == "metastoreAssignment"

type NamedIdMap

type NamedIdMap struct {
	Named
	IdPath   []*Field
	NamePath []*Field
	Entity   *Entity

	// if List method returns []Item directly
	// without generated iteration wrapper
	Direct bool
}

NamedIdMap depends on Pagination and is generated, when paginated item entity has Identifier and Name fields. End-users usually use this method for drop-downs or any other selectors.

func (*NamedIdMap) Id

func (n *NamedIdMap) Id() *Field

type Package

type Package struct {
	Named
	Components *openapi.Components
	// contains filtered or unexported fields
}

Package represents a service package, which contains entities and interfaces that are relevant to a single service

func (*Package) FullName

func (pkg *Package) FullName() string

FullName just returns pacakge name

func (*Package) HasPagination

func (pkg *Package) HasPagination() bool

HasPagination returns try if any service within this package has result iteration

func (*Package) HasPathParams

func (pkg *Package) HasPathParams() bool

HasPathParams returns true if any service has methods that rely on path params

func (*Package) HasWaits

func (pkg *Package) HasWaits() bool

HasWaits returns true if any service has methods with long-running operations

func (*Package) ImportedEntities

func (pkg *Package) ImportedEntities() (res []*Entity)

func (*Package) ImportedPackages

func (pkg *Package) ImportedPackages() (res []string)

func (*Package) Load

func (pkg *Package) Load(ctx context.Context, spec *openapi.Specification, tag openapi.Tag) error

Load takes OpenAPI specification and loads a service model

func (*Package) MainService added in v0.2.0

func (pkg *Package) MainService() *Service

MainService returns a Service that matches Package name

func (*Package) Services

func (pkg *Package) Services() (types []*Service)

Services returns sorted slice of services

func (*Package) ServicesSortedByParent added in v0.34.0

func (pkg *Package) ServicesSortedByParent() []*Service

Returns the Services sorted such has parents always come before subservices.

func (*Package) Types

func (pkg *Package) Types() (types []*Entity)

Types returns sorted slice of types

type Pagination

type Pagination struct {
	Offset    *Field
	Limit     *Field
	Results   *Field
	Entity    *Entity
	Token     *Binding
	Increment int
}

Pagination holds definition of result iteration type per specific RPC. Databricks as of now has a couple different types of pagination:

  • next_token/next_page_token + repeated field
  • offset/limit with zero-based offsets + repeated field
  • page/limit with 1-based pages + repeated field
  • repeated inline field
  • repeated field

func (*Pagination) MultiRequest

func (p *Pagination) MultiRequest() bool

type PathPart

type PathPart struct {
	Prefix      string
	Field       *Field
	IsAccountId bool
}

PathPart represents required field, that is always part of the path

type Service

type Service struct {
	Named
	PathStyle  openapi.PathStyle
	IsAccounts bool
	Package    *Package

	ByPathParamsMethods []*Shortcut
	ParentService       *Service
	// contains filtered or unexported fields
}

Service represents specific Databricks API

func (*Service) Create added in v0.2.0

func (svc *Service) Create() *Method

List returns a method annotated with x-databricks-crud:create

func (*Service) Delete added in v0.2.0

func (svc *Service) Delete() *Method

List returns a method annotated with x-databricks-crud:delete

func (*Service) FullName

func (svc *Service) FullName() string

FullName holds package name and service name

func (*Service) HasPagination

func (svc *Service) HasPagination() bool

HasPagination returns true if any method has result iteration

func (*Service) HasParent added in v0.34.0

func (svc *Service) HasParent() bool

Returns whether the service has a parent service

func (*Service) HasSubservices added in v0.34.0

func (svc *Service) HasSubservices() bool

Returns whether the service has subservices

func (*Service) HasWaits added in v0.6.0

func (svc *Service) HasWaits() bool

func (*Service) IsPrivatePreview added in v0.10.0

func (svc *Service) IsPrivatePreview() bool

IsPrivatePreview flags object being in private preview.

func (*Service) IsPublicPreview added in v0.10.0

func (svc *Service) IsPublicPreview() bool

IsPublicPreview flags object being in public preview.

func (*Service) List added in v0.2.0

func (svc *Service) List() *Method

List returns a method annotated with x-databricks-crud:list

func (*Service) MatchesPackageName

func (svc *Service) MatchesPackageName() bool

MatchesPackageName if package name and service name are the same, e.g. `clusters` package & `Clusters` service

func (*Service) Methods

func (svc *Service) Methods() (methods []*Method)

Methods returns sorted slice of methods

func (*Service) Read added in v0.2.0

func (svc *Service) Read() *Method

List returns a method annotated with x-databricks-crud:read

func (*Service) Subservices added in v0.34.0

func (svc *Service) Subservices() (services []*Service)

Returns the list of subservices

func (*Service) Update added in v0.2.0

func (svc *Service) Update() *Method

List returns a method annotated with x-databricks-crud:update

func (*Service) Waits added in v0.6.0

func (svc *Service) Waits() (waits []*Wait)

type Shortcut

type Shortcut struct {
	Named
	Params []Field
	Method *Method
}

Shortcut holds definition of "shortcut" methods, that are generated for methods with request entities only with required fields.

type Wait

type Wait struct {
	Named
	// represents a method that triggers the start of the long-running operation
	Method *Method
}

Wait represents a long-running operation, that requires multiple RPC calls

func (*Wait) Binding

func (w *Wait) Binding() (binding []Binding)

Binding returns a slice of request and response connections

func (*Wait) ComplexMessagePath

func (w *Wait) ComplexMessagePath() bool

func (*Wait) Failure

func (w *Wait) Failure() (match []EnumEntry)

Failure holds the failed end-states of the operation

func (*Wait) ForceBindRequest

func (w *Wait) ForceBindRequest() bool

ForceBindRequest is a workaround for Jobs#RepairRun, that does not send run_id in response

func (*Wait) MessagePath

func (w *Wait) MessagePath() (path []*Field)

MessagePath holds the path to the field of polled entity, that can tell about current inner status of the long-running operation

func (*Wait) MessagePathHead

func (w *Wait) MessagePathHead() *Field

func (*Wait) Poll

func (w *Wait) Poll() *Method

Poll returns method definition for checking the state of the long running operation

func (*Wait) Status added in v0.8.0

func (w *Wait) Status() *Field

func (*Wait) StatusPath

func (w *Wait) StatusPath() (path []*Field)

StatusPath holds the path to the field of polled entity, that holds current state of the long-running operation

func (*Wait) Success

func (w *Wait) Success() (match []EnumEntry)

Success holds the successful end-states of the operation

func (*Wait) Timeout

func (w *Wait) Timeout() int

Timeout returns timeout in minutes, defaulting to 20

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL