Skip to content

Commit 4534fd4

Browse files
[GOV-358] Optionally Hydrate Project and Environment For a Service (#868)
* Hydrate service project and environment by looking them up for just the service and leave those values empty if the requestor doens't have access * caputre http errors * Add a regression test for the case we ran into * Add http notfound error which can wrap other errors * Use not found in service for 404's on project and environment. Also move reponse errors into their own project and environemtn fakes GitOrigin-RevId: c273ff7298c7899e0c4bae673e2a0a08d16bf266
1 parent ef214e7 commit 4534fd4

11 files changed

Lines changed: 433 additions & 25 deletions

File tree

‎cmd/serviceupdate_test.go‎

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -440,6 +440,53 @@ func TestServiceUpdate_DefaultTextOutput(t *testing.T) {
440440
assert.Contains(t, result.Stdout, "text-service-renamed")
441441
}
442442

443+
func TestServiceUpdate_IPAllowListWithoutMetadata(t *testing.T) {
444+
for _, tc := range []struct {
445+
name string
446+
output string
447+
status int
448+
}{
449+
{name: "forbidden text", output: "text", status: http.StatusForbidden},
450+
{name: "forbidden json", output: "json", status: http.StatusForbidden},
451+
{name: "not found text", output: "text", status: http.StatusNotFound},
452+
{name: "not found json", output: "json", status: http.StatusNotFound},
453+
} {
454+
t.Run(tc.name, func(t *testing.T) {
455+
harness := newServiceUpdateHarness(t)
456+
svc := harness.addWebService("scoped-service")
457+
// Optional metadata may be inaccessible or missing even when the
458+
// service update succeeds.
459+
harness.server.Projects.RespondWithErrorForGet(tc.status)
460+
harness.server.Projects.RespondWithErrorForList(tc.status)
461+
harness.server.Environments.RespondWithErrorForGet(tc.status)
462+
harness.server.Environments.RespondWithErrorForList(tc.status)
463+
464+
result, err := harness.execute(svc.Id,
465+
"--ip-allow-list", "cidr=203.0.113.5/32,description=office",
466+
"--output", tc.output,
467+
)
468+
469+
request, ok := harness.server.LastRequest("PATCH", "/services/"+svc.Id)
470+
require.True(t, ok, "the IP allow-list update must reach the API")
471+
assert.JSONEq(t, `{"serviceDetails":{"ipAllowList":[{"cidrBlock":"203.0.113.5/32","description":"office"}]}}`, string(request.Body))
472+
require.NoError(t, err, "unavailable display metadata must not turn a successful update into a command failure")
473+
if tc.output == "json" {
474+
body := testrequire.ParseJSONMap(t, result.Stdout)
475+
testassert.MapContains(t, body, map[string]any{
476+
"data": map[string]any{
477+
"id": svc.Id, "environmentId": *svc.EnvironmentId, "projectId": nil,
478+
},
479+
})
480+
} else {
481+
assert.Contains(t, result.Stdout, "Updated this service:")
482+
assert.Contains(t, result.Stdout, "scoped-service")
483+
assert.Contains(t, result.Stdout, "Environment: "+*svc.EnvironmentId)
484+
assert.NotContains(t, result.Stdout, "Project:")
485+
}
486+
})
487+
}
488+
}
489+
443490
func TestServiceUpdate_ServiceDetailsPatchReachesAPI(t *testing.T) {
444491
harness := newServiceUpdateHarness(t)
445492
svc := harness.addWebService("plan-service")
Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
package renderapi
2+
3+
import "github.com/render-oss/cli/pkg/client"
4+
5+
// EnvironmentResource holds environment fixtures and queued errors for the fake API.
6+
type EnvironmentResource struct {
7+
Resource[*client.Environment]
8+
getErrors []int
9+
listErrors []int
10+
}
11+
12+
// RespondWithErrorForGet queues an HTTP error for the next environment retrieval.
13+
func (r *EnvironmentResource) RespondWithErrorForGet(status int) {
14+
r.getErrors = append(r.getErrors, status)
15+
}
16+
17+
// RespondWithErrorForList queues an HTTP error for the next environment listing.
18+
func (r *EnvironmentResource) RespondWithErrorForList(status int) {
19+
r.listErrors = append(r.listErrors, status)
20+
}
Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
package renderapi
2+
3+
import "github.com/render-oss/cli/pkg/client"
4+
5+
// ProjectResource holds project fixtures and queued errors for the fake API.
6+
type ProjectResource struct {
7+
Resource[*client.Project]
8+
getErrors []int
9+
listErrors []int
10+
}
11+
12+
// RespondWithErrorForGet queues an HTTP error for the next project retrieval.
13+
func (r *ProjectResource) RespondWithErrorForGet(status int) {
14+
r.getErrors = append(r.getErrors, status)
15+
}
16+
17+
// RespondWithErrorForList queues an HTTP error for the next project listing.
18+
func (r *ProjectResource) RespondWithErrorForList(status int) {
19+
r.listErrors = append(r.listErrors, status)
20+
}

‎internal/fakes/renderapi/server.go‎

Lines changed: 28 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -299,8 +299,8 @@ type Server struct {
299299
Requests []RecordedRequest
300300
CurrentUser *client.User
301301
Owners *Resource[*client.Owner]
302-
Projects *Resource[*client.Project]
303-
Environments *Resource[*client.Environment]
302+
Projects *ProjectResource
303+
Environments *EnvironmentResource
304304
KV *KVResource
305305
Postgres *PostgresResource
306306
Services *ServiceResource
@@ -421,8 +421,8 @@ func NewServer(t *testing.T) *Server {
421421

422422
s := &Server{
423423
Owners: &Resource[*client.Owner]{},
424-
Projects: &Resource[*client.Project]{},
425-
Environments: &Resource[*client.Environment]{},
424+
Projects: &ProjectResource{},
425+
Environments: &EnvironmentResource{},
426426
KV: &KVResource{},
427427
Postgres: &PostgresResource{},
428428
Services: &ServiceResource{},
@@ -534,6 +534,12 @@ func NewServer(t *testing.T) *Server {
534534
// GET /projects — list projects (supports ?ownerId= and ?name= filters)
535535
mux.HandleFunc("GET /projects", func(w http.ResponseWriter, r *http.Request) {
536536
record(r)
537+
if len(s.Projects.listErrors) > 0 {
538+
status := s.Projects.listErrors[0]
539+
s.Projects.listErrors = s.Projects.listErrors[1:]
540+
w.WriteHeader(status)
541+
return
542+
}
537543
result := s.Projects.Instances
538544
if ownerIDs := queryListValues(r, "ownerId"); len(ownerIDs) > 0 {
539545
var filtered []*client.Project
@@ -571,6 +577,12 @@ func NewServer(t *testing.T) *Server {
571577
// GET /projects/{id} — retrieve project by ID
572578
mux.HandleFunc("GET /projects/{id}", func(w http.ResponseWriter, r *http.Request) {
573579
record(r)
580+
if len(s.Projects.getErrors) > 0 {
581+
status := s.Projects.getErrors[0]
582+
s.Projects.getErrors = s.Projects.getErrors[1:]
583+
w.WriteHeader(status)
584+
return
585+
}
574586
id := r.PathValue("id")
575587
for _, stored := range s.Projects.Instances {
576588
if stored.Id == id {
@@ -592,6 +604,12 @@ func NewServer(t *testing.T) *Server {
592604
// GET /environments — list environments (supports ?projectId= and ?name= filters)
593605
mux.HandleFunc("GET /environments", func(w http.ResponseWriter, r *http.Request) {
594606
record(r)
607+
if len(s.Environments.listErrors) > 0 {
608+
status := s.Environments.listErrors[0]
609+
s.Environments.listErrors = s.Environments.listErrors[1:]
610+
w.WriteHeader(status)
611+
return
612+
}
595613
result := s.Environments.Instances
596614
if projectIDs := queryListValues(r, "projectId"); len(projectIDs) > 0 {
597615
var filtered []*client.Environment
@@ -621,6 +639,12 @@ func NewServer(t *testing.T) *Server {
621639
// GET /environments/{id} — retrieve environment by ID
622640
mux.HandleFunc("GET /environments/{id}", func(w http.ResponseWriter, r *http.Request) {
623641
record(r)
642+
if len(s.Environments.getErrors) > 0 {
643+
status := s.Environments.getErrors[0]
644+
s.Environments.getErrors = s.Environments.getErrors[1:]
645+
w.WriteHeader(status)
646+
return
647+
}
624648
id := r.PathValue("id")
625649
for _, e := range s.Environments.Instances {
626650
if e.Id == id {

‎internal/fakes/renderapi/server_test.go‎

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
package renderapi
22

33
import (
4+
"net/http"
45
"testing"
56

67
"github.com/stretchr/testify/require"
@@ -16,3 +17,48 @@ func newServerAndClient(t *testing.T) (*Server, *client.ClientWithResponses) {
1617
require.NoError(t, err)
1718
return server, c
1819
}
20+
21+
func TestMetadataReadErrorsAreQueuedPerOperation(t *testing.T) {
22+
for _, resource := range []string{"projects", "environments"} {
23+
t.Run(resource, func(t *testing.T) {
24+
server := NewServer(t)
25+
owner := server.Owners.Add(NewOwner(client.Owner{}))
26+
seeded := server.CreateProject(ProjectAttrs{OwnerId: owner.Id}, EnvAttrs{Name: "production"})
27+
28+
getPath := "/projects/" + seeded.Project.Id
29+
listPath := "/projects"
30+
queueGet := server.Projects.RespondWithErrorForGet
31+
queueList := server.Projects.RespondWithErrorForList
32+
if resource == "environments" {
33+
getPath = "/environments/" + seeded.Env("production").Id
34+
listPath = "/environments"
35+
queueGet = server.Environments.RespondWithErrorForGet
36+
queueList = server.Environments.RespondWithErrorForList
37+
}
38+
39+
queueGet(http.StatusForbidden)
40+
queueGet(http.StatusNotFound)
41+
queueList(http.StatusInternalServerError)
42+
queueList(http.StatusUnauthorized)
43+
44+
for _, request := range []struct {
45+
path string
46+
wantStatus int
47+
}{
48+
{getPath, http.StatusForbidden},
49+
{listPath, http.StatusInternalServerError},
50+
{getPath, http.StatusNotFound},
51+
{getPath, http.StatusOK},
52+
{listPath, http.StatusUnauthorized},
53+
{listPath, http.StatusOK},
54+
} {
55+
req, err := http.NewRequestWithContext(t.Context(), http.MethodGet, server.URL()+request.path, nil)
56+
require.NoError(t, err)
57+
resp, err := http.DefaultClient.Do(req)
58+
require.NoError(t, err)
59+
require.NoError(t, resp.Body.Close())
60+
require.Equal(t, request.wantStatus, resp.StatusCode, "GET %s", request.path)
61+
}
62+
})
63+
}
64+
}

‎pkg/client/client.go‎

Lines changed: 23 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@ import (
1717

1818
var ErrUnauthorized = errors.New("unauthorized")
1919
var ErrForbidden = errors.New("forbidden")
20+
var ErrNotFound = errors.New("not found")
2021
var ErrTooManyRequests = errors.New("too many requests")
2122

2223
const (
@@ -119,16 +120,34 @@ func ErrorFromResponse(v any) error {
119120

120121
message := pointers.StringValue(responseErr.Message)
121122
errorCode := pointers.StringValue(responseErr.Error.Code)
123+
var err error
122124
switch {
123125
case message != "" && errorCode != "":
124-
return fmt.Errorf("received response code %d (%s): %s", responseErr.Code, errorCode, message)
126+
err = fmt.Errorf("received response code %d (%s): %s", responseErr.Code, errorCode, message)
125127
case message != "":
126-
return fmt.Errorf("received response code %d: %s", responseErr.Code, message)
128+
err = fmt.Errorf("received response code %d: %s", responseErr.Code, message)
127129
case errorCode != "":
128-
return fmt.Errorf("received response code %d (%s)", responseErr.Code, errorCode)
130+
err = fmt.Errorf("received response code %d (%s)", responseErr.Code, errorCode)
129131
default:
130-
return fmt.Errorf("received response code %d", responseErr.Code)
132+
err = fmt.Errorf("received response code %d", responseErr.Code)
131133
}
134+
if responseErr.Code == http.StatusNotFound {
135+
return &notFoundError{message: err.Error()}
136+
}
137+
return err
138+
}
139+
140+
// notFoundError preserves the API's error details while supporting errors.Is.
141+
type notFoundError struct {
142+
message string
143+
}
144+
145+
func (e *notFoundError) Error() string {
146+
return e.message
147+
}
148+
149+
func (e *notFoundError) Unwrap() error {
150+
return ErrNotFound
132151
}
133152

134153
type ErrorWithCode struct {

‎pkg/client/client_test.go‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,15 @@ func TestErrorFromResponse(t *testing.T) {
2626

2727
require.ErrorIs(t, err, client.ErrForbidden)
2828
})
29+
t.Run("status code 404", func(t *testing.T) {
30+
err := client.ErrorFromResponse(&client.ListSnapshotsResponse{
31+
Body: []byte(`{"message":"resource not found"}`),
32+
HTTPResponse: &http.Response{StatusCode: http.StatusNotFound},
33+
})
34+
35+
require.ErrorIs(t, err, client.ErrNotFound)
36+
require.EqualError(t, err, "received response code 404: resource not found")
37+
})
2938
t.Run("status code 429", func(t *testing.T) {
3039
// the API usually declares that errors have a `message` and `detail` field.
3140
// however, the rate-limit error response does not conform to this standard.

‎pkg/environment/repo.go‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,10 @@ func (e *Repo) GetEnvironment(ctx context.Context, id string) (*client.Environme
2525
return nil, err
2626
}
2727

28+
if err := client.ErrorFromResponse(resp); err != nil {
29+
return nil, err
30+
}
31+
2832
if resp.JSON200 == nil {
2933
return nil, fmt.Errorf("unexpected response: %v", resp.Status())
3034
}

‎pkg/project/repo.go‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -87,6 +87,10 @@ func (p *Repo) GetProject(ctx context.Context, id string) (*client.Project, erro
8787
return nil, err
8888
}
8989

90+
if err := client.ErrorFromResponse(resp); err != nil {
91+
return nil, err
92+
}
93+
9094
if resp.JSON200 == nil {
9195
return nil, fmt.Errorf("unexpected response: %v", resp.Status())
9296
}

‎pkg/service/service.go‎

Lines changed: 22 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ package service
22

33
import (
44
"context"
5+
"errors"
56

67
"github.com/render-oss/cli/pkg/client"
78
"github.com/render-oss/cli/pkg/environment"
@@ -59,32 +60,36 @@ func (s *Service) GetService(ctx context.Context, id string) (*Model, error) {
5960
return nil, err
6061
}
6162

62-
// TODO(GROW-2652): This hydrates one service by listing every project in the workspace
63-
// and then that project's environments. Resolve the service's project and
64-
// environment more directly (get each by ID).
65-
projects, err := s.projectRepo.ListProjects(ctx)
66-
if err != nil {
67-
return nil, err
68-
}
69-
70-
return s.hydrateServiceModel(ctx, service, projects)
63+
return s.hydrateServiceModel(ctx, service)
7164
}
7265

7366
func (s *Service) RestartService(ctx context.Context, id string) error {
7467
return s.repo.RestartService(ctx, id)
7568
}
7669

77-
func (s *Service) hydrateServiceModel(ctx context.Context, service *client.Service, projects []*client.Project) (*Model, error) {
70+
func (s *Service) hydrateServiceModel(ctx context.Context, service *client.Service) (*Model, error) {
7871
model := &Model{Service: service}
72+
if service.EnvironmentId == nil {
73+
return model, nil
74+
}
7975

80-
model.Project = s.projectForService(service, projects)
76+
// An api token might have access to a service but not it's project or environment.
77+
// In that case, we still want to return the service model, but without the project and environment.
78+
env, err := s.environmentRepo.GetEnvironment(ctx, *service.EnvironmentId)
79+
if errors.Is(err, client.ErrForbidden) || errors.Is(err, client.ErrNotFound) {
80+
return model, nil
81+
}
82+
if err != nil {
83+
return nil, err
84+
}
85+
model.Environment = env
8186

82-
if model.Project != nil {
83-
envs, err := s.allEnvironments(ctx, []*client.Project{model.Project})
84-
if err != nil {
85-
return nil, err
86-
}
87-
model.Environment = s.environmentForService(service, envs)
87+
model.Project, err = s.projectRepo.GetProject(ctx, model.Environment.ProjectId)
88+
if errors.Is(err, client.ErrForbidden) || errors.Is(err, client.ErrNotFound) {
89+
return model, nil
90+
}
91+
if err != nil {
92+
return nil, err
8893
}
8994

9095
return model, nil

0 commit comments

Comments
 (0)