Skip to content

feat(transformations): Added rotate keys api endpoint support in sdk - #2921

Merged
karthikeyanraghavan merged 6 commits into
masterfrom
add-external-data-source-rotate-keys-api
Nov 6, 2026
Merged

karthikeyanraghavan merged 6 commits into
masterfrom
add-external-data-source-rotate-keys-api

Conversation

@karthikeyanraghavan

@karthikeyanraghavan karthikeyanraghavan commented Nov 4, 2026 •

Copy link
Copy Markdown
Contributor

Description

  • Added a new method rotate_keys to rotate the credentials for external data sources (currently supported for snowflake only)
  • Added code samples for rotating credentials for snowflake data sources
  • Added unit tests for the above feature addition

Checklist:

  • Tests added/updated.
  • Documentation updated. Documentation is generated from docstrings - these must be updated according to your change.
    If a new method has been added it should be referenced in cognite.rst in order to generate docs based on its docstring.
  • The PR title follows the Conventional Commit spec.

@karthikeyanraghavan
karthikeyanraghavan marked this pull request as ready for review November 4, 2026 09:57
@karthikeyanraghavan
karthikeyanraghavan requested review from a team as code owners November 4, 2026 09:57
@karthikeyanraghavan karthikeyanraghavan changed the title Added rotate keys api endpoint support in sdk feat(transformations): Added rotate keys api endpoint support in sdk Nov 4, 2026

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Code Review

This pull request introduces a new rotate_keys endpoint to rotate Snowflake external data source keys, adding the corresponding async/sync API methods, data classes, documentation, and unit tests. The review feedback suggests enhancing rotate_keys to support dictionary inputs in addition to typed objects, ensuring consistency with other SDK methods and preventing runtime errors.

Comment on lines +342 to +357
items = [rotation] if isinstance(rotation, ExternalDataSourceRotateKeys) else list(rotation)
if not items:
return ExternalDataSourceRotatedKeysList([])
if len(items) > self._ROTATE_KEYS_LIMIT:
raise ValueError(
f"At most {self._ROTATE_KEYS_LIMIT} data sources can be rotated per call (the operation is atomic "
f"and cannot be split), got {len(items)}"
)
self._rotate_keys_warning.warn()
res = await self._post(
url_path=self._RESOURCE_PATH + "/rotatekeys",
json={"items": [item.dump(camel_case=True) for item in items]},
semaphore=self._get_semaphore("write"),
)
rotated = ExternalDataSourceRotatedKeysList._load(res.json()["items"])
return rotated[0] if isinstance(rotation, ExternalDataSourceRotateKeys) else rotated

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

high

The current implementation of rotate_keys does not support passing a dictionary or a list of dictionaries as input, which is inconsistent with other SDK methods (e.g., create, retrieve). Furthermore, if a dictionary is passed, isinstance(rotation, ExternalDataSourceRotateKeys) evaluates to False, and list(rotation) extracts the dictionary keys (['externalId', 'expiryTime']), leading to a cryptic AttributeError: 'str' object has no attribute 'dump' at runtime.

To align with the SDK's established patterns and improve robustness, we should support both ExternalDataSourceRotateKeys and dict inputs, loading them properly using ExternalDataSourceRotateKeys.load.

        is_single = isinstance(rotation, (ExternalDataSourceRotateKeys, dict))
        items = [rotation] if is_single else list(rotation)
        if not items:
            return ExternalDataSourceRotatedKeysList([])
        if len(items) > self._ROTATE_KEYS_LIMIT:
            raise ValueError(
                f"At most {self._ROTATE_KEYS_LIMIT} data sources can be rotated per call (the operation is atomic "
                f"and cannot be split), got {len(items)}"
            )
        processed_items: list[ExternalDataSourceRotateKeys] = []
        for item in items:
            if isinstance(item, dict):
                processed_items.append(ExternalDataSourceRotateKeys.load(item))
            elif isinstance(item, ExternalDataSourceRotateKeys):
                processed_items.append(item)
            else:
                raise TypeError(f"Expected ExternalDataSourceRotateKeys or dict, got {type(item)}")
        self._rotate_keys_warning.warn()
        res = await self._post(
            url_path=self._RESOURCE_PATH + "/rotatekeys",
            json={"items": [item.dump(camel_case=True) for item in processed_items]},
            semaphore=self._get_semaphore("write"),
        )
        rotated = ExternalDataSourceRotatedKeysList._load(res.json()["items"])
        return rotated[0] if is_single else rotated
References
  1. Consistency: Follow established patterns across the codebase. (link)
  2. Error Handling: Provide meaningful error messages. (link)

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

This is not true. Create and retrieve doesn't support dict or list of dicts. Will leave for reviewer in case they think otherwise

@codecov

codecov Bot commented Nov 4, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 93.68%. Comparing base (d7f60c1) to head (f933c76).
⚠️ Report is 1 commits behind head on master.

Additional details and impacted files
@@            Coverage Diff             @@
##           master    #2921      +/-   ##
==========================================
- Coverage   93.69%   93.68%   -0.02%     
==========================================
  Files         540      540              
  Lines       57203    57248      +45     
==========================================
+ Hits        53598    53633      +35     
- Misses       3605     3615      +10     
Files with missing lines Coverage Δ
...ognite/client/_api/transformations/externaldata.py 100.00% <100.00%> (ø)
...e/client/_sync_api/transformations/externaldata.py 100.00% <100.00%> (ø)
...te/client/data_classes/transformations/__init__.py 85.51% <ø> (ø)
...lient/data_classes/transformations/externaldata.py 100.00% <100.00%> (ø)
...nit/test_api/test_transformations_external_data.py 100.00% <100.00%> (ø)

... and 6 files with indirect coverage changes

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@HMEiding HMEiding left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Looks good to me, just one nit.

@HMEiding HMEiding left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🦄

HMEiding
HMEiding previously approved these changes Nov 4, 2026
>>> from cognite.client.utils._time import timestamp_to_ms
>>> client = CogniteClient()
>>> # async_client = AsyncCogniteClient() # another option
>>> expiry_time = timestamp_to_ms("now") + 30 * 24 * 3600 * 1000

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

I have commented on this a number of times now, I would prefer if you used the “days ahead” syntax

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Oh my bad. I will fix this.

from cognite.client.utils._time import timestamp_to_ms

rotated = client.transformations.external_data_sources.rotate_keys(
ExternalDataSourceRotateKeys("snowflake-analytics-prod", timestamp_to_ms("now") + 30 * 24 * 3600 * 1000)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Here as well

@karthikeyanraghavan
karthikeyanraghavan requested review from HMEiding and removed request for HMEiding November 5, 2026 06:07
@karthikeyanraghavan karthikeyanraghavan added the waiting-for-risk-review Waiting for a member of the risk review team to take an action label Nov 6, 2026
@haakonvt

haakonvt commented Nov 6, 2026

Copy link
Copy Markdown
Contributor

🦄

@haakonvt haakonvt self-assigned this Nov 6, 2026
@haakonvt haakonvt added risk-review-ongoing Risk review is in progress waiting-for-team Waiting for the submitter or reviewer of the PR to take an action and removed waiting-for-risk-review Waiting for a member of the risk review team to take an action labels Nov 6, 2026
@karthikeyanraghavan
karthikeyanraghavan added this pull request to the merge queue Nov 6, 2026
Merged via the queue into master with commit dd77f4c Nov 6, 2026
23 checks passed
@karthikeyanraghavan
karthikeyanraghavan deleted the add-external-data-source-rotate-keys-api branch November 6, 2026 10:25
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

risk-review-ongoing Risk review is in progress waiting-for-team Waiting for the submitter or reviewer of the PR to take an action

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants