From c20de5038c32bdb267cf045e2ee5cc9aa992e693 Mon Sep 17 00:00:00 2001 From: Michael Suchacz <203725896+ibetitsmike@users.noreply.github.com> Date: Fri, 30 Oct 2026 21:16:36 +0100 Subject: [PATCH] refactor(codersdk): add chat client request helpers (#30961) Adds two unexported helpers to `codersdk/chats.go` and moves the 16 chat project and chat model client methods onto them. `requestJSON[T]` sends the request, checks for the one status the method expects, and decodes the JSON body. `requestNoContent` does the same for `204 No Content`. Each converted method drops its own copy of that block, so the file loses 116 lines (+46/-162). The test changes in `codersdk/chats_test.go` are +59/-0. **Why it is safe:** the helpers return the same errors as the code they replace: the `Client.Request` error unchanged, `ReadBodyAsError` for any other status, and the `ReadBodyAsJSON` error. A script did the conversion. It rewrites a method only when its body ends in exactly that block, with a zero value that matches the decoded type, and it keeps the HTTP method, path, body, request options, and expected status. **Behavior change:** the helpers close an unexpected-status response body once, in `ReadBodyAsError`, where the old methods also deferred a second `Close`. Standard `net/http` bodies tolerate the second `Close`, but a custom transport's body may not (one whose `Close` closes a channel panics), and #30963 would otherwise have added it to `CreateChat` and `CreateChatMessage`, which closed once. - `TestChatClientRequests` passes here and fails on each of 7 helper mutants (`go test -overlay`): drop the transport error (`requestNoContent`), wrap it with `%v` (`requestJSON`), move the deferred `Close` back above the status check or drop it (one each per helper), and drop the decode error. - Its `ClosesResponseBodyOnce` case, added here, requires exactly one `Close` per call for each helper's success and unexpected status and for an invalid JSON body. Without it the test passed with the `Close` above the status check. It replaces the `Close` counts this layer had added to cases that #30960 dropped after review. - The 776 tests in test files that call a chat client method (12 packages) pass on `main` and here. With `-coverpkg=./codersdk`, every converted method's success path runs and both helpers are fully covered. - Call-site mutants fail existing coderd tests: `CreateChatProject` expecting 200 (`TestChatProjectsCRUDListAndDeleteDetaches`, `TestChatProjectLimit`), `DeleteChatProjectMemory` sending GET (`TestChatProjectMemoriesCRUD`), `ChatModelACLAvailable` without its query option (`TestChatModelACLAvailable`), and `UpdateChatModel` without a body (`TestUpdateChatModel`). **Review focus:** the two helpers; the next two layers only add call sites. `ListChatProjects`, `UpdateChatProject`, `DeleteChatProject`, and `ChatProjectInstructions` stay as they are, so #30439 and #30683 still apply cleanly. Validation: `go test ./codersdk -count=1` passes, `golangci-lint run ./codersdk/` reports 0 issues, and the pre-commit hook passed. ## Stack This stack removes two unused chat exports from `codersdk` and moves 70 chat client methods in `codersdk/chats.go` onto two shared request helpers. Client behavior does not change, except that #30961 closes an unexpected-status response body once instead of twice. 1. #30959 Remove unused chat exports from codersdk 2. #30960 Cover chat client request errors 3. #30961 Add chat client request helpers, for the project and model methods 4. #30962 Move the chat settings methods onto the request helpers 5. #30963 Move the chat methods onto the request helpers > Xum, an AI agent, opened this PR for @ibetitsmike and wrote this description. --- codersdk/chats.go | 208 +++++++++-------------------------------- codersdk/chats_test.go | 59 ++++++++++++ 2 files changed, 105 insertions(+), 162 deletions(-) diff --git a/codersdk/chats.go b/codersdk/chats.go index 860b4437152..ddd3c0c5b1a 100644 --- a/codersdk/chats.go +++ b/codersdk/chats.go @@ -2416,6 +2416,34 @@ type ListChatsOptions struct { Pagination } +func requestJSON[T any](ctx context.Context, c *Client, method, path string, wantStatus int, body any, opts ...RequestOption) (T, error) { + var out T + res, err := c.Request(ctx, method, path, body, opts...) + if err != nil { + return out, err + } + if res.StatusCode != wantStatus { + // ReadBodyAsError closes the body. + return out, ReadBodyAsError(res) + } + defer res.Body.Close() + err = ReadBodyAsJSON(res, &out) + return out, err +} + +func requestNoContent(ctx context.Context, c *Client, method, path string, body any, opts ...RequestOption) error { + res, err := c.Request(ctx, method, path, body, opts...) + if err != nil { + return err + } + if res.StatusCode != http.StatusNoContent { + // ReadBodyAsError closes the body. + return ReadBodyAsError(res) + } + defer res.Body.Close() + return nil +} + // ListChats returns all chats for the authenticated user. func (c *Client) ListChats(ctx context.Context, opts *ListChatsOptions) ([]Chat, error) { var reqOpts []RequestOption @@ -2489,30 +2517,12 @@ func (c *ExperimentalClient) ListChatProjects(ctx context.Context) ([]ChatProjec // CreateChatProject creates a chat project in an organization. func (c *ExperimentalClient) CreateChatProject(ctx context.Context, organizationID uuid.UUID, req CreateChatProjectRequest) (ChatProject, error) { - res, err := c.Request(ctx, http.MethodPost, chatProjectsPath(organizationID), req) - if err != nil { - return ChatProject{}, err - } - defer res.Body.Close() - if res.StatusCode != http.StatusCreated { - return ChatProject{}, ReadBodyAsError(res) - } - var project ChatProject - return project, ReadBodyAsJSON(res, &project) + return requestJSON[ChatProject](ctx, c.Client, http.MethodPost, chatProjectsPath(organizationID), http.StatusCreated, req) } // GetChatProject gets a chat project. func (c *ExperimentalClient) GetChatProject(ctx context.Context, organizationID, projectID uuid.UUID) (ChatProject, error) { - res, err := c.Request(ctx, http.MethodGet, chatProjectPath(organizationID, projectID), nil) - if err != nil { - return ChatProject{}, err - } - defer res.Body.Close() - if res.StatusCode != http.StatusOK { - return ChatProject{}, ReadBodyAsError(res) - } - var project ChatProject - return project, ReadBodyAsJSON(res, &project) + return requestJSON[ChatProject](ctx, c.Client, http.MethodGet, chatProjectPath(organizationID, projectID), http.StatusOK, nil) } // UpdateChatProject updates a chat project. @@ -2586,85 +2596,33 @@ func (c *ExperimentalClient) ChatProjectInstructions(ctx context.Context, organi // UpdateChatProjectInstructions creates or replaces a chat project's // instructions. func (c *ExperimentalClient) UpdateChatProjectInstructions(ctx context.Context, organizationID, projectID uuid.UUID, req UpdateChatProjectInstructionsRequest) (ChatProjectInstructions, error) { - res, err := c.Request(ctx, http.MethodPut, chatProjectPath(organizationID, projectID)+"/instructions", req) - if err != nil { - return ChatProjectInstructions{}, err - } - defer res.Body.Close() - if res.StatusCode != http.StatusOK { - return ChatProjectInstructions{}, ReadBodyAsError(res) - } - var instructions ChatProjectInstructions - return instructions, ReadBodyAsJSON(res, &instructions) + return requestJSON[ChatProjectInstructions](ctx, c.Client, http.MethodPut, chatProjectPath(organizationID, projectID)+"/instructions", http.StatusOK, req) } // DeleteChatProjectInstructions clears a chat project's instructions. It // succeeds when the project has no instructions. func (c *ExperimentalClient) DeleteChatProjectInstructions(ctx context.Context, organizationID, projectID uuid.UUID) error { - res, err := c.Request(ctx, http.MethodDelete, chatProjectPath(organizationID, projectID)+"/instructions", nil) - if err != nil { - return err - } - defer res.Body.Close() - if res.StatusCode != http.StatusNoContent { - return ReadBodyAsError(res) - } - return nil + return requestNoContent(ctx, c.Client, http.MethodDelete, chatProjectPath(organizationID, projectID)+"/instructions", nil) } // ListChatProjectMemories lists memories for a chat project. func (c *ExperimentalClient) ListChatProjectMemories(ctx context.Context, organizationID, projectID uuid.UUID) ([]ChatProjectMemory, error) { - res, err := c.Request(ctx, http.MethodGet, chatProjectPath(organizationID, projectID)+"/memories", nil) - if err != nil { - return nil, err - } - defer res.Body.Close() - if res.StatusCode != http.StatusOK { - return nil, ReadBodyAsError(res) - } - var memories []ChatProjectMemory - return memories, ReadBodyAsJSON(res, &memories) + return requestJSON[[]ChatProjectMemory](ctx, c.Client, http.MethodGet, chatProjectPath(organizationID, projectID)+"/memories", http.StatusOK, nil) } // CreateChatProjectMemory creates a project memory. func (c *ExperimentalClient) CreateChatProjectMemory(ctx context.Context, organizationID, projectID uuid.UUID, req CreateChatProjectMemoryRequest) (ChatProjectMemory, error) { - res, err := c.Request(ctx, http.MethodPost, chatProjectPath(organizationID, projectID)+"/memories", req) - if err != nil { - return ChatProjectMemory{}, err - } - defer res.Body.Close() - if res.StatusCode != http.StatusCreated { - return ChatProjectMemory{}, ReadBodyAsError(res) - } - var memory ChatProjectMemory - return memory, ReadBodyAsJSON(res, &memory) + return requestJSON[ChatProjectMemory](ctx, c.Client, http.MethodPost, chatProjectPath(organizationID, projectID)+"/memories", http.StatusCreated, req) } // GetChatProjectMemory gets a project memory. func (c *ExperimentalClient) GetChatProjectMemory(ctx context.Context, organizationID, projectID, memoryID uuid.UUID) (ChatProjectMemory, error) { - res, err := c.Request(ctx, http.MethodGet, fmt.Sprintf("%s/memories/%s", chatProjectPath(organizationID, projectID), memoryID), nil) - if err != nil { - return ChatProjectMemory{}, err - } - defer res.Body.Close() - if res.StatusCode != http.StatusOK { - return ChatProjectMemory{}, ReadBodyAsError(res) - } - var memory ChatProjectMemory - return memory, ReadBodyAsJSON(res, &memory) + return requestJSON[ChatProjectMemory](ctx, c.Client, http.MethodGet, fmt.Sprintf("%s/memories/%s", chatProjectPath(organizationID, projectID), memoryID), http.StatusOK, nil) } // DeleteChatProjectMemory deletes a project memory. func (c *ExperimentalClient) DeleteChatProjectMemory(ctx context.Context, organizationID, projectID, memoryID uuid.UUID) error { - res, err := c.Request(ctx, http.MethodDelete, fmt.Sprintf("%s/memories/%s", chatProjectPath(organizationID, projectID), memoryID), nil) - if err != nil { - return err - } - defer res.Body.Close() - if res.StatusCode != http.StatusNoContent { - return ReadBodyAsError(res) - } - return nil + return requestNoContent(ctx, c.Client, http.MethodDelete, fmt.Sprintf("%s/memories/%s", chatProjectPath(organizationID, projectID), memoryID), nil) } // ListUserAIProviderKeyConfigs returns user-scoped AI provider key configs. @@ -2716,78 +2674,28 @@ func userAIProviderKeysPath(user string) string { // organization, plus the redacted provider descriptors the authoring page // needs, for org-scoped management and picker surfaces. func (c *Client) ChatModels(ctx context.Context, organizationID uuid.UUID) (OrganizationChatModelsResponse, error) { - res, err := c.Request(ctx, http.MethodGet, fmt.Sprintf("/api/v2/organizations/%s/chats/models", organizationID), nil) - if err != nil { - return OrganizationChatModelsResponse{}, err - } - defer res.Body.Close() - if res.StatusCode != http.StatusOK { - return OrganizationChatModelsResponse{}, ReadBodyAsError(res) - } - - var resp OrganizationChatModelsResponse - return resp, ReadBodyAsJSON(res, &resp) + return requestJSON[OrganizationChatModelsResponse](ctx, c, http.MethodGet, fmt.Sprintf("/api/v2/organizations/%s/chats/models", organizationID), http.StatusOK, nil) } // ChatModel fetches one chat model config by ID in an organization. func (c *Client) ChatModel(ctx context.Context, organizationID, modelConfigID uuid.UUID) (ChatModel, error) { - res, err := c.Request(ctx, http.MethodGet, fmt.Sprintf("/api/v2/organizations/%s/chats/models/%s", organizationID, modelConfigID), nil) - if err != nil { - return ChatModel{}, err - } - defer res.Body.Close() - if res.StatusCode != http.StatusOK { - return ChatModel{}, ReadBodyAsError(res) - } - - var config ChatModel - return config, ReadBodyAsJSON(res, &config) + return requestJSON[ChatModel](ctx, c, http.MethodGet, fmt.Sprintf("/api/v2/organizations/%s/chats/models/%s", organizationID, modelConfigID), http.StatusOK, nil) } // CreateChatModel creates a chat model config in the given organization. func (c *Client) CreateChatModel(ctx context.Context, organizationID uuid.UUID, req CreateChatModelRequest) (ChatModel, error) { - res, err := c.Request(ctx, http.MethodPost, fmt.Sprintf("/api/v2/organizations/%s/chats/models", organizationID), req) - if err != nil { - return ChatModel{}, err - } - defer res.Body.Close() - if res.StatusCode != http.StatusCreated { - return ChatModel{}, ReadBodyAsError(res) - } - - var model ChatModel - return model, ReadBodyAsJSON(res, &model) + return requestJSON[ChatModel](ctx, c, http.MethodPost, fmt.Sprintf("/api/v2/organizations/%s/chats/models", organizationID), http.StatusCreated, req) } // UpdateChatModel updates a ChatModel in an organization. func (c *Client) UpdateChatModel(ctx context.Context, organizationID, modelID uuid.UUID, req UpdateChatModelRequest) (ChatModel, error) { - res, err := c.Request(ctx, http.MethodPatch, fmt.Sprintf("/api/v2/organizations/%s/chats/models/%s", organizationID, modelID), req) - if err != nil { - return ChatModel{}, err - } - defer res.Body.Close() - if res.StatusCode != http.StatusOK { - return ChatModel{}, ReadBodyAsError(res) - } - - var model ChatModel - return model, ReadBodyAsJSON(res, &model) + return requestJSON[ChatModel](ctx, c, http.MethodPatch, fmt.Sprintf("/api/v2/organizations/%s/chats/models/%s", organizationID, modelID), http.StatusOK, req) } // ChatModelACL returns the access control list for a chat model in an // organization. func (c *Client) ChatModelACL(ctx context.Context, organizationID, modelID uuid.UUID) (ChatModelACL, error) { - res, err := c.Request(ctx, http.MethodGet, fmt.Sprintf("/api/v2/organizations/%s/chats/models/%s/acl", organizationID, modelID), nil) - if err != nil { - return ChatModelACL{}, err - } - defer res.Body.Close() - if res.StatusCode != http.StatusOK { - return ChatModelACL{}, ReadBodyAsError(res) - } - - var modelACL ChatModelACL - return modelACL, ReadBodyAsJSON(res, &modelACL) + return requestJSON[ChatModelACL](ctx, c, http.MethodGet, fmt.Sprintf("/api/v2/organizations/%s/chats/models/%s/acl", organizationID, modelID), http.StatusOK, nil) } // ChatModelACLAvailable returns available users and groups that can be assigned @@ -2795,51 +2703,27 @@ func (c *Client) ChatModelACL(ctx context.Context, organizationID, modelID uuid. // to users. Groups reuse the user search query and q/limit semantics. Pass // codersdk.UsersRequest{} when no filtering is desired. func (c *Client) ChatModelACLAvailable(ctx context.Context, organizationID, modelID uuid.UUID, req UsersRequest) (ACLAvailable, error) { - res, err := c.Request( + return requestJSON[ACLAvailable]( ctx, + c, http.MethodGet, fmt.Sprintf("/api/v2/organizations/%s/chats/models/%s/acl/available", organizationID, modelID), + http.StatusOK, nil, req.Pagination.asRequestOption(), req.asRequestOption(), ) - if err != nil { - return ACLAvailable{}, err - } - defer res.Body.Close() - if res.StatusCode != http.StatusOK { - return ACLAvailable{}, ReadBodyAsError(res) - } - - var acl ACLAvailable - return acl, ReadBodyAsJSON(res, &acl) } // UpdateChatModelACL applies a sparse access control list update to a chat // model in an organization. func (c *Client) UpdateChatModelACL(ctx context.Context, organizationID, modelID uuid.UUID, req UpdateChatModelACLRequest) error { - res, err := c.Request(ctx, http.MethodPatch, fmt.Sprintf("/api/v2/organizations/%s/chats/models/%s/acl", organizationID, modelID), req) - if err != nil { - return err - } - defer res.Body.Close() - if res.StatusCode != http.StatusNoContent { - return ReadBodyAsError(res) - } - return nil + return requestNoContent(ctx, c, http.MethodPatch, fmt.Sprintf("/api/v2/organizations/%s/chats/models/%s/acl", organizationID, modelID), req) } // DeleteChatModel deletes a ChatModel in an organization. func (c *Client) DeleteChatModel(ctx context.Context, organizationID, modelID uuid.UUID) error { - res, err := c.Request(ctx, http.MethodDelete, fmt.Sprintf("/api/v2/organizations/%s/chats/models/%s", organizationID, modelID), nil) - if err != nil { - return err - } - defer res.Body.Close() - if res.StatusCode != http.StatusNoContent { - return ReadBodyAsError(res) - } - return nil + return requestNoContent(ctx, c, http.MethodDelete, fmt.Sprintf("/api/v2/organizations/%s/chats/models/%s", organizationID, modelID), nil) } // ChatModelProviderDescriptor is the redacted view of an AI provider carried diff --git a/codersdk/chats_test.go b/codersdk/chats_test.go index ed1093cb09d..4d71b98211c 100644 --- a/codersdk/chats_test.go +++ b/codersdk/chats_test.go @@ -9,6 +9,7 @@ import ( "net/url" "reflect" "strings" + "sync/atomic" "testing" "time" @@ -63,6 +64,16 @@ func TestUploadChatWorkspaceFileContentType(t *testing.T) { } } +type closeCountingBody struct { + io.Reader + closes *atomic.Int32 +} + +func (b closeCountingBody) Close() error { + b.closes.Add(1) + return nil +} + func TestChatClientRequests(t *testing.T) { t.Parallel() @@ -100,6 +111,54 @@ func TestChatClientRequests(t *testing.T) { _, err := client.ChatModel(t.Context(), uuid.New(), uuid.New()) require.Error(t, err) }) + + // ReadBodyAsError closes the body itself, and io.Closer leaves a + // second Close undefined. + t.Run("ClosesResponseBodyOnce", func(t *testing.T) { + t.Parallel() + + getModel := func(ctx context.Context, client *codersdk.Client) error { + _, err := client.ChatModel(ctx, uuid.New(), uuid.New()) + return err + } + deleteModel := func(ctx context.Context, client *codersdk.Client) error { + return client.DeleteChatModel(ctx, uuid.New(), uuid.New()) + } + for _, tc := range []struct { + name string + call func(context.Context, *codersdk.Client) error + status int + body string + wantErr bool + }{ + {name: "JSON", call: getModel, status: http.StatusOK, body: `{}`}, + {name: "JSONUnexpectedStatus", call: getModel, status: http.StatusInternalServerError, body: `{"message":"failed"}`, wantErr: true}, + {name: "JSONInvalidBody", call: getModel, status: http.StatusOK, body: `{"id":`, wantErr: true}, + {name: "NoContent", call: deleteModel, status: http.StatusNoContent}, + {name: "NoContentUnexpectedStatus", call: deleteModel, status: http.StatusInternalServerError, body: `{"message":"failed"}`, wantErr: true}, + } { + t.Run(tc.name, func(t *testing.T) { + t.Parallel() + + var closes atomic.Int32 + client := newClient(t, func(req *http.Request) (*http.Response, error) { + return &http.Response{ + StatusCode: tc.status, + Header: http.Header{"Content-Type": []string{"application/json"}}, + Body: closeCountingBody{Reader: strings.NewReader(tc.body), closes: &closes}, + Request: req, + }, nil + }) + err := tc.call(t.Context(), client) + if tc.wantErr { + require.Error(t, err) + } else { + require.NoError(t, err) + } + require.EqualValues(t, 1, closes.Load()) + }) + } + }) } func TestChatMessageWorkspaceFileReference_JSONRoundTrip(t *testing.T) {