Skip to content

Conversation

@jpvajda
Copy link
Contributor

@jpvajda jpvajda commented Jul 17, 2025

PR Summary: Add TTL Support to Grant Token Endpoint

TL;DR

  • Added ttl_seconds parameter support to the grant token endpoint in the Deepgram Go SDK.
  • Implementation is fully backward compatible and follows OpenAPI specifications.

🚀 Changes Made

Core Implementation

  • Added GrantTokenRequest struct (pkg/api/auth/v1/interfaces/types.go)

    • Supports optional ttl_seconds parameter (1-3600 seconds)
    • Uses *int with omitempty for proper JSON marshaling
    • Handles nil values gracefully for backward compatibility
  • Updated GrantToken method (pkg/api/auth/v1/grant-token.go)

    • Now accepts *GrantTokenRequest parameter
    • Maintains backward compatibility with nil parameter
    • Proper JSON encoding and HTTP request handling

Examples & Documentation

  • Enhanced grant token example (examples/auth/grant-token/main.go)
    • Demonstrates both default (30s) and custom TTL (60s) usage
    • Shows proper API usage patterns
    • Maintains full backward compatibility demonstration

Testing

  • Added comprehensive unit tests (tests/unit_test/auth/grant_token_test.go)
    • Tests struct creation and JSON marshaling/unmarshaling
    • Validates boundary conditions and edge cases
    • Tests nil handling and omitempty behavior
    • 100% test coverage for the new functionality

🔄 Backward Compatibility

  • Existing code unchanged: client.GrantToken(ctx, nil) works as before
  • No breaking changes: All existing functionality preserved
  • Future-proof: Ready for when API bug is fixed

📋 Usage Examples

// Default behavior (30 seconds) - UNCHANGED
token, err := client.GrantToken(ctx, nil)

// Custom TTL (60 seconds) - NEW
ttl := 60
token, err := client.GrantToken(ctx, &interfaces.GrantTokenRequest{
    TTLSeconds: &ttl,
})

🧪 Testing Results

  • ✅ All existing tests pass
  • ✅ New unit tests pass (100% coverage)
  • ✅ Integration tests pass
  • ✅ Example demonstrates expected behavior

🎯 Files Changed

  • pkg/api/auth/v1/interfaces/types.go - Added GrantTokenRequest struct
  • pkg/api/auth/v1/grant-token.go - Updated method signature and implementation
  • examples/auth/grant-token/main.go - Enhanced example with TTL demonstration
  • tests/unit_test/auth/grant_token_test.go - Added comprehensive unit tests

Types of changes

What types of changes does your code introduce to the community Go SDK?
Put an x in the boxes that apply

  • Bugfix (non-breaking change which fixes an issue)
  • New feature (non-breaking change which adds functionality)
  • Breaking change (fix or feature that would cause existing functionality to not work as expected)
  • Documentation update or tests (if none of the other choices apply)

Checklist

Put an x in the boxes that apply. You can also fill these out after creating the PR. If you're unsure about any of them, don't hesitate to ask. We're here to help! This is simply a reminder of what we are going to look for before merging your code.

  • I have read the CONTRIBUTING doc
  • I have lint'ed all of my code using repo standards
  • I have added tests that prove my fix is effective or that my feature works
  • I have added necessary documentation (if appropriate)

Summary by CodeRabbit

  • New Features

    • Added support for requesting temporary access tokens with a custom time-to-live (TTL) value.
    • Introduced a new request structure allowing specification of TTL when granting tokens.
  • Bug Fixes

    • Improved error handling and messaging when requesting tokens with custom parameters.
  • Tests

    • Added comprehensive unit tests for the new token request structure and TTL handling.
  • Chores

    • Updated test response data files with refreshed metadata.

@jpvajda jpvajda requested a review from lukeocodes July 17, 2025 00:13
@coderabbitai
Copy link
Contributor

coderabbitai bot commented Jul 17, 2025

Walkthrough

This change introduces the ability to request temporary access tokens with a custom time-to-live (TTL) by extending the GrantToken method to accept a request parameter specifying TTL. It adds a new request struct, updates related method signatures, demonstrates usage in an example, and provides unit tests for the new struct.

Changes

File(s) Change Summary
examples/auth/grant-token/main.go Adds demonstration of requesting a token with custom TTL; imports new struct; updates method usage.
pkg/api/auth/v1/grant-token.go Updates GrantToken to accept a request parameter and handle JSON encoding for request body.
pkg/api/auth/v1/interfaces/types.go Adds new GrantTokenRequest struct with optional TTLSeconds field.
tests/unit_test/auth/grant_token_test.go Adds unit tests for GrantTokenRequest struct, covering instantiation and JSON handling.
tests/response_data/642c86c60eedbc4af873632b86d68164149599cf97131d81a63a2711f0563d37... Updates test data: new request ID and timestamp, content otherwise unchanged.
tests/response_data/bfae00d50d521f470ff9d1943f32225fcfeffe51eff47984886930b71fae0929... Updates test data: new request ID and timestamp, minor float differences, content unchanged.

Sequence Diagram(s)

sequenceDiagram
    participant UserApp
    participant AuthClient
    participant API

    UserApp->>AuthClient: GrantToken(ctx, &GrantTokenRequest{TTLSeconds: 60})
    AuthClient->>API: POST /grant-token (body: {"ttl_seconds":60})
    API-->>AuthClient: Token response (with TTL)
    AuthClient-->>UserApp: GrantToken result (token, TTL)
Loading

Possibly related PRs

Suggested reviewers

  • naomi-lgbt
✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch feat/grant-ttl-support

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Explain this complex logic.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai explain this code block.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai auto-generate unit tests to generate unit tests for this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 0

🧹 Nitpick comments (3)
tests/unit_test/auth/grant_token_test.go (1)

101-101: Consider extracting repeated string constant.

The empty JSON object "{}" appears multiple times. Consider extracting it as a constant to improve maintainability.

+const emptyJSON = "{}"
+
 func TestGrantTokenRequestJSON(t *testing.T) {
 	// ... other code ...
 	
-		expectedJSON := `{}`
+		expectedJSON := emptyJSON
 		if string(jsonData) != expectedJSON {
 			t.Errorf("Expected JSON: %s, got: %s", expectedJSON, string(jsonData))
 		}
 	})
 
 	t.Run("Test_GrantTokenRequest_JSON_unmarshaling_empty", func(t *testing.T) {
-		jsonData := `{}`
+		jsonData := emptyJSON

Also applies to: 126-126

pkg/api/auth/v1/grant-token.go (1)

28-37: Optimize request body handling for better performance.

The current implementation unnecessarily converts the buffer to a string and then back to a reader. Since bytes.Buffer implements io.Reader, you can use it directly.

Apply this diff for better performance:

 var body io.Reader
 if req != nil {
   var buf bytes.Buffer
   if err := json.NewEncoder(&buf).Encode(req); err != nil {
     klog.V(1).Infof("GrantToken json.NewEncoder().Encode() failed. Err: %v\n", err)
     klog.V(6).Infof("auth.GrantToken() LEAVE\n")
     return nil, err
   }
-  body = strings.NewReader(buf.String())
+  body = &buf
 }

This eliminates the unnecessary string conversion and memory allocation.

tests/response_data/642c86c60eedbc4af873632b86d68164149599cf97131d81a63a2711f0563d37-response.json (1)

1-1: Snapshots churn due to dynamic metadata—consider normalizing request_id & created

Refreshing UUIDs and timestamps adds noise to PRs and can break brittle assertions. Prefer stripping or hard-coding these dynamic fields in test fixtures to keep snapshots deterministic.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 87ddfa5 and 4499cff.

📒 Files selected for processing (6)
  • examples/auth/grant-token/main.go (3 hunks)
  • pkg/api/auth/v1/grant-token.go (2 hunks)
  • pkg/api/auth/v1/interfaces/types.go (1 hunks)
  • tests/response_data/642c86c60eedbc4af873632b86d68164149599cf97131d81a63a2711f0563d37-response.json (1 hunks)
  • tests/response_data/bfae00d50d521f470ff9d1943f32225fcfeffe51eff47984886930b71fae0929-response.json (1 hunks)
  • tests/unit_test/auth/grant_token_test.go (1 hunks)
🧰 Additional context used
🧠 Learnings (1)
examples/auth/grant-token/main.go (7)
Learnt from: dvonthenen
PR: deepgram/deepgram-go-sdk#252
File: examples/manage/usage/main.go:17-17
Timestamp: 2024-06-25T18:05:26.824Z
Learning: The `pkg/client/rest/v1` directory in the `deepgram-go-sdk` is not deprecated, and its usage is still valid except for the direct use of the helper file `pkg/client/rest/client.go`.
Learnt from: dvonthenen
PR: deepgram/deepgram-go-sdk#252
File: examples/manage/scopes/main.go:14-14
Timestamp: 2024-06-25T18:05:47.921Z
Learning: The `pkg/client/rest/v1` directory in the deepgram-go-sdk is not deprecated, only the direct use of `pkg/client/rest/client.go` is affected. This distinction is important for accurate codebase analysis and comments.
Learnt from: dvonthenen
PR: deepgram/deepgram-go-sdk#252
File: examples/manage/usage/main.go:17-17
Timestamp: 2024-10-09T02:19:48.728Z
Learning: The `pkg/client/rest/v1` directory in the `deepgram-go-sdk` is not deprecated, and its usage is still valid except for the direct use of the helper file `pkg/client/rest/client.go`.
Learnt from: dvonthenen
PR: deepgram/deepgram-go-sdk#258
File: pkg/api/speak/v1/websocket/interfaces/interfaces.go:31-43
Timestamp: 2024-10-09T02:19:46.086Z
Learning: The `SpeakMessageCallback` and `SpeakMessageChan` interfaces in the Deepgram Go SDK are distinct because they accommodate different transport mechanisms.
Learnt from: dvonthenen
PR: deepgram/deepgram-go-sdk#258
File: pkg/api/speak/v1/websocket/interfaces/interfaces.go:31-43
Timestamp: 2024-08-23T04:42:57.605Z
Learning: The `SpeakMessageCallback` and `SpeakMessageChan` interfaces in the Deepgram Go SDK are distinct because they accommodate different transport mechanisms.
Learnt from: dvonthenen
PR: deepgram/deepgram-go-sdk#252
File: examples/manage/usage/main.go:17-17
Timestamp: 2024-06-25T18:06:34.961Z
Learning: User dvonthenen clarified that the introduction of the `manage` client in the `deepgram-go-sdk` is to prevent direct creation of a `rest` client and to add a level of indirection. This design choice encapsulates functionalities and controls the interface more effectively.
Learnt from: dvonthenen
PR: deepgram/deepgram-go-sdk#252
File: examples/manage/usage/main.go:17-17
Timestamp: 2024-10-09T02:19:46.086Z
Learning: User dvonthenen clarified that the introduction of the `manage` client in the `deepgram-go-sdk` is to prevent direct creation of a `rest` client and to add a level of indirection. This design choice encapsulates functionalities and controls the interface more effectively.
🧬 Code Graph Analysis (3)
examples/auth/grant-token/main.go (1)
pkg/api/auth/v1/interfaces/types.go (2)
  • GrantToken (20-23)
  • GrantTokenRequest (15-17)
tests/unit_test/auth/grant_token_test.go (1)
pkg/api/auth/v1/interfaces/types.go (1)
  • GrantTokenRequest (15-17)
pkg/api/auth/v1/grant-token.go (4)
pkg/api/auth/v1/auth.go (1)
  • Client (21-23)
pkg/client/auth/v1/types.go (1)
  • Client (13-15)
pkg/api/auth/v1/interfaces/types.go (2)
  • GrantToken (20-23)
  • GrantTokenRequest (15-17)
pkg/api/version/auth-version.go (1)
  • GrantTokenURI (16-16)
🪛 GitHub Check: Lint
tests/unit_test/auth/grant_token_test.go

[failure] 101-101:
string {} has 2 occurrences, make it a constant (goconst)

🔇 Additional comments (11)
tests/response_data/bfae00d50d521f470ff9d1943f32225fcfeffe51eff47984886930b71fae0929-response.json (1)

1-1: Test data refresh with updated metadata.

Similar to the other response file, only metadata fields are updated. This is routine test data maintenance.

pkg/api/auth/v1/interfaces/types.go (1)

14-17: Well-designed struct for optional TTL specification.

The implementation follows Go best practices:

  • Pointer type allows for proper optional field handling
  • JSON tag uses appropriate snake_case convention
  • omitempty ensures clean JSON when field is not specified
  • Field name follows Go naming conventions
examples/auth/grant-token/main.go (3)

13-13: Import addition supports new functionality.

The import of authInterfaces is correctly added to support the new GrantTokenRequest struct usage.


39-39: Explicit nil parameter maintains clarity.

Good practice to explicitly pass nil to demonstrate the optional nature of the request parameter and maintain backward compatibility.


51-71: Excellent demonstration of custom TTL functionality.

The new Phase 1.5 effectively demonstrates:

  • Custom TTL value assignment
  • Proper struct initialization
  • Error handling
  • Secure token display (truncated)
  • Clear output formatting
tests/unit_test/auth/grant_token_test.go (3)

14-70: Comprehensive struct testing with excellent coverage.

The test functions thoroughly cover all scenarios:

  • Struct creation with various TTL values
  • Nil value handling
  • Boundary conditions (0, 3600 seconds)
  • Proper pointer dereferencing

Test organization and naming conventions are excellent.


72-138: Thorough JSON serialization testing.

The JSON marshaling/unmarshaling tests effectively verify:

  • Correct JSON field naming (ttl_seconds)
  • Proper omitempty behavior when TTL is nil
  • Bidirectional serialization consistency
  • Empty JSON handling

140-177: Comprehensive validation testing covers expected use cases.

The validation tests cover the documented TTL range (1-3600 seconds) and include typical values that users would likely use.

pkg/api/auth/v1/grant-token.go (3)

12-12: LGTM! Import additions are appropriate.

The new imports are correctly added to support JSON encoding and request body handling functionality.

Also applies to: 14-16


25-25: LGTM! Method signature change maintains backward compatibility.

The addition of the optional req parameter using a pointer type allows for backward compatibility while enabling the new TTL functionality.


40-40: LGTM! APIRequest call correctly updated.

The APIRequest call properly passes the body parameter while maintaining existing error handling and return logic.

@jpvajda jpvajda merged commit 021aade into main Jul 21, 2025
3 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants