Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Configure apiKey, additionalHeaders, and host through environment variables #22

Merged
merged 11 commits into from
May 16, 2024
Merged
Show file tree
Hide file tree
Changes from 5 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .env.example
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
API_KEY="<Project API Key>"
PINECONE_API_KEY="<Project API Key>"
TEST_POD_INDEX_NAME="<Pod based Index name>"
TEST_SERVERLESS_INDEX_NAME="<Serverless based Index name>"
4 changes: 2 additions & 2 deletions .github/workflows/ci.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ jobs:
- name: Setup Go
uses: actions/setup-go@v4
with:
go-version: '1.21.x'
go-version: "1.21.x"
- name: Install dependencies
run: |
go get ./pinecone
Expand All @@ -21,4 +21,4 @@ jobs:
env:
TEST_POD_INDEX_NAME: ${{ secrets.TEST_POD_INDEX_NAME }}
TEST_SERVERLESS_INDEX_NAME: ${{ secrets.TEST_SERVERLESS_INDEX_NAME }}
API_KEY: ${{ secrets.API_KEY }}
INTEGRATION_PINECONE_API_KEY: ${{ secrets.API_KEY }}
140 changes: 111 additions & 29 deletions pinecone/client.go
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Could we have two different constructors? One that requires an ApiKey and the other that requires a different auth mechanism (bearer token? oauth token?). It feels clunky that the "ApiKey is required unless..."

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

That does seem reasonable. I'm less clear on what this would look like though since we don't officially offer alternative methods of authentication quite yet. The other clients require an API key for instance.

If the user is able to supply headers directly then they could technically always pass their own auth headers. I think this would also be an issue on Python and TypeScript since they don't do any checking of the headers that are provided. You could also consider this a user-error that they'd need to resolve themselves.

I'm a bit unsure of what would make the most sense here to be honest. 🤔

Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,10 @@ import (
"encoding/json"
"fmt"
"io"
"log"
"net/http"
"strings"
"net/url"
"os"

"github.com/deepmap/oapi-codegen/v2/pkg/securityprovider"
"github.com/pinecone-io/go-pinecone/internal/gen/control"
Expand All @@ -16,25 +18,41 @@ import (

type Client struct {
apiKey string
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is apiKey still needed in the Client struct?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Removed from Client as well as IndexConnection.

headers map[string]string
restClient *control.Client
sourceTag string
headers map[string]string
}

type NewClientBaseParams struct {
Headers map[string]string
Host string
RestClient *http.Client
SourceTag string
}

type NewClientParams struct {
ApiKey string // required unless Authorization header provided
SourceTag string // optional
Headers map[string]string // optional
RestClient *http.Client // optional
ApiKey string
Headers map[string]string
Host string
RestClient *http.Client
SourceTag string
}

func NewClient(in NewClientParams) (*Client, error) {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'd expect this func to just call NewClientBase and configure the ApiKey as an auth header

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It now ultimately calls NewClientBase and passes the ApiKey through as part of the Headers map.

clientOptions, err := buildClientOptions(in)
clientOptions, err := in.buildClientOptions()
if err != nil {
return nil, err
}

client, err := control.NewClient("https://api.pinecone.io", clientOptions...)
controlHostOverride := valueOrFallback(in.Host, os.Getenv("PINECONE_CONTROLLER_HOST"))
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

"CONTROL" vs "CONTROLLER"? (Assuming this is talking about the control plane?

Copy link
Contributor Author

@austin-denoble austin-denoble May 15, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I went with PINECONE_CONTROLLER_HOST because that's the env key that's used in the Python and TypeScript clients for the same config value:

I suppose it is a bit confusing given it's applied as an override to the control plane. I think staying consistent makes sense, although the variable name here is confusing. What do you think?

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nice job throwing this in for consistency with other clients.

if controlHostOverride != "" {
controlHostOverride, err = ensureHTTPS(controlHostOverride)
if err != nil {
return nil, err
}
}

client, err := control.NewClient(valueOrFallback(controlHostOverride, "https://api.pinecone.io"), clientOptions...)
if err != nil {
return nil, err
}
Expand All @@ -43,6 +61,27 @@ func NewClient(in NewClientParams) (*Client, error) {
return &c, nil
}

func NewClientBase(in NewClientBaseParams) (*Client, error) {
clientOptions := in.buildClientBaseOptions()
var err error

controlHostOverride := valueOrFallback(in.Host, os.Getenv("PINECONE_CONTROLLER_HOST"))
if controlHostOverride != "" {
controlHostOverride, err = ensureHTTPS(controlHostOverride)
if err != nil {
return nil, err
}
}

client, err := control.NewClient(valueOrFallback(controlHostOverride, "https://api.pinecone.io"), clientOptions...)
if err != nil {
return nil, err
}

c := Client{restClient: client, sourceTag: in.SourceTag, headers: in.Headers}
return &c, nil
}

func (c *Client) Index(host string) (*IndexConnection, error) {
return c.IndexWithAdditionalMetadata(host, "", nil)
}
Expand Down Expand Up @@ -421,39 +460,82 @@ func derefOrDefault[T any](ptr *T, defaultValue T) T {
return *ptr
}

func buildClientOptions(in NewClientParams) ([]control.ClientOption, error) {
func (ncp *NewClientParams) buildClientOptions() ([]control.ClientOption, error) {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

could buildClientOptions to be a wrapper around buildClientBaseOptions?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I slimmed things down to just buildClientBaseOptions, lemme know if that makes sense.

clientOptions := []control.ClientOption{}
hasAuthorizationHeader := false
hasApiKey := in.ApiKey != ""
osApiKey := os.Getenv("PINECONE_API_KEY")
hasApiKey := (ncp.ApiKey != "" || osApiKey != "")

userAgentProvider := provider.NewHeaderProvider("User-Agent", useragent.BuildUserAgent(in.SourceTag))
clientOptions = append(clientOptions, control.WithRequestEditorFn(userAgentProvider.Intercept))
if !hasApiKey {
return nil, fmt.Errorf("no API key provided, please pass an API key for authorization")
}

for key, value := range in.Headers {
headerProvider := provider.NewHeaderProvider(key, value)
appliedApiKey := valueOrFallback(ncp.ApiKey, osApiKey)
apiKeyProvider, err := securityprovider.NewSecurityProviderApiKey("header", "Api-Key", appliedApiKey)
if err != nil {
return nil, err
}
clientOptions = append(clientOptions, control.WithRequestEditorFn(apiKeyProvider.Intercept))

if strings.Contains(strings.ToLower(key), "authorization") {
hasAuthorizationHeader = true
}
baseClient := NewClientBaseParams{ncp.Headers, ncp.Host, ncp.RestClient, ncp.SourceTag}
baseClientOptions := baseClient.buildClientBaseOptions()
clientOptions = append(clientOptions, baseClientOptions...)

clientOptions = append(clientOptions, control.WithRequestEditorFn(headerProvider.Intercept))
}
return clientOptions, nil
}

func (ncbp *NewClientBaseParams) buildClientBaseOptions() []control.ClientOption {
clientOptions := []control.ClientOption{}

envAdditionalHeaders, hasEnvAdditionalHeaders := os.LookupEnv("PINECONE_ADDITIONAL_HEADERS")

// build and apply user agent
fmt.Printf("Source tag on its way in: %v\n", ncbp.SourceTag)
userAgentProvider := provider.NewHeaderProvider("User-Agent", useragent.BuildUserAgent(ncbp.SourceTag))
clientOptions = append(clientOptions, control.WithRequestEditorFn(userAgentProvider.Intercept))

if !hasAuthorizationHeader {
apiKeyProvider, err := securityprovider.NewSecurityProviderApiKey("header", "Api-Key", in.ApiKey)
// apply headers from parameters if passed, otherwise use environment headers
if ncbp.Headers != nil {
for key, value := range ncbp.Headers {
headerProvider := provider.NewHeaderProvider(key, value)
clientOptions = append(clientOptions, control.WithRequestEditorFn(headerProvider.Intercept))
}
} else if hasEnvAdditionalHeaders {
additionalHeaders := make(map[string]string)
err := json.Unmarshal([]byte(envAdditionalHeaders), &additionalHeaders)
if err != nil {
return nil, err
log.Printf("failed to parse PINECONE_ADDITIONAL_HEADERS: %v", err)
} else {
for header, value := range additionalHeaders {
headerProvider := provider.NewHeaderProvider(header, value)
clientOptions = append(clientOptions, control.WithRequestEditorFn(headerProvider.Intercept))
}
}
clientOptions = append(clientOptions, control.WithRequestEditorFn(apiKeyProvider.Intercept))
}

if !hasAuthorizationHeader && !hasApiKey {
return nil, fmt.Errorf("no API key provided, please pass an API key for authorization")
if ncbp.RestClient != nil {
clientOptions = append(clientOptions, control.WithHTTPClient(ncbp.RestClient))
}

return clientOptions
}

func ensureHTTPS(inputURL string) (string, error) {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

can we add the option to disable https? (i'm thinking for local dev)

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The way it's written currently means if you provide a Host or PINECONE_CONTROLLER_HOST, you're able to use whatever scheme as long as url.Parse() can read it out. https is only applied if there's no scheme, do you think that's sufficient?

For example, you should be able to pass http://localhost:9999 properly without "https" being added.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

yup that works. The function name is a bit confusing...

parsedURL, err := url.Parse(inputURL)
if err != nil {
return "", fmt.Errorf("invalid URL: %v", err)
}

if in.RestClient != nil {
clientOptions = append(clientOptions, control.WithHTTPClient(in.RestClient))
if parsedURL.Scheme == "" {
return "https://" + inputURL, nil
}
return inputURL, nil
}

return clientOptions, nil
func valueOrFallback[T comparable](value, fallback T) T {
var zero T
if value != zero {
return value
} else {
return fallback
}
}
Loading
Loading