Skip to content

[cozystack-api] Fix non-existing OpenAPI refs - #1208

Merged
Andrei Kvapil (kvaps) merged 1 commit into
mainfrom
fix-openapi
Jul 17, 2025
Merged

[cozystack-api] Fix non-existing OpenAPI refs#1208
Andrei Kvapil (kvaps) merged 1 commit into
mainfrom
fix-openapi

Conversation

@kvaps

@kvaps Andrei Kvapil (kvaps) commented Jul 16, 2025

Copy link
Copy Markdown
Member

Signed-off-by: Andrei Kvapil kvapss@gmail.com

What this PR does

Release note

[cozystack-api] Fix non-existing OpenAPI refs

Summary by CodeRabbit

Summary by CodeRabbit

  • Refactor

    • Improved and unified the processing of OpenAPI schemas for both v3 and v2 formats, resulting in more consistent and maintainable API documentation.
    • Enhanced support for status schemas and improved handling of schema references across different resource types.
  • Bug Fixes

    • Fixed issues with schema references to ensure they correctly point to kind-specific definitions in generated OpenAPI documentation.

@coderabbitai

coderabbitai Bot commented Jul 16, 2025

Copy link
Copy Markdown
Contributor

"""

Walkthrough

This update refactors and extends the OpenAPI schema post-processing logic for both v2 and v3 formats. It introduces new helper functions for cloning and patching schemas, adds support for status schemas, unifies cloning logic, and implements a comprehensive mechanism to rewrite $ref references for multiple kinds in the OpenAPI documents.

Changes

File(s) Change Summary
pkg/cmd/server/openapi.go Refactored schema cloning and patching logic; added status schema support; introduced recursive $ref rewriting; unified logic for OpenAPI v2 and v3 post-processing; added new helper functions for schema manipulation and reference rewriting.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant Server
    participant OpenAPIProcessor

    User->>Server: Request OpenAPI schema
    Server->>OpenAPIProcessor: Build and post-process schema
    OpenAPIProcessor->>OpenAPIProcessor: Clone base, status, and list schemas per kind
    OpenAPIProcessor->>OpenAPIProcessor: Patch .spec with user schema
    OpenAPIProcessor->>OpenAPIProcessor: Rewrite all $ref references
    OpenAPIProcessor->>Server: Return processed OpenAPI schema
    Server->>User: Respond with OpenAPI schema
Loading

Possibly related PRs

Suggested labels

bug, size:M

Suggested reviewers

  • klinch0
  • lllamnyp

Poem

In the warren of schemas, we hop and we bound,
Cloning and patching wherever they're found.
With $refs redirected and status in tow,
Our OpenAPI gardens continue to grow.
🐇✨
A hop, a skip, a schema anew—
The docs are now clearer, for all of the crew!
"""

✨ Finishing Touches
  • 📝 Generate Docstrings

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 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.

@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.

Summary of Changes

Hello Andrei Kvapil (@kvaps), 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 addresses an issue where the generated OpenAPI specifications (both v2 and v3) contained non-existing or incorrect internal references ($ref) for custom resource schemas. My changes introduce a robust system to dynamically clone base schemas, apply correct Group-Version-Kind (GVK) extensions, and globally rewrite all internal references to accurately reflect the specific custom resource kind, ensuring the OpenAPI spec is valid and correctly consumable by API clients.

Highlights

  • OpenAPI Reference Correction: I've implemented a new mechanism to dynamically rewrite OpenAPI $ref (references) within the generated specification. This ensures that schema references, particularly for status and list objects, correctly point to the specific custom resource kind (e.g., MyKindStatus, MyKindList) instead of a generic Application type.
  • Unified Schema Generation Logic: I've introduced a new helper function, cloneKindSchemas, to centralize the logic for cloning base schemas (Application, ApplicationList, ApplicationStatus) and applying x-kubernetes-group-version-kind extensions for each custom resource kind. This reduces duplication and improves maintainability for both OpenAPI v2 and v3 generation.
  • Global Document Reference Rewriting: A recursive document traversal (walkAndRewriteRefs) has been added to find and correct all $ref instances across the entire OpenAPI document. This ensures comprehensive consistency in references after the initial schema cloning and GVK application.
  • Improved Schema Management: I've introduced an apiPrefix constant and baseStatusRef to improve the organization and completeness of base schema definitions. Minor refinements were also made to deepCopySchema and findSpecContainer for robustness and clarity.
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 in your pull request via creating an issue comment (i.e. comment on the pull request page) using either /gemini <command> or @gemini-code-assist <command>. Below is a summary of the supported commands.

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 (@gemini-code-assist) Responds in comments when explicitly tagged, both in issue 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 is currently in preview and may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counter productive. You can react with 👍 and 👎 on Gemini (@gemini-code-assist) comments to provide feedback.

You can also get AI-powered code generation, chat, as well as code reviews directly in the IDE at no cost with the Gemini Code Assist IDE Extension.

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.

@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 refactors the OpenAPI post-processing logic to correctly handle and rewrite references for custom resource kinds, fixing an issue with non-existing refs. The changes introduce several helper functions to reduce code duplication between the v2 and v3 processors, which improves maintainability. The review focuses on error handling, identifying places where errors are silently ignored, which could lead to hard-to-debug issues. Suggestions are provided to handle these errors properly.

Comment thread pkg/cmd/server/openapi.go Outdated
Comment thread pkg/cmd/server/openapi.go
Comment thread pkg/cmd/server/openapi.go

@coderabbitai coderabbitai 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.

Actionable comments posted: 2

🧹 Nitpick comments (2)
pkg/cmd/server/openapi.go (2)

249-255: Improve error context for document rewriting failures.

The error from rewriteDocRefs or the final json.Unmarshal could be more descriptive.

 // Rewrite all $ref in the document
 out, err := rewriteDocRefs(doc)
 if err != nil {
-	return nil, err
+	return nil, fmt.Errorf("failed to rewrite document refs: %w", err)
 }
-return doc, json.Unmarshal(out, doc)
+if err := json.Unmarshal(out, doc); err != nil {
+	return nil, fmt.Errorf("failed to unmarshal rewritten document: %w", err)
+}
+return doc, nil

308-314: Apply consistent error handling improvements as in v3 processor.

Similar to the v3 processor, improve error context for better debugging.

 // Rewrite all $ref in the document
 out, err := rewriteDocRefs(sw)
 if err != nil {
-	return nil, err
+	return nil, fmt.Errorf("failed to rewrite swagger refs: %w", err)
 }
-return sw, json.Unmarshal(out, sw)
+if err := json.Unmarshal(out, sw); err != nil {
+	return nil, fmt.Errorf("failed to unmarshal rewritten swagger: %w", err)
+}
+return sw, nil
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between f2a8c3d and fa0b9b6.

📒 Files selected for processing (1)
  • pkg/cmd/server/openapi.go (3 hunks)
🧰 Additional context used
🧠 Learnings (1)
📓 Common learnings
Learnt from: NickVolynkin
PR: cozystack/cozystack#1120
File: packages/apps/ferretdb/README.md:35-37
Timestamp: 2025-07-02T09:58:11.406Z
Learning: In the cozystack repository, the maintainer NickVolynkin prefers to keep realistic-looking example credentials in README documentation rather than using generic placeholders like <ACCESS_KEY>, even though they are just examples and not real secrets.
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (1)
  • GitHub Check: Build
🔇 Additional comments (5)
pkg/cmd/server/openapi.go (5)

16-22: Good refactoring to extract common prefix and add status reference.

The extraction of apiPrefix constant improves maintainability, and adding baseStatusRef completes the schema reference set needed for proper OpenAPI generation.


35-53: Safe simplification of the Properties check.

The removal of Properties != nil check is safe since Go's map access on a nil map returns the zero value and ok will be false.


55-79: Clean refactoring of patchSpec function.

The simplified assignment of AdditionalProperties maintains the same behavior while improving readability.


171-192: Well-implemented reference rewriting logic.

The function correctly handles both OpenAPI v3 and v2 reference formats and appropriately transforms Application references to kind-specific ones.


121-130: Add error handling for final JSON marshaling.

While the initial unmarshal error is handled, the final json.Marshal on line 129 could fail and should be checked.

 func rewriteDocRefs(doc interface{}) ([]byte, error) {
 	raw, _ := json.Marshal(doc)
 	var any interface{}
 	if err := json.Unmarshal(raw, &any); err != nil {
 		return nil, err
 	}
 	walkAndRewriteRefs(any, "")
-	return json.Marshal(any)
+	result, err := json.Marshal(any)
+	if err != nil {
+		return nil, fmt.Errorf("failed to marshal rewritten document: %w", err)
+	}
+	return result, nil
 }

Likely an incorrect or invalid review comment.

Comment thread pkg/cmd/server/openapi.go
Comment thread pkg/cmd/server/openapi.go
Signed-off-by: Andrei Kvapil <kvapss@gmail.com>

@coderabbitai coderabbitai 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.

Actionable comments posted: 2

🧹 Nitpick comments (1)
pkg/cmd/server/openapi.go (1)

92-100: Inconsistent error handling approach.

The nil checks after deepCopySchema calls are unreachable since deepCopySchema will panic on marshaling errors rather than return nil. Consider either:

  1. Removing the nil checks since panics are expected behavior
  2. Modifying deepCopySchema to return errors instead of panicking
-	// Ensure we have valid clones
-	if obj == nil || status == nil || list == nil {
-		return nil, nil, nil
-	}

Since deepCopySchema panics on errors, these nil checks are redundant and unreachable.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 1dd5d83 and 181e8dc.

📒 Files selected for processing (1)
  • pkg/cmd/server/openapi.go (3 hunks)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (1)
  • GitHub Check: Build
🔇 Additional comments (7)
pkg/cmd/server/openapi.go (7)

16-22: LGTM: Good consolidation of string constants.

The addition of baseStatusRef and consolidation of API prefix constants improves maintainability and aligns with the PR objective of fixing OpenAPI references.


24-39: LGTM: Error handling properly implemented.

The function now correctly handles marshaling/unmarshaling errors with panic and proper error wrapping, addressing the critical issues raised in previous reviews. Panicking is appropriate here since schema marshaling failures indicate programming errors rather than recoverable runtime conditions.


68-68: LGTM: Improved struct initialization clarity.

The explicit struct initialization for SchemaOrBool improves code readability and makes the intent clearer.

Also applies to: 78-78


134-146: LGTM: Proper error handling implemented.

The function correctly handles marshaling errors, addressing the issues raised in previous reviews. The approach of using generic interface{} for document manipulation is appropriate for this ref rewriting task.


148-208: LGTM: Comprehensive ref rewriting implementation.

The recursive walking logic correctly handles both GVK extraction and ref rewriting. The scoped context approach (passing currentKind by value) ensures that kind context is properly isolated between different schema sections.

The rewriteRefForKind function correctly handles all Application* ref patterns and supports both OpenAPI v2 and v3 formats.


1-332: Overall: Strong refactoring that addresses PR objectives.

This comprehensive refactoring successfully addresses the PR objective of fixing non-existing OpenAPI refs by:

  1. Adding ApplicationStatus support - introduces baseStatusRef and handles status schemas
  2. Implementing comprehensive ref rewriting - the new rewriteDocRefs mechanism ensures all $ref references are properly updated
  3. Improving error handling - addresses previous review comments about silent failures
  4. Consolidating duplicate code - the cloneKindSchemas helper eliminates repetition

The changes maintain backward compatibility while significantly improving the robustness of the OpenAPI schema processing.


46-50: No panic: map key lookup on nil Properties is safe
In Go, reading s.Properties["spec"] on a nil map returns the zero value and ok==false — it does not panic. The removed Properties != nil check isn’t needed.

Comment thread pkg/cmd/server/openapi.go
Comment thread pkg/cmd/server/openapi.go
@kvaps
Andrei Kvapil (kvaps) merged commit 4728127 into main Jul 17, 2025
42 of 48 checks passed
@kvaps
Andrei Kvapil (kvaps) deleted the fix-openapi branch July 17, 2025 09:42
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.

1 participant