Skip to content

Unregister dev mode session on shutdown #379

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 4 commits into from
Jun 11, 2025
Merged

Unregister dev mode session on shutdown #379

merged 4 commits into from
Jun 11, 2025

Conversation

jhaynie
Copy link
Member

@jhaynie jhaynie commented Jun 11, 2025

Summary by CodeRabbit

  • Bug Fixes
    • Improved server shutdown reliability by ensuring connections are properly closed and cleanup requests are sent to the API.
  • Refactor
    • Enhanced API client initialization to prevent premature cancellation during server shutdown.
  • Updates
    • Updated development environment URLs to point to the new domain for improved consistency.

Copy link
Contributor

coderabbitai bot commented Jun 11, 2025

"""

Walkthrough

The Server.Close() method in internal/dev/server.go was updated to call a new private method, closeConnection(), which sends a DELETE request to an API endpoint for cleanup. The Server constructor now initializes the API client with a non-cancellable context to prevent premature cancellation. Additionally, internal/util/api.go was updated to change development environment URLs from .dev to .io domains and corresponding app and transport URLs.

Changes

File(s) Change Summary
internal/dev/server.go Added closeConnection() method for API cleanup; updated Server.Close() to call it; changed New() to use a non-cancellable context for API client initialization.
internal/util/api.go Updated development environment URLs from .dev to .io domains; changed app and transport URLs accordingly.

Sequence Diagram(s)

sequenceDiagram
    participant Client
    participant Server
    participant API

    Client->>Server: Call Close()
    Server->>API: DELETE /cli/devmode/{projectId}/{serverId}
    API-->>Server: Response (success or error)
    Server->>Server: Wait for goroutines, close TLS connection
    Server-->>Client: Close() returns
Loading

Poem

A server’s farewell, a gentle goodbye,
With DELETE it whispers, as connections untie.
Contexts now sturdy, no cancel in sight,
Cleanup is tidy, all ends put right.
The code hops ahead, with a rabbit’s delight! 🐇
"""


📜 Recent review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 842997c and 6876ec8.

📒 Files selected for processing (1)
  • internal/util/api.go (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • internal/util/api.go
⏰ Context from checks skipped due to timeout of 90000ms (3)
  • GitHub Check: Build and Test (macos-latest)
  • GitHub Check: Test CLI Upgrade Path (windows-latest)
  • GitHub Check: Analyze (go)
✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate Unit Tests
  • Create PR with Unit Tests
  • Commit Unit Tests in branch unregister-devmode
  • Post Copyable Unit Tests in Comment

🪧 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

🔭 Outside diff range comments (1)
internal/dev/server.go (1)

108-116: 🛠️ Refactor suggestion

Order of operations could unintentionally rely on implementation details

Close() cancels s.ctx before invoking s.closeConnection().
Because s.apiclient was built with context.WithoutCancel(ctx), this works today, but the correctness now relies on:

  1. util.NewAPIClient only using the supplied context and never the later-cancelled s.ctx.
  2. Future maintainers remembering this subtle coupling.

Placing s.closeConnection() before s.cancel() would avoid the dependency and make the intent obvious.

-        s.cancel()
-        s.closeConnection()
+        s.closeConnection()
+        s.cancel()
🧹 Nitpick comments (2)
internal/dev/server.go (2)

123-127: closeConnection lacks timeout / 404 handling

The DELETE call can hang indefinitely or treat a legitimate “already gone” 404 as an error.
Consider:

  • Wrapping the request in a short context timeout so shutdown cannot block forever.
  • Treating 404/410 responses as success.
 func (s *Server) closeConnection() {
-    if err := s.apiclient.Do("DELETE", "/cli/devmode/"+s.Project.Project.ProjectId+"/"+s.ID, nil, nil); err != nil {
-        s.logger.Error("failed to send close connection: %s", err)
-    }
+    ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
+    defer cancel()
+
+    if err := s.apiclient.DoWithContext(ctx, "DELETE",
+        "/cli/devmode/"+s.Project.Project.ProjectId+"/"+s.ID, nil, nil); err != nil &&
+        !util.IsNotFound(err) {                 // helper that maps 404/410 to nil
+        s.logger.Warn("devmode unregister failed: %s", err)
+    }
 }

668-672: Good call on context.WithoutCancel, but watch for orphaned requests

Using context.WithoutCancel(ctx) ensures API calls survive Server cancellation, which fixes premature shutdowns.
Just make sure util.APIClient respects request-scoped contexts (e.g., takes one in Do(...)) so long-running or hung requests can still be aborted by upper layers; otherwise they may leak.

No action required, just flagging the trade-off for future maintenance.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 58621d9 and 21599d7.

📒 Files selected for processing (1)
  • internal/dev/server.go (3 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (2)
  • GitHub Check: Test CLI Upgrade Path (windows-latest)
  • GitHub Check: Analyze (go)

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: 1

🔭 Outside diff range comments (1)
internal/util/api.go (1)

238-260: ⚠️ Potential issue

Dev container rewrite now misses the new .io domain

TransformUrl still only recognises api.agentuity.dev; after this PR, dev traffic will use api.agentuity.io, so the Docker-host rewrite will silently stop working.
Add the .io checks (and prefix variant) to keep “inside-container” flows functional.

-if strings.Contains(urlString, "api.agentuity.dev") || strings.Contains(urlString, "localhost:") || strings.Contains(urlString, "127.0.0.1:") {
+if strings.Contains(urlString, "api.agentuity.dev") ||      // legacy
+   strings.Contains(urlString, "api.agentuity.io") ||       // new
+   strings.Contains(urlString, "localhost:") ||
+   strings.Contains(urlString, "127.0.0.1:") {
@@
-  if strings.HasPrefix(urlString, "https://api.agentuity.dev") {
+  if strings.HasPrefix(urlString, "https://api.agentuity.dev") ||
+     strings.HasPrefix(urlString, "https://api.agentuity.io") {
🧹 Nitpick comments (1)
internal/util/api.go (1)

269-272: Nit: misleading log message

The message still says “dev” but we are matching the .io domain now.
Consider clarifying to avoid confusion when reading logs.

-logger.Debug("switching app url to dev since the api url is dev")
+logger.Debug("switching app url to io-dev since the api url is io")
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 21599d7 and 842997c.

📒 Files selected for processing (2)
  • internal/dev/server.go (3 hunks)
  • internal/util/api.go (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • internal/dev/server.go
🧰 Additional context used
🧠 Learnings (1)
internal/util/api.go (1)
Learnt from: pec1985
PR: agentuity/cli#342
File: cmd/logs.go:58-60
Timestamp: 2025-05-26T08:15:51.542Z
Learning: In the agentuity/cli codebase, util.GetURLs returns (apiUrl, appUrl, transportUrl string) and util.EnsureLoggedIn returns (apikey, userId string). These functions handle errors internally and call os.Exit(1) for fatal conditions rather than returning errors. The blank identifiers in calls to these functions are for ignoring unused return values, not errors.
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: Test CLI Upgrade Path (windows-latest)

@jhaynie jhaynie merged commit 7fe3b17 into main Jun 11, 2025
17 of 20 checks passed
@jhaynie jhaynie deleted the unregister-devmode branch June 11, 2025 15:36
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.

2 participants