codegen

package
v0.1.2 Latest Latest
Warning

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

Go to latest
Published: Aug 28, 2018 License: MIT Imports: 28 Imported by: 18

Documentation

Index

Constants

View Source
const (
	// SingleModule defines a module class type that has 1 directory
	SingleModule moduleClassType = iota
	// MultiModule defines a module class type with multiple nested directories
	MultiModule moduleClassType = iota
)
View Source
const (

	// AntHTTPReqDefBoxed annotates a method so that the genereted method takes
	// generated argument directly instead of a struct that warps the argument.
	// The annotated method should have one and only one argument.
	AntHTTPReqDefBoxed = "%s.http.req.def"
)

Variables

View Source
var CommonInitialisms = map[string]bool{
	"ACL":   true,
	"API":   true,
	"ASCII": true,
	"CPU":   true,
	"CSS":   true,
	"DNS":   true,
	"EOF":   true,
	"GUID":  true,
	"HTML":  true,
	"HTTP":  true,
	"HTTPS": true,
	"ID":    true,
	"IP":    true,
	"JSON":  true,
	"LHS":   true,
	"OS":    true,
	"QPS":   true,
	"RAM":   true,
	"RHS":   true,
	"RPC":   true,
	"SLA":   true,
	"SMTP":  true,
	"SQL":   true,
	"SSH":   true,
	"TCP":   true,
	"TLS":   true,
	"TTL":   true,
	"UDP":   true,
	"UI":    true,
	"UID":   true,
	"UUID":  true,
	"URI":   true,
	"URL":   true,
	"UTF8":  true,
	"VM":    true,
	"XML":   true,
	"XMPP":  true,
	"XSRF":  true,
	"XSS":   true,
}

CommonInitialisms is taken from https://github.com/golang/lint/blob/206c0f020eba0f7fbcfbc467a5eb808037df2ed6/lint.go#L731

Functions

func CamelCase

func CamelCase(src string) string

CamelCase converts the given string to camel case

func CamelToSnake

func CamelToSnake(s string) string

CamelToSnake converts a given string to snake case, based on https://github.com/serenize/snaker/blob/master/snaker.go

func FindClientsWithFixture

func FindClientsWithFixture(instance *ModuleInstance) (map[string]string, error)

FindClientsWithFixture finds the given module's dependent clients that have fixture config

func FormatGoFile

func FormatGoFile(filePath string) error

FormatGoFile reformat the go file imports

func GenerateDependencyStruct

func GenerateDependencyStruct(
	instance *ModuleInstance,
	packageHelper *PackageHelper,
	template *Template,
) ([]byte, error)

GenerateDependencyStruct generates a module struct with placeholders for the instance module based on the defined dependency configuration

func GenerateInitializer

func GenerateInitializer(
	instance *ModuleInstance,
	packageHelper *PackageHelper,
	template *Template,
) ([]byte, error)

GenerateInitializer generates a file that initializes a module fully recursively, i.e. by initializing all of its dependencies in the correct order

func GoReferenceType

func GoReferenceType(p PackageNameResolver, spec compile.TypeSpec) (string, error)

GoReferenceType returns the Go reference type string representation for the given thrift type. for types like slice and map that are already of reference type, it returns the result of GoType; for struct type, it returns the pointer of the result of GoType.

func GoType

func GoType(p PackageNameResolver, spec compile.TypeSpec) (string, error)

GoType returns the Go type string representation for the given thrift type.

func IsStructType

func IsStructType(spec compile.TypeSpec) bool

IsStructType returns true if the given thrift type is struct, false otherwise.

func LintAcronym

func LintAcronym(key string) string

LintAcronym correct the naming for initialisms

func PascalCase

func PascalCase(src string) string

PascalCase converts the given string to pascal case

func PrintGenLine

func PrintGenLine(
	classType, className, instanceName, buildPath string,
	idx, count int,
)

PrintGenLine prints the module generation process to stdout

func ReflectInterface

func ReflectInterface(projRoot string, pathSymbolMap map[string]string) (map[string]*model.Package, error)

ReflectInterface uses reflection to obtain interface information for each path symbol pair in the pathSympolMap projRoot is the root dir where mockgen is installed as a vendor package

func SchemaValidateGo

func SchemaValidateGo(schemaFile string, arbitraryObj map[string]interface{}) error

SchemaValidateGo performs JSON schema validation from schema file on to arbitrary Go object

func WriteAndFormat

func WriteAndFormat(path string, data []byte) error

WriteAndFormat writes the data (Go code) to given file path, creates path if it does not exist and formats the file using gofmt

Types

type AssetProvider

type AssetProvider interface {
	// AssetNames returns a list of named assets available
	AssetNames() []string
	// Asset returns the bytes for a provided asset name
	Asset(string) ([]byte, error)
}

AssetProvider provides access to template assets

type BodyType

type BodyType string

BodyType can either be `json` or `string`

type BuildGenerator

type BuildGenerator interface {
	Generate(
		instance *ModuleInstance,
	) (*BuildResult, error)
}

BuildGenerator provides a function to generate a module instance build artifact from its configuration as part of a build step. For example, an Endpoint module instance may generate endpoint handler code

type BuildResult

type BuildResult struct {
	// Files contains a map of file names to file bytes to be written to the
	// module build directory
	Files map[string][]byte
	// Spec is an arbitrary type that can be used to share computed data
	// between dependencies
	Spec interface{}
}

BuildResult is the result of running a module generator

type ClientClassConfig

type ClientClassConfig struct {
	Name         string                 `json:"name"`
	Type         string                 `json:"type"`
	Config       map[string]interface{} `json:"config"`
	Dependencies Dependencies           `json:"dependencies"`
}

