SecretIterator not working as expected because of cancelled context

68 views Asked by At

I'm using GCP for fetching secrets from secretsmanager. As part of this while fetching list of secrets, the iterator values are not getting propagated correctly.

Below is the code that I'm using,

func listSecrets(client *secretmanager.Client, req *secretmanagerpb.ListSecretsRequest) *secretmanager.SecretIterator {
    ctx, cancelFunc := context.WithTimeout(context.Background(), 5*time.Second)
    defer cancelFunc()
    return client.ListSecrets(ctx, req)
}

func main() {
    client, err := secretmanager.NewClient(context.Background())
    .
    .
    .
    req := &secretmanagerpb.ListSecretsRequest{
      Parent: parent,
      Filter: filter,
    }

    result := listSecrets(client, req)
    .
    .
}

because the result of listSecrets() is directly returned (which is an iterator) & since context is cancelled (just before returning), the output that I'm getting in the calling function is, rpc error: code = Canceled desc = context canceled

The code works fine if I move the fetch part from listSecrets() to main().

func main() {
    .
    .
    ctx, cancelFunc := context.WithTimeout(context.Background(), 5*time.Second)
    defer cancelFunc()
    
    result := client.ListSecrets(ctx, req)
    .
    .

or if context is passed as an input to listSecrets()

func listSecrets(ctx context.Context, client ..., req ...) *secretmanager.SecretIterator {
    return client.ListSecrets(ctx, req)
}

func main() {
    .
    .
    ctx, cancelFunc := context.WithTimeout(context.Background(), 5*time.Second)
    defer cancelFunc()
    result := listSecrets(ctx, client, req)
    .
    .
}

I want to fetch secrets through a helper function without passing context as an argument. Is there a way to achieve this ?

0

There are 0 answers