api

package
v0.10.1 Latest Latest
Warning

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

Go to latest
Published: Apr 10, 2026 License: Apache-2.0 Imports: 4 Imported by: 0

Documentation

Overview

Package api defines the data model representing a parsed API surface.

Index

Constants

View Source
const (
	// StandardFieldNameForResourceRef is the standard name for resource references
	// to the resource being operated on by standard methods as defined by AIPs.
	StandardFieldNameForResourceRef = "name"

	// StandardFieldNameForParentResourceRef is the standard name for resource references
	// to the child resource being operated on by standard methods as defined by AIPs.
	StandardFieldNameForParentResourceRef = "parent"

	// GenericResourceType is a special resource type that may be used by resource references
	// in contexts where the referenced resource may be of any type, as defined by AIPs.
	GenericResourceType = "*"

	// StandardFieldNameForUpdateMask is the standard name for the update mask field
	// in update operations as defined by AIP-134.
	StandardFieldNameForUpdateMask = "update_mask"
)
View Source
const (
	// SingleSegmentWildcard is a special routing path segment which indicates
	// "match anything that does not include a `/`".
	SingleSegmentWildcard = "*"

	// MultiSegmentWildcard is a special routing path segment which indicates
	// "match anything including `/`".
	MultiSegmentWildcard = "**"
)
View Source
const (
	// ReservedPackageName is a package name reserved for maps and other
	// synthetic messages that do not exist in the input specification.
	//
	// We need a place to put these in the data model without conflicts with the
	// input data model. This symbol is unused in all the IDLs we support.
	ReservedPackageName = "$"
)

Variables

This section is empty.

Functions

func BuildHeuristicVocabulary added in v0.8.4

func BuildHeuristicVocabulary(model *API) map[string]bool

BuildHeuristicVocabulary builds the vocabulary of valid resource tokens based on the last literal before a variable in Get/List methods.

func CrossReference

func CrossReference(model *API) error

CrossReference fills out the cross-references in `model` that the parser(s) missed.

The parsers cannot always cross-reference all elements because the elements are built incrementally, and may not be available until the parser has completed all the work.

This function is called after the parser has completed its work but before the codecs run. It populates links between the parsed elements that the codecs need. For example, the `oneof` fields use the containing `OneOf` to reference any types or names of the `OneOf` during their generation.

func FindDependencies

func FindDependencies(model *API, ids []string) (map[string]bool, error)

FindDependencies returns the IDs of model elements required by the given set of `ids`

We can think of the `model` as a directed graph, with nodes for each of the model elements. Finding required elements is a graph traversal problem.

First observe that:

  • if we are given a service, we want to include all of its methods.
  • if we are given a method, we need to include its service, but not necessarily any of its sibling methods.

This implies that simply fanning out over the nodes is not sufficient.

We resolve this by making two passes. In the first pass, we fan out over all child elements of the given elements. In the second pass, we add all required parents of any found elements.

In the first pass, we compute the reachable set of the given `ids`, with edges from...

- a service to each of its methods - a method to its request/response messages - an LRO method to its metadata/response type messages - a message to each of its fields' types (if they are a message or enum)

In the second pass, we compute the reachable set of the nodes found from the first pass. This time, the graph has edges from...

- a method to its service - a child message to its parent message - a child enum to its parent message - a message to each of its fields' types (if they are a message or enum)

  • this edge is only necessary because we are too lazy to support pruning the fields of a message.

func IdentifyTargetResources added in v0.8.4

func IdentifyTargetResources(model *API, enableHeuristics bool) error

IdentifyTargetResources populates the TargetResource field in PathBinding for all methods in the API.

This is done in two passes:

  1. Explicit Identification: Matches google.api.resource_reference annotations with fields present in the PathTemplate.
  2. Heuristic Identification: If enableHeuristics is true and the service is allow-listed, uses path segment patterns to identify resources when annotations are missing.

func LabelRecursiveFields

func LabelRecursiveFields(model *API)

LabelRecursiveFields labels fields that recursively reference other messages.

func PatchDocumentation

func PatchDocumentation(model *API, overrides []DocumentationOverride) error

PatchDocumentation overrides the documentation of the API model with the provided overrides.

func SkipModelElements

func SkipModelElements(model *API, overrides ModelOverride) error

SkipModelElements prunes the model of any elements that are not desired.

The elements to be pruned are determined by the `overrides`.

If `overrides.IncludedIDs` is set, then any element that is not a dependency of one of the listed IDs is pruned.

If `overrides.SkippedIDs` is set, then any element with an ID in this list is pruned.

It is an error to specify both `IncludedIDs` and `SkippedIDs`.

func UpdateMethodPagination added in v0.8.4

func UpdateMethodPagination(overrides []PaginationOverride, a *API)

UpdateMethodPagination marks all methods that conform to [AIP-4233](https://google.aip.dev/client-libraries/4233) as pageable.

func Validate

func Validate(model *API) error

Validate verifies the model satisfies the requires to be used by Codecs.

Types

type API

type API struct {
	// Name of the API (e.g. secretmanager).
	Name string
	// Name of the package name in the source specification format. For Protobuf
	// this may be `google.cloud.secretmanager.v1`.
	PackageName string
	// The API Title (e.g. "Secret Manager API" or "Cloud Spanner API").
	Title string
	// The API Description.
	Description string
	// The API Revision. In discovery-based services this is the "revision"
	// attribute.
	Revision string
	// Services are a collection of services that make up the API.
	Services []*Service
	// Messages are a collection of messages used to process request and
	// responses in the API.
	Messages []*Message
	// Enums
	Enums []*Enum
	// State contains helpful information that can be used when generating
	// clients.
	State *APIState
	// ResourceDefinitions contains the data from the `google.api.resource_definition` annotation.
	ResourceDefinitions []*Resource
	// QuickstartService is the service that will be used to generate the quickstart sample
	// at the package level.
	QuickstartService *Service
	// Language specific annotations.
	Codec any
}

API represents and API surface.

func NewTestAPI

func NewTestAPI(messages []*Message, enums []*Enum, services []*Service) *API

NewTestAPI creates a new test API.

func (*API) HasDeprecatedEntities

func (model *API) HasDeprecatedEntities() bool

HasDeprecatedEntities returns true if the API has any deprecated entities.

func (*API) HasMessages

func (api *API) HasMessages() bool

HasMessages returns true if the API contains messages (most do).

This is useful in the mustache templates to skip code that only makes sense when per-message code follows.

func (*API) LoadWellKnownTypes

func (model *API) LoadWellKnownTypes()

LoadWellKnownTypes adds well-known types to `state`.

Some source specification formats (Discovery, OpenAPI) must manually add the well-known types. In Protobuf these types are automatically defined in the protoc output.

func (*API) ModelCodec

func (a *API) ModelCodec() any

ModelCodec returns the Codec field with an alternative name.

In some mustache templates we want to access the annotations for the enclosing model. In mustache you can get a field from an enclosing context *if* the name is unique.

type APIState

type APIState struct {
	// ServiceByID returns a service that is associated with the API.
	ServiceByID map[string]*Service
	// MethodByID returns a method that is associated with the API.
	MethodByID map[string]*Method
	// MessageByID returns a message that is associated with the API.
	MessageByID map[string]*Message
	// EnumByID returns a message that is associated with the API.
	EnumByID map[string]*Enum
	// ResourceByType returns a resource that is associated with the API.
	ResourceByType map[string]*Resource
}

APIState contains helpful information that can be used when generating clients.

type Discovery added in v0.8.4

type Discovery struct {
	// The ID of the LRO operation type.
	//
	// For example: ".google.cloud.compute.v1.Operation".
	OperationID string

	// Possible prefixes to match the LRO polling RPCs.
	//
	// In discovery-based services there may be multiple resources and RPCs that
	// service as LRO pollers. The order is important, sidekick picks the first
	// match, so the configuration should list preferred matches first.
	Pollers []*Poller
}

Discovery defines the configuration for discovery docs.

It is too complex to just use key/value pairs in the `Config.Source` field.

func (*Discovery) LroServices added in v0.8.4

func (d *Discovery) LroServices() map[string]bool

LroServices returns the set of Discovery LRO services.

The discovery doc parser avoids generating LRO annotations for methods in this set. These functions return the LRO operation, but are inserted to that list, poll, wait for, and cancel LROs. They do not need the annotations and generated helpers.

type DiscoveryLro

type DiscoveryLro struct {
	// The path parameters required by the polling operation.
	PollingPathParameters []string
	// Language specific annotations.
	Codec any
}

DiscoveryLro contains old-style long-running operation descriptors.

type DocumentationOverride added in v0.8.4

type DocumentationOverride struct {
	ID      string
	Match   string
	Replace string
}

DocumentationOverride describes overrides for the documentation of a single element.

This should be used sparingly. Generally we should prefer updating the comments upstream, and then getting a new version of the services' specification. The exception may be when the fixes take a long time, or are specific to one language.

type Enum

type Enum struct {
	// Documentation for the message.
	Documentation string
	// Name of the attribute.
	Name string
	// ID is a unique identifier.
	ID string
	// Some source specifications allow marking enums as deprecated.
	Deprecated bool
	// Values associated with the Enum.
	Values []*EnumValue
	// The unique integer values, some enums have multiple aliases for the
	// same number (e.g. `enum X { a = 0, b = 0, c = 1 }`).
	UniqueNumberValues []*EnumValue
	// ValuesForExamples contains a subset of values suitable for use in generated samples.
	// e.g. non-deprecated, non-zero values.
	ValuesForExamples []*SampleValue
	// Parent returns the ancestor of this node, if any.
	Parent *Message
	// The Protobuf package this enum belongs to.
	Package string
	// Language specific annotations.
	Codec any
}

Enum defines a message used in request/response handling.

func (*Enum) Scopes

func (x *Enum) Scopes() []string

Scopes returns the scopes for an enum.

type EnumValue

type EnumValue struct {
	// Documentation for the message.
	Documentation string
	// Name of the attribute.
	Name string
	// ID is a unique identifier.
	ID string
	// Some source specifications allow marking enum values as deprecated.
	Deprecated bool
	// Number of the attribute.
	Number int32
	// Parent returns the ancestor of this node, if any.
	Parent *Enum
	// Language specific annotations.
	Codec any
}

EnumValue defines a value in an Enum.

func (*EnumValue) Scopes

func (x *EnumValue) Scopes() []string

Scopes returns the scopes for an enum value.

type Field

type Field struct {
	// Documentation for the field.
	Documentation string
	// Name of the attribute.
	Name string
	// ID is a unique identifier.
	ID string
	// Typez is the datatype of the field.
	Typez Typez
	// TypezID is the ID of the type the field refers to. This value is populated
	// for message-like types only.
	TypezID string
	// JSONName is the name of the field as it appears in JSON. Useful for
	// serializing to JSON.
	JSONName string
	// Optional indicates that the field is marked as optional in proto3.
	Optional bool

	// For a given field, at most one of `Repeated` or `Map` is true.
	//
	// Using booleans (as opposed to an enum) makes it easier to write mustache
	// templates.
	//
	// Repeated is true if the field is a repeated field.
	Repeated bool
	// Map is true if the field is a map.
	Map bool
	// Some source specifications allow marking fields as deprecated.
	Deprecated bool
	// IsOneOf is true if the field is related to a one-of and not
	// a proto3 optional field.
	IsOneOf bool
	// Some fields have a type that refers (sometimes indirectly) to the
	// containing message. That triggers slightly different code generation for
	// some languages.
	Recursive bool
	// AutoPopulated is true if the field is eligible to be auto-populated,
	// per the requirements in AIP-4235.
	//
	// That is:
	// - It has Typez == STRING_TYPE
	// - For Protobuf, does not have the `google.api.field_behavior = REQUIRED` annotation
	// - For Protobuf, has the `google.api.field_info.format = UUID4` annotation
	// - For OpenAPI, it is an optional field
	// - For OpenAPI, it has format == "uuid"
	AutoPopulated bool
	// FieldBehavior indicates how the field behaves in requests and responses.
	//
	// For example, that a field is required in requests, or given as output
	// but ignored as input.
	Behavior []FieldBehavior
	// For fields that are part of a OneOf, the group of fields that makes the
	// OneOf.
	Group *OneOf
	// The message that contains this field.
	Parent *Message
	// The message type for this field, can be nil.
	MessageType *Message
	// The enum type for this field, can be nil.
	EnumType *Enum
	// ResourceReference contains the data from the `google.api.resource_reference`
	// annotation.
	ResourceReference *ResourceReference
	// Codec is a placeholder to put language specific annotations.
	Codec any
}

Field defines a field in a Message.

func NewTestField added in v0.8.4

func NewTestField(name string) *Field

NewTestField creates a field with defaults for testing. JSONName is automatically camelCased.

func (*Field) DocumentAsRequired

func (field *Field) DocumentAsRequired() bool

DocumentAsRequired returns true if the field should be documented as required.

func (*Field) FieldCodec

func (f *Field) FieldCodec() any

FieldCodec returns the Codec field with an alternative name.

In some mustache templates we want to access the codec for the enclosing field. In mustache you can get a field from an enclosing context *if* the name is unique.

func (*Field) FieldParent

func (f *Field) FieldParent() *Message

FieldParent returns the Parent field with an alternative name.

In some mustache templates we want to access the parent for the enclosing field. In mustache you can get a field from an enclosing context *if* the name is unique.

func (*Field) IsBool

func (f *Field) IsBool() bool

IsBool returns true if the primitive type of a field is `BOOL_TYPE`.

This is useful for mustache templates that differ only in the broad category of field type involved.

func (*Field) IsBytes

func (f *Field) IsBytes() bool

IsBytes returns true if the primitive type of a field is `BYTES_TYPE`.

This is useful for mustache templates that differ only in the broad category of field type involved.

func (*Field) IsEnum

func (f *Field) IsEnum() bool

IsEnum returns true if the primitive type of a field is `ENUM_TYPE`.

This is useful for mustache templates that differ only in the broad category of field type involved.

func (*Field) IsLikeFloat

func (f *Field) IsLikeFloat() bool

IsLikeFloat returns true if the primitive type of a field is a float or double.

This is useful for mustache templates that differ only in the broad category of field type involved.

func (*Field) IsLikeInt

func (f *Field) IsLikeInt() bool

IsLikeInt returns true if the primitive type of a field is one of the integer types.

This is useful for mustache templates that differ only in the broad category of field type involved.

func (*Field) IsLikeUInt added in v0.8.0

func (f *Field) IsLikeUInt() bool

IsLikeUInt returns true if the primitive type of a field is one of the unsigned integer types.

This is useful for mustache templates that differ only in the broad category of field type involved.

func (*Field) IsObject

func (f *Field) IsObject() bool

IsObject returns true if the primitive type of a field is `OBJECT_TYPE`.

This is useful for mustache templates that differ only in the broad category of field type involved.

The templates *should* first check if the field is singular, as all maps are also objects.

func (*Field) IsResourceReference added in v0.8.0

func (f *Field) IsResourceReference() bool

IsResourceReference returns true if the field is annotated with google.api.resource_reference.

func (*Field) IsString

func (f *Field) IsString() bool

IsString returns true if the primitive type of a field is `STRING_TYPE`.

This is useful for mustache templates that differ only in the broad category of field type involved.

func (*Field) NameEqualJSONName

func (f *Field) NameEqualJSONName() bool

NameEqualJSONName returns true if the field's name is the same as its JSON name.

func (*Field) Singular

func (f *Field) Singular() bool

Singular returns true if the field is not a map or a repeated field.

func (*Field) WithBehavior added in v0.8.4

func (f *Field) WithBehavior(behaviors ...FieldBehavior) *Field

WithBehavior adds behavior(s) to the field.

func (*Field) WithChildTypeReference added in v0.8.4

func (f *Field) WithChildTypeReference(childType string) *Field

WithChildTypeReference sets the child type resource reference on a field.

func (*Field) WithMap added in v0.8.4

func (f *Field) WithMap() *Field

WithMap marks the field as a map.

func (*Field) WithMessageType added in v0.8.4

func (f *Field) WithMessageType(msg *Message) *Field

WithMessageType sets the field's message type. It sets MessageType, Typez=MESSAGE_TYPE, and TypezID.

func (*Field) WithRepeated added in v0.8.4

func (f *Field) WithRepeated() *Field

WithRepeated marks the field as repeated.

func (*Field) WithResourceReference added in v0.8.4

func (f *Field) WithResourceReference(refType string) *Field

WithResourceReference sets the resource reference on a field.

func (*Field) WithType added in v0.8.4

func (f *Field) WithType(t Typez) *Field

WithType sets the type of the field.

type FieldBehavior

type FieldBehavior int

FieldBehavior represents annotations for how the code generator handles a field.

Regardless of the underlying data type and whether it is required or optional on the wire, some fields must be present for requests to succeed. Or may not be included in a request.

const (
	// FIELD_BEHAVIOR_UNSPECIFIED is the default, unspecified field behavior.
	FIELD_BEHAVIOR_UNSPECIFIED FieldBehavior = iota

	// FIELD_BEHAVIOR_OPTIONAL specifically denotes a field as optional.
	//
	// While Google Cloud uses proto3, where fields are either optional or have
	// a default value, this may be specified for emphasis.
	FIELD_BEHAVIOR_OPTIONAL

	// FIELD_BEHAVIOR_REQUIRED denotes a field as required.
	//
	// This indicates that the field **must** be provided as part of the request,
	// and failure to do so will cause an error (usually `INVALID_ARGUMENT`).
	//
	// Code generators may change the generated types to include this field as a
	// parameter necessary to construct the request.
	FIELD_BEHAVIOR_REQUIRED

	// FIELD_BEHAVIOR_OUTPUT_ONLY denotes a field as output only.
	//
	// Some messages (and their fields) are used in both requests and responses.
	// This indicates that the field is provided in responses, but including the
	// field in a request does nothing (the server *must* ignore it and
	// *must not* throw an error as a result of the field's presence).
	//
	// Code generators that use different builders for "the message as part of a
	// request" vs. "the standalone message" may omit this field in the former.
	FIELD_BEHAVIOR_OUTPUT_ONLY

	// FIELD_BEHAVIOR_INPUT_ONLY denotes a field as input only.
	//
	// This indicates that the field is provided in requests, and the
	// corresponding field is not included in output.
	FIELD_BEHAVIOR_INPUT_ONLY

	// FIELD_BEHAVIOR_IMMUTABLE denotes a field as immutable.
	//
	// This indicates that the field may be set once in a request to create a
	// resource, but may not be changed thereafter.
	FIELD_BEHAVIOR_IMMUTABLE

	// FIELD_BEHAVIOR_UNORDERED_LIST denotes that a (repeated) field is an unordered list.
	//
	// This indicates that the service may provide the elements of the list
	// in any arbitrary  order, rather than the order the user originally
	// provided. Additionally, the list's order may or may not be stable.
	FIELD_BEHAVIOR_UNORDERED_LIST

	// FIELD_BEHAVIOR_UNORDERED_NON_EMPTY_DEFAULT denotes that this field returns a non-empty default value if not set.
	//
	// This indicates that if the user provides the empty value in a request,
	// a non-empty value will be returned. The user will not be aware of what
	// non-empty value to expect.
	FIELD_BEHAVIOR_UNORDERED_NON_EMPTY_DEFAULT

	// FIELD_BEHAVIOR_IDENTIFIER denotes that the field in a resource (a message annotated with
	// google.api.resource) is used in the resource name to uniquely identify the
	// resource.
	//
	// For AIP-compliant APIs, this should only be applied to the
	// `name` field on the resource.
	//
	// This behavior should not be applied to references to other resources within
	// the message.
	//
	// The identifier field of resources often have different field behavior
	// depending on the request it is embedded in (e.g. for Create methods name
	// is optional and unused, while for Update methods it is required). Instead
	// of method-specific annotations, only `IDENTIFIER` is required.
	FIELD_BEHAVIOR_IDENTIFIER
)

type Message

type Message struct {
	// Documentation for the message.
	Documentation string
	// Name of the attribute.
	Name string
	// ID is a unique identifier.
	ID string
	// Some source specifications allow marking messages as deprecated.
	Deprecated bool
	// Fields associated with the Message.
	Fields []*Field
	// If true, this is a synthetic request message.
	//
	// These messages are created by sidekick when parsing Discovery docs and
	// OpenAPI specifications. The query and request parameters for each method
	// are grouped into a synthetic message.
	SyntheticRequest bool
	// If true, this message is a placeholder / doppelganger for a `api.Service`.
	//
	// These messages are created by sidekick when parsing Discovery docs and
	// OpenAPI specifications. All the synthetic messages for a service need to
	// be grouped under a unique namespace to avoid clashes with similar
	// synthetic messages in other services. Sidekick creates a placeholder
	// message that represents "the service".
	//
	// That is, `service1` and `service2` may both have a synthetic `getRequest`
	// message, with different attributes. We need these to be different
	// messages, with different names. So we create a different parent message
	// for each.
	ServicePlaceholder bool
	// Enums associated with the Message.
	Enums []*Enum
	// Messages associated with the Message. In protobuf these are referred to as
	// nested messages.
	Messages []*Message
	// OneOfs associated with the Message.
	OneOfs []*OneOf
	// Parent returns the ancestor of this message, if any.
	Parent *Message
	// The Protobuf package this message belongs to.
	Package string
	IsMap   bool
	// Indicates that this Message is returned by a standard
	// List RPC and conforms to [AIP-4233](https://google.aip.dev/client-libraries/4233).
	Pagination *PaginationInfo
	// Resource contains the data from the `google.api.resource` annotation.
	Resource *Resource
	// Language specific annotations.
	Codec any
}

Message defines a message used in request/response handling.

func NewTestMessage added in v0.8.4

func NewTestMessage(name string) *Message

NewTestMessage creates a message with defaults for testing. Default package is "test".

func (*Message) HasFields

func (m *Message) HasFields() bool

HasFields returns true if the message has fields.

func (*Message) Scopes

func (x *Message) Scopes() []string

Scopes returns the scopes for a message.

func (*Message) WithFields added in v0.8.4

func (m *Message) WithFields(fields ...*Field) *Message

WithFields adds fields to the message and updates their parent/ID.

func (*Message) WithID added in v0.8.4

func (m *Message) WithID(id string) *Message

WithID overrides the message's ID.

func (*Message) WithPackage added in v0.8.4

func (m *Message) WithPackage(pkg string) *Message

WithPackage sets the package for the message and updates its ID.

func (*Message) WithResource added in v0.8.4

func (m *Message) WithResource(resource *Resource) *Message

WithResource sets the resource definition on the message.

type Method

type Method struct {
	// Documentation is the documentation for the method.
	Documentation string
	// Name is the name of the attribute.
	Name string
	// ID is a unique identifier.
	ID string
	// Deprecated is true if the method is deprecated.
	Deprecated bool
	// InputTypeID is the ID of the input type for the Method.
	InputTypeID string
	// InputType is the input to the Method.
	InputType *Message
	// OutputTypeID is the ID of the output type for the Method.
	OutputTypeID string
	// OutputType is the output of the Method.
	OutputType *Message
	// ReturnsEmpty is true if the method returns nothing.
	//
	// Protobuf uses the well-known type `google.protobuf.Empty` message to
	// represent this.
	//
	// OpenAPIv3 uses a missing content field:
	//   https://swagger.io/docs/specification/v3_0/describing-responses/#empty-response-body
	ReturnsEmpty bool
	// PathInfo contains information about the HTTP request.
	PathInfo *PathInfo
	// Pagination holds the `page_token` field if the method conforms to the
	// standard defined by [AIP-4233](https://google.aip.dev/client-libraries/4233).
	Pagination *Field
	// ClientSideStreaming is true if the method supports client-side streaming.
	ClientSideStreaming bool
	// ServerSideStreaming is true if the method supports server-side streaming.
	ServerSideStreaming bool
	// OperationInfo contains information for methods returning long-running operations.
	OperationInfo *OperationInfo
	// DiscoveryLro has a value if this is a discovery-style long-running operation.
	DiscoveryLro *DiscoveryLro
	// Routing contains the routing annotations, if any.
	Routing []*RoutingInfo
	// AutoPopulated contains the auto-populated (request_id) field, if any, as defined in
	// [AIP-4235](https://google.aip.dev/client-libraries/4235)
	//
	// The field must be eligible for auto-population, and be listed in the
	// `google.api.MethodSettings.auto_populated_fields` entry in
	// `google.api.Publishing.method_settings` in the service config file.
	AutoPopulated []*Field
	// APIVersion contains the interface-based-versioning version.
	//
	// If this is empty, then the method does not have a version annotation.
	APIVersion string
	// Model is the model this method belongs to, mustache templates use this field to
	// navigate the data structure.
	Model *API
	// Service is the service this method belongs to, mustache templates use this field to
	// navigate the data structure.
	Service *Service
	// `SourceService` is the original service this method belongs to. For most
	// methods `SourceService` and `Service` are the same. For mixins, the
	// source service is the mixin, such as longrunning.Operations.
	SourceService *Service
	// `SourceServiceID` is the original service ID for this method.
	SourceServiceID string
	// IsSimple is true if the method is not a streaming, pagination or LRO method.
	IsSimple bool
	// IsLRO is true if the method is a long-running operation.
	IsLRO bool
	// LongRunningResponseType is the response type of the long-running operation.
	LongRunningResponseType *Message
	// LongRunningReturnsEmpty is true if the long-running operation returns an empty response.
	LongRunningReturnsEmpty bool
	// IsList is true if the method is a list operation.
	IsList bool
	// IsStreaming is true if the method is client-side or server-side streaming.
	IsStreaming bool
	// IsAIPStandard is true if the method is one of the AIP standard methods.
	IsAIPStandard bool
	// IsAIPStandardGet is true if the method is an AIP standard get method.
	IsAIPStandardGet bool
	// IsAIPStandardDelete is true if the method is an AIP standard delete method.
	IsAIPStandardDelete bool
	// IsAIPStandardUndelete is true if the method is an AIP standard undelete method.
	IsAIPStandardUndelete bool
	// IsAIPStandardCreate is true if the method is an AIP standard create method.
	IsAIPStandardCreate bool
	// IsAIPStandardUpdate is true if the method is an AIP standard update method.
	IsAIPStandardUpdate bool
	// IsAIPStandardList is true if the method is an AIP standard list method.
	IsAIPStandardList bool
	// SampleInfo may contain sample generation information for this method,
	// usually if it is an AIP conforming metho.
	SampleInfo *SampleInfo
	// Codec contains language specific annotations.
	Codec any
}

Method defines a RPC belonging to a Service.

func NewTestMethod added in v0.8.4

func NewTestMethod(name string) *Method

NewTestMethod creates a method with defaults for testing. Default package is "test" (implies ID .test.Name).

func (*Method) HasAutoPopulatedFields

func (m *Method) HasAutoPopulatedFields() bool

HasAutoPopulatedFields returns true if the method has auto-populated fields.

func (*Method) HasRouting

func (m *Method) HasRouting() bool

HasRouting returns true if the method has routing information.

func (*Method) RoutingCombos

func (m *Method) RoutingCombos() []*RoutingInfoCombo

RoutingCombos returns all combinations of routing parameters.

The routing info is stored as a map from the key to a list of the variants. e.g.:

```

{
  a: [va1, va2, va3],
  b: [vb1, vb2]
  c: [vc1]
}

```

We reorganize each kv pair into a list of pairs. e.g.:

``` [

[(a, va1), (a, va2), (a, va3)],
[(b, vb1), (b, vb2)],
[(c, vc1)],

] ```

Then we take a Cartesian product of that list to find all the combinations. e.g.:

``` [

[(a, va1), (b, vb1), (c, vc1)],
[(a, va1), (b, vb2), (c, vc1)],
[(a, va2), (b, vb1), (c, vc1)],
[(a, va2), (b, vb2), (c, vc1)],
[(a, va3), (b, vb1), (c, vc1)],
[(a, va3), (b, vb2), (c, vc1)],

] ```.

func (*Method) WithInput added in v0.8.4

func (m *Method) WithInput(msg *Message) *Method

WithInput sets the input type message for the method. It sets both InputType and InputTypeID.

func (*Method) WithOutput added in v0.8.4

func (m *Method) WithOutput(msg *Message) *Method

WithOutput sets the output type message for the method. It sets both OutputType and OutputTypeID.

func (*Method) WithPathTemplate added in v0.8.4

func (m *Method) WithPathTemplate(pt *PathTemplate) *Method

WithPathTemplate sets the path template for the first binding.

func (*Method) WithVerb added in v0.8.4

func (m *Method) WithVerb(verb string) *Method

WithVerb sets the HTTP verb for the first binding.

type ModelOverride added in v0.8.3

type ModelOverride struct {
	Name        string
	Title       string
	Description string
	IncludedIDs []string
	SkippedIDs  []string
}

ModelOverride holds configuration overrides for an API model.

type OneOf

type OneOf struct {
	// Name of the attribute.
	Name string
	// ID is a unique identifier.
	ID string
	// Documentation for the field.
	Documentation string
	// Fields associated with the one-of.
	Fields []*Field
	// The best field to show in a oneof related samples.
	// Non deprecated fields are preferred, then scalar, repeated, map fields
	// in that order.
	ExampleField *Field
	// Codec is a placeholder to put language specific annotations.
	Codec any
}

OneOf is a group of fields that are mutually exclusive. Notably, proto3 optional fields are all their own one-of.

type OperationInfo

type OperationInfo struct {
	// The metadata type. If there is no metadata, this is set to
	// `.google.protobuf.Empty`.
	MetadataTypeID string
	// The result type. This is the expected type when the long running
	// operation completes successfully.
	ResponseTypeID string
	// The method.
	Method *Method
	// Language specific annotations.
	Codec any
}

OperationInfo contains normalized long running operation info.

type PaginationInfo

type PaginationInfo struct {
	// The field that gives us the next page token.
	NextPageToken *Field
	// PageableItem is the field to be paginated over.
	PageableItem *Field
}

PaginationInfo contains information related to pagination aka [AIP-4233](https://google.aip.dev/client-libraries/4233).

type PaginationOverride added in v0.8.4

type PaginationOverride struct {
	// The method ID.
	ID string
	// The name of the field used for `items`.
	ItemField string
}

PaginationOverride describes overrides for pagination config of a method.

type Pair

type Pair struct {
	// Key of the pair.
	Key string
	// Value of the pair.
	Value string
}

Pair is a key-value pair.

type PathBinding

type PathBinding struct {
	// HTTP Verb.
	//
	// This is one of:
	// - GET
	// - POST
	// - PUT
	// - DELETE
	// - PATCH
	Verb string
	// The path broken by components.
	PathTemplate *PathTemplate
	// Query parameter fields.
	QueryParameters map[string]bool
	// TargetResource contains the results of the resource name identification.
	// This helps identify which resource this path is likely targeting.
	TargetResource *TargetResource
	// Language specific annotations.
	Codec any
}

PathBinding is a binding of a path to a method.

type PathInfo

type PathInfo struct {
	// The list of bindings, including the top-level binding.
	Bindings []*PathBinding
	// Body is the name of the field that should be used as the body of the
	// request.
	//
	// This is a string that may be "*" which indicates that the entire request
	// should be used as the body.
	//
	// If this is empty then the body is not used.
	BodyFieldPath string
	// Language specific annotations.
	Codec any
}

PathInfo contains normalized request path information.

type PathSegment

type PathSegment struct {
	Literal  *string
	Variable *PathVariable
}

PathSegment is a segment of a path.

func NewPathSegment added in v0.8.0

func NewPathSegment() *PathSegment

NewPathSegment creates a new path segment.

func ParseTemplateForTest added in v0.8.4

func ParseTemplateForTest(template string) []PathSegment

ParseTemplateForTest converts a string literal into a []PathSegment slice for testing purposes.

func (*PathSegment) WithLiteral added in v0.8.0

func (s *PathSegment) WithLiteral(l string) *PathSegment

WithLiteral adds a literal to the path segment.

func (*PathSegment) WithVariable added in v0.8.0

func (s *PathSegment) WithVariable(v *PathVariable) *PathSegment

WithVariable adds a variable to the path segment.

type PathTemplate

type PathTemplate struct {
	Segments []PathSegment
	Verb     *string
}

PathTemplate is a template for a path.

func NewPathTemplate

func NewPathTemplate() *PathTemplate

NewPathTemplate creates a new PathTemplate.

func (*PathTemplate) FlatPath

func (template *PathTemplate) FlatPath() string

FlatPath returns a simplified representation of the path template as a string.

In the context of discovery LROs it is useful to get the path template as a simplified string, such as "compute/v1/projects/{project}/zones/{zone}/instances". The path can be matched against LRO prefixes and then mapped to the correct poller RPC.

func (*PathTemplate) WithLiteral

func (p *PathTemplate) WithLiteral(l string) *PathTemplate

WithLiteral adds a literal to the path template.

func (*PathTemplate) WithVariable

func (p *PathTemplate) WithVariable(v *PathVariable) *PathTemplate

WithVariable adds a variable to the path template.

func (*PathTemplate) WithVariableNamed

func (p *PathTemplate) WithVariableNamed(fields ...string) *PathTemplate

WithVariableNamed adds a variable with the given name to the path template.

func (*PathTemplate) WithVerb

func (p *PathTemplate) WithVerb(v string) *PathTemplate

WithVerb adds a verb to the path template.

type PathVariable

type PathVariable struct {
	FieldPath []string
	Segments  []string
	// Allow characters defined as `reserved` by RFC-6570 1.5 to pass through without
	// percent encoding. See RFC-6570 1.2 for examples.
	AllowReserved bool
}

PathVariable is a variable in a path.

func NewPathVariable

func NewPathVariable(fields ...string) *PathVariable

NewPathVariable creates a new path variable.

func (*PathVariable) WithAllowReserved added in v0.8.0

func (v *PathVariable) WithAllowReserved() *PathVariable

WithAllowReserved marks the variable as allowing reserved characters to remain unescaped.

func (*PathVariable) WithLiteral

func (v *PathVariable) WithLiteral(l string) *PathVariable

WithLiteral adds a literal to the path variable.

func (*PathVariable) WithMatch

func (v *PathVariable) WithMatch() *PathVariable

WithMatch adds a match to the path variable.

func (*PathVariable) WithMatchRecursive

func (v *PathVariable) WithMatchRecursive() *PathVariable

WithMatchRecursive adds a recursive match to the path variable.

type Poller added in v0.8.4

type Poller struct {
	// An acceptable prefix for the URL path, for example:
	//     `compute/v1/projects/{project}/zones/{zone}`
	Prefix string

	// The corresponding method ID.
	MethodID string
}

Poller defines how to find a suitable poller RPC.

For operations that may be LROs sidekick will match the URL path of the RPC against the prefixes.

func (*Poller) PathParameters added in v0.8.4

func (p *Poller) PathParameters() []string

PathParameters returns the list of path parameters associated with a LRO poller.

In discovery-based APIs different LRO functions use different polling methods. Each one of those methods uses a *subset* of the LRO functions to poll the operation. This method returns that subset.

type Resource added in v0.8.0

type Resource struct {
	// Type identifies the kind of resource (e.g., "cloudresourcemanager.googleapis.com/Project").
	// This string is globally unique and identifies the type of resource across Google Cloud.
	Type string
	// Pattern is a list of resource patterns, where each pattern is a sequence of path segments.
	// This defines the structure of the resource's unique identifier.
	Patterns []ResourcePattern
	// Plural is the plural form of the resource name.
	// For example, for a "Book" resource, Plural would be "books".
	Plural string
	// Singular is the singular form of the resource name.
	// For example, for a "Book" resource, Singular would be "book".
	Singular string
	// Self points to the Message that defines this resource.
	// This creates a back-reference for navigating the API model,
	// allowing a Resource definition to access its originating Message structure.
	Self *Message
	// Language specific annotations.
	Codec any
}

Resource is a fundamental building block of an API, representing an individually-named entity (a "noun").

Resources are typically organized into a hierarchy, where each node is either a simple resource or a collection of resources. This definition is based on AIP-121 (https://google.aip.dev/121).

func NewTestResource added in v0.8.4

func NewTestResource(typez string) *Resource

NewTestResource creates a resource with defaults.

func (*Resource) WithPatterns added in v0.8.4

func (r *Resource) WithPatterns(patterns ...ResourcePattern) *Resource

WithPatterns adds patterns to the resource.

func (*Resource) WithSingular added in v0.8.4

func (r *Resource) WithSingular(singular string) *Resource

WithSingular sets the singular name of the resource.

type ResourcePattern added in v0.8.0

type ResourcePattern []PathSegment

ResourcePattern is a sequence of path segments that defines the structure of a resource's unique identifier.

type ResourceReference added in v0.8.0

type ResourceReference struct {
	// Type is the unique identifier of the referenced resource's kind (e.g., "library.googleapis.com/Shelf").
	// This string matches the `Type` field in the corresponding `Resource` definition.
	Type string
	// ChildType is the unique identifier of a *child* resource's kind.
	// This is used when a field references a parent resource (e.g., "Shelf"), but the context
	// implies interaction with a specific child type (e.g., "Book" within that shelf).
	ChildType string
	// Language specific annotations.
	Codec any
}

ResourceReference describes a field's relationship to another resource type. It acts as a foreign key, indicating that the field's value identifies an instance of another resource. This relationship is established via the `google.api.resource_reference` annotation in Protobuf.

type RoutingInfo

type RoutingInfo struct {
	// The name in `x-goog-request-params`.
	Name string
	// Group the possible variants for the given name.
	//
	// The variants are parsed into the reverse order of definition. AIP-4222
	// declares:
	//
	//   In cases when multiple routing parameters have the same resource ID
	//   path segment name, thus referencing the same header key, the
	//   "last one wins" rule is used to determine which value to send.
	//
	// Reversing the order allows us to implement "the first match wins". That
	// is easier and more efficient in most languages.
	Variants []*RoutingInfoVariant
}

RoutingInfo contains normalized routing info.

The routing information format is documented in:

https://google.aip.dev/client-libraries/4222

At a high level, it consists of a field name (from the request) that is used to match a certain path template. If the value of the field matches the template, the matching portion is added to `x-goog-request-params`.

An empty `Name` field is used as the special marker to cover this case in AIP-4222:

An empty google.api.routing annotation is acceptable. It means that no
routing headers should be generated for the RPC, when they otherwise
would be e.g. implicitly from the google.api.http annotation.

type RoutingInfoCombo

type RoutingInfoCombo struct {
	Items []*RoutingInfoComboItem
}

RoutingInfoCombo represents a single combination of routing parameters.

type RoutingInfoComboItem

type RoutingInfoComboItem struct {
	Name    string
	Variant *RoutingInfoVariant
}

RoutingInfoComboItem represents a single item in a RoutingInfoCombo.

type RoutingInfoVariant

type RoutingInfoVariant struct {
	// The sequence of field names accessed to get the routing information.
	FieldPath []string
	// A path template that must match the beginning of the field value.
	Prefix RoutingPathSpec
	// A path template that, if matching, is used in the `x-goog-request-params`.
	Matching RoutingPathSpec
	// A path template that must match the end of the field value.
	Suffix RoutingPathSpec
	// Language specific information
	Codec any
}

RoutingInfoVariant represents the routing information stripped of its name.

func (*RoutingInfoVariant) FieldName

func (v *RoutingInfoVariant) FieldName() string

FieldName returns the field path as a string.

func (*RoutingInfoVariant) TemplateAsString

func (v *RoutingInfoVariant) TemplateAsString() string

TemplateAsString returns the template as a string.

type RoutingPathSpec

type RoutingPathSpec struct {
	// A sequence of matching segments.
	//
	// A template like `projects/*/location/*/**` maps to
	// `["projects", "*", "locations", "*", "**"]`.
	Segments []string
}

RoutingPathSpec is a specification for a routing path.

type SampleInfo added in v0.8.4

type SampleInfo struct {
	// ResourceNameField is the field containing the resource name or parent resource name.
	ResourceNameField *Field
	// ResourceIDField is the field containing the resource ID, usually present in Create methods.
	ResourceIDField *Field
	// MessageField is the field containing the message body to be created or updated.
	MessageField *Field
	// UpdateMaskField is the field containing the update mask, present in Update methods.
	UpdateMaskField *Field
}

SampleInfo contains sample generation information for a single method, usually if it is an AIP conforming method.

type SampleValue added in v0.8.4

type SampleValue struct {
	// The enum value.
	EnumValue *EnumValue
	// The index of the value in the sample list (0-based).
	Index int
}

SampleValue represents a value used in a sample.

type Service

type Service struct {
	// Documentation for the service.
	Documentation string
	// Name of the attribute.
	Name string
	// ID is a unique identifier.
	ID string
	// Some source specifications allow marking services as deprecated.
	Deprecated bool
	// Methods associated with the Service.
	Methods []*Method
	// DefaultHost fragment of a URL.
	DefaultHost string
	// The Protobuf package this service belongs to.
	Package string

	// The model this service belongs to, mustache templates use this field to
	// navigate the data structure.
	Model *API
	// QuickstartMethod is the method that will be used to generate the quickstart sample
	// for this service.
	QuickstartMethod *Method
	// Language specific annotations.
	Codec any
}

Service represents a service in an API.

func NewTestService added in v0.8.4

func NewTestService(name string) *Service

NewTestService creates a service with defaults for testing. Default package is "test".

func (*Service) Scopes

func (x *Service) Scopes() []string

Scopes returns the scopes for a service.

func (*Service) WithMethods added in v0.8.4

func (s *Service) WithMethods(methods ...*Method) *Service

WithMethods adds methods to the service and updates their ID/Service.

func (*Service) WithPackage added in v0.8.4

func (s *Service) WithPackage(pkg string) *Service

WithPackage sets the package for the service and updates its ID.

type ServiceDependencies

type ServiceDependencies struct {
	Messages []string
	Enums    []string
}

ServiceDependencies holds the message and enum dependencies for a service.

func FindServiceDependencies

func FindServiceDependencies(model *API, serviceID string) *ServiceDependencies

FindServiceDependencies returns the message and enum IDs that are required by a given service.

The function traverses `model` starting from the definition of `serviceID`.

  • Any message used by a method of the service is included in the results.
  • Any message used by LROs of the service is included in the results.
  • The results are recursively scanned searching for any fields of the messages included above.
  • If a nested message is included in the results, then the parent message is also included (recursively) in the results.

type TargetResource added in v0.8.4

type TargetResource struct {
	// FieldPaths is a list of field name sequences that, when joined, form a resource name.
	// For example, [["project"], ["zone"], ["instance"]] identifies a multi-part resource.
	FieldPaths [][]string

	// Template is the canonical HTTP path template for the resource, derived from the PathBinding's PathTemplate by removing the API version prefix.
	// For example, if the PathTemplate is "//compute.googleapis.com/projects/{project}/zones/{zone}", the Template will be a []PathSegment containing:
	// - a Literal segment for "//compute.googleapis.com"
	// - a Literal segment for "projects"
	// - a Variable segment with FieldPath ["project"]
	// - a Literal segment for "zones"
	// - a Variable segment with FieldPath ["zone"]
	Template []PathSegment
}

TargetResource contains the results of the resource name identification. It provides the sequences of fields used by language-specific generators to inject tracing attributes.

type Typez

type Typez int

Typez represent different field types that may be found in messages.

const (
	UNDEFINED_TYPE Typez = 0
	DOUBLE_TYPE    Typez = 1
	FLOAT_TYPE     Typez = 2
	INT64_TYPE     Typez = 3
	UINT64_TYPE    Typez = 4
	INT32_TYPE     Typez = 5
	FIXED64_TYPE   Typez = 6
	FIXED32_TYPE   Typez = 7
	BOOL_TYPE      Typez = 8
	STRING_TYPE    Typez = 9
	GROUP_TYPE     Typez = 10
	MESSAGE_TYPE   Typez = 11
	BYTES_TYPE     Typez = 12
	UINT32_TYPE    Typez = 13
	ENUM_TYPE      Typez = 14
	SFIXED32_TYPE  Typez = 15
	SFIXED64_TYPE  Typez = 16
	SINT32_TYPE    Typez = 17
	SINT64_TYPE    Typez = 18
)

These are the different field types as defined in descriptorpb.FieldDescriptorProto_Type.

func (Typez) String added in v0.10.0

func (t Typez) String() string

String returns the symbolic name for the Typez.

Directories

Path Synopsis
Package apitest provides helper functions for testing the api package.
Package apitest provides helper functions for testing the api package.

Jump to

Keyboard shortcuts

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