hub

package
v1.5.0-dev Latest Latest
Warning

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

Go to latest
Published: Jul 17, 2024 License: Apache-2.0 Imports: 11 Imported by: 0

README

Tanzu Hub Client

This package enables the creation of authenticated Tanzu Hub clients which in turn enables the interaction with Tanzu Hub endpoint through GraphQL queries for the tanzu context.

Note: The Tanzu Hub Client feature is an EXPERIMENTAL feature. The API signature and implementation are subjected to change/removal if an alternative means to provide equivalent functionality can be introduced.

Creating a Tanzu Hub Client

To create a Tanzu Hub client, use the NewClient(contextName string) API by providing the tanzu context name. An authenticated Tanzu Hub client for the specified tanzu context will be returned. Internally it configures the client with an access token for each request. By default, it will get the Tanzu Hub endpoint from the specified context metadata. To specify any custom Tanzu Hub endpoint for testing please configure the TANZU_HUB_ENDPOINT environment variable.

Note that the authenticated client is assured to have at least 30 min access to the GraphQL endpoint. If you want a long running client beyond this period, recommendation is to reinitialize your client.

Examples

Query/Mutation
const QueryAllProjects_Operation = `
query QueryAllProjects {
    applicationEngineQuery {
        queryProjects(first: 1000) {
            projects {
                name
            }
        }
    }
}`

// getProjects is a wrapper of an `QueryAllProjects“ API call to fetch project names
func getProjects(contextName string) ([]string, error) {
    hc, err := NewClient(contextName )

    req := &hub.Request{
        OpName: "QueryAllProjects",
        Query:  QueryAllProjects_Operation,
    }
    var responseData QueryAllProjectsResponse // Assuming the response type is already defined
    err := hc.Request(context.Background(), req, &responseData)
    if err != nil {
        return nil, err
    }

    // Process the response
    projects := []string{}
    for _, p := range responseData.ApplicationEngineQuery.QueryProjects.Projects {
        projects = append(projects, p.Name)
    }

    return projects, nil
}
Subscriptions
const SubscribeAppLogs_Operation = `
subscription appLogs($appEntityId: EntityId!) {
  kubernetesAppLogs(appEntityId: $appEntityId, logParams: {includeTimestamps: true, tailLines: 50, includePrevious: false}) {
    value
    timestamp
  }
}`

func subscribeAppLogs(contextName, appEntityId string) ([]string, error) {
    hc, err := NewClient(contextName )

    req := &hub.Request{
        OpName: "SubscribeAppLogs",
        Query:  SubscribeAppLogs_Operation,
        Variables: map[string]string{"appEntityId": appEntityId}
    }

    err := hc.Subscribe(context.Background(), req, logEventHandler)
    if err != nil {
        return nil, err
    }

    return nil
}

func logEventHandler(eventResponse EventResponse) {
    rawData := eventResponse.RawData
    responseData := eventResponse.ResponseData
    fmt.Println(string(rawData))
    fmt.Println(responseData)
}

Generating the golang stub for the GraphQL queries

There are many golang client libraries for the GraphQL, however, Tanzu Plugin Runtime recommends using github.com/Khan/genqlient for generating type definitions for your GraphQL queries.

Note: Client does not require users to use this library for generating type definitions and users can always define the Golang type definitions for the specified query by themselves.

Documentation

Overview

Package hub provides functions to create Tanzu Hub client for specific context

Package hub provides functions to create Tanzu Hub client for specific context

Package hub provides functions to create Tanzu Hub client for specific context

Index

Constants

View Source
const (
	EnvTanzuHubEndpoint = "TANZU_HUB_ENDPOINT"
)

Variables

This section is empty.

Functions

This section is empty.

Types

type Client added in v1.4.0

