Skip to content

feat: add group v2 support #132

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

Open
wants to merge 1 commit into
base: main
Choose a base branch
from

Conversation

sorccu
Copy link
Contributor

@sorccu sorccu commented Jun 16, 2025

Tests to follow

Affected Components

  • New Features
  • Bug Fixing
  • Types
  • Tests
  • Docs
  • Other

Style

  • Go code is formatted with go fmt

Notes for the Reviewer

Resolves #[issue-number]

New Dependency Submission

Copy link

coderabbitai bot commented Jun 16, 2025

"""

Walkthrough

The changes introduce API versioning support in the client by refactoring HTTP API call methods to use explicit versioned wrappers (apiCallV1, apiCallV2). New methods and types for version 2 of check groups are added, including GroupV2 and related configuration structs. Custom JSON marshaling logic for RetryStrategy is implemented, and corresponding unit tests are provided.

Changes

Files / Areas Change Summary
checkly.go Refactored API calls to use versioned wrappers (apiCallV1, apiCallV2); added v2 group methods; updated apiCall to accept version parameter.
types.go Added GroupV2, AlertSettingsV2, APICheckDefaultsV2 structs; extended Client interface with v2 group methods; implemented custom JSON marshaling for RetryStrategy.
types_test.go Added unit tests for RetryStrategy JSON marshaling and unmarshaling.
"""
✨ Finishing Touches
  • 📝 Generate Docstrings

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

Copy link

@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

🧹 Nitpick comments (3)
types.go (1)

822-831: Strict string comparison may reject valid JSON with insignificant whitespace.

bytes.Equal(data, []byte("FALLBACK")) only passes for the exact byte sequence "FALLBACK". Inputs like " FALLBACK" or "\n\"FALLBACK\" " are valid JSON but fail the check. Consider decoding to a string first or trimming surrounding whitespace before the comparison.

types_test.go (1)

441-446: Mark helper to improve failure location.

testBytesEqual should call t.Helper() so that failures are reported at the caller, not inside the helper itself.

 func testBytesEqual(t *testing.T, got, want []byte) {
-	if !bytes.Equal(got, want) {
-		t.Fatalf("expected: %s, got: %s", want, got)
-	}
+	t.Helper()
+	if !bytes.Equal(got, want) {
+		t.Fatalf("expected: %s, got: %s", want, got)
+	}
 }
checkly.go (1)

1863-1864: Use path.Join (or sanitize) to avoid double slashes in the request URL.

fmt.Sprintf("%s/v%d/%s", c.url, version, URL) will emit // if c.url already ends with / or if URL is prefixed with /. A safer approach is:

requestURL := fmt.Sprintf("%s/v%d/%s", strings.TrimRight(c.url, "/"), version, strings.TrimLeft(URL, "/"))

or path.Join for clarity.

This avoids subtle 301/308 redirects and mismatched signature checks.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 9431512 and 13a5072.

📒 Files selected for processing (3)
  • checkly.go (63 hunks)
  • types.go (7 hunks)
  • types_test.go (2 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (2)
types_test.go (1)
types.go (1)
  • RetryStrategy (814-820)
checkly.go (1)
types.go (2)
  • GroupV2 (901-924)
  • Group (870-898)

@sorccu sorccu force-pushed the simokinnunen/sc-24521/tf-groups-v2-support branch from 13a5072 to a4c1309 Compare June 16, 2025 11:40
Copy link

@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

🧹 Nitpick comments (1)
types.go (1)

134-140: Expose CreateGroupV2 but consider parity helpers.

Introducing a V2 creation method is great, but the interface is starting to bloat.
If V1 is going away soon, think about embedding a dedicated GroupServiceV2 (or similar) instead of piling more methods onto the main interface.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 13a5072 and a4c1309.

📒 Files selected for processing (3)
  • checkly.go (63 hunks)
  • types.go (7 hunks)
  • types_test.go (2 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
  • types_test.go
  • checkly.go
🔇 Additional comments (7)
types.go (7)

4-4: bytes import looks correct.

The additional import is required for the bytes.Equal comparison introduced later in the file – no issues spotted.


148-154: Method naming is consistent – good job.

GetGroupV2 mirrors the existing V1 signature, keeping cognitive load low.


164-172: Consistency check: missing DeleteGroupV2.

You added create/get/update for V2 but not delete. Deliberate? If the endpoint exists, omitting it forces callers to mix versions.


772-779: Pointer fields correctly convey “optional”.

Using pointers inside AlertSettingsV2 avoids accidental zero-value overrides – nice.


853-867: MarshalJSON path is symmetric – all good.

The fallback-as-string encoding matches the unmarshal logic.


900-924: GroupV2 design is flexible but double-check required fields.

Using pointers for every field lets callers perform partial updates, yet it also means forgetting to set Name (still non-pointer) will yield confusing 422s from the API. Ensure upstream validators or builders enforce the minimal set.


936-944: APICheckDefaultsV2 mirrors V1 cleanly – nice extraction.

Pointer slices keep zero-value vs “explicit empty” semantics intact.

types.go Outdated
Comment on lines 822 to 851
func (s *RetryStrategy) UnmarshalJSON(data []byte) error {
// This is a special value for a group, indicating that all checks in
// the group should use their own retry strategies. For the Go API we
// just pretend it's an actual retry strategy type.
if bytes.Equal(data, []byte(`"FALLBACK"`)) {
*s = RetryStrategy{
Type: "FALLBACK",
}

return nil
}

type Underlying RetryStrategy

var underlying *Underlying

if err := json.Unmarshal(data, &underlying); err != nil {
return err
}

*s = RetryStrategy{
Type: underlying.Type,
BaseBackoffSeconds: underlying.BaseBackoffSeconds,
MaxRetries: underlying.MaxRetries,
MaxDurationSeconds: underlying.MaxDurationSeconds,
SameRegion: underlying.SameRegion,
}

return nil
}
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Guard against null and simplify unmarshal logic.

A null JSON payload will leave underlying == nil, triggering a panic when you copy its fields.
You can also avoid the double-pointer dance:

 func (s *RetryStrategy) UnmarshalJSON(data []byte) error {
     // special string case
     if bytes.Equal(data, []byte(`"FALLBACK"`)) {
         *s = RetryStrategy{Type: "FALLBACK"}
         return nil
     }
+
+    // treat explicit null as zero-value
+    if bytes.Equal(bytes.TrimSpace(data), []byte("null")) {
+        *s = RetryStrategy{}
+        return nil
+    }
 
-    type Underlying RetryStrategy
-    var underlying *Underlying
-    if err := json.Unmarshal(data, &underlying); err != nil {
-        return err
-    }
-    *s = RetryStrategy{
-        Type:               underlying.Type,
-        BaseBackoffSeconds: underlying.BaseBackoffSeconds,
-        MaxRetries:         underlying.MaxRetries,
-        MaxDurationSeconds: underlying.MaxDurationSeconds,
-        SameRegion:         underlying.SameRegion,
-    }
+    type alias RetryStrategy
+    var tmp alias
+    if err := json.Unmarshal(data, &tmp); err != nil {
+        return err
+    }
+    *s = RetryStrategy(tmp)
     return nil
 }

This removes a potential nil-pointer panic and halves the code.

📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
func (s *RetryStrategy) UnmarshalJSON(data []byte) error {
// This is a special value for a group, indicating that all checks in
// the group should use their own retry strategies. For the Go API we
// just pretend it's an actual retry strategy type.
if bytes.Equal(data, []byte(`"FALLBACK"`)) {
*s = RetryStrategy{
Type: "FALLBACK",
}
return nil
}
type Underlying RetryStrategy
var underlying *Underlying
if err := json.Unmarshal(data, &underlying); err != nil {
return err
}
*s = RetryStrategy{
Type: underlying.Type,
BaseBackoffSeconds: underlying.BaseBackoffSeconds,
MaxRetries: underlying.MaxRetries,
MaxDurationSeconds: underlying.MaxDurationSeconds,
SameRegion: underlying.SameRegion,
}
return nil
}
func (s *RetryStrategy) UnmarshalJSON(data []byte) error {
// This is a special value for a group, indicating that all checks in
// the group should use their own retry strategies. For the Go API we
// just pretend it's an actual retry strategy type.
if bytes.Equal(data, []byte(`"FALLBACK"`)) {
*s = RetryStrategy{
Type: "FALLBACK",
}
return nil
}
// treat explicit null as zero-value
if bytes.Equal(bytes.TrimSpace(data), []byte("null")) {
*s = RetryStrategy{}
return nil
}
type alias RetryStrategy
var tmp alias
if err := json.Unmarshal(data, &tmp); err != nil {
return err
}
*s = RetryStrategy(tmp)
return nil
}
🤖 Prompt for AI Agents
In types.go around lines 822 to 851, the UnmarshalJSON method for RetryStrategy
does not guard against a null JSON payload, which can cause a nil-pointer panic
when accessing underlying fields. To fix this, change the unmarshalling target
from a pointer to a value type to avoid the double-pointer usage, and add a
check to handle null data by returning early or setting a default value. This
simplifies the code and prevents panics by ensuring underlying is never nil
before accessing its fields.

@sorccu sorccu force-pushed the simokinnunen/sc-24521/tf-groups-v2-support branch from a4c1309 to 95ca8e4 Compare June 16, 2025 11:45
Copy link

@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

♻️ Duplicate comments (1)
types.go (1)

822-851: Simplify and harden RetryStrategy.UnmarshalJSON

  1. Struct-literal copy is unnecessary; you can cast the alias back to the real type:
-	*s = RetryStrategy{
-		Type:               underlying.Type,
-		BaseBackoffSeconds: underlying.BaseBackoffSeconds,
-		MaxRetries:         underlying.MaxRetries,
-		MaxDurationSeconds: underlying.MaxDurationSeconds,
-		SameRegion:         underlying.SameRegion,
-	}
+	*s = RetryStrategy(underlying)
  1. A "null" payload still triggers json.Unmarshal and leaves underlying zero-valued, but the API currently panics on an explicit null. Guard for it up-front:
+	if bytes.Equal(bytes.TrimSpace(data), []byte("null")) {
+		*s = RetryStrategy{}
+		return nil
+	}

Result: shorter code, nil-safety, and fixed gosimple S1016 warning.

🧹 Nitpick comments (2)
checkly.go (2)

1856-1864: Potential double “/” in constructed URLs

requestURL := fmt.Sprintf("%s/v%d/%s", c.url, version, URL)
If baseURL already ends with /, the final URL contains //v1/…. Although most servers accept this, it’s best avoided:

-	requestURL := fmt.Sprintf("%s/v%d/%s", c.url, version, URL)
+	requestURL := fmt.Sprintf("%s/v%d/%s",
+		strings.TrimRight(c.url, "/"),
+		version,
+		strings.TrimLeft(URL, "/"))

606-635: Allocate empty slices once to avoid escaped heap allocations

In UpdateGroupV2 you build an anonymous slice each time:

group.Locations = &[]string{}

Reuse a package-level var to avoid repeated allocations:

var emptyStringSlice = []string{}

if group.Locations == nil {
    group.Locations = &emptyStringSlice
}
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between a4c1309 and 95ca8e4.

📒 Files selected for processing (3)
  • checkly.go (63 hunks)
  • types.go (7 hunks)
  • types_test.go (2 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • types_test.go
🧰 Additional context used
🧬 Code Graph Analysis (1)
checkly.go (1)
types.go (2)
  • GroupV2 (901-924)
  • Group (870-898)
🪛 golangci-lint (1.64.8)
types.go

842-842: S1016: should convert underlying (type Underlying) to RetryStrategy instead of using struct literal

(gosimple)

🔇 Additional comments (3)
types.go (1)

900-924: GroupV2 still forces Name on PATCH-like updates

All other fields are pointers to distinguish “unset” vs. “zero”, but Name (and ID) are values, making them mandatory on every UpdateGroupV2 call.
Double-check the backend: if it allows partial updates, consider changing to *string (and *int64 for ID) to align with the optional semantics you introduced for the rest of the struct.

checkly.go (2)

1838-1855: Nice abstraction for versioned endpoints

The thin apiCallV1 / apiCallV2 wrappers read well and keep call sites clean. 👍


822-851: ```shell
#!/bin/bash

Ensure no remaining direct calls to apiCall without the version wrappers.

rg --line-number '.apiCall(' | grep -v 'func (c *client) apiCall' | grep -v 'apiCallV[12]'


</details>

</blockquote></details>

</details>

<!-- This is an auto-generated comment by CodeRabbit for review status -->

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