ClientClassConfig represents the specific config for a client. This is a downcast of the moduleClassConfig.

type ClientMeta

type ClientMeta struct {
	Instance         *ModuleInstance
	ExportName       string
	ExportType       string
	ClientID         string
	IncludedPackages []GoPackageImport
	Services         []*ServiceSpec
	ExposedMethods   map[string]string
	SidecarRouter    string
	Fixture          *Fixture
	StagingReqHeader string
	DeputyReqHeader  string
}

ClientMeta ...

type ClientSpec

type ClientSpec struct {
	// ModuleSpec holds the thrift module information
	ModuleSpec *ModuleSpec
	// JSONFile for this spec
	JSONFile string
	// ClientType, currently "http", "tchannel" and "custom" are supported
	ClientType string
	// If "custom" then where to import custom code from
	CustomImportPath string
	// The path to the client package import
	ImportPackagePath string
	// The globally unique package alias for the import
	ImportPackageAlias string
	// ExportName is the name that should be used when initializing the module
	// on a dependency struct.
	ExportName string
	// ExportType refers to the type returned by the module initializer
	ExportType string
	// ThriftFile, absolute path to thrift file
	ThriftFile string
	// ClientID, used for logging and metrics, must be lowercase
	// and use dashes.
	ClientID string
	// ClientName, PascalCase name of the client, the generated
	// `Clients` struct will contain a field of this name
	ClientName string
	// ExposedMethods is a map of exposed method name to thrift "$service::$method"
	// only the method values in this map are generated for the client
	ExposedMethods map[string]string
	// SidecarRouter indicates the client uses the given sidecar router to
	// to communicate with downstream service, it's not relevant to custom clients.
	SidecarRouter string
}

ClientSpec holds information about each client in the gateway included its thriftFile and other meta info

func NewClientSpec

func NewClientSpec(
	instance *ModuleInstance,
	h *PackageHelper,
) (*ClientSpec, error)

NewClientSpec creates a client spec from a json file.

func NewCustomClientSpec

func NewCustomClientSpec(
	instance *ModuleInstance,
	clientConfig *ClientClassConfig,
	h *PackageHelper,
) (*ClientSpec, error)

NewCustomClientSpec creates a client spec from a json file whose type is custom

func NewHTTPClientSpec

func NewHTTPClientSpec(
	instance *ModuleInstance,
	clientConfig *ClientClassConfig,
	h *PackageHelper,
) (*ClientSpec, error)

NewHTTPClientSpec creates a client spec from a http client module instance

func NewTChannelClientSpec

func NewTChannelClientSpec(
	instance *ModuleInstance,
	clientConfig *ClientClassConfig,
	h *PackageHelper,
) (*ClientSpec, error)

NewTChannelClientSpec creates a client spec from a json file whose type is tchannel

type ClientTestFixture

type ClientTestFixture struct {
	ClientID         string          `json:"clientId"`
	ClientMethod     string          `json:"clientMethod"`
	ClientRequest    FixtureRequest  `json:"clientRequest"` // there's no difference between http or tchannel request
	ClientReqHeaders FixtureBlob     `json:"clientReqHeaders"`
	ClientResponse   FixtureResponse `json:"clientResponse"`
	ClientResHeaders FixtureBlob     `json:"clientResHeaders"`
}

ClientTestFixture saves mocked client request/response for an endpoint test.

type CustomClientGenerator

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

CustomClientGenerator gathers the custom client spec for future use in ClientsInitGenerator

func (*CustomClientGenerator) Generate

func (g *CustomClientGenerator) Generate(
	instance *ModuleInstance,
) (*BuildResult, error)

Generate returns the custom client build result, which contains the generated client spec and no files

type Dependencies

type Dependencies struct {
	Client []string `json:"client"`
}

Dependencies lists all dependencies of a module

type EndpointClassConfig

type EndpointClassConfig struct {
	Name   string `json:"name"`
	Type   string `json:"type"`
	Config struct {
		Ratelimit int32    `json:"rateLimit"`
		Endpoints []string `json:"endpoints"`
	} `json:"config"`
	Dependencies map[string][]string `json:"dependencies"`
}

EndpointClassConfig represents the specific config for an endpoint group. This is a downcast of the moduleClassConfig.

type EndpointCollectionMeta

type EndpointCollectionMeta struct {
	Instance     *ModuleInstance
	EndpointMeta []*EndpointMeta
}

EndpointCollectionMeta saves information used to generate an initializer for a collection of endpoints

type EndpointGenerator

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

EndpointGenerator generates a group of zanzibar endpoints that proxy corresponding clients

func (*EndpointGenerator) Generate

func (g *EndpointGenerator) Generate(
	instance *ModuleInstance,
) (*BuildResult, error)

Generate returns the endpoint build result, which contains a file per endpoint handler and a list of handler specs

type EndpointMeta

type EndpointMeta struct {
	Instance               *ModuleInstance
	Spec                   *EndpointSpec
	GatewayPackageName     string
	IncludedPackages       []GoPackageImport
	Method                 *MethodSpec
	ClientName             string
	ClientID               string
	ClientMethodName       string
	WorkflowPkg            string
	ReqHeaders             map[string]*TypedHeader
	ReqHeadersKeys         []string
	ReqRequiredHeadersKeys []string
	ResHeaders             map[string]*TypedHeader
	ResHeadersKeys         []string
	ResRequiredHeadersKeys []string
	TraceKey               string
	DeputyReqHeader        string
}

EndpointMeta saves meta data used to render an endpoint.

type EndpointSpec

type EndpointSpec struct {
	// ModuleSpec holds the thrift module info
	ModuleSpec *ModuleSpec
	// JSONFile for this endpoint spec
	JSONFile string
	// GoStructsFileName is where structs are generated
	GoStructsFileName string
	// GoFolderName is the folder where all the endpoints
	// are generated.
	GoFolderName string
	// GoPackageName is the package import path.
	GoPackageName string

	// EndpointType, currently only "http"
	EndpointType string
	// EndpointID, used in metrics and logging, lower case.
	EndpointID string
	// HandleID, used in metrics and logging, lowercase.
	HandleID string
	// ThriftFile, the thrift file for this endpoint
	ThriftFile string
	// ThriftMethodName, which thrift method to use.
	ThriftMethodName string
	// ThriftServiceName, which thrift service to use.
	ThriftServiceName string
	// TestFixtures, meta data to generate tests,
	TestFixtures map[string]*EndpointTestFixture
	// Middlewares, meta data to add middlewares,
	Middlewares []MiddlewareSpec
	// HeadersPropagate, a map from endpoint request headers to
	// client request fields.
	HeadersPropagate map[string]FieldMapperEntry
	// ReqTransforms, a map from client request fields to endpoint
	// request fields that should override their values.
	ReqTransforms map[string]FieldMapperEntry
	// RespTransforms, a map from endpoint response fields to client
	// response fields that should override their values.
	RespTransforms map[string]FieldMapperEntry
	// ReqHeaders maps headers from server to client
	ReqHeaders map[string]*TypedHeader
	// ResHeaders maps headers from client to server
	ResHeaders map[string]*TypedHeader
	// WorkflowType, either "httpClient" or "custom".
	// A httpClient workflow generates a http client Caller
	// A custom workflow just imports the custom code
	WorkflowType string
	// If "custom" then where to import custom code from
	WorkflowImportPath string
	// if "httpClient", which client to call.
	ClientID string
	// if "httpClient", which client method to call.
	ClientMethod string
	// The client for this endpoint if httpClient or tchannelClient
	ClientSpec *ClientSpec
}

EndpointSpec holds information about each endpoint in the gateway including its thriftFile and meta data

func NewEndpointSpec

func NewEndpointSpec(
	jsonFile string,
	h *PackageHelper,
	midSpecs map[string]*MiddlewareSpec,
) (*EndpointSpec, error)

NewEndpointSpec creates an endpoint spec from a json file.

func (*EndpointSpec) EndpointTestConfigPath

func (e *EndpointSpec) EndpointTestConfigPath() string

EndpointTestConfigPath generates a filepath for each endpoint test config

func (*EndpointSpec) SetDownstream

func (e *EndpointSpec) SetDownstream(
	clientModules []*ClientSpec,
	h *PackageHelper,
) error

SetDownstream configures the downstream client for this endpoint spec

func (*EndpointSpec) TargetEndpointPath

func (e *EndpointSpec) TargetEndpointPath(
	serviceName string, methodName string,
) string

TargetEndpointPath generates a filepath for each endpoint method

func (*EndpointSpec) TargetEndpointTestPath

func (e *EndpointSpec) TargetEndpointTestPath(
	serviceName string, methodName string,
) string

TargetEndpointTestPath generates a filepath for each endpoint test

type EndpointTestFixture

type EndpointTestFixture struct {
	TestName           string                        `json:"testName"`
	EndpointID         string                        `json:"endpointId"`
	HandleID           string                        `json:"handleId"`
	EndpointRequest    FixtureRequest                `json:"endpointRequest"` // there's no difference between http or tchannel request
	EndpointReqHeaders FixtureBlob                   `json:"endpointReqHeaders"`
	EndpointResponse   FixtureResponse               `json:"endpointResponse"`
	EndpointResHeaders FixtureBlob                   `json:"endpointResHeaders"`
	ClientTestFixtures map[string]*ClientTestFixture `json:"clientTestFixtures"`
	TestServiceName    string                        `json:"testServiceName"` // The service module that mounts the endpoint
}

EndpointTestFixture saves mocked requests/responses for an endpoint test.

type EndpointTestMeta

type EndpointTestMeta struct {
	Instance           *ModuleInstance
	Method             *MethodSpec
	TestFixtures       map[string]*EndpointTestFixture `json:"testFixtures"`
	ReqHeaders         map[string]*TypedHeader
	ResHeaders         map[string]*TypedHeader
	ClientName         string
	ClientID           string
	RelativePathToRoot string
	IncludedPackages   []GoPackageImport
}

EndpointTestMeta saves meta data used to render an endpoint test.

type ExceptionSpec

type ExceptionSpec struct {
	StructSpec

	StatusCode StatusCode
}

ExceptionSpec contains information about thrift exceptions

type FieldAssignment

type FieldAssignment struct {
	From           *compile.FieldSpec
	FromIdentifier string
	To             *compile.FieldSpec
	ToIdentifier   string
	TypeCast       string
	ExtraNilCheck  bool
}

FieldAssignment is responsible to generate an assignment

func (*FieldAssignment) Generate

func (f *FieldAssignment) Generate(indent string, uninitialized map[string]*fieldStruct, prevKeyPrefixes []string, useRecurGen bool) string

Generate generates assignment

func (*FieldAssignment) IsTransform

func (f *FieldAssignment) IsTransform() bool

IsTransform returns true if field assignment is not proxy

type FieldMapperEntry

type FieldMapperEntry struct {
	QualifiedName string //
	Field         *compile.FieldSpec

	Override bool
	// contains filtered or unexported fields
}

FieldMapperEntry defines a source field and optional arguments converting and overriding fields.

type Fixture

type Fixture struct {
	// ImportPath is the package where the user-defined Fixture global variable is contained.
	// The Fixture object defines, for a given client, the standardized list of fixture scenarios for that client
	ImportPath string `json:"importPath"`
	// Scenarios is a map from zanzibar's exposed method name to a list of user-defined fixture scenarios for a client
	Scenarios map[string][]string `json:"scenarios"`
}

Fixture specifies client fixture import path and all scenarios

func (*Fixture) Validate

func (f *Fixture) Validate(methods map[string]interface{}) error

Validate the fixture configuration

type FixtureBlob

type FixtureBlob map[string]interface{}

FixtureBlob is map[string]interface{} that implements default string used for headers and (http | tchannel) request/response

func (*FixtureBlob) String

func (fb *FixtureBlob) String() string

String convert FixtureBlob to string

type FixtureBody

type FixtureBody struct {
	BodyType   BodyType     `json:"bodyType,omitempty"`
	BodyString string       `json:"bodyString,omitempty"` // set BodyString if response body is string
	BodyJSON   *FixtureBlob `json:"bodyJson,omitempty"`   // set BodyJSON if response body is object
}

FixtureBody is used to create http body in test fixtures

func (*FixtureBody) String

func (fb *FixtureBody) String() string

String convert FixtureBody to string This String() panics inside if type and value mismatch during unmarshal because template cannot handle errors

type FixtureHTTPRequest

type FixtureHTTPRequest struct {
	Method HTTPMethodType `json:"method,omitempty"`
	Body   *FixtureBody   `json:"body,omitempty"`
}

FixtureHTTPRequest is test fixture for client/endpoint request

type FixtureHTTPResponse

type FixtureHTTPResponse struct {
	StatusCode int          `json:"statusCode"`
	Body       *FixtureBody `json:"body,omitempty"`
}

FixtureHTTPResponse is test fixture for http response

type FixtureRequest

type FixtureRequest struct {
	RequestType     ProtocalType        `json:"requestType"`
	HTTPRequest     *FixtureHTTPRequest `json:"httpRequest,omitempty"`
	TChannelRequest FixtureBlob         `json:"tchannelRequest,omitempty"`
}

FixtureRequest is test fixture for client/endpoint request

func (*FixtureRequest) Body

func (fr *FixtureRequest) Body() string

Body returns the string representation of FixtureRequest

type FixtureResponse

type FixtureResponse struct {
	ResponseType     ProtocalType         `json:"responseType"`
	HTTPResponse     *FixtureHTTPResponse `json:"httpResponse,omitempty"`
	TChannelResponse FixtureBlob          `json:"tchannelResponse,omitempty"`
}

FixtureResponse is test fixture for client/endpoint response

func (*FixtureResponse) Body

func (fr *FixtureResponse) Body() string

Body returns the string representation of FixtureResponse

type GatewayServiceGenerator

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

GatewayServiceGenerator generates an entry point for a single service as a main.go that bootstraps the service and its dependencies

func NewGatewayServiceGenerator

func NewGatewayServiceGenerator(t *Template, h *PackageHelper) *GatewayServiceGenerator

NewGatewayServiceGenerator creates a new gateway service generator.

func (*GatewayServiceGenerator) Generate

func (generator *GatewayServiceGenerator) Generate(
	instance *ModuleInstance,
) (*BuildResult, error)

Generate returns the gateway build result, which contains the service and service test main files, and no spec

type GoPackageImport

type GoPackageImport struct {
	PackageName string
	AliasName   string
}

GoPackageImport ...

type HTTPClientGenerator

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

HTTPClientGenerator generates an instance of a zanzibar http client

func (*HTTPClientGenerator) Generate

func (g *HTTPClientGenerator) Generate(
	instance *ModuleInstance,
) (*BuildResult, error)

Generate returns the HTTP client build result, which contains the files and the generated client spec

type HTTPMethodType

type HTTPMethodType string

HTTPMethodType can only be valid http method

type HeaderFieldInfo

type HeaderFieldInfo struct {
	FieldIdentifier string
	IsPointer       bool
}

HeaderFieldInfo contains information about where to store the string from headers into the request/response body.

type HeaderPropagator

type HeaderPropagator struct {
	LineBuilder
	Helper PackageNameResolver
}

HeaderPropagator generates function propagates endpoint request headers to client request body

func NewHeaderPropagator

func NewHeaderPropagator(h PackageNameResolver) *HeaderPropagator

NewHeaderPropagator returns an instance of HeaderPropagator

func (*HeaderPropagator) Propagate

func (hp *HeaderPropagator) Propagate(
	headers []string,
	toFields []*compile.FieldSpec,
	fieldMap map[string]FieldMapperEntry,
) error

Propagate assigns header value to downstream client request fields based on fieldMap

type JSONClassConfig

type JSONClassConfig struct {
	// Name is the class instance name used to identify the module as a
	// dependency. The combination of the class Name and this instance name
	// is unique.
	Name string `json:"name"`
	// The configuration map for this class instance. This depends on the
	// class name and class type, and is interpreted by each module generator.
	Config map[string]interface{} `json:"config"`
	// Dependencies is a map of class name to a list of instance names. This
	// infers the dependencies struct generated for the initializer
	Dependencies map[string][]string `json:"dependencies"`
	// Type refers to the class type used to generate the dependency
	Type string `json:"type"`
	// IsExportGenerated determines whether or not the export lives in
	// IsExportGenerated defaults to true if not set.
	IsExportGenerated *bool `json:"IsExportGenerated"`
}

JSONClassConfig maps onto a json configuration for a class type

func (*JSONClassConfig) Read

func (jsonConfig *JSONClassConfig) Read(
	classConfigPath string,
) ([]byte, error)

Read will read a class configuration json file into a jsonClassConfig struct or return an error if it cannot be unmarshaled into the struct

type LineBuilder

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

LineBuilder struct just appends/builds lines.

func (*LineBuilder) GetLines

func (l *LineBuilder) GetLines() []string

GetLines returns the lines in the line builder

type MethodSpec

type MethodSpec struct {
	Name       string
	HTTPMethod string
	// Used by edge gateway to generate endpoint.
	EndpointName string
	HTTPPath     string
	PathSegments []PathSegment

	IsEndpoint bool

	// Statements for reading query parameters.
	ParseQueryParamGoStatements []string

	// Statements for writing query parameters
	WriteQueryParamGoStatements []string

	// Statements for reading request headers
	ReqHeaderGoStatements []string

	// Statements for reading request headers for clients
	ReqClientHeaderGoStatements []string

	// ResHeaderFields is a map of header name to a golang
	// field accessor expression used to read fields out
	// of the response body and place them into response headers
	ResHeaderFields map[string]HeaderFieldInfo

	// ReqHeaders needed, generated from "zanzibar.http.reqHeaders"
	ReqHeaders []string
	// ResHeaders needed, generated from "zanzibar.http.resHeaders"
	ResHeaders []string

	RequestType       string
	ShortRequestType  string
	ResponseType      string
	ShortResponseType string
	OKStatusCode      StatusCode
	Exceptions        []ExceptionSpec
	ExceptionsIndex   map[string]ExceptionSpec
	ValidStatusCodes  []int
	// Additional struct generated from the bundle of request args.
	RequestBoxed bool
	// Thrift service name the method belongs to.
	ThriftService string
	// The thriftrw-generated go package name
	GenCodePkgName string
	// Whether the method needs annotation or not.
	WantAnnot bool
	// The thriftrw compiled spec, used to extract type information
	CompiledThriftSpec *compile.FunctionSpec
	// The downstream service method set by endpoint config
	Downstream *ModuleSpec
	// the downstream service name
	DownstreamService string
	// The downstream method spec for the endpoint
	DownstreamMethod *MethodSpec

	// Statements for converting request types
	ConvertRequestGoStatements []string

	// Statements for converting response types
	ConvertResponseGoStatements []string

	// Statements for propagating headers to client requests
	PropagateHeadersGoStatements []string

	// Statements for reading data out of url params (server)
	RequestParamGoStatements []string
	// contains filtered or unexported fields
}

MethodSpec specifies all needed parts to generate code for a method in service.

func NewMethod

func NewMethod(
	thriftFile string,
	funcSpec *compile.FunctionSpec,
	packageHelper *PackageHelper,
	wantAnnot bool,
	isEndpoint bool,
	thriftService string,
) (*MethodSpec, error)

NewMethod creates new method specification.

func (*MethodSpec) RefResponse

func (ms *MethodSpec) RefResponse(respVar string) string

RefResponse prepends the response variable with '&' if it is not of reference type It is used to construct the `Success` field of the `$service_$method_Result` struct generated by thriftrw, which is always of reference type.

type MiddlewareConfig

type MiddlewareConfig struct {
	Name         string                  `json:"name"`
	Dependencies *Dependencies           `json:"dependencies,omitempty"`
	Config       *MiddlewareConfigConfig `json:"config"`
}

MiddlewareConfig represents configuration for a middleware as is written in the json file

func (*MiddlewareConfig) Validate

func (mid *MiddlewareConfig) Validate(configDirName string) error

Validate the config spec attributes

type MiddlewareConfigConfig

type MiddlewareConfigConfig struct {
	OptionsSchemaFile string `json:"schema"`
	ImportPath        string `json:"path"`
}

MiddlewareConfigConfig is the inner config object as prescribed by module_system json conventions

type MiddlewareGenerator

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

MiddlewareGenerator generates a group of zanzibar endpoints that proxy corresponding clients

func (*MiddlewareGenerator) Generate

func (g *MiddlewareGenerator) Generate(
	instance *ModuleInstance,
) (*BuildResult, error)

Generate returns the endpoint build result, which contains a file per endpoint handler and a list of handler specs

type MiddlewareSpec

type MiddlewareSpec struct {
	// The middleware package name.
	Name string
	// Middleware specific configuration options.
	Options map[string]interface{}
	// Options pretty printed for template initialization
	PrettyOptions map[string]string
	// Module Dependencies,  clients etc.
	Dependencies *Dependencies
	// Go Import Path for MiddlewareHandle implementation
	ImportPath string
	// Location of JSON Schema file for the configured endpoint options
	OptionsSchemaFile string
}

MiddlewareSpec holds information about each middleware at the endpoint

type MockgenBin

type MockgenBin struct {
	// Bin is the absolute path to the mockgen binary built from vendor
	Bin string
	// contains filtered or unexported fields
}

MockgenBin is a struct abstracts the mockgen binary built from mockgen package in vendor

func NewMockgenBin

func NewMockgenBin(h *PackageHelper, t *Template) (*MockgenBin, error)

NewMockgenBin builds the mockgen binary from vendor directory

func (MockgenBin) AugmentMockWithFixture

func (m MockgenBin) AugmentMockWithFixture(pkg *model.Package, f *Fixture, intf string) ([]byte, []byte, error)

AugmentMockWithFixture generates mocks with fixture for the interface in the given package

func (MockgenBin) GenMock

func (m MockgenBin) GenMock(importPath, pkg, intf string) ([]byte, error)

GenMock generates mocks for given module instance, pkg is the package name of the generated mocks, and intf is the interface name to generate mock for

type ModuleClass

type ModuleClass struct {
	Name        string
	ClassType   moduleClassType
	Directories []string
	DependsOn   []string
	DependedBy  []string
	// contains filtered or unexported fields
}

ModuleClass defines a module class in the build configuration directory. THis could be something like an Endpoint class which contains multiple endpoint configurations, or a Lib class, that is itself a module instance

type ModuleClassConfig

type ModuleClassConfig struct {
	Name   string      `json:"name"`
	Type   string      `json:"type"`
	Config interface{} `json:"config"`
}

ModuleClassConfig represents the generic JSON config for all modules. This will be provided by the module package.

type ModuleDependency

type ModuleDependency struct {
	// ClassName is the name of the class as defined in the module system
	ClassName string
	// InstanceName is the name of the dependency instance as configu
	InstanceName string
}

ModuleDependency defines a module instance required by another instance

type ModuleInstance

type ModuleInstance struct {

	// PackageInfo is the name for the generated module instance
	PackageInfo *PackageInfo
	// ClassName is the name of the class as defined in the module system
	ClassName string
	// ClassType is the type of the class as defined in the module system
	ClassType string
	// BaseDirectory is the absolute path to module system system top level
	// directory
	BaseDirectory string
	// Directory is the relative instance directory
	Directory string
	// InstanceName is the name of the instance as configured in the instance's
	// json file
	InstanceName string
	// Config is a reference to the instance "config" key in the instances json
	//file.
	Config map[string]interface{}
	// Dependencies is a list of dependent modules as defined in the instances
	// json file
	Dependencies []ModuleDependency
	// Resolved dependencies is a list of direct dependent modules after processing
	// (fully resolved)
	ResolvedDependencies map[string][]*ModuleInstance
	// Recursive dependencies is a list of dependent modules and all of their
	// dependencies, i.e. the full tree of dependencies for this module. Each
	// class list is sorted for initialization order
	RecursiveDependencies map[string][]*ModuleInstance
	// DependencyOrder is the bottom to top order in which the recursively
	// resolved dependency class names can depend on each other
	DependencyOrder []string
	// The JSONFileName is file name of the instance json file
	JSONFileName string
	// JSONFileRaw is the raw JSON file read as bytes used for future parsing
	JSONFileRaw []byte
	// contains filtered or unexported fields
}

ModuleInstance is a configured module inside a module class directory. For example, this could be

ClassName:    "Endpoint,
ClassType:    "http",
BaseDirectory "/path/to/service/base/"
Directory:    "clients/health/"
InstanceName: "health",

func (*ModuleInstance) GeneratedSpec

func (instance *ModuleInstance) GeneratedSpec() interface{}

GeneratedSpec returns the last spec result returned for the module instance

type ModuleSpec

type ModuleSpec struct {
	// CompiledModule is the resolved module from thrift file
	// that will contain modules and typedefs not directly mounted on AST
	CompiledModule *compile.Module `json:"omitempty"`
	// Source thrift file to generate the code.
	ThriftFile string
	// Whether the ThriftFile should have annotations or not
	WantAnnot bool
	// Whether the module is for an endpoint vs downstream client
	IsEndpoint bool
	// Go package name, generated base on module name.
	PackageName string
	// Go client types file path, generated from thrift file.
	GoThriftTypesFilePath string
	// Generated imports
	IncludedPackages []GoPackageImport
	Services         []*ServiceSpec
}

ModuleSpec collects the service specifications from thrift file.

func NewModuleSpec

func NewModuleSpec(
	thrift string,
	wantAnnot bool,
	isEndpoint bool,
	packageHelper *PackageHelper,
) (*ModuleSpec, error)

NewModuleSpec returns a specification for a thrift module

func (*ModuleSpec) AddImports

func (ms *ModuleSpec) AddImports(module *compile.Module, packageHelper *PackageHelper) error

AddImports adds imported Go packages in ModuleSpec in alphabetical order.

func (*ModuleSpec) AddServices

func (ms *ModuleSpec) AddServices(module *compile.Module, packageHelper *PackageHelper) error

AddServices adds services in ModuleSpec in alphabetical order of service names.

func (*ModuleSpec) SetDownstream

func (ms *ModuleSpec) SetDownstream(
	e *EndpointSpec,
	h *PackageHelper,
) error

SetDownstream ...

type ModuleSystem

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

ModuleSystem defines the module classes and their type generators

func NewDefaultModuleSystem

func NewDefaultModuleSystem(
	h *PackageHelper,
	hooks ...PostGenHook,
) (*ModuleSystem, error)

NewDefaultModuleSystem creates a fresh instance of the default zanzibar module system (clients, endpoints, services)

func NewDefaultModuleSystemWithMockHook

func NewDefaultModuleSystemWithMockHook(
	h *PackageHelper,
	hooks ...PostGenHook,
) (*ModuleSystem, error)

NewDefaultModuleSystemWithMockHook creates a fresh instance of the default zanzibar module system (clients, endpoints, services) with a post build hook to generate client and service mocks

func NewModuleSystem

func NewModuleSystem(postGenHook ...PostGenHook) *ModuleSystem

NewModuleSystem returns a new module system

func (*ModuleSystem) GenerateBuild

func (system *ModuleSystem) GenerateBuild(
	packageRoot string,
	baseDirectory string,
	targetGenDir string,
	commitChange bool,
) (map[string][]*ModuleInstance, error)

GenerateBuild will, given a module system configuration directory and a target build directory, run the generators assigned to each type of module and write the generated output to the module build directory if commitChange

func (*ModuleSystem) RegisterClass

func (system *ModuleSystem) RegisterClass(class ModuleClass) error

RegisterClass defines a class of module in the module system For example, an "Endpoint" class or a "Client" class

func (*ModuleSystem) RegisterClassDir

func (system *ModuleSystem) RegisterClassDir(className string, dir string) error

RegisterClassDir adds the given dir to the directories of the module class with given className. This method allows projects built on zanzibar to have arbitrary directories to host module class configs, therefore is mainly intended for external use.

func (*ModuleSystem) RegisterClassType

func (system *ModuleSystem) RegisterClassType(
	className string,
	classType string,
	generator BuildGenerator,
) error

RegisterClassType registers a type generator for a specific module class For example, the "http"" type generator for the "Endpoint"" class

func (*ModuleSystem) ResolveModules

func (system *ModuleSystem) ResolveModules(
	packageRoot string,
	baseDirectory string,
	targetGenDir string,
) (map[string][]*ModuleInstance, error)

ResolveModules resolves the module instances from the config on disk Using the system class and type definitions, the class directories are walked, and a module instance is initialized for each identified module in the target directory.

type PackageHelper

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

PackageHelper manages the mapping from thrift file to generated type code and service code.

func NewPackageHelper

func NewPackageHelper(
	packageRoot string,
	configRoot string,
	options *PackageHelperOptions,
) (*PackageHelper, error)

NewPackageHelper creates a package helper. packageRoot is the project root package path, configRoot is the project config dir path. options can be nil, in which case all optional settings for the package are set to default values.

func (PackageHelper) CodeGenTargetPath

func (p PackageHelper) CodeGenTargetPath() string

CodeGenTargetPath returns the file path where the code should be generated.

func (PackageHelper) ConfigRoot

func (p PackageHelper) ConfigRoot() string

ConfigRoot returns the service's absolute config root path

func (PackageHelper) DeputyReqHeader

func (p PackageHelper) DeputyReqHeader() string

DeputyReqHeader returns the header name that will be checked to determine if a request should go to the deputy downstream client

func (PackageHelper) EndpointTestConfigPath

func (p PackageHelper) EndpointTestConfigPath(
	serviceName, methodName string,
) string

EndpointTestConfigPath returns the path for the endpoint test configs

func (PackageHelper) GoGatewayPackageName

func (p PackageHelper) GoGatewayPackageName() string

GoGatewayPackageName returns the name of the gateway package

func (PackageHelper) MiddlewareSpecs

func (p PackageHelper) MiddlewareSpecs() map[string]*MiddlewareSpec

MiddlewareSpecs returns a map of middlewares available

func (PackageHelper) PackageRoot

func (p PackageHelper) PackageRoot() string

PackageRoot returns the service's root package name

func (PackageHelper) StagingReqHeader

func (p PackageHelper) StagingReqHeader() string

StagingReqHeader returns the header name that will be checked to determine if a request should go to the staging downstream client

func (PackageHelper) TargetClientsInitPath

func (p PackageHelper) TargetClientsInitPath() string

TargetClientsInitPath returns where the clients init should go

func (PackageHelper) TargetEndpointsRegisterPath

func (p PackageHelper) TargetEndpointsRegisterPath() string

TargetEndpointsRegisterPath returns where the endpoints register file should be written to

func (PackageHelper) ThriftIDLPath

func (p PackageHelper) ThriftIDLPath() string

ThriftIDLPath returns the file path to the thrift idl folder

func (PackageHelper) TypeFullName

func (p PackageHelper) TypeFullName(typeSpec compile.TypeSpec) (string, error)

TypeFullName returns the referred Go type name in generated code.

func (PackageHelper) TypeImportPath

func (p PackageHelper) TypeImportPath(thrift string) (string, error)

TypeImportPath returns the Go import path for types defined in a thrift file.

func (PackageHelper) TypePackageName

func (p PackageHelper) TypePackageName(thrift string) (string, error)

TypePackageName returns the package name that defines the type.

type PackageHelperOptions

type PackageHelperOptions struct {
	// relative path to the idl dir, defaults to "./idl"
	RelThriftRootDir string
	// relative path to the target dir that will contain generated code, defaults to "./build"
	RelTargetGenDir string
	// relative path to the middleware config dir, defaults to "./middlewares"
	RelMiddlewareConfigDir string

	// package path to the generated code, defaults to PackageRoot + "/" + RelTargetGenDir + "/gen-code"
	GenCodePackage string

	// thrift http annotation prefix, defaults to "zanzibar"
	AnnotationPrefix string

	// copyright header in generated code, defaults to ""
	CopyrightHeader string
	// header key to redirect client requests to staging environment, defaults to "X-Zanzibar-Use-Staging"
	StagingReqHeader string
	// header key to redirect client requests to local environment, defaults to "x-deputy-forwarded"
	DeputyReqHeader string
	// header key to uniquely identifies request/response pair, defaults to "x-trace-id"
	TraceKey string
}

PackageHelperOptions set the optional configurations for the project package. Each field is optional, if not set, it is set to the corresponding default value.

func NewDefaultPackageHelperOptions

func NewDefaultPackageHelperOptions() *PackageHelperOptions

NewDefaultPackageHelperOptions returns a new default PackageHelperOptions, all optional fields are set as default.

type PackageInfo

type PackageInfo struct {
	// PackageName is the name of the generated package, and should be the same
	// as the package name used by any custom code in the config directory
	PackageName string
	// PackageAlias is the unique import alias for non-generated packages
	PackageAlias string
	// GeneratedPackageAlias is the unique import alias for generated packages
	GeneratedPackageAlias string
	// ModulePackageAlias is the unique import alias for the module system's,
	// generated subpackage
	ModulePackageAlias string
	// PackagePath is the full package path for the non-generated code
	PackagePath string
	// GeneratedPackagePath is the full package path for the generated code
	GeneratedPackagePath string
	// ModulePacakgePath is the full package path for the generated dependency
	// structs and initializers
	ModulePackagePath string
	// QualifiedInstanceName for this package. Pascal case name for this module.
	QualifiedInstanceName string
	// ExportName is the name on the module initializer function
	ExportName string
	// ExportType refers to the type returned by the module initializer
	ExportType string
	// InitializerName is the name of function that can fully initialize the
	// module and its dependencies
	InitializerName string
	// IsExportGenerated is true if the export type is provided by the
	// generated package, otherwise it is assumed that the export type resides
	// in the non-generated package
	IsExportGenerated bool
}

PackageInfo provides information about the package associated with a module instance.

func (*PackageInfo) ImportPackageAlias

func (info *PackageInfo) ImportPackageAlias() string

ImportPackageAlias returns the correct package alias for referencing the module's exported type, depending on whether or not the export is generated

func (*PackageInfo) ImportPackagePath

func (info *PackageInfo) ImportPackagePath() string

ImportPackagePath returns the correct package path for the module's exported type, depending on which package (generated or not) the type lives in

type PackageNameResolver

type PackageNameResolver interface {
	TypePackageName(thriftFile string) (string, error)
}

PackageNameResolver interface allows for resolving what the package name for a thrift file is. This depends on where the thrift-based structs are generated.

type PathSegment

type PathSegment struct {
	Type           string
	Text           string
	BodyIdentifier string
	ParamName      string
	Required       bool
}

PathSegment represents a part of the http path.

type PostGenHook

type PostGenHook func(map[string][]*ModuleInstance) error

PostGenHook provides a way to do work after the build is generated, useful to augment the build, e.g. generate mocks after interfaces are generated

func ClientMockGenHook

func ClientMockGenHook(h *PackageHelper, t *Template) (PostGenHook, error)

ClientMockGenHook returns a PostGenHook to generate client mocks

func ServiceMockGenHook

func ServiceMockGenHook(h *PackageHelper, t *Template) PostGenHook

ServiceMockGenHook returns a PostGenHook to generate service mocks

func WorkflowMockGenHook

func WorkflowMockGenHook(h *PackageHelper, t *Template) PostGenHook

WorkflowMockGenHook returns a PostGenHook to generate endpoint workflow mocks

type ProtocalType

type ProtocalType string

ProtocalType can either be `http` or `tchannel`

type ServiceSpec

type ServiceSpec struct {
	// Service name
	Name string
	// Source thrift file to generate the code.
	ThriftFile string
	// Whether the service should have annotations or not
	WantAnnot bool
	// Whether the service is for an endpoint vs downstream client
	IsEndpoint bool
	// List of methods/endpoints of the service
	Methods []*MethodSpec
	// thriftrw compile spec.
	CompileSpec *compile.ServiceSpec
}

ServiceSpec specifies a service.

func NewServiceSpec

func NewServiceSpec(
	spec *compile.ServiceSpec,
	wantAnnot bool,
	isEndpoint bool,
	packageHelper *PackageHelper,
) (*ServiceSpec, error)

NewServiceSpec creates a service specification from given thrift file path.

func (*ServiceSpec) NewMethod

func (s *ServiceSpec) NewMethod(
	funcSpec *compile.FunctionSpec, packageHelper *PackageHelper,
) (*MethodSpec, error)

NewMethod creates new method specification.

type StatusCode

type StatusCode struct {
	Code    int
	Message string
}

StatusCode is for http status code with exception message.

type StructMeta

type StructMeta struct {
	Instance *ModuleInstance
	Spec     *ModuleSpec
}

StructMeta saves information to generate an endpoint's thrift structs file

type StructSpec

type StructSpec struct {
	Type        string
	Name        string
	Annotations map[string]string
}

StructSpec specifies a Go struct to be generated.

type TChannelClientGenerator

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

TChannelClientGenerator generates an instance of a zanzibar TChannel client

func (*TChannelClientGenerator) Generate

func (g *TChannelClientGenerator) Generate(
	instance *ModuleInstance,
) (*BuildResult, error)

Generate returns the TChannel client build result, which contains the files and the generated client spec

type Template

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

Template generates code for edge gateway clients and edgegateway endpoints.

func NewDefaultTemplate

func NewDefaultTemplate() (*Template, error)

NewDefaultTemplate creates a bundle of templates.

func NewTemplate

func NewTemplate(
	assetProvider AssetProvider,
	functionMap tmpl.FuncMap,
) (*Template, error)

NewTemplate returns a template helper for the provided asset collection

func (*Template) ExecTemplate

func (t *Template) ExecTemplate(
	tplName string,
	tplData interface{},
	pkgHelper *PackageHelper,
	buildTags ...string,
) (ret []byte, rErr error)

ExecTemplate executes the named templated, returning the generated bytes

type TypeConverter

type TypeConverter struct {
	LineBuilder
	Helper PackageNameResolver
	// contains filtered or unexported fields
}

TypeConverter can generate a function body that converts two thriftrw FieldGroups from one to another. It's assumed that the converted code operates on two variables, "in" and "out" and that both are a go struct.

func NewTypeConverter

func NewTypeConverter(h PackageNameResolver, optionalEntries map[string]FieldMapperEntry) *TypeConverter

NewTypeConverter returns *TypeConverter (tc) @optionalEntries contains Entries that already set for tc fromFields entry set in @optionalEntries, tc will not raise error when this entry is required for toFields but missing from fromFields

func (*TypeConverter) GenStructConverter

func (c *TypeConverter) GenStructConverter(
	fromFields []*compile.FieldSpec,
	toFields []*compile.FieldSpec,
	fieldMap map[string]FieldMapperEntry,
) error

GenStructConverter will add lines to the TypeConverter for mapping from one go struct to another based on two thriftrw.FieldGroups. fieldMap is a may from keys that are the qualified field path names for destination fields (sent to the downstream client) and the entries are source fields (from the incoming request)

type TypedHeader

type TypedHeader struct {
	Name        string
	TransformTo string
	Field       *compile.FieldSpec
}

TypedHeader is typed header for headers resolved from header schema

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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