type Client interface {
	// Request sends a GraphQL request to the Tanzu Hub endpoint
	//
	//	ctx context.Context: The context for the request. If provided, it will be used to cancel the request if the context is canceled.
	//	req *Request: The GraphQL request to be sent.
	//	responseData interface{}: The interface to store the response data. The response data will be unmarshaled into this interface.
	Request(ctx context.Context, req *Request, responseData interface{}) error

	// Subscribe to a GraphQL endpoint and streams events to the provided handler
	//
	//	ctx context.Context: The context for the subscription. If provided, it will be used to cancel the subscription if the context is canceled.
	//	req *Request: The GraphQL subscription request to be sent.
	//	handler EventResponseHandler: The handler function to process incoming events.
	Subscribe(ctx context.Context, req *Request, handler EventResponseHandler) error
}

Client is an interface for the Tanzu Hub Client

func NewClient added in v1.4.0

func NewClient(contextName string, opts ...ClientOptions) (Client, error)

NewClient returns an authenticated Tanzu Hub client for the specified tanzu context. Internally it configures the client with CSP access token for each request

Note that the authenticated client is assured to have at least 30 min access to the GraphQL endpoint. If you want a long running client beyond this period, recommendation is to reinitialize your client.

EXPERIMENTAL: Both the function's signature and implementation are subjected to change/removal if an alternative means to provide equivalent functionality can be introduced.

type ClientOptions added in v1.4.0

type ClientOptions func(o *hubClient)

func WithAccessToken added in v1.4.0

func WithAccessToken(token string) ClientOptions

WithAccessToken creates the Client using the specified Access Token

func WithEndpoint added in v1.4.0

func WithEndpoint(endpoint string) ClientOptions

WithEndpoint creates the Client using the specified Endpoint

func WithHTTPClient added in v1.4.0

func WithHTTPClient(httpClient *http.Client) ClientOptions

WithHTTPClient creates the Client using the specified HttpClient

type EventResponse added in v1.4.0

type EventResponse struct {
	// Name contains the value of the "event:" header from the event stream.
	Name string
	// ID contains the value of the "id:" header from the event stream.
	ID string
	// RawData contains the concatenated payload from the "data:" headers received as part of the event stream.
	RawData []byte
	// ResponseData contains the parsed GraphQL response object if the RawData can be successfully parsed to Response object, otherwise it is nil.
	ResponseData *Response
	// Retry contains the value of the "retry:" header from the event stream.
	Retry string
}

EventResponse represents a Server-Sent event response

type EventResponseHandler added in v1.4.0

type EventResponseHandler func(eventResponse EventResponse)

EventResponseHandler represents a Subscription event handler function that will be passed to the `Subscribe` method

type Request added in v1.4.0

type Request struct {
	// The literal string representing the GraphQL query, e.g.
	// `query myQuery { myField }`.
	Query string `json:"query"`
	// A JSON-marshalable value containing the variables to be sent
	// along with the query, or nil if there are none.
	Variables interface{} `json:"variables,omitempty"`
	// The GraphQL operation name. The server typically doesn't
	// require this unless there are multiple queries in the
	// document.
	OpName string `json:"operationName"`
}

Request contains all the values required to build queries executed by the Client.

Typically, GraphQL APIs will accept a JSON payload of the form

{"query": "query myQuery { ... }", "variables": {...}}`

and Request marshals to this format.

type Response added in v1.4.0

type Response struct {
	Data       interface{}            `json:"data"`
	Extensions map[string]interface{} `json:"extensions,omitempty"`
	Errors     gqlerror.List          `json:"errors,omitempty"`
}

Response that contains data returned by the GraphQL API.

Typically, GraphQL APIs will return a JSON payload of the form

{"data": {...}, "errors": {...}}

It may additionally contain a key named "extensions", that might hold GraphQL protocol extensions. Extensions and Errors are optional, depending on the values returned by the server.

Directories

Path Synopsis
Package testing exports a GraphQL Mock Server that facilitates the testing of client.
Package testing exports a GraphQL Mock Server that facilitates the testing of client.

Jump to

Keyboard shortcuts

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