Skip to content

feat(policy): add sort ListSubjectMappings API#3255

Merged
dsm20 merged 11 commits intomainfrom
feat/DSPX-2685-add-sort-listsubjectmappings
Apr 8, 2026
Merged

feat(policy): add sort ListSubjectMappings API#3255
dsm20 merged 11 commits intomainfrom
feat/DSPX-2685-add-sort-listsubjectmappings

Conversation

@dsm20
Copy link
Copy Markdown
Contributor

@dsm20 dsm20 commented Apr 2, 2026

Resolves DSPX-2685

Proposed Changes

Changes

Protoservice/policy/subjectmapping/subject_mapping.proto

  • SortSubjectMappingsType enum (UNSPECIFIED, CREATED_AT, UPDATED_AT)
  • SubjectMappingsSort message (field + direction)
  • repeated SubjectMappingsSort sort = 11 on ListSubjectMappingsRequest with max_items = 1 constraint
  • Regenerated protos and docs

SQLservice/policy/db/queries/subject_mappings.sql

  • CASE WHEN ORDER BY blocks for created_at and updated_at (ASC/DESC each)
  • Fallback sm.created_at DESC + tiebreaker sm.id ASC

Goservice/policy/db/utils.go + service/policy/db/subject_mappings.go

  • GetSubjectMappingsSortParams(): maps enum to SQL-compatible field/direction strings
  • ListSubjectMappings handler wired to call mapper and pass params to sqlc query
  • Extracted sortFieldCreatedAt/sortFieldUpdatedAt constants in utils.go to resolve goconst lint across all sort helpers (slightly out of scope but necessary to avoid goconst errors)

Tests

  • 9 unit tests for the enum mapper helper (nil, empty, unspecified, each field + direction)
  • 5 integration tests (created_at ASC/DESC, updated_at ASC/DESC, unspecified fallback) using createSortTestSubjectMappings suite helper
  • Protovalidate sort constraint test (Test_ListSubjectMappingsRequest_Sort)

Notes

Checklist

  • I have added or updated unit tests
  • I have added or updated integration tests (if appropriate)
  • I have added or updated documentation

Summary by CodeRabbit

  • New Features

    • Added sorting to the subject mappings list: sort by created_at or updated_at, ASC/DESC, max one sort field per request.
  • Documentation

    • gRPC and OpenAPI docs updated to describe new sort enum, sort object, and request sort field.
  • Tests

    • Added unit and integration tests covering sort parameter validation and ordering behavior.

@dsm20 dsm20 requested review from a team as code owners April 2, 2026 17:38
@dsm20 dsm20 marked this pull request as draft April 2, 2026 17:38
@coderabbitai
Copy link
Copy Markdown

coderabbitai bot commented Apr 2, 2026

📝 Walkthrough

Walkthrough

Adds single-field sorting to ListSubjectMappings: proto/schemas for sort, mapping of sort to SQL field/direction, query ORDER BY made dynamic, utilities and tests updated, and docs/OpenAPI extended.

Changes

Cohort / File(s) Summary
Proto Definitions
service/policy/subjectmapping/subject_mapping.proto
Added SortSubjectMappingsType enum and SubjectMappingsSort message; added repeated SubjectMappingsSort sort = 11 to ListSubjectMappingsRequest with max_items = 1 validation.
Database Query Layer
service/policy/db/queries/subject_mappings.sql, service/policy/db/subject_mappings.sql.go, service/policy/db/subject_mappings.go
Reworked listSubjectMappings to accept sort_field/sort_direction parameters; replaced fixed ORDER BY sm.created_at DESC with conditional CASE-based ordering using chosen field/direction; updated parameter ordering and LIMIT/OFFSET placeholders and threaded new params through Go query params.
Sort Parameter Utilities & Tests
service/policy/db/utils.go, service/policy/db/utils_test.go
Added GetSubjectMappingsSortParams to map proto sort input to SQL field/direction strings; introduced shared created_at/updated_at constants; added unit tests covering nil/empty/unset/ASC/DESC cases.
Integration & Proto Tests
service/integration/subject_mappings_test.go, service/policy/subjectmapping/subject_mapping_test.go
Added integration tests verifying ASC/DESC ordering for created_at and updated_at (including timestamp adjustments), and proto validator tests ensuring sort allows 0–1 entries and rejects >1.
API Documentation / OpenAPI
docs/grpc/index.html, docs/openapi/policy/subjectmapping/subject_mapping.openapi.yaml
Documented new SubjectMappingsSort message and SortSubjectMappingsType enum; updated OpenAPI schemas and added optional sort array (items: SubjectMappingsSort, maxItems: 1) to ListSubjectMappingsRequest.

Sequence Diagram(s)

sequenceDiagram
    participant Client
    participant API as Policy API
    participant DBClient as PolicyDBClient
    participant DB as Database

    Client->>API: ListSubjectMappingsRequest(sort)
    API->>DBClient: GetSubjectMappingsSortParams(sort)
    DBClient->>DB: listSubjectMappings(namespace, sort_field, sort_direction, limit, offset)
    DB-->>DBClient: rows (ordered by chosen field/direction)
    DBClient-->>API: subject mappings
    API-->>Client: ListSubjectMappingsResponse
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Suggested reviewers

  • c-r33d
  • alkalescent

Poem

🐰 I hopped through proto, SQL, and docs with cheer,
Chose created_at or updated_at clear,
ASC or DESC, one field to impart —
Now lists sort tidy, right from the start! ✨

🚥 Pre-merge checks | ✅ 2 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 27.27% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (2 passed)
Check name Status Explanation
Title check ✅ Passed The title accurately and concisely describes the main change: adding sort support to the ListSubjectMappings API.
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feat/DSPX-2685-add-sort-listsubjectmappings

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

Comment @coderabbitai help to get the list of available commands and usage tips.

@github-actions github-actions bot added comp:db DB component comp:policy Policy Configuration ( attributes, subject mappings, resource mappings, kas registry) docs Documentation labels Apr 2, 2026
@gemini-code-assist
Copy link
Copy Markdown
Contributor

Summary of Changes

Hello, I'm Gemini Code Assist1! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed!

This pull request introduces sorting capabilities to the ListSubjectMappings API. It defines the necessary protocol buffer structures, implements the mapping logic in the Go service layer, and updates the underlying SQL queries to handle dynamic sorting parameters. The changes ensure that API consumers can sort results by creation or update timestamps while maintaining backward compatibility.

Highlights

  • API Enhancement: Added support for sorting in the ListSubjectMappings API by introducing a new SortSubjectMappingsType enum and SubjectMappingsSort message.
  • Database Updates: Updated the SQL query to support dynamic sorting by created_at or updated_at fields, with a fallback to default ordering.
  • Testing: Added comprehensive unit tests for the sorting parameter mapper and integration tests to verify sorting behavior for both created_at and updated_at fields.

🧠 New Feature in Public Preview: You can now enable Memory to help Gemini Code Assist learn from your team's feedback. This makes future code reviews more consistent and personalized to your project's style. Click here to enable Memory in your admin console.

Ignored Files
  • Ignored by pattern: docs/openapi/**/* (2)
    • docs/openapi/authorization/authorization.openapi.yaml
    • docs/openapi/policy/subjectmapping/subject_mapping.openapi.yaml
  • Ignored by pattern: protocol/**/* (1)
    • protocol/go/policy/subjectmapping/subject_mapping.pb.go
Using Gemini Code Assist

The full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips.

Invoking Gemini

You can request assistance from Gemini at any point by creating a comment using either /gemini <command> or @gemini-code-assist <command>. Below is a summary of the supported commands on the current page.

Feature Command Description
Code Review /gemini review Performs a code review for the current pull request in its current state.
Pull Request Summary /gemini summary Provides a summary of the current pull request in its current state.
Comment @gemini-code-assist Responds in comments when explicitly tagged, both in pull request comments and review comments.
Help /gemini help Displays a list of available commands.

Customization

To customize Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a .gemini/ folder in the base of the repository. Detailed instructions can be found here.

Limitations & Feedback

Gemini Code Assist may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counter productive. You can react with 👍 and 👎 on @gemini-code-assist comments. If you're interested in giving your feedback about your experience with Gemini Code Assist for GitHub and other Google products, sign up here.


The list was static, fixed in time, Now sorting makes it feel sublime. By date or update, order flows, As logic in the database grows.

Footnotes

  1. Review the Privacy Notices, Generative AI Prohibited Use Policy, Terms of Service, and learn how to configure Gemini Code Assist in GitHub here. Gemini can make mistakes, so double check it and use code with caution.

@github-actions github-actions bot added the size/m label Apr 2, 2026
Copy link
Copy Markdown
Contributor

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

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 sorting capabilities for listing subject mappings, allowing users to sort by creation and update timestamps in both ascending and descending order. The changes include updates to the protobuf definitions, database queries, and utility functions, supported by comprehensive integration and unit tests. Review feedback highlights opportunities to reduce code duplication in the new integration tests by extracting a helper method for subject mapping creation and to simplify a switch statement within the sorting utility function.

@github-actions
Copy link
Copy Markdown
Contributor

github-actions bot commented Apr 2, 2026

Benchmark results, click to expand

Benchmark authorization.GetDecisions Results:

Metric Value
Approved Decision Requests 1000
Denied Decision Requests 0
Total Time 202.048429ms

Benchmark authorization.v2.GetMultiResourceDecision Results:

Metric Value
Approved Decision Requests 1000
Denied Decision Requests 0
Total Time 98.477362ms

Benchmark Statistics

Name № Requests Avg Duration Min Duration Max Duration

Bulk Benchmark Results

Metric Value
Total Decrypts 100
Successful Decrypts 100
Failed Decrypts 0
Total Time 390.201096ms
Throughput 256.28 requests/second

TDF3 Benchmark Results:

Metric Value
Total Requests 5000
Successful Requests 5000
Failed Requests 0
Concurrent Requests 50
Total Time 40.765670014s
Average Latency 406.077835ms
Throughput 122.65 requests/second

@github-actions
Copy link
Copy Markdown
Contributor

github-actions bot commented Apr 2, 2026

dsm20 added 10 commits April 7, 2026 12:45
define SortSubjectMappingsType enum and SubjectMappingsSort message for strongly-typed sort on ListSubjectMappings RPC
following the pattern, change the ORDER BY to incorporate CASE WHEN structuring with the sort fields
helper maps proto enum values to strings, handler passes strings to sqlc
implement unit tests for all sort functions including nil, empty slice, nill element ([nill])
added 5 integration tests: CreatedAt ASC/DESC, UpdatedAt ASC/DESC, and then FallsBackToDefault (CreatedAt DESC)
ran buf generate originally, but needed to do 'make proto-generate' to capture grpc and openai docs
CREATED_AT and UPDATED_AT are used in this case for the protovalidate
test which covers 3 cases: no sort (valid), one item sort (also valid),
and two sort items (invalid, since max_items is 1 in the proto).
added helper (createSortTestSubjectMappings()), then refactored existing
5 sort cases to use the helper. added neccesary fmt import. improved
existing test (UpdatedAt_ASC). this list API only requires 1 helper
since it only uses time based tests.
created_at and updated_at sort fields are now constants defined at the
beginning of utils.go. This is because goconst will fail on the case
that these strings are being used more than 3 times without their own
variable.
@dsm20 dsm20 force-pushed the feat/DSPX-2685-add-sort-listsubjectmappings branch from 234f300 to 7970007 Compare April 7, 2026 17:55
@github-actions
Copy link
Copy Markdown
Contributor

github-actions bot commented Apr 7, 2026

Benchmark results, click to expand

Benchmark authorization.GetDecisions Results:

Metric Value
Approved Decision Requests 1000
Denied Decision Requests 0
Total Time 193.289368ms

Benchmark authorization.v2.GetMultiResourceDecision Results:

Metric Value
Approved Decision Requests 1000
Denied Decision Requests 0
Total Time 99.409611ms

Benchmark Statistics

Name № Requests Avg Duration Min Duration Max Duration

Bulk Benchmark Results

Metric Value
Total Decrypts 100
Successful Decrypts 100
Failed Decrypts 0
Total Time 408.780636ms
Throughput 244.63 requests/second

TDF3 Benchmark Results:

Metric Value
Total Requests 5000
Successful Requests 5000
Failed Requests 0
Concurrent Requests 50
Total Time 41.208107536s
Average Latency 410.466252ms
Throughput 121.34 requests/second

@dsm20 dsm20 marked this pull request as ready for review April 7, 2026 18:10
Copy link
Copy Markdown

@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: 2

🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@docs/openapi/policy/subjectmapping/subject_mapping.openapi.yaml`:
- Around line 1580-1586: Update the description for the "sort" property in the
policy.subjectmapping.SubjectMappings schema to explicitly state the server's
default/fallback ordering when the field is omitted or empty (e.g., "When not
provided, results are ordered by <primaryField> ascending, then by
<secondaryField> descending" or whatever the server actually implements); keep
the existing maxItems note and add a sentence describing deterministic behavior
so clients can rely on the default order, referencing the sort array and the
SubjectMappingsSort item type.

In `@service/policy/db/utils.go`:
- Around line 317-321: The helper currently maps any non-DESC value to "ASC",
causing invalid/future policy.SortDirection values to be treated as ascending;
change the logic so only an explicit SORT_DIRECTION_ASC returns "ASC" and
SORT_DIRECTION_DESC returns "DESC", otherwise return an empty/invalid direction
(e.g., "" or nil-equivalent) so callers can detect invalid directions and fall
back to the default ordering (created_at DESC); update the branch that checks
s.GetDirection() (and the local variable direction) to only set "ASC" when
s.GetDirection() == policy.SortDirection_SORT_DIRECTION_ASC and "DESC" when ==
policy.SortDirection_SORT_DIRECTION_DESC, leaving direction empty for all other
values.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: ASSERTIVE

Plan: Pro

Run ID: 21c7e93f-ce5e-435f-8469-3dbec3932a87

📥 Commits

Reviewing files that changed from the base of the PR and between 234f300 and 7970007.

⛔ Files ignored due to path filters (1)
  • protocol/go/policy/subjectmapping/subject_mapping.pb.go is excluded by !**/*.pb.go
📒 Files selected for processing (10)
  • docs/grpc/index.html
  • docs/openapi/policy/subjectmapping/subject_mapping.openapi.yaml
  • service/integration/subject_mappings_test.go
  • service/policy/db/queries/subject_mappings.sql
  • service/policy/db/subject_mappings.go
  • service/policy/db/subject_mappings.sql.go
  • service/policy/db/utils.go
  • service/policy/db/utils_test.go
  • service/policy/subjectmapping/subject_mapping.proto
  • service/policy/subjectmapping/subject_mapping_test.go

was not using getSortDirection here, incorrect.
@github-actions
Copy link
Copy Markdown
Contributor

github-actions bot commented Apr 7, 2026

Benchmark results, click to expand

Benchmark authorization.GetDecisions Results:

Metric Value
Approved Decision Requests 1000
Denied Decision Requests 0
Total Time 198.869332ms

Benchmark authorization.v2.GetMultiResourceDecision Results:

Metric Value
Approved Decision Requests 1000
Denied Decision Requests 0
Total Time 94.2424ms

Benchmark Statistics

Name № Requests Avg Duration Min Duration Max Duration

Bulk Benchmark Results

Metric Value
Total Decrypts 100
Successful Decrypts 100
Failed Decrypts 0
Total Time 394.26373ms
Throughput 253.64 requests/second

TDF3 Benchmark Results:

Metric Value
Total Requests 5000
Successful Requests 5000
Failed Requests 0
Concurrent Requests 50
Total Time 40.292269996s
Average Latency 400.766236ms
Throughput 124.09 requests/second

@github-actions
Copy link
Copy Markdown
Contributor

github-actions bot commented Apr 7, 2026

⚠️ Govulncheck found vulnerabilities ⚠️

The following modules have known vulnerabilities:

  • service
  • tests-bdd

See the workflow run for details.

@dsm20 dsm20 added this pull request to the merge queue Apr 8, 2026
Merged via the queue into main with commit 9d5d757 Apr 8, 2026
40 checks passed
@dsm20 dsm20 deleted the feat/DSPX-2685-add-sort-listsubjectmappings branch April 8, 2026 16:06
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

comp:db DB component comp:policy Policy Configuration ( attributes, subject mappings, resource mappings, kas registry) docs Documentation size/m

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants