Skip to content

refactor: deployment API & model for connection pattern & format code#160

Merged
pan93412 merged 2 commits intozeabur:mainfrom
ridemountainpig:refactor-deployment-api
Jan 28, 2026
Merged

refactor: deployment API & model for connection pattern & format code#160
pan93412 merged 2 commits intozeabur:mainfrom
ridemountainpig:refactor-deployment-api

Conversation

@ridemountainpig
Copy link
Contributor

@ridemountainpig ridemountainpig commented Jan 28, 2026

Description (required)

  • Renamed deploymrnt.go to deployment.go and updated the deployment API to use DeploymentConnection and DeploymentEdge for GraphQL connection pattern.
  • In ServiceByName (pkg/fill/fill.go), when serviceName is set but serviceID is empty, the service is now resolved by name in the project and serviceID is filled in.
  • Improved code formatting in multiple files.

Before:
Cursor 2026-01-28 10 59 05

After:
CleanShot 2026-01-28 at 10 51 28

Related issues & labels (optional)

  • Closes #
  • Suggested label:

Summary by CodeRabbit

  • New Features

    • Service selection now supports lookup by name.
    • Deployment records include start and finish timestamps.
  • Refactor

    • Deployment listing now uses edge-based pagination with a single per-page parameter.
    • Upload flow updated to use SHA‑256 hashing and presigned multipart uploads for integrity.
  • Style

    • Widespread formatting cleanup and modernized octal literal notation.

✏️ Tip: You can customize this high-level summary in your review settings.

Renamed deploymrnt.go to deployment.go and updated the deployment API to use DeploymentConnection and DeploymentEdge for GraphQL connection pattern. Adjusted related interface, model, and usage throughout the codebase. Also standardized struct definitions and improved code formatting in multiple files.
@coderabbitai
Copy link

coderabbitai bot commented Jan 28, 2026

Walkthrough

Mostly formatting and import/layout cleanup across many files; plus functional changes: deployment pagination (edges connection and perPage), added Deployment timestamps (StartedAt, FinishedAt), new SHA-256 multipart upload flow for service uploads, and service lookup-by-name logic.

Changes

Cohort / File(s) Summary
Formatting: Empty Structs
internal/cmd/auth/logout/logout.go, internal/cmd/context/clear/clear.go, internal/cmd/context/get/get.go, internal/cmd/project/list/list.go, internal/cmd/template/list/list.go, internal/cmd/upload/upload.go, pkg/printer/printer.go, pkg/prompt/prompter.go
Converted multi-line empty struct declarations to single-line (struct { }struct{}). No behavior changes.
Import & Spacing Adjustments
internal/cmd/project/get/get.go, internal/cmd/project/list/list.go, internal/cmd/service/list/list.go, internal/cmdutil/constants.go, internal/util/project.go, internal/util/runE.go, internal/util/service.go, pkg/api/variable.go, pkg/model/domain.go, pkg/model/user.go
Added/removed blank lines and reordered imports for consistency. No functional changes.
Whitespace / Comment Normalization
internal/cmd/auth/auth.go, internal/cmd/deployment/list/list.go, pkg/api/git.go, pkg/model/project.go, internal/cmd/template/delete/delete.go, internal/cmd/template/get/get.go, internal/util/pack.go, pkg/api/domain.go, pkg/api/environment.go, pkg/api/log.go, pkg/api/project.go
Standardized comment spacing and removed extraneous blank lines inside functions and after API calls. No control-flow changes.
Deployment API & Model
pkg/api/deployment.go, pkg/api/interface.go, pkg/model/deployment.go
Replaced skip/limit pagination with a single perPage parameter; changed ListDeployments return type from *model.Connection[model.Deployment] to *model.DeploymentConnection; added DeploymentConnection/DeploymentEdge types and StartedAt/FinishedAt fields on Deployment. Update affects GraphQL query mapping and callers.
Service Upload Workflow
pkg/api/service.go
Added SHA-256 hashing and multipart upload workflow: compute SHA-256, base64-encode content hash, create upload session (/v2/upload), upload to S3 using presigned data, and call prepare endpoint (/v2/upload/{upload_id}/prepare). Added crypto/sha256 import and adjusted request/response handling.
Service Lookup by Name
pkg/fill/fill.go
Implemented lookup when a service name is provided: selects service by name within current project (Auto:true, CreateNew:false) with a FilterFunc, propagates errors, and returns error if not found.
Config Literal Style
pkg/config/init.go
Replaced octal literal 0755 with 0o755 in MkdirAll call. No functional change.
Misc. Minor API Formatting
pkg/api/domain.go, pkg/api/environment.go, pkg/api/log.go, pkg/api/project.go, pkg/api/deployment.go
Small whitespace/formatting edits around GraphQL calls and function signatures; pkg/api/deployment.go contains the substantive pagination/return-type changes noted above.

Sequence Diagram(s)

sequenceDiagram
    participant Client
    participant ServiceAPI as Service API (pkg/api/service.go)
    participant UploadSvc as Upload Service (/v2/upload)
    participant S3
    participant DeploySvc as Prepare Endpoint (/v2/upload/{id}/prepare)

    Client->>ServiceAPI: UploadZipToService(zipBytes, serviceID, envID)
    ServiceAPI->>ServiceAPI: Compute SHA-256 of zipBytes\nBase64-encode => contentHash
    ServiceAPI->>UploadSvc: POST /v2/upload {contentHash, algorithm, length}
    UploadSvc-->>ServiceAPI: presign data (upload_id, url, method, headers)
    ServiceAPI->>S3: PUT/POST to presigned URL with zip bytes
    S3-->>ServiceAPI: upload response (status OK)
    ServiceAPI->>DeploySvc: POST /v2/upload/{upload_id}/prepare {serviceID, environmentID}
    DeploySvc-->>ServiceAPI: prepare confirmed
    ServiceAPI-->>Client: return success / nil
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

🚥 Pre-merge checks | ✅ 2 | ❌ 1
❌ Failed checks (1 warning)
Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 10.00% 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
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title 'refactor: deployment API & model for connection pattern & format code' accurately captures the two main changes: refactoring the deployment API/model to use the connection pattern and formatting code throughout the codebase.

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

✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment

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.

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

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
pkg/api/service.go (1)

484-484: Return type mismatch: function always returns nil for service despite signature declaring *model.Service.

The function signature at pkg/api/service.go:372 declares a return type of (*model.Service, error), but the implementation ends at line 484 with return nil, nil. The caller at internal/cmd/deploy/deploy.go:99 already discards the first return value with _, indicating this gap has been worked around rather than fixed.

After completing all steps (hash calculation, upload session creation, S3 upload, and prepare deployment), the function exits without decoding the prepare response or returning the updated service object. Either the return type should be changed to (error) only, or the function should fetch and return the service after the upload is prepared.

🤖 Fix all issues with AI agents
In `@pkg/api/deployment.go`:
- Around line 28-39: ListAllDeployments currently only fetches a single page of
5 results by calling ListDeployments(ctx, serviceID, environmentID, 0, 5) and
returning conn.Edges, which violates the function name; either implement proper
cursor-based pagination to aggregate all pages into model.Deployments (loop
calling ListDeployments using the returned page info/cursor until no more pages
and append edge.Node from each page) or rename the function to something like
ListRecentDeployments to reflect the limited fetch; update references to
ListAllDeployments accordingly and ensure you use the pagination metadata from
the DeploymentConnection response to drive the loop.
- Around line 9-10: The ListDeployments function currently accepts a skip
parameter but discards it by calling "_, limit = normalizePagination(skip,
limit)", which misleads callers; fix by honoring the returned offset: change the
call to capture the offset (e.g., "offset, limit := normalizePagination(skip,
limit)") and use that offset when constructing the request/query in
ListDeployments (update any downstream call that builds pagination parameters),
or if the API is cursor-based, remove the skip parameter from the
ListDeployments signature and adjust the interface and all callers accordingly;
reference the ListDeployments method and the normalizePagination helper when
making the change.

In `@pkg/fill/fill.go`:
- Around line 212-218: When resolving by serviceName inside
f.selector.SelectService call, don't overwrite the existing opt.FilterFunc;
instead wrap/compose it so the resulting FilterFunc returns true only if the
service name matches and the original opt.FilterFunc (if non-nil) also returns
true. Update the selector.SelectServiceOptions being passed (where FilterFunc is
currently set to func(s *model.Service) bool { return s.Name == *serviceName })
to call the original opt.FilterFunc(s) when present and combine it with the name
check so both constraints are enforced.

In `@pkg/model/deployment.go`:
- Around line 33-40: DeploymentConnection is missing the PageInfo field used by
other connection types; update the struct DeploymentConnection to include a
PageInfo *PageInfo field so it matches the generic Connection[T] pattern and
provides pagination metadata. Locate the DeploymentConnection definition and add
PageInfo *PageInfo (matching the PageInfo type used by
ProjectConnection/TemplateConnection in pageable.go), ensure JSON/graphQL tags
mirror the existing convention (e.g., `json:"pageInfo" graphql:"pageInfo"`), and
run tests/compilation to validate no other callers need adjustments.
🧹 Nitpick comments (2)
pkg/model/project.go (1)

96-99: Pre-existing type mismatch in constants.

While not part of this PR's changes, these constants are typed as ServiceTemplate but should be RegionProvider based on their naming and intended usage.

♻️ Suggested fix
 const (
-	RegionProviderAWS ServiceTemplate = "AWS"
-	RegionProviderGCP ServiceTemplate = "GCP"
+	RegionProviderAWS RegionProvider = "AWS"
+	RegionProviderGCP RegionProvider = "GCP"
 )
pkg/api/service.go (1)

396-403: Confusing variable names: request variables named as responses.

createUploadResp and prepareResp are *http.Request objects, not responses. This harms readability.

Suggested rename
-	createUploadResp, err := http.NewRequestWithContext(ctx, "POST", constant.ZeaburServerURL+"/v2/upload", bytes.NewReader(createUploadBody))
+	createUploadReq, err := http.NewRequestWithContext(ctx, "POST", constant.ZeaburServerURL+"/v2/upload", bytes.NewReader(createUploadBody))
 	if err != nil {
 		return nil, fmt.Errorf("failed to create upload request: %w", err)
 	}
 
 	token := viper.GetString("token")
-	createUploadResp.Header.Set("Content-Type", "application/json")
-	createUploadResp.Header.Set("Cookie", "token="+token)
+	createUploadReq.Header.Set("Content-Type", "application/json")
+	createUploadReq.Header.Set("Cookie", "token="+token)
 
 	client := &http.Client{Timeout: 30 * time.Second}
-	resp, err := client.Do(createUploadResp)
+	resp, err := client.Do(createUploadReq)

Apply similar fix for prepareRespprepareReq at lines 464-474.

Also applies to: 464-472

@pan93412
Copy link
Member

你先修掉 CodeRabbit 指出的問題吧

@ridemountainpig
Copy link
Contributor Author

你先修掉 CodeRabbit 指出的問題吧

有修改好了,第二個 issue 可以再請你看一下要如何處理

@pan93412 pan93412 merged commit 3476d8b into zeabur:main Jan 28, 2026
5 checks passed
@ridemountainpig ridemountainpig deleted the refactor-deployment-api branch January 28, 2026 15:22
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