From 3770ad9769fd95eed4f02eec2dde4134e6dddbe5 Mon Sep 17 00:00:00 2001 From: purplenicole730 Date: Wed, 6 Nov 2024 12:58:31 -0500 Subject: [PATCH 01/75] add organization wrappers --- app/app_client.go | 176 ++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 176 insertions(+) create mode 100644 app/app_client.go diff --git a/app/app_client.go b/app/app_client.go new file mode 100644 index 00000000000..97ef241573a --- /dev/null +++ b/app/app_client.go @@ -0,0 +1,176 @@ +package app + +import ( + "context" + "errors" + "fmt" + + pb "go.viam.com/api/app/v1" +) + +type AppClient struct { + client pb.AppServiceClient +} + +func (c *AppClient) GetUserIDByEmail(ctx context.Context, email string) (string, error) { + resp, err := c.client.GetUserIDByEmail(ctx, &pb.GetUserIDByEmailRequest{ + Email: email, + }) + if err != nil { + return "", err + } + return resp.UserId, nil +} + +func (c *AppClient) CreateOrganization(ctx context.Context, name string) (*pb.Organization, error) { + resp, err := c.client.CreateOrganization(ctx, &pb.CreateOrganizationRequest{ + Name: name, + }) + if err != nil { + return nil, err + } + return resp.Organization, nil +} + +func (c *AppClient) ListOrganizations(ctx context.Context) ([]*pb.Organization, error) { + resp, err := c.client.ListOrganizations(ctx, &pb.ListOrganizationsRequest{}) + if err != nil { + return nil, err + } + return resp.Organizations, nil +} + +func (c *AppClient) GetOrganizationsWithAccessToLocation(ctx context.Context, locationId string) ([]*pb.OrganizationIdentity, error) { + resp, err := c.client.GetOrganizationsWithAccessToLocation(ctx, &pb.GetOrganizationsWithAccessToLocationRequest{ + LocationId: locationId, + }) + if err != nil { + return nil, err + } + return resp.OrganizationIdentities, nil +} + +func (c *AppClient) ListOrganizationsByUser(ctx context.Context, userId string) ([]*pb.OrgDetails, error) { + resp, err := c.client.ListOrganizationsByUser(ctx, &pb.ListOrganizationsByUserRequest{ + UserId: userId, + }) + if err != nil { + return nil, err + } + return resp.Orgs, nil +} + +func (c *AppClient) GetOrganization(ctx context.Context, orgId string) (*pb.Organization, error) { + resp, err := c.client.GetOrganization(ctx, &pb.GetOrganizationRequest{ + OrganizationId: orgId, + }) + if err != nil { + return nil, err + } + return resp.Organization, nil +} + +func (c *AppClient) GetOrganizationNamespaceAvailability(ctx context.Context, namespace string) (bool, error) { + resp, err := c.client.GetOrganizationNamespaceAvailability(ctx, &pb.GetOrganizationNamespaceAvailabilityRequest{ + PublicNamespace: namespace, + }) + if err != nil { + return false, err + } + return resp.Available, nil +} + + +func (c *AppClient) UpdateOrganization(ctx context.Context, orgId string, name *string, namespace *string, region *string, cid *string) (*pb.Organization, error) { + resp, err := c.client.UpdateOrganization(ctx, &pb.UpdateOrganizationRequest{ + OrganizationId: orgId, + Name: name, + PublicNamespace: namespace, + Region: region, + Cid: cid, + }) + if err != nil { + return nil, err + } + return resp.Organization, nil +} + +func (c *AppClient) DeleteOrganization(ctx context.Context, orgId string) error { + _, err := c.client.DeleteOrganization(ctx, &pb.DeleteOrganizationRequest{ + OrganizationId: orgId, + }) + if err != nil { + return err + } + return nil +} + +func (c *AppClient) ListOrganizationMembers(ctx context.Context, orgId string) ([]*pb.OrganizationMember, []*pb.OrganizationInvite, error) { + resp, err := c.client.ListOrganizationMembers(ctx, &pb.ListOrganizationMembersRequest{ + OrganizationId: orgId, + }) + if err != nil { + return nil, nil, err + } + return resp.Members, resp.Invites, nil +} + +func (c *AppClient) CreateOrganizationInvite(ctx context.Context, orgId string, email string, authorizations []*pb.Authorization, sendEmailInvite *bool) (*pb.OrganizationInvite, error) { + resp, err := c.client.CreateOrganizationInvite(ctx, &pb.CreateOrganizationInviteRequest{ + OrganizationId: orgId, + Email: email, + Authorizations: authorizations, + SendEmailInvite: sendEmailInvite, + }) + if err != nil { + return nil, err + } + return resp.Invite, nil +} + +func (c *AppClient) UpdateOrganizationInviteAuthorizations(ctx context.Context, orgId string, email string, addAuthorizations []*pb.Authorization, removeAuthorizations []*pb.Authorization) (*pb.OrganizationInvite, error) { + resp, err := c.client.UpdateOrganizationInviteAuthorizations(ctx, &pb.UpdateOrganizationInviteAuthorizationsRequest{ + OrganizationId: orgId, + Email: email, + AddAuthorizations: addAuthorizations, + RemoveAuthorizations: removeAuthorizations, + }) + if err != nil { + return nil, err + } + return resp.Invite, nil +} + +func (c *AppClient) DeleteOrganizationMember(ctx context.Context, orgId string, userId string) error { + _, err := c.client.DeleteOrganizationMember(ctx, &pb.DeleteOrganizationMemberRequest{ + OrganizationId: orgId, + UserId: userId, + }) + if err != nil { + return err + } + return nil +} + +func (c *AppClient) DeleteOrganizationInvite(ctx context.Context, orgId string, email string) error { + _, err := c.client.DeleteOrganizationInvite(ctx, &pb.DeleteOrganizationInviteRequest{ + OrganizationId: orgId, + Email: email, + }) + if err != nil { + return err + } + return nil +} + +func (c *AppClient) ResendOrganizationInvite(ctx context.Context, orgId string, email string) (*pb.OrganizationInvite, error) { + resp, err := c.client.ResendOrganizationInvite(ctx, &pb.ResendOrganizationInviteRequest{ + OrganizationId: orgId, + Email: email, + }) + if err != nil { + return nil, err + } + return resp.Invite, nil +} + From 90126b6294ef8da389f6211906e55c0404538d6c Mon Sep 17 00:00:00 2001 From: purplenicole730 Date: Wed, 6 Nov 2024 12:59:05 -0500 Subject: [PATCH 02/75] add comments --- app/app_client.go | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/app/app_client.go b/app/app_client.go index 97ef241573a..e0cfa77f0dd 100644 --- a/app/app_client.go +++ b/app/app_client.go @@ -12,6 +12,7 @@ type AppClient struct { client pb.AppServiceClient } +// GetUserIDByEmail gets the ID of the user with the given email. func (c *AppClient) GetUserIDByEmail(ctx context.Context, email string) (string, error) { resp, err := c.client.GetUserIDByEmail(ctx, &pb.GetUserIDByEmailRequest{ Email: email, @@ -22,6 +23,7 @@ func (c *AppClient) GetUserIDByEmail(ctx context.Context, email string) (string, return resp.UserId, nil } +// CreateOrganization creates a new organization. func (c *AppClient) CreateOrganization(ctx context.Context, name string) (*pb.Organization, error) { resp, err := c.client.CreateOrganization(ctx, &pb.CreateOrganizationRequest{ Name: name, @@ -32,6 +34,7 @@ func (c *AppClient) CreateOrganization(ctx context.Context, name string) (*pb.Or return resp.Organization, nil } +// ListOrganizations lists all the organizations. func (c *AppClient) ListOrganizations(ctx context.Context) ([]*pb.Organization, error) { resp, err := c.client.ListOrganizations(ctx, &pb.ListOrganizationsRequest{}) if err != nil { @@ -40,6 +43,7 @@ func (c *AppClient) ListOrganizations(ctx context.Context) ([]*pb.Organization, return resp.Organizations, nil } +// GetOrganizationsWithAccessToLocation gets all the organizations that have access to a location. func (c *AppClient) GetOrganizationsWithAccessToLocation(ctx context.Context, locationId string) ([]*pb.OrganizationIdentity, error) { resp, err := c.client.GetOrganizationsWithAccessToLocation(ctx, &pb.GetOrganizationsWithAccessToLocationRequest{ LocationId: locationId, @@ -50,6 +54,7 @@ func (c *AppClient) GetOrganizationsWithAccessToLocation(ctx context.Context, lo return resp.OrganizationIdentities, nil } +// ListOrganizationsByUser lists all the organizations that a user belongs to. func (c *AppClient) ListOrganizationsByUser(ctx context.Context, userId string) ([]*pb.OrgDetails, error) { resp, err := c.client.ListOrganizationsByUser(ctx, &pb.ListOrganizationsByUserRequest{ UserId: userId, @@ -60,6 +65,7 @@ func (c *AppClient) ListOrganizationsByUser(ctx context.Context, userId string) return resp.Orgs, nil } +// GetOrganization gets an organization. func (c *AppClient) GetOrganization(ctx context.Context, orgId string) (*pb.Organization, error) { resp, err := c.client.GetOrganization(ctx, &pb.GetOrganizationRequest{ OrganizationId: orgId, @@ -70,6 +76,7 @@ func (c *AppClient) GetOrganization(ctx context.Context, orgId string) (*pb.Orga return resp.Organization, nil } +// GetOrganizationNamespaceAvailability checks for namespace availability throughout all organizations. func (c *AppClient) GetOrganizationNamespaceAvailability(ctx context.Context, namespace string) (bool, error) { resp, err := c.client.GetOrganizationNamespaceAvailability(ctx, &pb.GetOrganizationNamespaceAvailabilityRequest{ PublicNamespace: namespace, @@ -81,6 +88,7 @@ func (c *AppClient) GetOrganizationNamespaceAvailability(ctx context.Context, na } +// UpdateOrganization updates an organization. func (c *AppClient) UpdateOrganization(ctx context.Context, orgId string, name *string, namespace *string, region *string, cid *string) (*pb.Organization, error) { resp, err := c.client.UpdateOrganization(ctx, &pb.UpdateOrganizationRequest{ OrganizationId: orgId, @@ -95,6 +103,7 @@ func (c *AppClient) UpdateOrganization(ctx context.Context, orgId string, name * return resp.Organization, nil } +// DeleteOrganization deletes an organization. func (c *AppClient) DeleteOrganization(ctx context.Context, orgId string) error { _, err := c.client.DeleteOrganization(ctx, &pb.DeleteOrganizationRequest{ OrganizationId: orgId, @@ -105,6 +114,7 @@ func (c *AppClient) DeleteOrganization(ctx context.Context, orgId string) error return nil } +// ListOrganizationMembers lists all members of an organization and all invited members to the organization. func (c *AppClient) ListOrganizationMembers(ctx context.Context, orgId string) ([]*pb.OrganizationMember, []*pb.OrganizationInvite, error) { resp, err := c.client.ListOrganizationMembers(ctx, &pb.ListOrganizationMembersRequest{ OrganizationId: orgId, @@ -115,6 +125,7 @@ func (c *AppClient) ListOrganizationMembers(ctx context.Context, orgId string) ( return resp.Members, resp.Invites, nil } +// CreateOrganizaitonInvite creates an organization invite to an organization. func (c *AppClient) CreateOrganizationInvite(ctx context.Context, orgId string, email string, authorizations []*pb.Authorization, sendEmailInvite *bool) (*pb.OrganizationInvite, error) { resp, err := c.client.CreateOrganizationInvite(ctx, &pb.CreateOrganizationInviteRequest{ OrganizationId: orgId, @@ -128,6 +139,7 @@ func (c *AppClient) CreateOrganizationInvite(ctx context.Context, orgId string, return resp.Invite, nil } +// UpdateOrganizationInviteAuthorizations updates the authorizations attached to an organization invite. func (c *AppClient) UpdateOrganizationInviteAuthorizations(ctx context.Context, orgId string, email string, addAuthorizations []*pb.Authorization, removeAuthorizations []*pb.Authorization) (*pb.OrganizationInvite, error) { resp, err := c.client.UpdateOrganizationInviteAuthorizations(ctx, &pb.UpdateOrganizationInviteAuthorizationsRequest{ OrganizationId: orgId, @@ -141,6 +153,7 @@ func (c *AppClient) UpdateOrganizationInviteAuthorizations(ctx context.Context, return resp.Invite, nil } +// DeleteOrganizationMember deletes an organization member from an organization. func (c *AppClient) DeleteOrganizationMember(ctx context.Context, orgId string, userId string) error { _, err := c.client.DeleteOrganizationMember(ctx, &pb.DeleteOrganizationMemberRequest{ OrganizationId: orgId, @@ -152,6 +165,7 @@ func (c *AppClient) DeleteOrganizationMember(ctx context.Context, orgId string, return nil } +// DeleteOrganizationInvite deletes an organization invite. func (c *AppClient) DeleteOrganizationInvite(ctx context.Context, orgId string, email string) error { _, err := c.client.DeleteOrganizationInvite(ctx, &pb.DeleteOrganizationInviteRequest{ OrganizationId: orgId, @@ -163,6 +177,7 @@ func (c *AppClient) DeleteOrganizationInvite(ctx context.Context, orgId string, return nil } +// ResendOrganizationInvite resends an organization invite. func (c *AppClient) ResendOrganizationInvite(ctx context.Context, orgId string, email string) (*pb.OrganizationInvite, error) { resp, err := c.client.ResendOrganizationInvite(ctx, &pb.ResendOrganizationInviteRequest{ OrganizationId: orgId, From 3d9a72f84887aa20dc8d542cea397c5c22b70174 Mon Sep 17 00:00:00 2001 From: purplenicole730 Date: Wed, 6 Nov 2024 12:59:48 -0500 Subject: [PATCH 03/75] add location wrappers --- app/app_client.go | 117 ++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 117 insertions(+) diff --git a/app/app_client.go b/app/app_client.go index e0cfa77f0dd..0bbb538945c 100644 --- a/app/app_client.go +++ b/app/app_client.go @@ -189,3 +189,120 @@ func (c *AppClient) ResendOrganizationInvite(ctx context.Context, orgId string, return resp.Invite, nil } +// CreateLocation creates a location. +func (c *AppClient) CreateLocation(ctx context.Context, orgId string, name string, parentLocationId *string) (*pb.Location, error) { + resp, err := c.client.CreateLocation(ctx, &pb.CreateLocationRequest{ + OrganizationId: orgId, + Name: name, + ParentLocationId: parentLocationId, + }) + if err != nil { + return nil, err + } + return resp.Location, nil +} + +// GetLocation gets a location. +func (c *AppClient) GetLocation(ctx context.Context, locationId string) (*pb.Location, error) { + resp, err := c.client.GetLocation(ctx, &pb.GetLocationRequest{ + LocationId: locationId, + }) + if err != nil { + return nil, err + } + return resp.Location, nil +} + +// UpdateLocation updates a location. +func (c *AppClient) UpdateLocation(ctx context.Context, locationId string, name *string, parentLocationId *string, region *string) (*pb.Location, error) { + resp, err := c.client.UpdateLocation(ctx, &pb.UpdateLocationRequest{ + LocationId: locationId, + Name: name, + ParentLocationId: parentLocationId, + Region: region, + }) + if err != nil { + return nil, err + } + return resp.Location, nil +} + +// DeleteLocation deletes a location. +func (c *AppClient) DeleteLocation(ctx context.Context, locationId string) error { + _, err := c.client.DeleteLocation(ctx, &pb.DeleteLocationRequest{ + LocationId: locationId, + }) + if err != nil { + return err + } + return nil +} + +// ListLocations gets a list of locations under the specified organization. +func (c *AppClient) ListLocations(ctx context.Context, orgId string) ([]*pb.Location, error) { + resp, err := c.client.ListLocations(ctx, &pb.ListLocationsRequest{ + OrganizationId: orgId, + }) + if err != nil { + return nil, err + } + return resp.Locations, nil +} + +// ShareLocation shares a location with an organization. +func (c *AppClient) ShareLocation(ctx context.Context, locationId string, orgId string) error { + _, err := c.client.ShareLocation(ctx, &pb.ShareLocationRequest{ + LocationId: locationId, + OrganizationId: orgId, + }) + if err != nil { + return err + } + return nil +} + +// UnshareLocation stops sharing a location with an organization. +func (c *AppClient) UnshareLocation(ctx context.Context, locationId string, orgId string) error { + _, err := c.client.UnshareLocation(ctx, &pb.UnshareLocationRequest{ + LocationId: locationId, + OrganizationId: orgId, + }) + if err != nil { + return err + } + return nil +} + +// LocationAuth gets a location's authorization secrets. +func (c *AppClient) LocationAuth(ctx context.Context, locationId string) (*pb.LocationAuth, error) { + resp, err := c.client.LocationAuth(ctx, &pb.LocationAuthRequest{ + LocationId: locationId, + }) + if err != nil { + return nil, err + } + return resp.Auth, nil +} + +// CreateLocationSecret creates a new generated secret in the location. Succeeds if there are no more than 2 active secrets after creation. +func (c *AppClient) CreateLocationSecret(ctx context.Context, locationId string) (*pb.LocationAuth, error) { + resp, err := c.client.CreateLocationSecret(ctx, &pb.CreateLocationSecretRequest{ + LocationId: locationId, + }) + if err != nil { + return nil, err + } + return resp.Auth, nil +} + +// Delete a secret from the location. +func (c *AppClient) DeleteLocationSecret(ctx context.Context, locationId string, secretId string) error { + _, err := c.client.DeleteLocationSecret(ctx, &pb.DeleteLocationSecretRequest{ + LocationId: locationId, + SecretId: secretId, + }) + if err != nil { + return err + } + return nil +} From 56ea1f401141634e47988487f965a473fb7730f6 Mon Sep 17 00:00:00 2001 From: purplenicole730 Date: Wed, 6 Nov 2024 13:01:27 -0500 Subject: [PATCH 04/75] add robot wrappers --- app/app_client.go | 224 ++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 224 insertions(+) diff --git a/app/app_client.go b/app/app_client.go index 0bbb538945c..dbf7b5c4203 100644 --- a/app/app_client.go +++ b/app/app_client.go @@ -6,6 +6,9 @@ import ( "fmt" pb "go.viam.com/api/app/v1" + common "go.viam.com/api/common/v1" + "google.golang.org/protobuf/types/known/structpb" + "google.golang.org/protobuf/types/known/timestamppb" ) type AppClient struct { @@ -306,3 +309,224 @@ func (c *AppClient) DeleteLocationSecret(ctx context.Context, locationId string, } return nil } + +// GetRobot gets a specific robot by ID. +func (c *AppClient) GetRobot(ctx context.Context, id string) (*pb.Robot, error) { + resp, err := c.client.GetRobot(ctx, &pb.GetRobotRequest{ + Id: id, + }) + if err != nil { + return nil, err + } + return resp.Robot, nil +} + +// GetRoverRentalRobots gets rover rental robots within an organization. +func (c *AppClient) GetRoverRentalRobots(ctx context.Context, orgId string) ([]*pb.RoverRentalRobot, error) { + resp, err := c.client.GetRoverRentalRobots(ctx, &pb.GetRoverRentalRobotsRequest{ + OrgId: orgId, + }) + if err != nil { + return nil, err + } + return resp.Robots, nil +} + +// GetRobotParts gets a list of all the parts under a specific machine. +func (c *AppClient) GetRobotParts(ctx context.Context, robotId string) ([]*pb.RobotPart, error) { + resp, err := c.client.GetRobotParts(ctx, &pb.GetRobotPartsRequest{ + RobotId: robotId, + }) + if err != nil { + return nil, err + } + return resp.Parts, nil +} + +// GetRobotPart gets a specific robot part and its config by ID. +func (c *AppClient) GetRobotPart(ctx context.Context, id string) (*pb.RobotPart, string, error) { + resp, err := c.client.GetRobotPart(ctx, &pb.GetRobotPartRequest{ + Id: id, + }) + if err != nil { + return nil, "", err + } + return resp.Part, resp.ConfigJson, nil +} + +// GetRobotPartLogs gets the logs associated with a robot part from a page, defaulting to the most recent page if pageToken is empty. Logs of all levels are returned when levels is empty. +func (c *AppClient) GetRobotPartLogs(ctx context.Context, id string, filter *string, pageToken *string, levels []string, start *timestamppb.Timestamp, end *timestamppb.Timestamp, limit *int64, source *string) ([]*common.LogEntry, string, error) { + resp, err := c.client.GetRobotPartLogs(ctx, &pb.GetRobotPartLogsRequest{ + Id: id, + Filter: filter, + PageToken: pageToken, + Levels: levels, + Start: start, + End: end, + Limit: limit, + Source: source, + }) + if err != nil { + return nil, "", err + } + return resp.Logs, resp.NextPageToken, nil +} + +// // TailRobotPartLogs gets a stream of log entries for a specific robot part. Logs are ordered by newest first. +// func (c *AppClient) TailRobotPartLogs(ctx context.Context) (AppService_TailRobotPartLogsClient, error) { +// resp, err := c.client. +// if err != nil { +// return nil, err +// } +// return resp, nil +// } + +// GetRobotPartHistory gets a specific robot part history by ID. +func (c *AppClient) GetRobotPartHistory(ctx context.Context, id string) ([]*pb.RobotPartHistoryEntry, error) { + resp, err := c.client.GetRobotPartHistory(ctx, &pb.GetRobotPartHistoryRequest{ + Id: id, + }) + if err != nil { + return nil, err + } + return resp.History, nil +} + +// UpdaetRobotPart updates a robot part. +func (c *AppClient) UpdateRobotPart(ctx context.Context, id string, name string, robotConfig *structpb.Struct) (*pb.RobotPart, error) { + resp, err := c.client.UpdateRobotPart(ctx, &pb.UpdateRobotPartRequest{ + Id: id, + Name: name, + RobotConfig: robotConfig, + }) + if err != nil { + return nil, err + } + return resp.Part, nil +} + +// NewRobotPart creates a new robot part. +func (c *AppClient) NewRobotPart(ctx context.Context, robotId string, partName string) (string, error) { + resp, err := c.client.NewRobotPart(ctx, &pb.NewRobotPartRequest{ + RobotId: robotId, + PartName: partName, + }) + if err != nil { + return "", err + } + return resp.PartId, nil +} + +// DeleteRobotPart deletes a robot part. +func (c *AppClient) DeleteRobotPart(ctx context.Context, partId string) error { + _, err := c.client.DeleteRobotPart(ctx, &pb.DeleteRobotPartRequest{ + PartId: partId, + }) + if err != nil { + return err + } + return nil +} + +// GetRobotAPIKeys gets the robot API keys for the robot. +func (c *AppClient) GetRobotAPIKeys(ctx context.Context, robotId string) ([]*pb.APIKeyWithAuthorizations, error) { + resp, err := c.client.GetRobotAPIKeys(ctx, &pb.GetRobotAPIKeysRequest{ + RobotId: robotId, + }) + if err != nil { + return nil, err + } + return resp.ApiKeys, nil +} + +// MarkPartAsMain marks the given part as the main part, and all the others as not. +func (c *AppClient) MarkPartAsMain(ctx context.Context, partId string) error { + _, err := c.client.MarkPartAsMain(ctx, &pb.MarkPartAsMainRequest{ + PartId: partId, + }) + if err != nil { + return err + } + return nil +} + +// MarkPartForRestart marks the given part for restart. Once the robot part checks-in with the app the flag is reset on the robot part. Calling this multiple times before a robot part checks-in has no effect. +func (c *AppClient) MarkPartForRestart(ctx context.Context, partId string) error { + _, err := c.client.MarkPartForRestart(ctx, &pb.MarkPartForRestartRequest{ + PartId: partId, + }) + if err != nil { + return err + } + return nil +} + +// CreateRobotPartSecret creates a new generated secret in the robot part. Succeeds if there are no more than 2 active secrets after creation. +func (c *AppClient) CreateRobotPartSecret(ctx context.Context, partId string) (*pb.RobotPart, error) { + resp, err := c.client.CreateRobotPartSecret(ctx, &pb.CreateRobotPartSecretRequest{ + PartId: partId, + }) + if err != nil { + return nil, err + } + return resp.Part, nil +} + +// DeleteRobotPartSecret deletes a secret from the robot part. +func (c *AppClient) DeleteRobotPartSecret(ctx context.Context, partId string, secretId string) error { + _, err := c.client.DeleteRobotPartSecret(ctx, &pb.DeleteRobotPartSecretRequest{ + PartId: partId, + SecretId: secretId, + }) + if err != nil { + return err + } + return nil +} + +// ListRobots gets a list of robots under a location. +func (c *AppClient) ListRobots(ctx context.Context, locationId string) ([]*pb.Robot, error) { + resp, err := c.client.ListRobots(ctx, &pb.ListRobotsRequest{ + LocationId: locationId, + }) + if err != nil { + return nil, err + } + return resp.Robots, nil +} + +// NewRobot creates a new robot. +func (c *AppClient) NewRobot(ctx context.Context, name string, location string) (string, error) { + resp, err := c.client.NewRobot(ctx, &pb.NewRobotRequest{ + Name: name, + Location: location, + }) + if err != nil { + return "", err + } + return resp.Id, nil +} + +// UpdateRobot updates a robot. +func (c *AppClient) UpdateRobot(ctx context.Context, id string, name string, location string) (*pb.Robot, error) { + resp, err := c.client.UpdateRobot(ctx, &pb.UpdateRobotRequest{ + Id: id, + Name: name, + Location: location, + }) + if err != nil { + return nil, err + } + return resp.Robot, nil +} + +// DeleteRobot deletes a robot. +func (c *AppClient) DeleteRobot(ctx context.Context, id string) error { + _, err := c.client.DeleteRobot(ctx, &pb.DeleteRobotRequest{ + Id: id, + }) + if err != nil { + return err + } + return nil +} From 0a6996970a7d851a06554a8315f1cb395758568c Mon Sep 17 00:00:00 2001 From: purplenicole730 Date: Wed, 6 Nov 2024 13:02:13 -0500 Subject: [PATCH 05/75] add fragment wrappers --- app/app_client.go | 89 +++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 89 insertions(+) diff --git a/app/app_client.go b/app/app_client.go index dbf7b5c4203..550d819b182 100644 --- a/app/app_client.go +++ b/app/app_client.go @@ -530,3 +530,92 @@ func (c *AppClient) DeleteRobot(ctx context.Context, id string) error { } return nil } + +// ListFragments gets a list of fragments. +func (c *AppClient) ListFragments(ctx context.Context, orgId string, showPublic bool, fragmentVisibility []pb.FragmentVisibility) ([]*pb.Fragment, error) { + resp, err := c.client.ListFragments(ctx, &pb.ListFragmentsRequest{ + OrganizationId: orgId, + ShowPublic: showPublic, + FragmentVisibility: fragmentVisibility, + }) + if err != nil { + return nil, err + } + return resp.Fragments, nil +} + +// GetFragment gets a single fragment. +func (c *AppClient) GetFragment(ctx context.Context, id string) (*pb.Fragment, error) { + resp, err := c.client.GetFragment(ctx, &pb.GetFragmentRequest{ + Id: id, + }) + if err != nil { + return nil, err + } + return resp.Fragment, nil +} + +// CreateFragment creates a fragment. +func (c *AppClient) CreateFragment(ctx context.Context, name string, config *structpb.Struct, orgId string, visibility *pb.FragmentVisibility) (*pb.Fragment, error) { + resp, err := c.client.CreateFragment(ctx, &pb.CreateFragmentRequest{ + Name: name, + Config: config, + OrganizationId: orgId, + Visibility: visibility, + }) + if err != nil { + return nil, err + } + return resp.Fragment, nil +} + +// UpdateFragment updates a fragment. +func (c *AppClient) UpdateFragment(ctx context.Context, id string, name string, config *structpb.Struct, public *bool, visibility *pb.FragmentVisibility) (*pb.Fragment, error) { + resp, err := c.client.UpdateFragment(ctx, &pb.UpdateFragmentRequest{ + Id: id, + Name: name, + Config: config, + Public: public, + Visibility: visibility, + }) + if err != nil { + return nil, err + } + return resp.Fragment, nil +} + +// DeleteFragment deletes a fragment. +func (c *AppClient) DeleteFragment(ctx context.Context, id string) error { + _, err := c.client.DeleteFragment(ctx, &pb.DeleteFragmentRequest{ + Id: id, + }) + if err != nil { + return err + } + return nil +} + +// ListMachineFragments gets top level and nested fragments for a amchine, as well as any other fragments specified by IDs. Additional fragments are useful when needing to view fragments that will be provisionally added to the machine alongside existing fragments. +func (c *AppClient) ListMachineFragments(ctx context.Context, machineId string, additionalFragmentIds []string) ([]*pb.Fragment, error) { + resp, err := c.client.ListMachineFragments(ctx, &pb.ListMachineFragmentsRequest{ + MachineId: machineId, + AdditionalFragmentIds: additionalFragmentIds, + }) + if err != nil { + return nil, err + } + return resp.Fragments, nil +} + +// GetFragmentHistory gets the fragment's history. +func (c *AppClient) GetFragmentHistory(ctx context.Context, id string, pageToken *string, pageLimit *int64) ([]*pb.FragmentHistoryEntry, string, error) { + resp, err := c.client.GetFragmentHistory(ctx, &pb.GetFragmentHistoryRequest{ + Id: id, + PageToken: pageToken, + PageLimit: pageLimit, + }) + if err != nil { + return nil, "", err + } + return resp.History, resp.NextPageToken, nil +} From 0e27df3c5de36fd84aa01451e1a4d41d1be81fae Mon Sep 17 00:00:00 2001 From: purplenicole730 Date: Wed, 6 Nov 2024 13:03:03 -0500 Subject: [PATCH 06/75] add authorization wrappers --- app/app_client.go | 92 +++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 92 insertions(+) diff --git a/app/app_client.go b/app/app_client.go index 550d819b182..cc25ace8f7a 100644 --- a/app/app_client.go +++ b/app/app_client.go @@ -619,3 +619,95 @@ func (c *AppClient) GetFragmentHistory(ctx context.Context, id string, pageToken } return resp.History, resp.NextPageToken, nil } + +func createAuthorization(orgId string, identityId string, identityType string, role string, resourceType string, resourceId string) (*pb.Authorization, error) { + if role != "owner" && role != "operator" { + return nil, errors.New("role string must be 'owner' or 'operator'") + } + if resourceType != "organization" && resourceType != "location" && resourceType != "robot" { + return nil, errors.New("resourceType must be 'organization', 'location', or 'robot'") + } + + return &pb.Authorization{ + AuthorizationType: role, + AuthorizationId: fmt.Sprintf("%s_%s", resourceType, role), + ResourceType: resourceType, + ResourceId: resourceId, + IdentityId: identityId, + OrganizationId: orgId, + IdentityType: identityType, + }, nil +} + +// AddRole creates an identity authorization. +func (c *AppClient) AddRole(ctx context.Context, orgId string, identityId string, role string, resourceType string, resourceId string) error { + authorization, err := createAuthorization(orgId, identityId, "", role, resourceType, resourceId) + if err != nil { + return err + } + _, err = c.client.AddRole(ctx, &pb.AddRoleRequest{ + Authorization: authorization, + }) + if err != nil { + return err + } + return nil +} + +// RemoveRole deletes an identity authorization. +func (c *AppClient) RemoveRole(ctx context.Context, orgId string, identityId string, role string, resourceType string, resourceId string) error { + authorization, err := createAuthorization(orgId, identityId, "", role, resourceType, resourceId) + if err != nil { + return err + } + _, err = c.client.RemoveRole(ctx, &pb.RemoveRoleRequest{ + Authorization: authorization, + }) + if err != nil { + return err + } + return nil +} + +// ChangeRole changes an identity authorization to a new identity authorization. +func (c *AppClient) ChangeRole(ctx context.Context, oldOrgId string, oldIdentityId string, oldRole string, oldResourceType string, oldResourceId string, newOrgId string, newIdentityId string, newRole string, newResourceType string, newResourceId string) error { + oldAuthorization, err := createAuthorization(oldOrgId, oldIdentityId, "", oldRole, oldResourceType, oldResourceId) + if err != nil { + return err + } + newAuthorization, err := createAuthorization(newOrgId, newIdentityId, "", newRole, newResourceType, newResourceId) + if err != nil { + return err + } + _, err = c.client.ChangeRole(ctx, &pb.ChangeRoleRequest{ + OldAuthorization: oldAuthorization, + NewAuthorization: newAuthorization, + }) + if err != nil { + return err + } + return nil +} + +// listAuthorizations returns all authorization roles for any given resources. If no resources are given, all resources within the organization will be included. +func (c *AppClient) ListAuthorizations(ctx context.Context, orgId string, resourceIds []string) ([]*pb.Authorization, error) { + resp, err := c.client.ListAuthorizations(ctx, &pb.ListAuthorizationsRequest{ + OrganizationId: orgId, + ResourceIds: resourceIds, + }) + if err != nil { + return nil, err + } + return resp.Authorizations, nil +} + +// CheckPermissions checks the validity of a list of permissions. +func (c *AppClient) CheckPermissions(ctx context.Context, permissions []*pb.AuthorizedPermissions) ([]*pb.AuthorizedPermissions, error) { + resp, err := c.client.CheckPermissions(ctx, &pb.CheckPermissionsRequest{ + Permissions: permissions, + }) + if err != nil { + return nil, err + } + return resp.AuthorizedPermissions, nil +} From e71fed63e366491796c757a502d00bf8f0a138f9 Mon Sep 17 00:00:00 2001 From: purplenicole730 Date: Wed, 6 Nov 2024 13:03:27 -0500 Subject: [PATCH 07/75] add registry item wrappers --- app/app_client.go | 80 +++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 80 insertions(+) diff --git a/app/app_client.go b/app/app_client.go index cc25ace8f7a..4cb38e2b9d7 100644 --- a/app/app_client.go +++ b/app/app_client.go @@ -711,3 +711,83 @@ func (c *AppClient) CheckPermissions(ctx context.Context, permissions []*pb.Auth } return resp.AuthorizedPermissions, nil } + +// GetRegistryItem gets a registry item. +func (c *AppClient) GetRegistryItem(ctx context.Context, itemId string) (*pb.RegistryItem, error) { + resp, err := c.client.GetRegistryItem(ctx, &pb.GetRegistryItemRequest{ + ItemId: itemId, + }) + if err != nil { + return nil, err + } + return resp.Item, nil +} + +// CreateRegistryItem creates a registry item. +func (c *AppClient) CreateRegistryItem(ctx context.Context, orgId string, name string, packageType packages.PackageType) error { + _, err := c.client.CreateRegistryItem(ctx, &pb.CreateRegistryItemRequest{ + OrganizationId: orgId, + Name: name, + Type: packageType, + }) + if err != nil { + return err + } + return nil +} + +// UpdateRegistryItem updates a registry item. +func (c *AppClient) UpdateRegistryItem(ctx context.Context, itemId string, packageType packages.PackageType, description string, visibility pb.Visibility, url *string) error { + _, err := c.client.UpdateRegistryItem(ctx, &pb.UpdateRegistryItemRequest{ + ItemId: itemId, + Type: packageType, + Description: description, + Visibility: visibility, + Url: url, + }) + if err != nil { + return err + } + return nil +} + +// ListRegistryItems lists the registry items in an organization. +func (c *AppClient) ListRegistryItems(ctx context.Context, orgId *string, types []packages.PackageType, visibilities []pb.Visibility, platforms []string, statuses []pb.RegistryItemStatus, searchTerm *string, pageToken *string, publicNamespaces []string) ([]*pb.RegistryItem, error) { + resp, err := c.client.ListRegistryItems(ctx, &pb.ListRegistryItemsRequest{ + OrganizationId: orgId, + Types: types, + Visibilities: visibilities, + Platforms: platforms, + Statuses: statuses, + SearchTerm: searchTerm, + PageToken: pageToken, + PublicNamespaces: publicNamespaces, + }) + if err != nil { + return nil, err + } + return resp.Items, nil +} + +// DeleteRegistryItem deletes a registry item given an ID that is formatted as `prefix:name`` where `prefix`` is the owner's organization ID or namespace. +func (c *AppClient) DeleteRegistryItem(ctx context.Context, itemId string) error { + _, err := c.client.DeleteRegistryItem(ctx, &pb.DeleteRegistryItemRequest{ + ItemId: itemId, + }) + if err != nil { + return err + } + return nil +} + +// TransferRegistryItem transfers a registry item to a namespace. +func (c *AppClient) TransferRegistryItem(ctx context.Context, itemId string, newPublicNamespace string) error { + _, err := c.client.TransferRegistryItem(ctx, &pb.TransferRegistryItemRequest{ + ItemId: itemId, + NewPublicNamespace: newPublicNamespace, + }) + if err != nil { + return err + } + return nil +} From a3856d419430b0e98380a4732dc01ba34ae94bff Mon Sep 17 00:00:00 2001 From: purplenicole730 Date: Wed, 6 Nov 2024 13:03:41 -0500 Subject: [PATCH 08/75] add packages --- app/app_client.go | 1 + 1 file changed, 1 insertion(+) diff --git a/app/app_client.go b/app/app_client.go index 4cb38e2b9d7..9102fa96f94 100644 --- a/app/app_client.go +++ b/app/app_client.go @@ -5,6 +5,7 @@ import ( "errors" "fmt" + packages "go.viam.com/api/app/packages/v1" pb "go.viam.com/api/app/v1" common "go.viam.com/api/common/v1" "google.golang.org/protobuf/types/known/structpb" From 6124c2764da11b0e908c9ddfb24ddc100a49926b Mon Sep 17 00:00:00 2001 From: purplenicole730 Date: Thu, 7 Nov 2024 10:15:29 -0500 Subject: [PATCH 09/75] add module wrappers --- app/app_client.go | 66 +++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 66 insertions(+) diff --git a/app/app_client.go b/app/app_client.go index 9102fa96f94..a9045479c2f 100644 --- a/app/app_client.go +++ b/app/app_client.go @@ -792,3 +792,69 @@ func (c *AppClient) TransferRegistryItem(ctx context.Context, itemId string, new } return nil } + +// CreateModule creates a module. +func (c *AppClient) CreateModule(ctx context.Context, orgId string, name string) (string, string, error) { + resp, err := c.client.CreateModule(ctx, &pb.CreateModuleRequest{ + OrganizationId: orgId, + Name: name, + }) + if err != nil { + return "", "", err + } + return resp.ModuleId, resp.Url, nil +} + +// UpdateModule updates the documentation URL, description, models, entrypoint, and/or the visibility of a module. A path to a setup script can be added that is run before a newly downloaded module starts. +func (c *AppClient) UpdateModule(ctx context.Context, moduleId string, visibility pb.Visibility, url string, description string, models []*pb.Model, entrypoint string, firstRun *string) (string, error) { + resp, err := c.client.UpdateModule(ctx, &pb.UpdateModuleRequest{ + ModuleId: moduleId, + Visibility: visibility, + Url: url, + Description: description, + Models: models, + Entrypoint: entrypoint, + FirstRun: firstRun, + }) + if err != nil { + return "", err + } + return resp.Url, nil +} + +// // type moduleFileType interface { +// // ~pb.UploadModuleFileRequest_File | ~pb.UploadModuleFileRequest_ModuleFileInfo +// // } + +// // func (c *AppClient) UploadModuleFile[moduleFileType moduleFileType](ctx context.Context, moduleFile moduleFileType) (string, error) { +// // resp, err := c.client.UploadModuleFile(ctx, &pb.UploadModuleFileRequest{ +// // ModuleFile: moduleFile, +// // }) +// // if err != nil { +// // return "", err +// // } +// // return resp.Url, nil +// // } + +// GetModule gets a module. +func (c *AppClient) GetModule(ctx context.Context, moduleId string) (*pb.Module, error) { + resp, err := c.client.GetModule(ctx, &pb.GetModuleRequest{ + ModuleId: moduleId, + }) + if err != nil { + return nil, err + } + return resp.Module, nil +} + +// ListModules lists the modules in the organization. +func (c *AppClient) ListModules(ctx context.Context, orgId *string) ([]*pb.Module, error) { + resp, err := c.client.ListModules(ctx, &pb.ListModulesRequest{ + OrganizationId: orgId, + }) + if err != nil { + return nil, err + } + return resp.Modules, nil +} + From 19038d9b85dcf1248fe9ff4d0c0a8d3db5db0112 Mon Sep 17 00:00:00 2001 From: purplenicole730 Date: Thu, 7 Nov 2024 10:17:15 -0500 Subject: [PATCH 10/75] add key wrappers --- app/app_client.go | 86 +++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 86 insertions(+) diff --git a/app/app_client.go b/app/app_client.go index a9045479c2f..24c3273fcce 100644 --- a/app/app_client.go +++ b/app/app_client.go @@ -858,3 +858,89 @@ func (c *AppClient) ListModules(ctx context.Context, orgId *string) ([]*pb.Modul return resp.Modules, nil } +// APIKeyAuthorization is a struct with the necessary authorization data to create an API key. +type APIKeyAuthorization struct { + // `role`` must be "owner" or "operator" + role string + // `resourceType` must be "organization", "location", or "robot" + resourceType string + resourceId string +} + +// CreateKey creates a new API key associated with a list of authorizations +func (c *AppClient) CreateKey(ctx context.Context, orgId string, keyAuthorizations []APIKeyAuthorization, name string) (string, string, error) { + var authorizations []*pb.Authorization + for _, keyAuthorization := range keyAuthorizations { + authorization, err := createAuthorization(orgId, "", "api-key", keyAuthorization.role, keyAuthorization.resourceType, keyAuthorization.resourceId) + if err != nil { + return "", "", nil + } + authorizations = append(authorizations, authorization) + } + + resp, err := c.client.CreateKey(ctx, &pb.CreateKeyRequest{ + Authorizations: authorizations, + Name: name, + }) + if err != nil { + return "", "", err + } + return resp.Key, resp.Id, nil +} + +// DeleteKey deletes an API key. +func (c *AppClient) DeleteKey(ctx context.Context, id string) error { + _, err := c.client.DeleteKey(ctx, &pb.DeleteKeyRequest{ + Id: id, + }) + if err != nil { + return err + } + return nil +} + +// ListKeys lists all the keys for the organization. +func (c *AppClient) ListKeys(ctx context.Context, orgId string) ([]*pb.APIKeyWithAuthorizations, error) { + resp, err := c.client.ListKeys(ctx, &pb.ListKeysRequest{ + OrgId: orgId, + }) + if err != nil { + return nil, err + } + return resp.ApiKeys, nil +} + +// RenameKey renames an API key. +func (c *AppClient) RenameKey(ctx context.Context, id string, name string) (string, string, error) { + resp, err := c.client.RenameKey(ctx, &pb.RenameKeyRequest{ + Id: id, + Name: name, + }) + if err != nil { + return "", "", err + } + return resp.Id, resp.Name, nil +} + +// RotateKey rotates an API key. +func (c *AppClient) RotateKey(ctx context.Context, id string) (string, string, error) { + resp, err := c.client.RotateKey(ctx, &pb.RotateKeyRequest{ + Id: id, + }) + if err != nil { + return "", "", err + } + return resp.Id, resp.Key, nil +} + +// CreateKeyFromExistingKeyAuthorizations creates a new API key with an existing key's authorizations. +func (c *AppClient) CreateKeyFromExistingKeyAuthorizations(ctx context.Context, id string) (string, string, error) { + resp, err := c.client.CreateKeyFromExistingKeyAuthorizations(ctx, &pb.CreateKeyFromExistingKeyAuthorizationsRequest{ + Id: id, + }) + if err != nil { + return "", "", err + } + return resp.Id, resp.Key, nil +} + From 239c2841297c3ea1623fc8fe2c329f05ff300799 Mon Sep 17 00:00:00 2001 From: purplenicole730 Date: Fri, 8 Nov 2024 16:24:03 -0500 Subject: [PATCH 11/75] make lint --- app/app_client.go | 218 +++++++++++++++++++++++----------------------- 1 file changed, 108 insertions(+), 110 deletions(-) diff --git a/app/app_client.go b/app/app_client.go index 24c3273fcce..6faf15149f4 100644 --- a/app/app_client.go +++ b/app/app_client.go @@ -91,15 +91,14 @@ func (c *AppClient) GetOrganizationNamespaceAvailability(ctx context.Context, na return resp.Available, nil } - // UpdateOrganization updates an organization. -func (c *AppClient) UpdateOrganization(ctx context.Context, orgId string, name *string, namespace *string, region *string, cid *string) (*pb.Organization, error) { +func (c *AppClient) UpdateOrganization(ctx context.Context, orgId string, name, namespace, region, cid *string) (*pb.Organization, error) { resp, err := c.client.UpdateOrganization(ctx, &pb.UpdateOrganizationRequest{ - OrganizationId: orgId, - Name: name, + OrganizationId: orgId, + Name: name, PublicNamespace: namespace, - Region: region, - Cid: cid, + Region: region, + Cid: cid, }) if err != nil { return nil, err @@ -130,11 +129,11 @@ func (c *AppClient) ListOrganizationMembers(ctx context.Context, orgId string) ( } // CreateOrganizaitonInvite creates an organization invite to an organization. -func (c *AppClient) CreateOrganizationInvite(ctx context.Context, orgId string, email string, authorizations []*pb.Authorization, sendEmailInvite *bool) (*pb.OrganizationInvite, error) { +func (c *AppClient) CreateOrganizationInvite(ctx context.Context, orgId, email string, authorizations []*pb.Authorization, sendEmailInvite *bool) (*pb.OrganizationInvite, error) { resp, err := c.client.CreateOrganizationInvite(ctx, &pb.CreateOrganizationInviteRequest{ - OrganizationId: orgId, - Email: email, - Authorizations: authorizations, + OrganizationId: orgId, + Email: email, + Authorizations: authorizations, SendEmailInvite: sendEmailInvite, }) if err != nil { @@ -144,11 +143,11 @@ func (c *AppClient) CreateOrganizationInvite(ctx context.Context, orgId string, } // UpdateOrganizationInviteAuthorizations updates the authorizations attached to an organization invite. -func (c *AppClient) UpdateOrganizationInviteAuthorizations(ctx context.Context, orgId string, email string, addAuthorizations []*pb.Authorization, removeAuthorizations []*pb.Authorization) (*pb.OrganizationInvite, error) { +func (c *AppClient) UpdateOrganizationInviteAuthorizations(ctx context.Context, orgId, email string, addAuthorizations, removeAuthorizations []*pb.Authorization) (*pb.OrganizationInvite, error) { resp, err := c.client.UpdateOrganizationInviteAuthorizations(ctx, &pb.UpdateOrganizationInviteAuthorizationsRequest{ - OrganizationId: orgId, - Email: email, - AddAuthorizations: addAuthorizations, + OrganizationId: orgId, + Email: email, + AddAuthorizations: addAuthorizations, RemoveAuthorizations: removeAuthorizations, }) if err != nil { @@ -158,10 +157,10 @@ func (c *AppClient) UpdateOrganizationInviteAuthorizations(ctx context.Context, } // DeleteOrganizationMember deletes an organization member from an organization. -func (c *AppClient) DeleteOrganizationMember(ctx context.Context, orgId string, userId string) error { +func (c *AppClient) DeleteOrganizationMember(ctx context.Context, orgId, userId string) error { _, err := c.client.DeleteOrganizationMember(ctx, &pb.DeleteOrganizationMemberRequest{ OrganizationId: orgId, - UserId: userId, + UserId: userId, }) if err != nil { return err @@ -170,10 +169,10 @@ func (c *AppClient) DeleteOrganizationMember(ctx context.Context, orgId string, } // DeleteOrganizationInvite deletes an organization invite. -func (c *AppClient) DeleteOrganizationInvite(ctx context.Context, orgId string, email string) error { +func (c *AppClient) DeleteOrganizationInvite(ctx context.Context, orgId, email string) error { _, err := c.client.DeleteOrganizationInvite(ctx, &pb.DeleteOrganizationInviteRequest{ OrganizationId: orgId, - Email: email, + Email: email, }) if err != nil { return err @@ -182,10 +181,10 @@ func (c *AppClient) DeleteOrganizationInvite(ctx context.Context, orgId string, } // ResendOrganizationInvite resends an organization invite. -func (c *AppClient) ResendOrganizationInvite(ctx context.Context, orgId string, email string) (*pb.OrganizationInvite, error) { +func (c *AppClient) ResendOrganizationInvite(ctx context.Context, orgId, email string) (*pb.OrganizationInvite, error) { resp, err := c.client.ResendOrganizationInvite(ctx, &pb.ResendOrganizationInviteRequest{ OrganizationId: orgId, - Email: email, + Email: email, }) if err != nil { return nil, err @@ -194,10 +193,10 @@ func (c *AppClient) ResendOrganizationInvite(ctx context.Context, orgId string, } // CreateLocation creates a location. -func (c *AppClient) CreateLocation(ctx context.Context, orgId string, name string, parentLocationId *string) (*pb.Location, error) { +func (c *AppClient) CreateLocation(ctx context.Context, orgId, name string, parentLocationId *string) (*pb.Location, error) { resp, err := c.client.CreateLocation(ctx, &pb.CreateLocationRequest{ - OrganizationId: orgId, - Name: name, + OrganizationId: orgId, + Name: name, ParentLocationId: parentLocationId, }) if err != nil { @@ -218,12 +217,12 @@ func (c *AppClient) GetLocation(ctx context.Context, locationId string) (*pb.Loc } // UpdateLocation updates a location. -func (c *AppClient) UpdateLocation(ctx context.Context, locationId string, name *string, parentLocationId *string, region *string) (*pb.Location, error) { +func (c *AppClient) UpdateLocation(ctx context.Context, locationId string, name, parentLocationId, region *string) (*pb.Location, error) { resp, err := c.client.UpdateLocation(ctx, &pb.UpdateLocationRequest{ - LocationId: locationId, - Name: name, + LocationId: locationId, + Name: name, ParentLocationId: parentLocationId, - Region: region, + Region: region, }) if err != nil { return nil, err @@ -254,9 +253,9 @@ func (c *AppClient) ListLocations(ctx context.Context, orgId string) ([]*pb.Loca } // ShareLocation shares a location with an organization. -func (c *AppClient) ShareLocation(ctx context.Context, locationId string, orgId string) error { +func (c *AppClient) ShareLocation(ctx context.Context, locationId, orgId string) error { _, err := c.client.ShareLocation(ctx, &pb.ShareLocationRequest{ - LocationId: locationId, + LocationId: locationId, OrganizationId: orgId, }) if err != nil { @@ -266,9 +265,9 @@ func (c *AppClient) ShareLocation(ctx context.Context, locationId string, orgId } // UnshareLocation stops sharing a location with an organization. -func (c *AppClient) UnshareLocation(ctx context.Context, locationId string, orgId string) error { +func (c *AppClient) UnshareLocation(ctx context.Context, locationId, orgId string) error { _, err := c.client.UnshareLocation(ctx, &pb.UnshareLocationRequest{ - LocationId: locationId, + LocationId: locationId, OrganizationId: orgId, }) if err != nil { @@ -300,10 +299,10 @@ func (c *AppClient) CreateLocationSecret(ctx context.Context, locationId string) } // Delete a secret from the location. -func (c *AppClient) DeleteLocationSecret(ctx context.Context, locationId string, secretId string) error { +func (c *AppClient) DeleteLocationSecret(ctx context.Context, locationId, secretId string) error { _, err := c.client.DeleteLocationSecret(ctx, &pb.DeleteLocationSecretRequest{ LocationId: locationId, - SecretId: secretId, + SecretId: secretId, }) if err != nil { return err @@ -356,16 +355,16 @@ func (c *AppClient) GetRobotPart(ctx context.Context, id string) (*pb.RobotPart, } // GetRobotPartLogs gets the logs associated with a robot part from a page, defaulting to the most recent page if pageToken is empty. Logs of all levels are returned when levels is empty. -func (c *AppClient) GetRobotPartLogs(ctx context.Context, id string, filter *string, pageToken *string, levels []string, start *timestamppb.Timestamp, end *timestamppb.Timestamp, limit *int64, source *string) ([]*common.LogEntry, string, error) { +func (c *AppClient) GetRobotPartLogs(ctx context.Context, id string, filter, pageToken *string, levels []string, start, end *timestamppb.Timestamp, limit *int64, source *string) ([]*common.LogEntry, string, error) { resp, err := c.client.GetRobotPartLogs(ctx, &pb.GetRobotPartLogsRequest{ - Id: id, - Filter: filter, + Id: id, + Filter: filter, PageToken: pageToken, - Levels: levels, - Start: start, - End: end, - Limit: limit, - Source: source, + Levels: levels, + Start: start, + End: end, + Limit: limit, + Source: source, }) if err != nil { return nil, "", err @@ -394,10 +393,10 @@ func (c *AppClient) GetRobotPartHistory(ctx context.Context, id string) ([]*pb.R } // UpdaetRobotPart updates a robot part. -func (c *AppClient) UpdateRobotPart(ctx context.Context, id string, name string, robotConfig *structpb.Struct) (*pb.RobotPart, error) { +func (c *AppClient) UpdateRobotPart(ctx context.Context, id, name string, robotConfig *structpb.Struct) (*pb.RobotPart, error) { resp, err := c.client.UpdateRobotPart(ctx, &pb.UpdateRobotPartRequest{ - Id: id, - Name: name, + Id: id, + Name: name, RobotConfig: robotConfig, }) if err != nil { @@ -407,9 +406,9 @@ func (c *AppClient) UpdateRobotPart(ctx context.Context, id string, name string, } // NewRobotPart creates a new robot part. -func (c *AppClient) NewRobotPart(ctx context.Context, robotId string, partName string) (string, error) { +func (c *AppClient) NewRobotPart(ctx context.Context, robotId, partName string) (string, error) { resp, err := c.client.NewRobotPart(ctx, &pb.NewRobotPartRequest{ - RobotId: robotId, + RobotId: robotId, PartName: partName, }) if err != nil { @@ -474,9 +473,9 @@ func (c *AppClient) CreateRobotPartSecret(ctx context.Context, partId string) (* } // DeleteRobotPartSecret deletes a secret from the robot part. -func (c *AppClient) DeleteRobotPartSecret(ctx context.Context, partId string, secretId string) error { +func (c *AppClient) DeleteRobotPartSecret(ctx context.Context, partId, secretId string) error { _, err := c.client.DeleteRobotPartSecret(ctx, &pb.DeleteRobotPartSecretRequest{ - PartId: partId, + PartId: partId, SecretId: secretId, }) if err != nil { @@ -497,9 +496,9 @@ func (c *AppClient) ListRobots(ctx context.Context, locationId string) ([]*pb.Ro } // NewRobot creates a new robot. -func (c *AppClient) NewRobot(ctx context.Context, name string, location string) (string, error) { +func (c *AppClient) NewRobot(ctx context.Context, name, location string) (string, error) { resp, err := c.client.NewRobot(ctx, &pb.NewRobotRequest{ - Name: name, + Name: name, Location: location, }) if err != nil { @@ -509,10 +508,10 @@ func (c *AppClient) NewRobot(ctx context.Context, name string, location string) } // UpdateRobot updates a robot. -func (c *AppClient) UpdateRobot(ctx context.Context, id string, name string, location string) (*pb.Robot, error) { +func (c *AppClient) UpdateRobot(ctx context.Context, id, name, location string) (*pb.Robot, error) { resp, err := c.client.UpdateRobot(ctx, &pb.UpdateRobotRequest{ - Id: id, - Name: name, + Id: id, + Name: name, Location: location, }) if err != nil { @@ -535,8 +534,8 @@ func (c *AppClient) DeleteRobot(ctx context.Context, id string) error { // ListFragments gets a list of fragments. func (c *AppClient) ListFragments(ctx context.Context, orgId string, showPublic bool, fragmentVisibility []pb.FragmentVisibility) ([]*pb.Fragment, error) { resp, err := c.client.ListFragments(ctx, &pb.ListFragmentsRequest{ - OrganizationId: orgId, - ShowPublic: showPublic, + OrganizationId: orgId, + ShowPublic: showPublic, FragmentVisibility: fragmentVisibility, }) if err != nil { @@ -559,10 +558,10 @@ func (c *AppClient) GetFragment(ctx context.Context, id string) (*pb.Fragment, e // CreateFragment creates a fragment. func (c *AppClient) CreateFragment(ctx context.Context, name string, config *structpb.Struct, orgId string, visibility *pb.FragmentVisibility) (*pb.Fragment, error) { resp, err := c.client.CreateFragment(ctx, &pb.CreateFragmentRequest{ - Name: name, - Config: config, + Name: name, + Config: config, OrganizationId: orgId, - Visibility: visibility, + Visibility: visibility, }) if err != nil { return nil, err @@ -571,12 +570,12 @@ func (c *AppClient) CreateFragment(ctx context.Context, name string, config *str } // UpdateFragment updates a fragment. -func (c *AppClient) UpdateFragment(ctx context.Context, id string, name string, config *structpb.Struct, public *bool, visibility *pb.FragmentVisibility) (*pb.Fragment, error) { +func (c *AppClient) UpdateFragment(ctx context.Context, id, name string, config *structpb.Struct, public *bool, visibility *pb.FragmentVisibility) (*pb.Fragment, error) { resp, err := c.client.UpdateFragment(ctx, &pb.UpdateFragmentRequest{ - Id: id, - Name: name, - Config: config, - Public: public, + Id: id, + Name: name, + Config: config, + Public: public, Visibility: visibility, }) if err != nil { @@ -599,7 +598,7 @@ func (c *AppClient) DeleteFragment(ctx context.Context, id string) error { // ListMachineFragments gets top level and nested fragments for a amchine, as well as any other fragments specified by IDs. Additional fragments are useful when needing to view fragments that will be provisionally added to the machine alongside existing fragments. func (c *AppClient) ListMachineFragments(ctx context.Context, machineId string, additionalFragmentIds []string) ([]*pb.Fragment, error) { resp, err := c.client.ListMachineFragments(ctx, &pb.ListMachineFragmentsRequest{ - MachineId: machineId, + MachineId: machineId, AdditionalFragmentIds: additionalFragmentIds, }) if err != nil { @@ -611,7 +610,7 @@ func (c *AppClient) ListMachineFragments(ctx context.Context, machineId string, // GetFragmentHistory gets the fragment's history. func (c *AppClient) GetFragmentHistory(ctx context.Context, id string, pageToken *string, pageLimit *int64) ([]*pb.FragmentHistoryEntry, string, error) { resp, err := c.client.GetFragmentHistory(ctx, &pb.GetFragmentHistoryRequest{ - Id: id, + Id: id, PageToken: pageToken, PageLimit: pageLimit, }) @@ -621,7 +620,7 @@ func (c *AppClient) GetFragmentHistory(ctx context.Context, id string, pageToken return resp.History, resp.NextPageToken, nil } -func createAuthorization(orgId string, identityId string, identityType string, role string, resourceType string, resourceId string) (*pb.Authorization, error) { +func createAuthorization(orgId, identityId, identityType, role, resourceType, resourceId string) (*pb.Authorization, error) { if role != "owner" && role != "operator" { return nil, errors.New("role string must be 'owner' or 'operator'") } @@ -631,17 +630,17 @@ func createAuthorization(orgId string, identityId string, identityType string, r return &pb.Authorization{ AuthorizationType: role, - AuthorizationId: fmt.Sprintf("%s_%s", resourceType, role), - ResourceType: resourceType, - ResourceId: resourceId, - IdentityId: identityId, - OrganizationId: orgId, - IdentityType: identityType, + AuthorizationId: fmt.Sprintf("%s_%s", resourceType, role), + ResourceType: resourceType, + ResourceId: resourceId, + IdentityId: identityId, + OrganizationId: orgId, + IdentityType: identityType, }, nil } // AddRole creates an identity authorization. -func (c *AppClient) AddRole(ctx context.Context, orgId string, identityId string, role string, resourceType string, resourceId string) error { +func (c *AppClient) AddRole(ctx context.Context, orgId, identityId, role, resourceType, resourceId string) error { authorization, err := createAuthorization(orgId, identityId, "", role, resourceType, resourceId) if err != nil { return err @@ -656,7 +655,7 @@ func (c *AppClient) AddRole(ctx context.Context, orgId string, identityId string } // RemoveRole deletes an identity authorization. -func (c *AppClient) RemoveRole(ctx context.Context, orgId string, identityId string, role string, resourceType string, resourceId string) error { +func (c *AppClient) RemoveRole(ctx context.Context, orgId, identityId, role, resourceType, resourceId string) error { authorization, err := createAuthorization(orgId, identityId, "", role, resourceType, resourceId) if err != nil { return err @@ -671,7 +670,7 @@ func (c *AppClient) RemoveRole(ctx context.Context, orgId string, identityId str } // ChangeRole changes an identity authorization to a new identity authorization. -func (c *AppClient) ChangeRole(ctx context.Context, oldOrgId string, oldIdentityId string, oldRole string, oldResourceType string, oldResourceId string, newOrgId string, newIdentityId string, newRole string, newResourceType string, newResourceId string) error { +func (c *AppClient) ChangeRole(ctx context.Context, oldOrgId, oldIdentityId, oldRole, oldResourceType, oldResourceId, newOrgId, newIdentityId, newRole, newResourceType, newResourceId string) error { oldAuthorization, err := createAuthorization(oldOrgId, oldIdentityId, "", oldRole, oldResourceType, oldResourceId) if err != nil { return err @@ -694,7 +693,7 @@ func (c *AppClient) ChangeRole(ctx context.Context, oldOrgId string, oldIdentity func (c *AppClient) ListAuthorizations(ctx context.Context, orgId string, resourceIds []string) ([]*pb.Authorization, error) { resp, err := c.client.ListAuthorizations(ctx, &pb.ListAuthorizationsRequest{ OrganizationId: orgId, - ResourceIds: resourceIds, + ResourceIds: resourceIds, }) if err != nil { return nil, err @@ -725,11 +724,11 @@ func (c *AppClient) GetRegistryItem(ctx context.Context, itemId string) (*pb.Reg } // CreateRegistryItem creates a registry item. -func (c *AppClient) CreateRegistryItem(ctx context.Context, orgId string, name string, packageType packages.PackageType) error { +func (c *AppClient) CreateRegistryItem(ctx context.Context, orgId, name string, packageType packages.PackageType) error { _, err := c.client.CreateRegistryItem(ctx, &pb.CreateRegistryItemRequest{ OrganizationId: orgId, - Name: name, - Type: packageType, + Name: name, + Type: packageType, }) if err != nil { return err @@ -740,11 +739,11 @@ func (c *AppClient) CreateRegistryItem(ctx context.Context, orgId string, name s // UpdateRegistryItem updates a registry item. func (c *AppClient) UpdateRegistryItem(ctx context.Context, itemId string, packageType packages.PackageType, description string, visibility pb.Visibility, url *string) error { _, err := c.client.UpdateRegistryItem(ctx, &pb.UpdateRegistryItemRequest{ - ItemId: itemId, - Type: packageType, + ItemId: itemId, + Type: packageType, Description: description, - Visibility: visibility, - Url: url, + Visibility: visibility, + Url: url, }) if err != nil { return err @@ -753,15 +752,15 @@ func (c *AppClient) UpdateRegistryItem(ctx context.Context, itemId string, packa } // ListRegistryItems lists the registry items in an organization. -func (c *AppClient) ListRegistryItems(ctx context.Context, orgId *string, types []packages.PackageType, visibilities []pb.Visibility, platforms []string, statuses []pb.RegistryItemStatus, searchTerm *string, pageToken *string, publicNamespaces []string) ([]*pb.RegistryItem, error) { +func (c *AppClient) ListRegistryItems(ctx context.Context, orgId *string, types []packages.PackageType, visibilities []pb.Visibility, platforms []string, statuses []pb.RegistryItemStatus, searchTerm, pageToken *string, publicNamespaces []string) ([]*pb.RegistryItem, error) { resp, err := c.client.ListRegistryItems(ctx, &pb.ListRegistryItemsRequest{ - OrganizationId: orgId, - Types: types, - Visibilities: visibilities, - Platforms: platforms, - Statuses: statuses, - SearchTerm: searchTerm, - PageToken: pageToken, + OrganizationId: orgId, + Types: types, + Visibilities: visibilities, + Platforms: platforms, + Statuses: statuses, + SearchTerm: searchTerm, + PageToken: pageToken, PublicNamespaces: publicNamespaces, }) if err != nil { @@ -770,7 +769,7 @@ func (c *AppClient) ListRegistryItems(ctx context.Context, orgId *string, types return resp.Items, nil } -// DeleteRegistryItem deletes a registry item given an ID that is formatted as `prefix:name`` where `prefix`` is the owner's organization ID or namespace. +// DeleteRegistryItem deletes a registry item given an ID that is formatted as `prefix:name“ where `prefix“ is the owner's organization ID or namespace. func (c *AppClient) DeleteRegistryItem(ctx context.Context, itemId string) error { _, err := c.client.DeleteRegistryItem(ctx, &pb.DeleteRegistryItemRequest{ ItemId: itemId, @@ -782,9 +781,9 @@ func (c *AppClient) DeleteRegistryItem(ctx context.Context, itemId string) error } // TransferRegistryItem transfers a registry item to a namespace. -func (c *AppClient) TransferRegistryItem(ctx context.Context, itemId string, newPublicNamespace string) error { +func (c *AppClient) TransferRegistryItem(ctx context.Context, itemId, newPublicNamespace string) error { _, err := c.client.TransferRegistryItem(ctx, &pb.TransferRegistryItemRequest{ - ItemId: itemId, + ItemId: itemId, NewPublicNamespace: newPublicNamespace, }) if err != nil { @@ -794,10 +793,10 @@ func (c *AppClient) TransferRegistryItem(ctx context.Context, itemId string, new } // CreateModule creates a module. -func (c *AppClient) CreateModule(ctx context.Context, orgId string, name string) (string, string, error) { +func (c *AppClient) CreateModule(ctx context.Context, orgId, name string) (string, string, error) { resp, err := c.client.CreateModule(ctx, &pb.CreateModuleRequest{ OrganizationId: orgId, - Name: name, + Name: name, }) if err != nil { return "", "", err @@ -806,15 +805,15 @@ func (c *AppClient) CreateModule(ctx context.Context, orgId string, name string) } // UpdateModule updates the documentation URL, description, models, entrypoint, and/or the visibility of a module. A path to a setup script can be added that is run before a newly downloaded module starts. -func (c *AppClient) UpdateModule(ctx context.Context, moduleId string, visibility pb.Visibility, url string, description string, models []*pb.Model, entrypoint string, firstRun *string) (string, error) { +func (c *AppClient) UpdateModule(ctx context.Context, moduleId string, visibility pb.Visibility, url, description string, models []*pb.Model, entrypoint string, firstRun *string) (string, error) { resp, err := c.client.UpdateModule(ctx, &pb.UpdateModuleRequest{ - ModuleId: moduleId, - Visibility: visibility, - Url: url, + ModuleId: moduleId, + Visibility: visibility, + Url: url, Description: description, - Models: models, - Entrypoint: entrypoint, - FirstRun: firstRun, + Models: models, + Entrypoint: entrypoint, + FirstRun: firstRun, }) if err != nil { return "", err @@ -864,10 +863,10 @@ type APIKeyAuthorization struct { role string // `resourceType` must be "organization", "location", or "robot" resourceType string - resourceId string + resourceId string } -// CreateKey creates a new API key associated with a list of authorizations +// CreateKey creates a new API key associated with a list of authorizations. func (c *AppClient) CreateKey(ctx context.Context, orgId string, keyAuthorizations []APIKeyAuthorization, name string) (string, string, error) { var authorizations []*pb.Authorization for _, keyAuthorization := range keyAuthorizations { @@ -877,10 +876,10 @@ func (c *AppClient) CreateKey(ctx context.Context, orgId string, keyAuthorizatio } authorizations = append(authorizations, authorization) } - + resp, err := c.client.CreateKey(ctx, &pb.CreateKeyRequest{ Authorizations: authorizations, - Name: name, + Name: name, }) if err != nil { return "", "", err @@ -911,9 +910,9 @@ func (c *AppClient) ListKeys(ctx context.Context, orgId string) ([]*pb.APIKeyWit } // RenameKey renames an API key. -func (c *AppClient) RenameKey(ctx context.Context, id string, name string) (string, string, error) { +func (c *AppClient) RenameKey(ctx context.Context, id, name string) (string, string, error) { resp, err := c.client.RenameKey(ctx, &pb.RenameKeyRequest{ - Id: id, + Id: id, Name: name, }) if err != nil { @@ -943,4 +942,3 @@ func (c *AppClient) CreateKeyFromExistingKeyAuthorizations(ctx context.Context, } return resp.Id, resp.Key, nil } - From 4f04533a3c0caf5c4f455f7aa8eb5ceb78b01e8f Mon Sep 17 00:00:00 2001 From: purplenicole730 Date: Fri, 8 Nov 2024 16:24:48 -0500 Subject: [PATCH 12/75] add function to create appclient --- app/app_client.go | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/app/app_client.go b/app/app_client.go index 6faf15149f4..874ed805545 100644 --- a/app/app_client.go +++ b/app/app_client.go @@ -8,6 +8,7 @@ import ( packages "go.viam.com/api/app/packages/v1" pb "go.viam.com/api/app/v1" common "go.viam.com/api/common/v1" + "go.viam.com/utils/rpc" "google.golang.org/protobuf/types/known/structpb" "google.golang.org/protobuf/types/known/timestamppb" ) @@ -16,6 +17,10 @@ type AppClient struct { client pb.AppServiceClient } +func NewAppClient(conn rpc.ClientConn) AppClient { + return AppClient{client: pb.NewAppServiceClient(conn)} +} + // GetUserIDByEmail gets the ID of the user with the given email. func (c *AppClient) GetUserIDByEmail(ctx context.Context, email string) (string, error) { resp, err := c.client.GetUserIDByEmail(ctx, &pb.GetUserIDByEmailRequest{ From 2ecd2c8327c6896f6b993cfa2a45ee6ca14aebf3 Mon Sep 17 00:00:00 2001 From: purplenicole730 Date: Fri, 8 Nov 2024 17:48:20 -0500 Subject: [PATCH 13/75] add tailrobotpartlogs --- app/app_client.go | 24 +++++++++----- app/app_stream.go | 84 +++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 100 insertions(+), 8 deletions(-) create mode 100644 app/app_stream.go diff --git a/app/app_client.go b/app/app_client.go index 874ed805545..ff377c9a646 100644 --- a/app/app_client.go +++ b/app/app_client.go @@ -4,6 +4,7 @@ import ( "context" "errors" "fmt" + "sync" packages "go.viam.com/api/app/packages/v1" pb "go.viam.com/api/app/v1" @@ -15,6 +16,8 @@ import ( type AppClient struct { client pb.AppServiceClient + + mu sync.Mutex } func NewAppClient(conn rpc.ClientConn) AppClient { @@ -377,14 +380,19 @@ func (c *AppClient) GetRobotPartLogs(ctx context.Context, id string, filter, pag return resp.Logs, resp.NextPageToken, nil } -// // TailRobotPartLogs gets a stream of log entries for a specific robot part. Logs are ordered by newest first. -// func (c *AppClient) TailRobotPartLogs(ctx context.Context) (AppService_TailRobotPartLogsClient, error) { -// resp, err := c.client. -// if err != nil { -// return nil, err -// } -// return resp, nil -// } +// TailRobotPartLogs gets a stream of log entries for a specific robot part. Logs are ordered by newest first. +func (c *AppClient) TailRobotPartLogs(ctx context.Context, id string, errorsOnly bool, filter *string, ch chan []*common.LogEntry) error { + stream := &appStream {client: c} + + err := stream.startStream(ctx, id, errorsOnly, filter, ch) + if err != nil { + return err + } + + c.mu.Lock() + defer c.mu.Unlock() + return nil +} // GetRobotPartHistory gets a specific robot part history by ID. func (c *AppClient) GetRobotPartHistory(ctx context.Context, id string) ([]*pb.RobotPartHistoryEntry, error) { diff --git a/app/app_stream.go b/app/app_stream.go new file mode 100644 index 00000000000..cc580a66e10 --- /dev/null +++ b/app/app_stream.go @@ -0,0 +1,84 @@ +package app + +import ( + "context" + "sync" + + pb "go.viam.com/api/app/v1" + common "go.viam.com/api/common/v1" + "go.viam.com/utils" +) + +type appStream struct { + *client + streamCancel context.CancelFunc + streamMu sync.Mutex + + activeBackgroundWorkers sync.WaitGroup +} + + +func (s *appStream) startStream(ctx context.Context, id string, errorsOnly bool, filter *string, ch chan []*common.LogEntry) error { + s.streamMu.Lock() + defer s.streamMu.Unlock() + + if ctx.Err() != nil { + return ctx.Err() + } + + ctx, cancel := context.WithCancel(ctx) + s.streamCancel = cancel + + select { + case <-ctx.Done(): + return ctx.Err() + default: + } + + req := &pb.TailRobotPartLogsRequest{ + Id: id, + ErrorsOnly: errorsOnly, + Filter: filter, + } + + // This call won't return any errors it had until the client tries to receive. + //nolint:errcheck + stream, _ := s.client.client.StreamTicks(ctx, req) + _, err := stream.Recv() + if err != nil { + s.client.logger.CError(ctx, err) + return err + } + + // Create a background go routine to receive from the server stream. + // We rely on calling the Done function here rather than in close stream + // since managed go calls that function when the routine exits. + s.activeBackgroundWorkers.Add(1) + utils.ManagedGo(func() { + s.receiveFromStream(ctx, stream, ch) + }, + s.activeBackgroundWorkers.Done) + return nil +} + +func (s *appStream) receiveFromStream(ctx context.Context, stream pb.AppService_TailRobotPartLogsClient, ch chan []*common.LogEntry) { + defer s.streamCancel() + + // repeatly receive from the stream + for { + select { + case <-ctx.Done(): + s.client.logger.Debug(ctx.Err()) + return + default: + } + streamResp, err := stream.Recv() + if err != nil { + // only debug log the context canceled error + s.client.logger.Debug(err) + return + } + // If there is a response, send to the logs channel. + ch <- streamResp.Logs + } +} From b458113835796d163cffbe181fddc8a9936b8b54 Mon Sep 17 00:00:00 2001 From: purplenicole730 Date: Fri, 8 Nov 2024 22:16:28 -0500 Subject: [PATCH 14/75] standardize function name --- app/app_client.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/app/app_client.go b/app/app_client.go index ff377c9a646..23440f513a6 100644 --- a/app/app_client.go +++ b/app/app_client.go @@ -20,7 +20,7 @@ type AppClient struct { mu sync.Mutex } -func NewAppClient(conn rpc.ClientConn) AppClient { +func NewClientFromConn(conn rpc.ClientConn) AppClient { return AppClient{client: pb.NewAppServiceClient(conn)} } From 32ff6290f706d1705dabcd8c41395d076d104807 Mon Sep 17 00:00:00 2001 From: purplenicole730 Date: Fri, 8 Nov 2024 22:21:26 -0500 Subject: [PATCH 15/75] change stream name --- app/app_client.go | 2 +- app/app_stream.go | 6 +++--- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/app/app_client.go b/app/app_client.go index 23440f513a6..edc3a9324f1 100644 --- a/app/app_client.go +++ b/app/app_client.go @@ -382,7 +382,7 @@ func (c *AppClient) GetRobotPartLogs(ctx context.Context, id string, filter, pag // TailRobotPartLogs gets a stream of log entries for a specific robot part. Logs are ordered by newest first. func (c *AppClient) TailRobotPartLogs(ctx context.Context, id string, errorsOnly bool, filter *string, ch chan []*common.LogEntry) error { - stream := &appStream {client: c} + stream := &logStream {client: c} err := stream.startStream(ctx, id, errorsOnly, filter, ch) if err != nil { diff --git a/app/app_stream.go b/app/app_stream.go index cc580a66e10..a62df485caa 100644 --- a/app/app_stream.go +++ b/app/app_stream.go @@ -9,7 +9,7 @@ import ( "go.viam.com/utils" ) -type appStream struct { +type logStream struct { *client streamCancel context.CancelFunc streamMu sync.Mutex @@ -18,7 +18,7 @@ type appStream struct { } -func (s *appStream) startStream(ctx context.Context, id string, errorsOnly bool, filter *string, ch chan []*common.LogEntry) error { +func (s *logStream) startStream(ctx context.Context, id string, errorsOnly bool, filter *string, ch chan []*common.LogEntry) error { s.streamMu.Lock() defer s.streamMu.Unlock() @@ -61,7 +61,7 @@ func (s *appStream) startStream(ctx context.Context, id string, errorsOnly bool, return nil } -func (s *appStream) receiveFromStream(ctx context.Context, stream pb.AppService_TailRobotPartLogsClient, ch chan []*common.LogEntry) { +func (s *logStream) receiveFromStream(ctx context.Context, stream pb.AppService_TailRobotPartLogsClient, ch chan []*common.LogEntry) { defer s.streamCancel() // repeatly receive from the stream From f378068c22e601c62b1cba407b4dbdcacc284fa8 Mon Sep 17 00:00:00 2001 From: purplenicole730 Date: Fri, 8 Nov 2024 22:22:09 -0500 Subject: [PATCH 16/75] start work with upload module file --- app/app_client.go | 63 +++++++++++++++++++++++++++++++++++++---------- 1 file changed, 50 insertions(+), 13 deletions(-) diff --git a/app/app_client.go b/app/app_client.go index edc3a9324f1..dfea38f95d0 100644 --- a/app/app_client.go +++ b/app/app_client.go @@ -834,19 +834,56 @@ func (c *AppClient) UpdateModule(ctx context.Context, moduleId string, visibilit return resp.Url, nil } -// // type moduleFileType interface { -// // ~pb.UploadModuleFileRequest_File | ~pb.UploadModuleFileRequest_ModuleFileInfo -// // } - -// // func (c *AppClient) UploadModuleFile[moduleFileType moduleFileType](ctx context.Context, moduleFile moduleFileType) (string, error) { -// // resp, err := c.client.UploadModuleFile(ctx, &pb.UploadModuleFileRequest{ -// // ModuleFile: moduleFile, -// // }) -// // if err != nil { -// // return "", err -// // } -// // return resp.Url, nil -// // } +// type isModuleFile interface { +// isUploadModuleFileRequest_ModuleFile() +// } + +// type UploadModuleFileRequest_ModuleFileInfo struct { +// *pb.UploadModuleFileRequest_ModuleFileInfo +// } + +// func (UploadModuleFileRequest_ModuleFileInfo) isUploadModuleFileRequest_ModuleFile() {} + +// type UploadModuleFileRequest_File struct { +// *pb.UploadModuleFileRequest_File +// } + +// func (UploadModuleFileRequest_File) isUploadModuleFileRequest_ModuleFile() {} + +// type uploadStream struct { +// gostream. +// } + +// func (c *AppClient) UploadModuleFile(ctx context.Context, moduleFile isModuleFile, ch ) (string, error) { +// c.mu.Lock() +// streamCtx, stream, + + // stream := &uploadStream{client: c} + + // err = stream.startStream(ctx, moduleFile, ch) + + // var req *pb.UploadModuleFileRequest + // switch moduleFileInfo := moduleFile.(type) { + // case UploadModuleFileRequest_ModuleFileInfo: + // req = &pb.UploadModuleFileRequest{ + // ModuleFile: &pb.UploadModuleFileRequest_ModuleFileInfo{ + // ModuleFileInfo: moduleFileInfo.ModuleFileInfo, + // }, + // } + // case UploadModuleFileRequest_File: + // req = &pb.UploadModuleFileRequest{ + // ModuleFile: &pb.UploadModuleFileRequest_File{ + // File: moduleFileInfo.File, + // }, + // } + // } + + // resp, err := c.client.UploadModuleFile(ctx, req) + // if err != nil { + // return "", err + // } + // return resp.Url, nil +// } // GetModule gets a module. func (c *AppClient) GetModule(ctx context.Context, moduleId string) (*pb.Module, error) { From 03488b5e463cdbc09fe15c06cdf9b621fe7a834e Mon Sep 17 00:00:00 2001 From: purplenicole730 Date: Fri, 8 Nov 2024 23:01:20 -0500 Subject: [PATCH 17/75] add organization shadow types --- app/app_client.go | 64 +++++++++++++++------- app/organizations.go | 125 +++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 169 insertions(+), 20 deletions(-) create mode 100644 app/organizations.go diff --git a/app/app_client.go b/app/app_client.go index dfea38f95d0..1779341f896 100644 --- a/app/app_client.go +++ b/app/app_client.go @@ -36,56 +36,71 @@ func (c *AppClient) GetUserIDByEmail(ctx context.Context, email string) (string, } // CreateOrganization creates a new organization. -func (c *AppClient) CreateOrganization(ctx context.Context, name string) (*pb.Organization, error) { +func (c *AppClient) CreateOrganization(ctx context.Context, name string) (*Organization, error) { resp, err := c.client.CreateOrganization(ctx, &pb.CreateOrganizationRequest{ Name: name, }) if err != nil { return nil, err } - return resp.Organization, nil + return ProtoToOrganization(resp.Organization), nil } // ListOrganizations lists all the organizations. -func (c *AppClient) ListOrganizations(ctx context.Context) ([]*pb.Organization, error) { +func (c *AppClient) ListOrganizations(ctx context.Context) ([]*Organization, error) { resp, err := c.client.ListOrganizations(ctx, &pb.ListOrganizationsRequest{}) if err != nil { return nil, err } - return resp.Organizations, nil + + var organizations []*Organization + for _, org := range resp.Organizations { + organizations = append(organizations, ProtoToOrganization(org)) + } + return organizations, nil } // GetOrganizationsWithAccessToLocation gets all the organizations that have access to a location. -func (c *AppClient) GetOrganizationsWithAccessToLocation(ctx context.Context, locationId string) ([]*pb.OrganizationIdentity, error) { +func (c *AppClient) GetOrganizationsWithAccessToLocation(ctx context.Context, locationId string) ([]*OrganizationIdentity, error) { resp, err := c.client.GetOrganizationsWithAccessToLocation(ctx, &pb.GetOrganizationsWithAccessToLocationRequest{ LocationId: locationId, }) if err != nil { return nil, err } - return resp.OrganizationIdentities, nil + + var organizations []*OrganizationIdentity + for _, org := range(resp.OrganizationIdentities) { + organizations = append(organizations, ProtoToOrganizationIdentity(org)) + } + return organizations, nil } // ListOrganizationsByUser lists all the organizations that a user belongs to. -func (c *AppClient) ListOrganizationsByUser(ctx context.Context, userId string) ([]*pb.OrgDetails, error) { +func (c *AppClient) ListOrganizationsByUser(ctx context.Context, userId string) ([]*OrgDetails, error) { resp, err := c.client.ListOrganizationsByUser(ctx, &pb.ListOrganizationsByUserRequest{ UserId: userId, }) if err != nil { return nil, err } - return resp.Orgs, nil + + var organizations []*OrgDetails + for _, org := range(resp.Orgs) { + organizations = append(organizations, ProtoToOrgDetails(org)) + } + return organizations, nil } // GetOrganization gets an organization. -func (c *AppClient) GetOrganization(ctx context.Context, orgId string) (*pb.Organization, error) { +func (c *AppClient) GetOrganization(ctx context.Context, orgId string) (*Organization, error) { resp, err := c.client.GetOrganization(ctx, &pb.GetOrganizationRequest{ OrganizationId: orgId, }) if err != nil { return nil, err } - return resp.Organization, nil + return ProtoToOrganization(resp.Organization), nil } // GetOrganizationNamespaceAvailability checks for namespace availability throughout all organizations. @@ -100,7 +115,7 @@ func (c *AppClient) GetOrganizationNamespaceAvailability(ctx context.Context, na } // UpdateOrganization updates an organization. -func (c *AppClient) UpdateOrganization(ctx context.Context, orgId string, name, namespace, region, cid *string) (*pb.Organization, error) { +func (c *AppClient) UpdateOrganization(ctx context.Context, orgId string, name, namespace, region, cid *string) (*Organization, error) { resp, err := c.client.UpdateOrganization(ctx, &pb.UpdateOrganizationRequest{ OrganizationId: orgId, Name: name, @@ -111,7 +126,7 @@ func (c *AppClient) UpdateOrganization(ctx context.Context, orgId string, name, if err != nil { return nil, err } - return resp.Organization, nil + return ProtoToOrganization(resp.Organization), nil } // DeleteOrganization deletes an organization. @@ -126,18 +141,27 @@ func (c *AppClient) DeleteOrganization(ctx context.Context, orgId string) error } // ListOrganizationMembers lists all members of an organization and all invited members to the organization. -func (c *AppClient) ListOrganizationMembers(ctx context.Context, orgId string) ([]*pb.OrganizationMember, []*pb.OrganizationInvite, error) { +func (c *AppClient) ListOrganizationMembers(ctx context.Context, orgId string) ([]*OrganizationMember, []*OrganizationInvite, error) { resp, err := c.client.ListOrganizationMembers(ctx, &pb.ListOrganizationMembersRequest{ OrganizationId: orgId, }) if err != nil { return nil, nil, err } - return resp.Members, resp.Invites, nil + + var members []*OrganizationMember + for _, member := range(resp.Members) { + members = append(members, ProtoToOrganizationMember(member)) + } + var invites []*OrganizationInvite + for _, invite := range(resp.Invites) { + invites = append(invites, ProtoToOrganizationInvite(invite)) + } + return members, invites, nil } // CreateOrganizaitonInvite creates an organization invite to an organization. -func (c *AppClient) CreateOrganizationInvite(ctx context.Context, orgId, email string, authorizations []*pb.Authorization, sendEmailInvite *bool) (*pb.OrganizationInvite, error) { +func (c *AppClient) CreateOrganizationInvite(ctx context.Context, orgId, email string, authorizations []*pb.Authorization, sendEmailInvite *bool) (*OrganizationInvite, error) { resp, err := c.client.CreateOrganizationInvite(ctx, &pb.CreateOrganizationInviteRequest{ OrganizationId: orgId, Email: email, @@ -147,11 +171,11 @@ func (c *AppClient) CreateOrganizationInvite(ctx context.Context, orgId, email s if err != nil { return nil, err } - return resp.Invite, nil + return ProtoToOrganizationInvite(resp.Invite), nil } // UpdateOrganizationInviteAuthorizations updates the authorizations attached to an organization invite. -func (c *AppClient) UpdateOrganizationInviteAuthorizations(ctx context.Context, orgId, email string, addAuthorizations, removeAuthorizations []*pb.Authorization) (*pb.OrganizationInvite, error) { +func (c *AppClient) UpdateOrganizationInviteAuthorizations(ctx context.Context, orgId, email string, addAuthorizations, removeAuthorizations []*pb.Authorization) (*OrganizationInvite, error) { resp, err := c.client.UpdateOrganizationInviteAuthorizations(ctx, &pb.UpdateOrganizationInviteAuthorizationsRequest{ OrganizationId: orgId, Email: email, @@ -161,7 +185,7 @@ func (c *AppClient) UpdateOrganizationInviteAuthorizations(ctx context.Context, if err != nil { return nil, err } - return resp.Invite, nil + return ProtoToOrganizationInvite(resp.Invite), nil } // DeleteOrganizationMember deletes an organization member from an organization. @@ -189,7 +213,7 @@ func (c *AppClient) DeleteOrganizationInvite(ctx context.Context, orgId, email s } // ResendOrganizationInvite resends an organization invite. -func (c *AppClient) ResendOrganizationInvite(ctx context.Context, orgId, email string) (*pb.OrganizationInvite, error) { +func (c *AppClient) ResendOrganizationInvite(ctx context.Context, orgId, email string) (*OrganizationInvite, error) { resp, err := c.client.ResendOrganizationInvite(ctx, &pb.ResendOrganizationInviteRequest{ OrganizationId: orgId, Email: email, @@ -197,7 +221,7 @@ func (c *AppClient) ResendOrganizationInvite(ctx context.Context, orgId, email s if err != nil { return nil, err } - return resp.Invite, nil + return ProtoToOrganizationInvite(resp.Invite), nil } // CreateLocation creates a location. diff --git a/app/organizations.go b/app/organizations.go new file mode 100644 index 00000000000..7b69daf6af5 --- /dev/null +++ b/app/organizations.go @@ -0,0 +1,125 @@ +package app + +import ( + pb "go.viam.com/api/app/v1" + "google.golang.org/protobuf/types/known/timestamppb" +) + +type Organization struct { + Id string + Name string + CreatedOn *timestamppb.Timestamp + PublicNamespace string + DefaultRegion string + Cid *string +} + +func ProtoToOrganization(organization *pb.Organization) *Organization { + return &Organization{ + Id: organization.Id, + Name: organization.Name, + CreatedOn: organization.CreatedOn, + PublicNamespace: organization.PublicNamespace, + DefaultRegion: organization.DefaultRegion, + Cid: organization.Cid, + } +} + +func OrganizationToProto(organization *Organization) *pb.Organization { + return &pb.Organization{ + Id: organization.Id, + Name: organization.Name, + CreatedOn: organization.CreatedOn, + PublicNamespace: organization.PublicNamespace, + DefaultRegion: organization.DefaultRegion, + Cid: organization.Cid, + } +} + +type OrganizationIdentity struct { + Id string + Name string +} + +func ProtoToOrganizationIdentity(organizationIdentity *pb.OrganizationIdentity) *OrganizationIdentity { + return &OrganizationIdentity{ + Id: organizationIdentity.Id, + Name: organizationIdentity.Name, + } +} + +func OrganizationIdentityToProto(organizationIdentity *OrganizationIdentity) (*pb.OrganizationIdentity, error) { + return &pb.OrganizationIdentity{ + Id: organizationIdentity.Id, + Name: organizationIdentity.Name, + }, nil +} + +type OrgDetails struct { + OrgId string + OrgName string +} + +func ProtoToOrgDetails(orgDetails *pb.OrgDetails) *OrgDetails { + return &OrgDetails{ + OrgId: orgDetails.OrgId, + OrgName: orgDetails.OrgName, + } +} + +func OrgDetailsToProto(orgDetails *OrgDetails) (*pb.OrgDetails, error) { + return &pb.OrgDetails{ + OrgId: orgDetails.OrgId, + OrgName: orgDetails.OrgName, + }, nil +} + +type OrganizationMember struct { + UserId string + Emails []string + DateAdded *timestamppb.Timestamp + LastLogin *timestamppb.Timestamp +} + +func ProtoToOrganizationMember(organizationMemOrganizationMember *pb.OrganizationMember) *OrganizationMember { + return &OrganizationMember{ + UserId: organizationMemOrganizationMember.UserId, + Emails: organizationMemOrganizationMember.Emails, + DateAdded: organizationMemOrganizationMember.DateAdded, + LastLogin: organizationMemOrganizationMember.LastLogin, + } +} + +func OrganizationMemberToProto(organizationMemOrganizationMember *OrganizationMember) (*pb.OrganizationMember, error) { + return &pb.OrganizationMember{ + UserId: organizationMemOrganizationMember.UserId, + Emails: organizationMemOrganizationMember.Emails, + DateAdded: organizationMemOrganizationMember.DateAdded, + LastLogin: organizationMemOrganizationMember.LastLogin, + }, nil +} + +type OrganizationInvite struct { + OrganizationId string + Email string + CreatedOn *timestamppb.Timestamp + Authorizations []*pb.Authorization +} + +func ProtoToOrganizationInvite(organizationInvite *pb.OrganizationInvite) *OrganizationInvite { + return &OrganizationInvite{ + OrganizationId: organizationInvite.OrganizationId, + Email: organizationInvite.Email, + CreatedOn: organizationInvite.CreatedOn, + Authorizations: organizationInvite.Authorizations, + } +} + +func OrganizationInviteToProto(organizationInvite *OrganizationInvite) (*pb.OrganizationInvite, error) { + return &pb.OrganizationInvite{ + OrganizationId: organizationInvite.OrganizationId, + Email: organizationInvite.Email, + CreatedOn: organizationInvite.CreatedOn, + Authorizations: organizationInvite.Authorizations, + }, nil +} From cf7a7c7d59c2f9e5add1047b320d8bd09f5538dd Mon Sep 17 00:00:00 2001 From: purplenicole730 Date: Tue, 12 Nov 2024 09:28:38 -0500 Subject: [PATCH 18/75] fix tail logs --- app/app_client.go | 6 ++++-- app/{app_stream.go => log_stream.go} | 4 ++-- 2 files changed, 6 insertions(+), 4 deletions(-) rename app/{app_stream.go => log_stream.go} (95%) diff --git a/app/app_client.go b/app/app_client.go index 1779341f896..8243d798e53 100644 --- a/app/app_client.go +++ b/app/app_client.go @@ -9,6 +9,7 @@ import ( packages "go.viam.com/api/app/packages/v1" pb "go.viam.com/api/app/v1" common "go.viam.com/api/common/v1" + "go.viam.com/rdk/logging" "go.viam.com/utils/rpc" "google.golang.org/protobuf/types/known/structpb" "google.golang.org/protobuf/types/known/timestamppb" @@ -16,12 +17,13 @@ import ( type AppClient struct { client pb.AppServiceClient + logger logging.Logger mu sync.Mutex } -func NewClientFromConn(conn rpc.ClientConn) AppClient { - return AppClient{client: pb.NewAppServiceClient(conn)} +func NewClientFromConn(conn rpc.ClientConn, logger logging.Logger) AppClient { + return AppClient{client: pb.NewAppServiceClient(conn), logger: logger} } // GetUserIDByEmail gets the ID of the user with the given email. diff --git a/app/app_stream.go b/app/log_stream.go similarity index 95% rename from app/app_stream.go rename to app/log_stream.go index a62df485caa..5442d169656 100644 --- a/app/app_stream.go +++ b/app/log_stream.go @@ -10,7 +10,7 @@ import ( ) type logStream struct { - *client + client *AppClient streamCancel context.CancelFunc streamMu sync.Mutex @@ -43,7 +43,7 @@ func (s *logStream) startStream(ctx context.Context, id string, errorsOnly bool, // This call won't return any errors it had until the client tries to receive. //nolint:errcheck - stream, _ := s.client.client.StreamTicks(ctx, req) + stream, _ := s.client.client.TailRobotPartLogs(ctx, req) _, err := stream.Recv() if err != nil { s.client.logger.CError(ctx, err) From 32ce5f2433e570158b52721497ccfe45c06ac6f7 Mon Sep 17 00:00:00 2001 From: purplenicole730 Date: Tue, 12 Nov 2024 11:11:05 -0500 Subject: [PATCH 19/75] add more organization proto wrappers --- app/{organizations.go => organization.go} | 48 +++++++++++++++++++++-- 1 file changed, 45 insertions(+), 3 deletions(-) rename app/{organizations.go => organization.go} (68%) diff --git a/app/organizations.go b/app/organization.go similarity index 68% rename from app/organizations.go rename to app/organization.go index 7b69daf6af5..98fc1d607a4 100644 --- a/app/organizations.go +++ b/app/organization.go @@ -103,23 +103,65 @@ type OrganizationInvite struct { OrganizationId string Email string CreatedOn *timestamppb.Timestamp - Authorizations []*pb.Authorization + Authorizations []*Authorization } func ProtoToOrganizationInvite(organizationInvite *pb.OrganizationInvite) *OrganizationInvite { + var authorizations []*Authorization + for _, authorization := range(organizationInvite.Authorizations) { + authorizations = append(authorizations, ProtoToAuthorization(authorization)) + } return &OrganizationInvite{ OrganizationId: organizationInvite.OrganizationId, Email: organizationInvite.Email, CreatedOn: organizationInvite.CreatedOn, - Authorizations: organizationInvite.Authorizations, + Authorizations: authorizations, } } func OrganizationInviteToProto(organizationInvite *OrganizationInvite) (*pb.OrganizationInvite, error) { + var authorizations []*pb.Authorization + for _, authorization := range(organizationInvite.Authorizations) { + authorizations = append(authorizations, AuthorizationToProto(authorization)) + } return &pb.OrganizationInvite{ OrganizationId: organizationInvite.OrganizationId, Email: organizationInvite.Email, CreatedOn: organizationInvite.CreatedOn, - Authorizations: organizationInvite.Authorizations, + Authorizations: authorizations, }, nil } + +type Authorization struct { + AuthorizationType string + AuthorizationId string + ResourceType string + ResourceId string + IdentityId string + OrganizationId string + IdentityType string +} + +func ProtoToAuthorization(authorization *pb.Authorization) *Authorization { + return &Authorization{ + AuthorizationType: authorization.AuthorizationType, + AuthorizationId: authorization.AuthorizationId, + ResourceType: authorization.ResourceType, + ResourceId: authorization.ResourceId, + IdentityId: authorization.IdentityId, + OrganizationId: authorization.OrganizationId, + IdentityType: authorization.IdentityType, + } +} + +func AuthorizationToProto(authorization *Authorization) *pb.Authorization { + return &pb.Authorization{ + AuthorizationType: authorization.AuthorizationType, + AuthorizationId: authorization.AuthorizationId, + ResourceType: authorization.ResourceType, + ResourceId: authorization.ResourceId, + IdentityId: authorization.IdentityId, + OrganizationId: authorization.OrganizationId, + IdentityType: authorization.IdentityType, + } +} From 3512fb5788e3126460088642fd706fea409bc0ee Mon Sep 17 00:00:00 2001 From: purplenicole730 Date: Tue, 12 Nov 2024 11:11:10 -0500 Subject: [PATCH 20/75] add location wrappers --- app/app_client.go | 29 ++++++---- app/location.go | 141 ++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 158 insertions(+), 12 deletions(-) create mode 100644 app/location.go diff --git a/app/app_client.go b/app/app_client.go index 8243d798e53..d2f9fb9b846 100644 --- a/app/app_client.go +++ b/app/app_client.go @@ -227,7 +227,7 @@ func (c *AppClient) ResendOrganizationInvite(ctx context.Context, orgId, email s } // CreateLocation creates a location. -func (c *AppClient) CreateLocation(ctx context.Context, orgId, name string, parentLocationId *string) (*pb.Location, error) { +func (c *AppClient) CreateLocation(ctx context.Context, orgId, name string, parentLocationId *string) (*Location, error) { resp, err := c.client.CreateLocation(ctx, &pb.CreateLocationRequest{ OrganizationId: orgId, Name: name, @@ -236,22 +236,22 @@ func (c *AppClient) CreateLocation(ctx context.Context, orgId, name string, pare if err != nil { return nil, err } - return resp.Location, nil + return ProtoToLocation(resp.Location), nil } // GetLocation gets a location. -func (c *AppClient) GetLocation(ctx context.Context, locationId string) (*pb.Location, error) { +func (c *AppClient) GetLocation(ctx context.Context, locationId string) (*Location, error) { resp, err := c.client.GetLocation(ctx, &pb.GetLocationRequest{ LocationId: locationId, }) if err != nil { return nil, err } - return resp.Location, nil + return ProtoToLocation(resp.Location), nil } // UpdateLocation updates a location. -func (c *AppClient) UpdateLocation(ctx context.Context, locationId string, name, parentLocationId, region *string) (*pb.Location, error) { +func (c *AppClient) UpdateLocation(ctx context.Context, locationId string, name, parentLocationId, region *string) (*Location, error) { resp, err := c.client.UpdateLocation(ctx, &pb.UpdateLocationRequest{ LocationId: locationId, Name: name, @@ -261,7 +261,7 @@ func (c *AppClient) UpdateLocation(ctx context.Context, locationId string, name, if err != nil { return nil, err } - return resp.Location, nil + return ProtoToLocation(resp.Location), nil } // DeleteLocation deletes a location. @@ -276,14 +276,19 @@ func (c *AppClient) DeleteLocation(ctx context.Context, locationId string) error } // ListLocations gets a list of locations under the specified organization. -func (c *AppClient) ListLocations(ctx context.Context, orgId string) ([]*pb.Location, error) { +func (c *AppClient) ListLocations(ctx context.Context, orgId string) ([]*Location, error) { resp, err := c.client.ListLocations(ctx, &pb.ListLocationsRequest{ OrganizationId: orgId, }) if err != nil { return nil, err } - return resp.Locations, nil + + var locations []*Location + for _, location := range(resp.Locations) { + locations = append(locations, ProtoToLocation(location)) + } + return locations, nil } // ShareLocation shares a location with an organization. @@ -311,25 +316,25 @@ func (c *AppClient) UnshareLocation(ctx context.Context, locationId, orgId strin } // LocationAuth gets a location's authorization secrets. -func (c *AppClient) LocationAuth(ctx context.Context, locationId string) (*pb.LocationAuth, error) { +func (c *AppClient) LocationAuth(ctx context.Context, locationId string) (*LocationAuth, error) { resp, err := c.client.LocationAuth(ctx, &pb.LocationAuthRequest{ LocationId: locationId, }) if err != nil { return nil, err } - return resp.Auth, nil + return ProtoToLocationAuth(resp.Auth), nil } // CreateLocationSecret creates a new generated secret in the location. Succeeds if there are no more than 2 active secrets after creation. -func (c *AppClient) CreateLocationSecret(ctx context.Context, locationId string) (*pb.LocationAuth, error) { +func (c *AppClient) CreateLocationSecret(ctx context.Context, locationId string) (*LocationAuth, error) { resp, err := c.client.CreateLocationSecret(ctx, &pb.CreateLocationSecretRequest{ LocationId: locationId, }) if err != nil { return nil, err } - return resp.Auth, nil + return ProtoToLocationAuth(resp.Auth), nil } // Delete a secret from the location. diff --git a/app/location.go b/app/location.go new file mode 100644 index 00000000000..b2bf2b02179 --- /dev/null +++ b/app/location.go @@ -0,0 +1,141 @@ +package app + +import ( + pb "go.viam.com/api/app/v1" + "google.golang.org/protobuf/types/known/timestamppb" +) + +type Location struct { + Id string + Name string + ParentLocationId string + Auth *LocationAuth + Organizations []*LocationOrganization + CreatedOn *timestamppb.Timestamp + RobotCount int32 + Config *pb.StorageConfig +} + +func ProtoToLocation(location *pb.Location) *Location { + var organizations []*LocationOrganization + for _, organization := range(location.Organizations) { + organizations = append(organizations, ProtoToLocationOrganization(organization)) + } + return &Location{ + Id: location.Id, + Name: location.Name, + ParentLocationId: location.ParentLocationId, + Auth: ProtoToLocationAuth(location.Auth), + Organizations: organizations, + CreatedOn: location.CreatedOn, + RobotCount: location.RobotCount, + Config: location.Config, + } +} + +func LocationToProto(location *Location) *pb.Location { + var organizations []*pb.LocationOrganization + for _, organization := range(location.Organizations) { + organizations = append(organizations, LocationOrganizationToProto(organization)) + } + return &pb.Location{ + Id: location.Id, + Name: location.Name, + ParentLocationId: location.ParentLocationId, + Auth: LocationAuthToProto(location.Auth), + Organizations: organizations, + CreatedOn: location.CreatedOn, + RobotCount: location.RobotCount, + Config: location.Config, + } +} + +type LocationOrganization struct { + OrganizationId string + Primary bool +} + +func ProtoToLocationOrganization(locationOrganization *pb.LocationOrganization) *LocationOrganization { + return &LocationOrganization{ + OrganizationId: locationOrganization.OrganizationId, + Primary: locationOrganization.Primary, + } +} + +func LocationOrganizationToProto(locationOrganization *LocationOrganization) *pb.LocationOrganization { + return &pb.LocationOrganization{ + OrganizationId: locationOrganization.OrganizationId, + Primary: locationOrganization.Primary, + } +} + +type LocationAuth struct { + LocationId string + Secrets []*pb.SharedSecret +} + +func ProtoToLocationAuth(locationAuth *pb.LocationAuth) *LocationAuth { + return &LocationAuth{ + LocationId: locationAuth.LocationId, + Secrets: locationAuth.Secrets, + } +} + +func LocationAuthToProto(locationAuth *LocationAuth) *pb.LocationAuth { + return &pb.LocationAuth{ + LocationId: locationAuth.LocationId, + Secrets: locationAuth.Secrets, + } +} + +type SharedSecret struct { + Id string + CreatedOn *timestamppb.Timestamp + State SharedSecret_State +} + +func ProtoToSharedSecret(sharedSecret *pb.SharedSecret) *SharedSecret { + return &SharedSecret{ + Id: sharedSecret.Id, + CreatedOn: sharedSecret.CreatedOn, + State: ProtoToSharedSecretState(sharedSecret.State), + } +} + +func SharedSecretToProto(sharedSecret *SharedSecret) *pb.SharedSecret { + return &pb.SharedSecret{ + Id: sharedSecret.Id, + CreatedOn: sharedSecret.CreatedOn, + State: SharedSecretStateToProto(sharedSecret.State), + } +} + +type SharedSecret_State int32 + +const ( + SharedSecret_STATE_UNSPECIFIED SharedSecret_State = 0 + SharedSecret_STATE_ENABLED SharedSecret_State = 1 + SharedSecret_STATE_DISABLED SharedSecret_State = 2 +) + +func ProtoToSharedSecretState(sharedSecretState pb.SharedSecret_State) SharedSecret_State { + switch sharedSecretState{ + case pb.SharedSecret_STATE_UNSPECIFIED: + return SharedSecret_STATE_UNSPECIFIED + case pb.SharedSecret_STATE_ENABLED: + return SharedSecret_STATE_ENABLED + case pb.SharedSecret_STATE_DISABLED: + return SharedSecret_STATE_DISABLED + } +} + +func SharedSecretStateToProto(sharedSecretState SharedSecret_State) pb.SharedSecret_State { + switch sharedSecretState{ + case SharedSecret_STATE_UNSPECIFIED: + return pb.SharedSecret_STATE_UNSPECIFIED + case SharedSecret_STATE_ENABLED: + return pb.SharedSecret_STATE_ENABLED + case SharedSecret_STATE_DISABLED: + return pb.SharedSecret_STATE_DISABLED + } +} From 760d2f2351d36ca7688843c96fa64097a9a4fec4 Mon Sep 17 00:00:00 2001 From: purplenicole730 Date: Tue, 12 Nov 2024 11:24:18 -0500 Subject: [PATCH 21/75] add error return for enum --- app/app_client.go | 36 +++++++++++++++---- app/location.go | 92 +++++++++++++++++++++++++++++++++-------------- 2 files changed, 95 insertions(+), 33 deletions(-) diff --git a/app/app_client.go b/app/app_client.go index d2f9fb9b846..86f9b662454 100644 --- a/app/app_client.go +++ b/app/app_client.go @@ -236,7 +236,11 @@ func (c *AppClient) CreateLocation(ctx context.Context, orgId, name string, pare if err != nil { return nil, err } - return ProtoToLocation(resp.Location), nil + location, err := ProtoToLocation(resp.Location) + if err != nil { + return nil, err + } + return location, nil } // GetLocation gets a location. @@ -247,7 +251,11 @@ func (c *AppClient) GetLocation(ctx context.Context, locationId string) (*Locati if err != nil { return nil, err } - return ProtoToLocation(resp.Location), nil + location, err := ProtoToLocation(resp.Location) + if err != nil { + return nil, err + } + return location, nil } // UpdateLocation updates a location. @@ -261,7 +269,11 @@ func (c *AppClient) UpdateLocation(ctx context.Context, locationId string, name, if err != nil { return nil, err } - return ProtoToLocation(resp.Location), nil + location, err := ProtoToLocation(resp.Location) + if err != nil { + return nil, err + } + return location, nil } // DeleteLocation deletes a location. @@ -286,7 +298,11 @@ func (c *AppClient) ListLocations(ctx context.Context, orgId string) ([]*Locatio var locations []*Location for _, location := range(resp.Locations) { - locations = append(locations, ProtoToLocation(location)) + l, err := ProtoToLocation(location) + if err != nil { + return nil, err + } + locations = append(locations, l) } return locations, nil } @@ -323,7 +339,11 @@ func (c *AppClient) LocationAuth(ctx context.Context, locationId string) (*Locat if err != nil { return nil, err } - return ProtoToLocationAuth(resp.Auth), nil + auth, err := ProtoToLocationAuth(resp.Auth) + if err != nil { + return nil, err + } + return auth, nil } // CreateLocationSecret creates a new generated secret in the location. Succeeds if there are no more than 2 active secrets after creation. @@ -334,7 +354,11 @@ func (c *AppClient) CreateLocationSecret(ctx context.Context, locationId string) if err != nil { return nil, err } - return ProtoToLocationAuth(resp.Auth), nil + auth, err := ProtoToLocationAuth(resp.Auth) + if err != nil { + return nil, err + } + return auth, nil } // Delete a secret from the location. diff --git a/app/location.go b/app/location.go index b2bf2b02179..852a18ad481 100644 --- a/app/location.go +++ b/app/location.go @@ -1,6 +1,8 @@ package app import ( + "fmt" + pb "go.viam.com/api/app/v1" "google.golang.org/protobuf/types/known/timestamppb" ) @@ -16,38 +18,46 @@ type Location struct { Config *pb.StorageConfig } -func ProtoToLocation(location *pb.Location) *Location { +func ProtoToLocation(location *pb.Location) (*Location, error) { var organizations []*LocationOrganization for _, organization := range(location.Organizations) { organizations = append(organizations, ProtoToLocationOrganization(organization)) } + auth, err := ProtoToLocationAuth(location.Auth) + if err != nil { + return nil, err + } return &Location{ Id: location.Id, Name: location.Name, ParentLocationId: location.ParentLocationId, - Auth: ProtoToLocationAuth(location.Auth), + Auth: auth, Organizations: organizations, CreatedOn: location.CreatedOn, RobotCount: location.RobotCount, Config: location.Config, - } + }, nil } -func LocationToProto(location *Location) *pb.Location { +func LocationToProto(location *Location) (*pb.Location, error) { var organizations []*pb.LocationOrganization for _, organization := range(location.Organizations) { organizations = append(organizations, LocationOrganizationToProto(organization)) } + auth, err := LocationAuthToProto(location.Auth) + if err != nil { + return nil, err + } return &pb.Location{ Id: location.Id, Name: location.Name, ParentLocationId: location.ParentLocationId, - Auth: LocationAuthToProto(location.Auth), + Auth: auth, Organizations: organizations, CreatedOn: location.CreatedOn, RobotCount: location.RobotCount, Config: location.Config, - } + }, nil } type LocationOrganization struct { @@ -71,21 +81,37 @@ func LocationOrganizationToProto(locationOrganization *LocationOrganization) *pb type LocationAuth struct { LocationId string - Secrets []*pb.SharedSecret + Secrets []*SharedSecret } -func ProtoToLocationAuth(locationAuth *pb.LocationAuth) *LocationAuth { +func ProtoToLocationAuth(locationAuth *pb.LocationAuth) (*LocationAuth, error) { + var secrets []*SharedSecret + for _, secret := range(locationAuth.Secrets) { + s, err := ProtoToSharedSecret(secret) + if err != nil { + return nil, err + } + secrets = append(secrets, s) + } return &LocationAuth{ LocationId: locationAuth.LocationId, - Secrets: locationAuth.Secrets, - } + Secrets: secrets, + }, nil } -func LocationAuthToProto(locationAuth *LocationAuth) *pb.LocationAuth { +func LocationAuthToProto(locationAuth *LocationAuth) (*pb.LocationAuth, error) { + var secrets []*pb.SharedSecret + for _, secret := range(locationAuth.Secrets) { + s, err := SharedSecretToProto(secret) + if err != nil { + return nil, err + } + secrets = append(secrets, s) + } return &pb.LocationAuth{ LocationId: locationAuth.LocationId, - Secrets: locationAuth.Secrets, - } + Secrets: secrets, + }, nil } type SharedSecret struct { @@ -94,20 +120,28 @@ type SharedSecret struct { State SharedSecret_State } -func ProtoToSharedSecret(sharedSecret *pb.SharedSecret) *SharedSecret { +func ProtoToSharedSecret(sharedSecret *pb.SharedSecret) (*SharedSecret, error) { + state, err := ProtoToSharedSecretState(sharedSecret.State) + if err != nil { + return nil, err + } return &SharedSecret{ Id: sharedSecret.Id, CreatedOn: sharedSecret.CreatedOn, - State: ProtoToSharedSecretState(sharedSecret.State), - } + State: state, + }, nil } -func SharedSecretToProto(sharedSecret *SharedSecret) *pb.SharedSecret { +func SharedSecretToProto(sharedSecret *SharedSecret) (*pb.SharedSecret, error) { + state, err := SharedSecretStateToProto(sharedSecret.State) + if err != nil { + return nil, err + } return &pb.SharedSecret{ Id: sharedSecret.Id, CreatedOn: sharedSecret.CreatedOn, - State: SharedSecretStateToProto(sharedSecret.State), - } + State: state, + }, nil } type SharedSecret_State int32 @@ -118,24 +152,28 @@ const ( SharedSecret_STATE_DISABLED SharedSecret_State = 2 ) -func ProtoToSharedSecretState(sharedSecretState pb.SharedSecret_State) SharedSecret_State { +func ProtoToSharedSecretState(sharedSecretState pb.SharedSecret_State) (SharedSecret_State, error) { switch sharedSecretState{ case pb.SharedSecret_STATE_UNSPECIFIED: - return SharedSecret_STATE_UNSPECIFIED + return SharedSecret_STATE_UNSPECIFIED, nil case pb.SharedSecret_STATE_ENABLED: - return SharedSecret_STATE_ENABLED + return SharedSecret_STATE_ENABLED, nil case pb.SharedSecret_STATE_DISABLED: - return SharedSecret_STATE_DISABLED + return SharedSecret_STATE_DISABLED, nil + default: + return 0, fmt.Errorf("uknown secret state: %v", sharedSecretState) } } -func SharedSecretStateToProto(sharedSecretState SharedSecret_State) pb.SharedSecret_State { +func SharedSecretStateToProto(sharedSecretState SharedSecret_State) (pb.SharedSecret_State, error) { switch sharedSecretState{ case SharedSecret_STATE_UNSPECIFIED: - return pb.SharedSecret_STATE_UNSPECIFIED + return pb.SharedSecret_STATE_UNSPECIFIED, nil case SharedSecret_STATE_ENABLED: - return pb.SharedSecret_STATE_ENABLED + return pb.SharedSecret_STATE_ENABLED, nil case SharedSecret_STATE_DISABLED: - return pb.SharedSecret_STATE_DISABLED + return pb.SharedSecret_STATE_DISABLED, nil + default: + return 0, fmt.Errorf("unknown secret state: %v", sharedSecretState) } } From 460d44b73bbf94b423ba06594c857552cbc4a529 Mon Sep 17 00:00:00 2001 From: purplenicole730 Date: Tue, 12 Nov 2024 12:49:45 -0500 Subject: [PATCH 22/75] add type wrappers for robot functions --- app/app_client.go | 119 ++++++++++++----- app/common.go | 63 +++++++++ app/log_stream.go | 16 ++- app/robot.go | 325 ++++++++++++++++++++++++++++++++++++++++++++++ 4 files changed, 489 insertions(+), 34 deletions(-) create mode 100644 app/common.go create mode 100644 app/robot.go diff --git a/app/app_client.go b/app/app_client.go index 86f9b662454..a7ce61c39b1 100644 --- a/app/app_client.go +++ b/app/app_client.go @@ -8,10 +8,9 @@ import ( packages "go.viam.com/api/app/packages/v1" pb "go.viam.com/api/app/v1" - common "go.viam.com/api/common/v1" "go.viam.com/rdk/logging" + "go.viam.com/utils/protoutils" "go.viam.com/utils/rpc" - "google.golang.org/protobuf/types/known/structpb" "google.golang.org/protobuf/types/known/timestamppb" ) @@ -374,51 +373,67 @@ func (c *AppClient) DeleteLocationSecret(ctx context.Context, locationId, secret } // GetRobot gets a specific robot by ID. -func (c *AppClient) GetRobot(ctx context.Context, id string) (*pb.Robot, error) { +func (c *AppClient) GetRobot(ctx context.Context, id string) (*Robot, error) { resp, err := c.client.GetRobot(ctx, &pb.GetRobotRequest{ Id: id, }) if err != nil { return nil, err } - return resp.Robot, nil + return ProtoToRobot(resp.Robot), nil } // GetRoverRentalRobots gets rover rental robots within an organization. -func (c *AppClient) GetRoverRentalRobots(ctx context.Context, orgId string) ([]*pb.RoverRentalRobot, error) { +func (c *AppClient) GetRoverRentalRobots(ctx context.Context, orgId string) ([]*RoverRentalRobot, error) { resp, err := c.client.GetRoverRentalRobots(ctx, &pb.GetRoverRentalRobotsRequest{ OrgId: orgId, }) if err != nil { return nil, err } - return resp.Robots, nil + var robots []*RoverRentalRobot + for _, robot := range(resp.Robots) { + robots = append(robots, ProtoToRoverRentalRobot(robot)) + } + return robots, nil } // GetRobotParts gets a list of all the parts under a specific machine. -func (c *AppClient) GetRobotParts(ctx context.Context, robotId string) ([]*pb.RobotPart, error) { +func (c *AppClient) GetRobotParts(ctx context.Context, robotId string) ([]*RobotPart, error) { resp, err := c.client.GetRobotParts(ctx, &pb.GetRobotPartsRequest{ RobotId: robotId, }) if err != nil { return nil, err } - return resp.Parts, nil + var parts []*RobotPart + for _, part := range(resp.Parts) { + p, err := ProtoToRobotPart(part) + if err != nil { + return nil, err + } + parts = append(parts, p) + } + return parts, nil } // GetRobotPart gets a specific robot part and its config by ID. -func (c *AppClient) GetRobotPart(ctx context.Context, id string) (*pb.RobotPart, string, error) { +func (c *AppClient) GetRobotPart(ctx context.Context, id string) (*RobotPart, string, error) { resp, err := c.client.GetRobotPart(ctx, &pb.GetRobotPartRequest{ Id: id, }) if err != nil { return nil, "", err } - return resp.Part, resp.ConfigJson, nil + part, err := ProtoToRobotPart(resp.Part) + if err != nil { + return nil, "", err + } + return part, resp.ConfigJson, nil } // GetRobotPartLogs gets the logs associated with a robot part from a page, defaulting to the most recent page if pageToken is empty. Logs of all levels are returned when levels is empty. -func (c *AppClient) GetRobotPartLogs(ctx context.Context, id string, filter, pageToken *string, levels []string, start, end *timestamppb.Timestamp, limit *int64, source *string) ([]*common.LogEntry, string, error) { +func (c *AppClient) GetRobotPartLogs(ctx context.Context, id string, filter, pageToken *string, levels []string, start, end *timestamppb.Timestamp, limit *int64, source *string) ([]*LogEntry, string, error) { resp, err := c.client.GetRobotPartLogs(ctx, &pb.GetRobotPartLogsRequest{ Id: id, Filter: filter, @@ -432,11 +447,19 @@ func (c *AppClient) GetRobotPartLogs(ctx context.Context, id string, filter, pag if err != nil { return nil, "", err } - return resp.Logs, resp.NextPageToken, nil + var logs []*LogEntry + for _, log := range(resp.Logs){ + l, err := ProtoToLogEntry(log) + if err != nil { + return nil, "", err + } + logs = append(logs, l) + } + return logs, resp.NextPageToken, nil } // TailRobotPartLogs gets a stream of log entries for a specific robot part. Logs are ordered by newest first. -func (c *AppClient) TailRobotPartLogs(ctx context.Context, id string, errorsOnly bool, filter *string, ch chan []*common.LogEntry) error { +func (c *AppClient) TailRobotPartLogs(ctx context.Context, id string, errorsOnly bool, filter *string, ch chan []*LogEntry) error { stream := &logStream {client: c} err := stream.startStream(ctx, id, errorsOnly, filter, ch) @@ -450,27 +473,43 @@ func (c *AppClient) TailRobotPartLogs(ctx context.Context, id string, errorsOnly } // GetRobotPartHistory gets a specific robot part history by ID. -func (c *AppClient) GetRobotPartHistory(ctx context.Context, id string) ([]*pb.RobotPartHistoryEntry, error) { +func (c *AppClient) GetRobotPartHistory(ctx context.Context, id string) ([]*RobotPartHistoryEntry, error) { resp, err := c.client.GetRobotPartHistory(ctx, &pb.GetRobotPartHistoryRequest{ Id: id, }) if err != nil { return nil, err } - return resp.History, nil + var history []*RobotPartHistoryEntry + for _, entry := range(resp.History){ + e, err := ProtoToRobotPartHistoryEntry(entry) + if err != nil { + return nil, err + } + history = append(history, e) + } + return history, nil } // UpdaetRobotPart updates a robot part. -func (c *AppClient) UpdateRobotPart(ctx context.Context, id, name string, robotConfig *structpb.Struct) (*pb.RobotPart, error) { +func (c *AppClient) UpdateRobotPart(ctx context.Context, id, name string, robotConfig interface{}) (*RobotPart, error) { + config, err := protoutils.StructToStructPb(robotConfig) + if err != nil { + return nil, err + } resp, err := c.client.UpdateRobotPart(ctx, &pb.UpdateRobotPartRequest{ Id: id, Name: name, - RobotConfig: robotConfig, + RobotConfig: config, }) if err != nil { return nil, err } - return resp.Part, nil + part, err := ProtoToRobotPart(resp.Part) + if err != nil { + return nil, err + } + return part, nil } // NewRobotPart creates a new robot part. @@ -497,14 +536,18 @@ func (c *AppClient) DeleteRobotPart(ctx context.Context, partId string) error { } // GetRobotAPIKeys gets the robot API keys for the robot. -func (c *AppClient) GetRobotAPIKeys(ctx context.Context, robotId string) ([]*pb.APIKeyWithAuthorizations, error) { +func (c *AppClient) GetRobotAPIKeys(ctx context.Context, robotId string) ([]*APIKeyWithAuthorizations, error) { resp, err := c.client.GetRobotAPIKeys(ctx, &pb.GetRobotAPIKeysRequest{ RobotId: robotId, }) if err != nil { return nil, err } - return resp.ApiKeys, nil + var keys []*APIKeyWithAuthorizations + for _, key := range(resp.ApiKeys) { + keys = append(keys, ProtoToAPIKeyWithAuthorizations(key)) + } + return keys, nil } // MarkPartAsMain marks the given part as the main part, and all the others as not. @@ -530,14 +573,18 @@ func (c *AppClient) MarkPartForRestart(ctx context.Context, partId string) error } // CreateRobotPartSecret creates a new generated secret in the robot part. Succeeds if there are no more than 2 active secrets after creation. -func (c *AppClient) CreateRobotPartSecret(ctx context.Context, partId string) (*pb.RobotPart, error) { +func (c *AppClient) CreateRobotPartSecret(ctx context.Context, partId string) (*RobotPart, error) { resp, err := c.client.CreateRobotPartSecret(ctx, &pb.CreateRobotPartSecretRequest{ PartId: partId, }) if err != nil { return nil, err } - return resp.Part, nil + part, err := ProtoToRobotPart(resp.Part) + if err != nil { + return nil, err + } + return part, nil } // DeleteRobotPartSecret deletes a secret from the robot part. @@ -553,14 +600,18 @@ func (c *AppClient) DeleteRobotPartSecret(ctx context.Context, partId, secretId } // ListRobots gets a list of robots under a location. -func (c *AppClient) ListRobots(ctx context.Context, locationId string) ([]*pb.Robot, error) { +func (c *AppClient) ListRobots(ctx context.Context, locationId string) ([]*Robot, error) { resp, err := c.client.ListRobots(ctx, &pb.ListRobotsRequest{ LocationId: locationId, }) if err != nil { return nil, err } - return resp.Robots, nil + var robots []*Robot + for _, robot := range(resp.Robots) { + robots = append(robots, ProtoToRobot(robot)) + } + return robots, nil } // NewRobot creates a new robot. @@ -576,7 +627,7 @@ func (c *AppClient) NewRobot(ctx context.Context, name, location string) (string } // UpdateRobot updates a robot. -func (c *AppClient) UpdateRobot(ctx context.Context, id, name, location string) (*pb.Robot, error) { +func (c *AppClient) UpdateRobot(ctx context.Context, id, name, location string) (*Robot, error) { resp, err := c.client.UpdateRobot(ctx, &pb.UpdateRobotRequest{ Id: id, Name: name, @@ -585,7 +636,7 @@ func (c *AppClient) UpdateRobot(ctx context.Context, id, name, location string) if err != nil { return nil, err } - return resp.Robot, nil + return ProtoToRobot(resp.Robot), nil } // DeleteRobot deletes a robot. @@ -624,10 +675,14 @@ func (c *AppClient) GetFragment(ctx context.Context, id string) (*pb.Fragment, e } // CreateFragment creates a fragment. -func (c *AppClient) CreateFragment(ctx context.Context, name string, config *structpb.Struct, orgId string, visibility *pb.FragmentVisibility) (*pb.Fragment, error) { +func (c *AppClient) CreateFragment(ctx context.Context, name string, config interface{}, orgId string, visibility *pb.FragmentVisibility) (*pb.Fragment, error) { + cfg, err := protoutils.StructToStructPb(config) + if err != nil { + return nil, err + } resp, err := c.client.CreateFragment(ctx, &pb.CreateFragmentRequest{ Name: name, - Config: config, + Config: cfg, OrganizationId: orgId, Visibility: visibility, }) @@ -638,11 +693,15 @@ func (c *AppClient) CreateFragment(ctx context.Context, name string, config *str } // UpdateFragment updates a fragment. -func (c *AppClient) UpdateFragment(ctx context.Context, id, name string, config *structpb.Struct, public *bool, visibility *pb.FragmentVisibility) (*pb.Fragment, error) { +func (c *AppClient) UpdateFragment(ctx context.Context, id, name string, config interface{}, public *bool, visibility *pb.FragmentVisibility) (*pb.Fragment, error) { + cfg, err := protoutils.StructToStructPb(config) + if err != nil { + return nil, err + } resp, err := c.client.UpdateFragment(ctx, &pb.UpdateFragmentRequest{ Id: id, Name: name, - Config: config, + Config: cfg, Public: public, Visibility: visibility, }) diff --git a/app/common.go b/app/common.go new file mode 100644 index 00000000000..dcfbcec6b1e --- /dev/null +++ b/app/common.go @@ -0,0 +1,63 @@ +package app + +import ( + common "go.viam.com/api/common/v1" + "go.viam.com/utils/protoutils" + "google.golang.org/protobuf/types/known/structpb" + "google.golang.org/protobuf/types/known/timestamppb" +) + +type LogEntry struct { + Host string + Level string + Time *timestamppb.Timestamp + LoggerName string + Message string + Caller *map[string]interface{} + Stack string + Fields []*map[string]interface{} +} + +func ProtoToLogEntry(logEntry *common.LogEntry) (*LogEntry, error) { + var fields []*map[string]interface{} + for _, field := range(logEntry.Fields) { + f := field.AsMap() + fields = append(fields, &f) + } + caller := logEntry.Caller.AsMap() + return &LogEntry{ + Host: logEntry.Host, + Level: logEntry.Level, + Time: logEntry.Time, + LoggerName: logEntry.LoggerName, + Message: logEntry.Message, + Caller: &caller, + Stack: logEntry.Stack, + Fields: fields, + }, nil +} + +func LogEntryToProto(logEntry *LogEntry) (*common.LogEntry, error) { + var fields []*structpb.Struct + for _, field := range(logEntry.Fields) { + f, err := protoutils.StructToStructPb(field) + if err != nil { + return nil, err + } + fields = append(fields, f) + } + caller, err := protoutils.StructToStructPb(logEntry.Caller) + if err != nil { + return nil, err + } + return &common.LogEntry{ + Host: logEntry.Host, + Level: logEntry.Level, + Time: logEntry.Time, + LoggerName: logEntry.LoggerName, + Message: logEntry.Message, + Caller: caller, + Stack: logEntry.Stack, + Fields: fields, + }, nil +} diff --git a/app/log_stream.go b/app/log_stream.go index 5442d169656..a7f31e2496a 100644 --- a/app/log_stream.go +++ b/app/log_stream.go @@ -5,7 +5,6 @@ import ( "sync" pb "go.viam.com/api/app/v1" - common "go.viam.com/api/common/v1" "go.viam.com/utils" ) @@ -18,7 +17,7 @@ type logStream struct { } -func (s *logStream) startStream(ctx context.Context, id string, errorsOnly bool, filter *string, ch chan []*common.LogEntry) error { +func (s *logStream) startStream(ctx context.Context, id string, errorsOnly bool, filter *string, ch chan []*LogEntry) error { s.streamMu.Lock() defer s.streamMu.Unlock() @@ -61,7 +60,7 @@ func (s *logStream) startStream(ctx context.Context, id string, errorsOnly bool, return nil } -func (s *logStream) receiveFromStream(ctx context.Context, stream pb.AppService_TailRobotPartLogsClient, ch chan []*common.LogEntry) { +func (s *logStream) receiveFromStream(ctx context.Context, stream pb.AppService_TailRobotPartLogsClient, ch chan []*LogEntry) { defer s.streamCancel() // repeatly receive from the stream @@ -79,6 +78,15 @@ func (s *logStream) receiveFromStream(ctx context.Context, stream pb.AppService_ return } // If there is a response, send to the logs channel. - ch <- streamResp.Logs + var logs []*LogEntry + for _, log := range(streamResp.Logs) { + l, err := ProtoToLogEntry(log) + if err != nil { + s.client.logger.Debug(err) + return + } + logs = append(logs, l) + } + ch <- logs } } diff --git a/app/robot.go b/app/robot.go new file mode 100644 index 00000000000..cfc41f1ac53 --- /dev/null +++ b/app/robot.go @@ -0,0 +1,325 @@ +package app + +import ( + "fmt" + + pb "go.viam.com/api/app/v1" + "go.viam.com/utils/protoutils" + "google.golang.org/protobuf/types/known/timestamppb" +) + +type Robot struct { + Id string + Name string + Location string + LastAccess *timestamppb.Timestamp + CreatedOn *timestamppb.Timestamp +} + +func ProtoToRobot(robot *pb.Robot) *Robot { + return &Robot{ + Id: robot.Id, + Name: robot.Name, + Location: robot.Location, + LastAccess: robot.LastAccess, + CreatedOn: robot.CreatedOn, + } +} + +func RobotToProto(robot *Robot) *pb.Robot { + return &pb.Robot{ + Id: robot.Id, + Name: robot.Name, + Location: robot.Location, + LastAccess: robot.LastAccess, + CreatedOn: robot.CreatedOn, + } +} + +type RoverRentalRobot struct { + RobotId string + LocationId string + RobotName string + RobotMainPartId string +} + +func ProtoToRoverRentalRobot(rrRobot *pb.RoverRentalRobot) *RoverRentalRobot { + return &RoverRentalRobot{ + RobotId: rrRobot.RobotId, + LocationId: rrRobot.LocationId, + RobotName: rrRobot.RobotName, + RobotMainPartId: rrRobot.RobotMainPartId, + } +} + +func RoverRentalRobotToProto(rrRobot *RoverRentalRobot) *pb.RoverRentalRobot { + return &pb.RoverRentalRobot{ + RobotId: rrRobot.RobotId, + LocationId: rrRobot.LocationId, + RobotName: rrRobot.RobotName, + RobotMainPartId: rrRobot.RobotMainPartId, + } +} + +type RobotPart struct { + Id string + Name string + DnsName string + Secret string + Robot string + LocationId string + RobotConfig map[string]interface{} + LastAccess *timestamppb.Timestamp + UserSuppliedInfo map[string]interface{} + MainPart bool + Fqdn string + LocalFqdn string + CreatedOn *timestamppb.Timestamp + Secrets []*SharedSecret + LastUpdated *timestamppb.Timestamp +} + +func ProtoToRobotPart(robotPart *pb.RobotPart) (*RobotPart, error) { + var secrets []*SharedSecret + for _, secret := range(robotPart.Secrets) { + s, err := ProtoToSharedSecret(secret) + if err != nil { + return nil, err + } + secrets = append(secrets, s) + } + return &RobotPart{ + Id: robotPart.Id, + Name: robotPart.Name, + DnsName: robotPart.DnsName, + Secret: robotPart.Secret, + Robot: robotPart.DnsName, + LocationId: robotPart.LocationId, + RobotConfig: robotPart.RobotConfig.AsMap(), + LastAccess: robotPart.LastAccess, + UserSuppliedInfo: robotPart.UserSuppliedInfo.AsMap(), + MainPart: robotPart.MainPart, + Fqdn: robotPart.Fqdn, + LocalFqdn: robotPart.LocalFqdn, + CreatedOn: robotPart.CreatedOn, + Secrets: secrets, + LastUpdated: robotPart.LastUpdated, + }, nil +} + +func RobotPartToProto(robotPart *RobotPart) (*pb.RobotPart, error) { + var secrets []*pb.SharedSecret + for _, secret := range(robotPart.Secrets) { + s, err := SharedSecretToProto(secret) + if err != nil { + return nil, err + } + secrets = append(secrets, s) + } + robotConfig, err := protoutils.StructToStructPb(robotPart.RobotConfig) + if err != nil { + return nil, err + } + userSuppliedInfo, err := protoutils.StructToStructPb(robotPart.UserSuppliedInfo) + if err != nil { + return nil, err + } + return &pb.RobotPart{ + Id: robotPart.Id, + Name: robotPart.Name, + DnsName: robotPart.DnsName, + Secret: robotPart.Secret, + Robot: robotPart.DnsName, + LocationId: robotPart.LocationId, + RobotConfig: robotConfig, + LastAccess: robotPart.LastAccess, + UserSuppliedInfo: userSuppliedInfo, + MainPart: robotPart.MainPart, + Fqdn: robotPart.Fqdn, + LocalFqdn: robotPart.LocalFqdn, + CreatedOn: robotPart.CreatedOn, + Secrets: secrets, + LastUpdated: robotPart.LastUpdated, + }, nil +} + +type RobotPartHistoryEntry struct { + Part string + Robot string + When *timestamppb.Timestamp + Old *RobotPart + EditedBy *AuthenticatorInfo +} + +func ProtoToRobotPartHistoryEntry(entry *pb.RobotPartHistoryEntry) (*RobotPartHistoryEntry, error) { + old, err := ProtoToRobotPart(entry.Old) + if err != nil { + return nil, err + } + info, err := ProtoToAuthenticatorInfo(entry.EditedBy) + if err != nil { + return nil, err + } + return &RobotPartHistoryEntry{ + Part: entry.Part, + Robot: entry.Robot, + When: entry.When, + Old: old, + EditedBy: info, + }, nil +} + +type AuthenticatorInfo struct { + Type AuthenticationType + Value string + IsDeactivated bool +} + +func ProtoToAuthenticatorInfo(info *pb.AuthenticatorInfo) (*AuthenticatorInfo, error){ + authenticationType, err := ProtoToAuthenticationType(info.Type) + if err != nil { + return nil, err + } + return &AuthenticatorInfo{ + Type: authenticationType, + Value: info.Value, + IsDeactivated: info.IsDeactivated, + }, nil +} + +func AuthenticatorInfoToProto(info *AuthenticatorInfo) (*pb.AuthenticatorInfo, error){ + authenticationType, err := AuthenticationTypeToProto(info.Type) + if err != nil { + return nil, err + } + return &pb.AuthenticatorInfo{ + Type: authenticationType, + Value: info.Value, + IsDeactivated: info.IsDeactivated, + }, nil +} + +type AuthenticationType int32 + +const ( + AuthenticationType_AUTHENTICATION_TYPE_UNSPECIFIED AuthenticationType = 0 + AuthenticationType_AUTHENTICATION_TYPE_WEB_OAUTH AuthenticationType = 1 + AuthenticationType_AUTHENTICATION_TYPE_API_KEY AuthenticationType = 2 + AuthenticationType_AUTHENTICATION_TYPE_ROBOT_PART_SECRET AuthenticationType = 3 + AuthenticationType_AUTHENTICATION_TYPE_LOCATION_SECRET AuthenticationType = 4 +) + + +func ProtoToAuthenticationType(authenticationType pb.AuthenticationType) (AuthenticationType, error) { + switch authenticationType{ + case pb.AuthenticationType_AUTHENTICATION_TYPE_UNSPECIFIED: + return AuthenticationType_AUTHENTICATION_TYPE_UNSPECIFIED, nil + case pb.AuthenticationType_AUTHENTICATION_TYPE_WEB_OAUTH: + return AuthenticationType_AUTHENTICATION_TYPE_WEB_OAUTH, nil + case pb.AuthenticationType_AUTHENTICATION_TYPE_API_KEY: + return AuthenticationType_AUTHENTICATION_TYPE_API_KEY, nil + case pb.AuthenticationType_AUTHENTICATION_TYPE_ROBOT_PART_SECRET: + return AuthenticationType_AUTHENTICATION_TYPE_ROBOT_PART_SECRET, nil + case pb.AuthenticationType_AUTHENTICATION_TYPE_LOCATION_SECRET: + return AuthenticationType_AUTHENTICATION_TYPE_LOCATION_SECRET, nil + default: + return 0, fmt.Errorf("uknown secret state: %v", authenticationType) + } +} + +func AuthenticationTypeToProto(authenticationType AuthenticationType) (pb.AuthenticationType, error) { + switch authenticationType{ + case AuthenticationType_AUTHENTICATION_TYPE_UNSPECIFIED: + return pb.AuthenticationType_AUTHENTICATION_TYPE_UNSPECIFIED, nil + case AuthenticationType_AUTHENTICATION_TYPE_WEB_OAUTH: + return pb.AuthenticationType_AUTHENTICATION_TYPE_WEB_OAUTH, nil + case AuthenticationType_AUTHENTICATION_TYPE_API_KEY: + return pb.AuthenticationType_AUTHENTICATION_TYPE_API_KEY, nil + case AuthenticationType_AUTHENTICATION_TYPE_ROBOT_PART_SECRET: + return pb.AuthenticationType_AUTHENTICATION_TYPE_ROBOT_PART_SECRET, nil + case AuthenticationType_AUTHENTICATION_TYPE_LOCATION_SECRET: + return pb.AuthenticationType_AUTHENTICATION_TYPE_LOCATION_SECRET, nil + default: + return 0, fmt.Errorf("unknown secret state: %v", authenticationType) + } +} + +type APIKeyWithAuthorizations struct { + ApiKey *APIKey + Authorizations []*AuthorizationDetails +} + +func ProtoToAPIKeyWithAuthorizations(key *pb.APIKeyWithAuthorizations) *APIKeyWithAuthorizations { + var details []*AuthorizationDetails + for _, detail := range(key.Authorizations){ + details = append(details, ProtoToAuthorizationDetails(detail)) + } + return &APIKeyWithAuthorizations{ + ApiKey: ProtoToAPIKey(key.ApiKey), + Authorizations: details, + } +} + +func APIKeyWithAuthorizationsToProto(key *APIKeyWithAuthorizations) *pb.APIKeyWithAuthorizations { + var details []*pb.AuthorizationDetails + for _, detail := range(key.Authorizations){ + details = append(details, AuthorizationDetailsToProto(detail)) + } + return &pb.APIKeyWithAuthorizations{ + ApiKey: APIKeyToProto(key.ApiKey), + Authorizations: details, + } +} + +type APIKey struct { + Id string + Key string + Name string + CreatedOn *timestamppb.Timestamp +} + +func ProtoToAPIKey(key *pb.APIKey) *APIKey { + return &APIKey{ + Id: key.Id, + Key: key.Key, + Name: key.Name, + CreatedOn: key.CreatedOn, + } +} + +func APIKeyToProto(key *APIKey) *pb.APIKey { + return &pb.APIKey{ + Id: key.Id, + Key: key.Key, + Name: key.Name, + CreatedOn: key.CreatedOn, + } +} + +type AuthorizationDetails struct { + AuthorizationType string + AuthorizationId string + ResourceType string + ResourceId string + OrgId string +} + +func ProtoToAuthorizationDetails(details *pb.AuthorizationDetails) *AuthorizationDetails { + return &AuthorizationDetails{ + AuthorizationType: details.AuthorizationType, + AuthorizationId: details.AuthorizationId, + ResourceType: details.ResourceType, + ResourceId: details.ResourceId, + OrgId: details.OrgId, + } +} + +func AuthorizationDetailsToProto(details *AuthorizationDetails) *pb.AuthorizationDetails { + return &pb.AuthorizationDetails{ + AuthorizationType: details.AuthorizationType, + AuthorizationId: details.AuthorizationId, + ResourceType: details.ResourceType, + ResourceId: details.ResourceId, + OrgId: details.OrgId, + } +} From b00b8d216ecf119b519ee65eef2d73194c195681 Mon Sep 17 00:00:00 2001 From: purplenicole730 Date: Tue, 12 Nov 2024 12:53:55 -0500 Subject: [PATCH 23/75] use Authorization wrapper --- app/app_client.go | 30 +++++++++++++++++++++++------- 1 file changed, 23 insertions(+), 7 deletions(-) diff --git a/app/app_client.go b/app/app_client.go index a7ce61c39b1..f26217d12f6 100644 --- a/app/app_client.go +++ b/app/app_client.go @@ -162,11 +162,15 @@ func (c *AppClient) ListOrganizationMembers(ctx context.Context, orgId string) ( } // CreateOrganizaitonInvite creates an organization invite to an organization. -func (c *AppClient) CreateOrganizationInvite(ctx context.Context, orgId, email string, authorizations []*pb.Authorization, sendEmailInvite *bool) (*OrganizationInvite, error) { +func (c *AppClient) CreateOrganizationInvite(ctx context.Context, orgId, email string, authorizations []*Authorization, sendEmailInvite *bool) (*OrganizationInvite, error) { + var pbAuthorizations []*pb.Authorization + for _, authorization := range(authorizations) { + pbAuthorizations = append(pbAuthorizations, AuthorizationToProto(authorization)) + } resp, err := c.client.CreateOrganizationInvite(ctx, &pb.CreateOrganizationInviteRequest{ OrganizationId: orgId, Email: email, - Authorizations: authorizations, + Authorizations: pbAuthorizations, SendEmailInvite: sendEmailInvite, }) if err != nil { @@ -176,12 +180,20 @@ func (c *AppClient) CreateOrganizationInvite(ctx context.Context, orgId, email s } // UpdateOrganizationInviteAuthorizations updates the authorizations attached to an organization invite. -func (c *AppClient) UpdateOrganizationInviteAuthorizations(ctx context.Context, orgId, email string, addAuthorizations, removeAuthorizations []*pb.Authorization) (*OrganizationInvite, error) { +func (c *AppClient) UpdateOrganizationInviteAuthorizations(ctx context.Context, orgId, email string, addAuthorizations, removeAuthorizations []*Authorization) (*OrganizationInvite, error) { + var pbAddAuthorizations []*pb.Authorization + for _, authorization := range(addAuthorizations) { + pbAddAuthorizations = append(pbAddAuthorizations, AuthorizationToProto(authorization)) + } + var pbRemoveAuthorizations []*pb.Authorization + for _, authorization := range(removeAuthorizations) { + pbRemoveAuthorizations = append(pbRemoveAuthorizations, AuthorizationToProto(authorization)) + } resp, err := c.client.UpdateOrganizationInviteAuthorizations(ctx, &pb.UpdateOrganizationInviteAuthorizationsRequest{ OrganizationId: orgId, Email: email, - AddAuthorizations: addAuthorizations, - RemoveAuthorizations: removeAuthorizations, + AddAuthorizations: pbAddAuthorizations, + RemoveAuthorizations: pbRemoveAuthorizations, }) if err != nil { return nil, err @@ -817,7 +829,7 @@ func (c *AppClient) ChangeRole(ctx context.Context, oldOrgId, oldIdentityId, old } // listAuthorizations returns all authorization roles for any given resources. If no resources are given, all resources within the organization will be included. -func (c *AppClient) ListAuthorizations(ctx context.Context, orgId string, resourceIds []string) ([]*pb.Authorization, error) { +func (c *AppClient) ListAuthorizations(ctx context.Context, orgId string, resourceIds []string) ([]*Authorization, error) { resp, err := c.client.ListAuthorizations(ctx, &pb.ListAuthorizationsRequest{ OrganizationId: orgId, ResourceIds: resourceIds, @@ -825,7 +837,11 @@ func (c *AppClient) ListAuthorizations(ctx context.Context, orgId string, resour if err != nil { return nil, err } - return resp.Authorizations, nil + var authorizations []*Authorization + for _, authorization := range(resp.Authorizations) { + authorizations = append(authorizations, ProtoToAuthorization(authorization)) + } + return authorizations, nil } // CheckPermissions checks the validity of a list of permissions. From 2434d2e32f8ee30bd46d12fd42adce2bffeb3d6a Mon Sep 17 00:00:00 2001 From: purplenicole730 Date: Tue, 12 Nov 2024 14:04:41 -0500 Subject: [PATCH 24/75] fix --- app/location.go | 30 +++++++++++++++++++++--------- app/robot.go | 14 ++++++++------ 2 files changed, 29 insertions(+), 15 deletions(-) diff --git a/app/location.go b/app/location.go index 852a18ad481..8a252ef07a0 100644 --- a/app/location.go +++ b/app/location.go @@ -15,7 +15,7 @@ type Location struct { Organizations []*LocationOrganization CreatedOn *timestamppb.Timestamp RobotCount int32 - Config *pb.StorageConfig + Config *StorageConfig } func ProtoToLocation(location *pb.Location) (*Location, error) { @@ -35,7 +35,7 @@ func ProtoToLocation(location *pb.Location) (*Location, error) { Organizations: organizations, CreatedOn: location.CreatedOn, RobotCount: location.RobotCount, - Config: location.Config, + Config: ProtoToStorageConfig(location.Config), }, nil } @@ -56,7 +56,7 @@ func LocationToProto(location *Location) (*pb.Location, error) { Organizations: organizations, CreatedOn: location.CreatedOn, RobotCount: location.RobotCount, - Config: location.Config, + Config: StorageConfigToProto(location.Config), }, nil } @@ -79,6 +79,18 @@ func LocationOrganizationToProto(locationOrganization *LocationOrganization) *pb } } +type StorageConfig struct { + Region string +} + +func ProtoToStorageConfig(config *pb.StorageConfig) *StorageConfig { + return &StorageConfig{Region: config.Region} +} + +func StorageConfigToProto(config *StorageConfig) *pb.StorageConfig { + return &pb.StorageConfig{Region: config.Region} +} + type LocationAuth struct { LocationId string Secrets []*SharedSecret @@ -152,8 +164,8 @@ const ( SharedSecret_STATE_DISABLED SharedSecret_State = 2 ) -func ProtoToSharedSecretState(sharedSecretState pb.SharedSecret_State) (SharedSecret_State, error) { - switch sharedSecretState{ +func ProtoToSharedSecretState(state pb.SharedSecret_State) (SharedSecret_State, error) { + switch state{ case pb.SharedSecret_STATE_UNSPECIFIED: return SharedSecret_STATE_UNSPECIFIED, nil case pb.SharedSecret_STATE_ENABLED: @@ -161,12 +173,12 @@ func ProtoToSharedSecretState(sharedSecretState pb.SharedSecret_State) (SharedSe case pb.SharedSecret_STATE_DISABLED: return SharedSecret_STATE_DISABLED, nil default: - return 0, fmt.Errorf("uknown secret state: %v", sharedSecretState) + return 0, fmt.Errorf("uknown secret state: %v", state) } } -func SharedSecretStateToProto(sharedSecretState SharedSecret_State) (pb.SharedSecret_State, error) { - switch sharedSecretState{ +func SharedSecretStateToProto(state SharedSecret_State) (pb.SharedSecret_State, error) { + switch state{ case SharedSecret_STATE_UNSPECIFIED: return pb.SharedSecret_STATE_UNSPECIFIED, nil case SharedSecret_STATE_ENABLED: @@ -174,6 +186,6 @@ func SharedSecretStateToProto(sharedSecretState SharedSecret_State) (pb.SharedSe case SharedSecret_STATE_DISABLED: return pb.SharedSecret_STATE_DISABLED, nil default: - return 0, fmt.Errorf("unknown secret state: %v", sharedSecretState) + return 0, fmt.Errorf("unknown secret state: %v", state) } } diff --git a/app/robot.go b/app/robot.go index cfc41f1ac53..a5a05648848 100644 --- a/app/robot.go +++ b/app/robot.go @@ -68,9 +68,9 @@ type RobotPart struct { Secret string Robot string LocationId string - RobotConfig map[string]interface{} + RobotConfig *map[string]interface{} LastAccess *timestamppb.Timestamp - UserSuppliedInfo map[string]interface{} + UserSuppliedInfo *map[string]interface{} MainPart bool Fqdn string LocalFqdn string @@ -88,6 +88,8 @@ func ProtoToRobotPart(robotPart *pb.RobotPart) (*RobotPart, error) { } secrets = append(secrets, s) } + cfg := robotPart.RobotConfig.AsMap() + info := robotPart.UserSuppliedInfo.AsMap() return &RobotPart{ Id: robotPart.Id, Name: robotPart.Name, @@ -95,9 +97,9 @@ func ProtoToRobotPart(robotPart *pb.RobotPart) (*RobotPart, error) { Secret: robotPart.Secret, Robot: robotPart.DnsName, LocationId: robotPart.LocationId, - RobotConfig: robotPart.RobotConfig.AsMap(), + RobotConfig: &cfg, LastAccess: robotPart.LastAccess, - UserSuppliedInfo: robotPart.UserSuppliedInfo.AsMap(), + UserSuppliedInfo: &info, MainPart: robotPart.MainPart, Fqdn: robotPart.Fqdn, LocalFqdn: robotPart.LocalFqdn, @@ -223,7 +225,7 @@ func ProtoToAuthenticationType(authenticationType pb.AuthenticationType) (Authen case pb.AuthenticationType_AUTHENTICATION_TYPE_LOCATION_SECRET: return AuthenticationType_AUTHENTICATION_TYPE_LOCATION_SECRET, nil default: - return 0, fmt.Errorf("uknown secret state: %v", authenticationType) + return 0, fmt.Errorf("uknown authentication type: %v", authenticationType) } } @@ -240,7 +242,7 @@ func AuthenticationTypeToProto(authenticationType AuthenticationType) (pb.Authen case AuthenticationType_AUTHENTICATION_TYPE_LOCATION_SECRET: return pb.AuthenticationType_AUTHENTICATION_TYPE_LOCATION_SECRET, nil default: - return 0, fmt.Errorf("unknown secret state: %v", authenticationType) + return 0, fmt.Errorf("unknown authentication type: %v", authenticationType) } } From 1f3fd68cc443a8cb1c636c13b8d225aa10ea172b Mon Sep 17 00:00:00 2001 From: purplenicole730 Date: Tue, 12 Nov 2024 14:04:49 -0500 Subject: [PATCH 25/75] add fragment wrappers --- app/app_client.go | 76 ++++++++++++++++++----- app/fragment.go | 152 ++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 214 insertions(+), 14 deletions(-) create mode 100644 app/fragment.go diff --git a/app/app_client.go b/app/app_client.go index f26217d12f6..aa506f5a8b5 100644 --- a/app/app_client.go +++ b/app/app_client.go @@ -663,49 +663,77 @@ func (c *AppClient) DeleteRobot(ctx context.Context, id string) error { } // ListFragments gets a list of fragments. -func (c *AppClient) ListFragments(ctx context.Context, orgId string, showPublic bool, fragmentVisibility []pb.FragmentVisibility) ([]*pb.Fragment, error) { +func (c *AppClient) ListFragments(ctx context.Context, orgId string, showPublic bool, fragmentVisibility []FragmentVisibility) ([]*Fragment, error) { + var visibilities []pb.FragmentVisibility + for _, visibility := range(fragmentVisibility) { + v, err := FragmentVisibilityToProto(visibility) + if err != nil { + return nil, err + } + visibilities = append(visibilities, v) + } resp, err := c.client.ListFragments(ctx, &pb.ListFragmentsRequest{ OrganizationId: orgId, ShowPublic: showPublic, - FragmentVisibility: fragmentVisibility, + FragmentVisibility: visibilities, }) if err != nil { return nil, err } - return resp.Fragments, nil + var fragments []*Fragment + for _, fragment := range(resp.Fragments) { + f, err := ProtoToFragment(fragment) + if err != nil { + return nil, err + } + fragments = append(fragments, f) + } + return fragments, nil } // GetFragment gets a single fragment. -func (c *AppClient) GetFragment(ctx context.Context, id string) (*pb.Fragment, error) { +func (c *AppClient) GetFragment(ctx context.Context, id string) (*Fragment, error) { resp, err := c.client.GetFragment(ctx, &pb.GetFragmentRequest{ Id: id, }) if err != nil { return nil, err } - return resp.Fragment, nil + fragment, err := ProtoToFragment(resp.Fragment) + if err != nil { + return nil, err + } + return fragment, nil } // CreateFragment creates a fragment. -func (c *AppClient) CreateFragment(ctx context.Context, name string, config interface{}, orgId string, visibility *pb.FragmentVisibility) (*pb.Fragment, error) { +func (c *AppClient) CreateFragment(ctx context.Context, name string, config interface{}, orgId string, visibility *FragmentVisibility) (*Fragment, error) { cfg, err := protoutils.StructToStructPb(config) if err != nil { return nil, err } + v, err := FragmentVisibilityToProto(*visibility) + if err != nil { + return nil, err + } resp, err := c.client.CreateFragment(ctx, &pb.CreateFragmentRequest{ Name: name, Config: cfg, OrganizationId: orgId, - Visibility: visibility, + Visibility: &v, }) if err != nil { return nil, err } - return resp.Fragment, nil + fragment, err := ProtoToFragment(resp.Fragment) + if err != nil { + return nil, err + } + return fragment, nil } // UpdateFragment updates a fragment. -func (c *AppClient) UpdateFragment(ctx context.Context, id, name string, config interface{}, public *bool, visibility *pb.FragmentVisibility) (*pb.Fragment, error) { +func (c *AppClient) UpdateFragment(ctx context.Context, id, name string, config interface{}, public *bool, visibility *pb.FragmentVisibility) (*Fragment, error) { cfg, err := protoutils.StructToStructPb(config) if err != nil { return nil, err @@ -720,7 +748,11 @@ func (c *AppClient) UpdateFragment(ctx context.Context, id, name string, config if err != nil { return nil, err } - return resp.Fragment, nil + fragment, err := ProtoToFragment(resp.Fragment) + if err != nil { + return nil, err + } + return fragment, nil } // DeleteFragment deletes a fragment. @@ -735,7 +767,7 @@ func (c *AppClient) DeleteFragment(ctx context.Context, id string) error { } // ListMachineFragments gets top level and nested fragments for a amchine, as well as any other fragments specified by IDs. Additional fragments are useful when needing to view fragments that will be provisionally added to the machine alongside existing fragments. -func (c *AppClient) ListMachineFragments(ctx context.Context, machineId string, additionalFragmentIds []string) ([]*pb.Fragment, error) { +func (c *AppClient) ListMachineFragments(ctx context.Context, machineId string, additionalFragmentIds []string) ([]*Fragment, error) { resp, err := c.client.ListMachineFragments(ctx, &pb.ListMachineFragmentsRequest{ MachineId: machineId, AdditionalFragmentIds: additionalFragmentIds, @@ -743,11 +775,19 @@ func (c *AppClient) ListMachineFragments(ctx context.Context, machineId string, if err != nil { return nil, err } - return resp.Fragments, nil + var fragments []*Fragment + for _, fragment := range(resp.Fragments) { + f, err := ProtoToFragment(fragment) + if err != nil { + return nil, err + } + fragments = append(fragments, f) + } + return fragments, nil } // GetFragmentHistory gets the fragment's history. -func (c *AppClient) GetFragmentHistory(ctx context.Context, id string, pageToken *string, pageLimit *int64) ([]*pb.FragmentHistoryEntry, string, error) { +func (c *AppClient) GetFragmentHistory(ctx context.Context, id string, pageToken *string, pageLimit *int64) ([]*FragmentHistoryEntry, string, error) { resp, err := c.client.GetFragmentHistory(ctx, &pb.GetFragmentHistoryRequest{ Id: id, PageToken: pageToken, @@ -756,7 +796,15 @@ func (c *AppClient) GetFragmentHistory(ctx context.Context, id string, pageToken if err != nil { return nil, "", err } - return resp.History, resp.NextPageToken, nil + var history []*FragmentHistoryEntry + for _, entry := range(resp.History) { + e, err := ProtoToFragmentHistoryEntry(entry) + if err != nil { + return nil, "", err + } + history = append(history, e) + } + return history, resp.NextPageToken, nil } func createAuthorization(orgId, identityId, identityType, role, resourceType, resourceId string) (*pb.Authorization, error) { diff --git a/app/fragment.go b/app/fragment.go new file mode 100644 index 00000000000..fbda3621471 --- /dev/null +++ b/app/fragment.go @@ -0,0 +1,152 @@ +package app + +import ( + "fmt" + + pb "go.viam.com/api/app/v1" + "go.viam.com/utils/protoutils" + "google.golang.org/protobuf/types/known/timestamppb" +) + +type Fragment struct { + Id string + Name string + Fragment *map[string]interface{} + OrganizationOwner string + Public bool + CreatedOn *timestamppb.Timestamp + OrganizationName string + RobotPartCount int32 + OrganizationCount int32 + OnlyUsedByOwner bool + Visibility FragmentVisibility + LastUpdated *timestamppb.Timestamp +} + +func ProtoToFragment(fragment *pb.Fragment) (*Fragment, error) { + f := fragment.Fragment.AsMap() + visibility, err := ProtoToFragmentVisibility(fragment.Visibility) + if err != nil { + return nil, err + } + return &Fragment{ + Id: fragment.Id, + Name: fragment.Name, + Fragment: &f, + OrganizationOwner: fragment.OrganizationOwner, + Public: fragment.Public, + CreatedOn: fragment.CreatedOn, + OrganizationName: fragment.OrganizationName, + RobotPartCount: fragment.RobotPartCount, + OrganizationCount: fragment.OrganizationCount, + OnlyUsedByOwner: fragment.OnlyUsedByOwner, + Visibility: visibility, + LastUpdated: fragment.LastUpdated, + }, nil +} + +func FragmentToProto(fragment *Fragment) (*pb.Fragment, error) { + f, err := protoutils.StructToStructPb(fragment.Fragment) + if err != nil { + return nil, err + } + visibility, err := FragmentVisibilityToProto(fragment.Visibility) + if err != nil { + return nil, err + } + return &pb.Fragment{ + Id: fragment.Id, + Name: fragment.Name, + Fragment: f, + OrganizationOwner: fragment.OrganizationOwner, + Public: fragment.Public, + CreatedOn: fragment.CreatedOn, + OrganizationName: fragment.OrganizationName, + RobotPartCount: fragment.RobotPartCount, + OrganizationCount: fragment.OrganizationCount, + OnlyUsedByOwner: fragment.OnlyUsedByOwner, + Visibility: visibility, + LastUpdated: fragment.LastUpdated, + }, nil +} + +type FragmentVisibility int32 + +const ( + FragmentVisibility_FRAGMENT_VISIBILITY_UNSPECIFIED FragmentVisibility = 0 + FragmentVisibility_FRAGMENT_VISIBILITY_PRIVATE FragmentVisibility = 1 + FragmentVisibility_FRAGMENT_VISIBILITY_PUBLIC FragmentVisibility = 2 + FragmentVisibility_FRAGMENT_VISIBILITY_PUBLIC_UNLISTED FragmentVisibility = 3 +) + +func ProtoToFragmentVisibility(visibility pb.FragmentVisibility) (FragmentVisibility, error) { + switch visibility{ + case pb.FragmentVisibility_FRAGMENT_VISIBILITY_UNSPECIFIED: + return FragmentVisibility_FRAGMENT_VISIBILITY_UNSPECIFIED, nil + case pb.FragmentVisibility_FRAGMENT_VISIBILITY_PRIVATE: + return FragmentVisibility_FRAGMENT_VISIBILITY_PRIVATE, nil + case pb.FragmentVisibility_FRAGMENT_VISIBILITY_PUBLIC: + return FragmentVisibility_FRAGMENT_VISIBILITY_PUBLIC, nil + case pb.FragmentVisibility_FRAGMENT_VISIBILITY_PUBLIC_UNLISTED: + return FragmentVisibility_FRAGMENT_VISIBILITY_PUBLIC_UNLISTED, nil + default: + return 0, fmt.Errorf("uknown fragment visibililty: %v", visibility) + } +} + +func FragmentVisibilityToProto(visibility FragmentVisibility) (pb.FragmentVisibility, error) { + switch visibility{ + case FragmentVisibility_FRAGMENT_VISIBILITY_UNSPECIFIED: + return pb.FragmentVisibility_FRAGMENT_VISIBILITY_UNSPECIFIED, nil + case FragmentVisibility_FRAGMENT_VISIBILITY_PRIVATE: + return pb.FragmentVisibility_FRAGMENT_VISIBILITY_PRIVATE, nil + case FragmentVisibility_FRAGMENT_VISIBILITY_PUBLIC: + return pb.FragmentVisibility_FRAGMENT_VISIBILITY_PUBLIC, nil + case FragmentVisibility_FRAGMENT_VISIBILITY_PUBLIC_UNLISTED: + return pb.FragmentVisibility_FRAGMENT_VISIBILITY_PUBLIC_UNLISTED, nil + default: + return 0, fmt.Errorf("unknown fragment visibility: %v", visibility) + } +} + +type FragmentHistoryEntry struct { + Fragment string + EditedOn *timestamppb.Timestamp + Old *Fragment + EditedBy *AuthenticatorInfo +} + +func ProtoToFragmentHistoryEntry(entry *pb.FragmentHistoryEntry) (*FragmentHistoryEntry, error) { + old, err := ProtoToFragment(entry.Old) + if err != nil { + return nil, err + } + editedBy, err := ProtoToAuthenticatorInfo(entry.EditedBy) + if err != nil { + return nil, err + } + return &FragmentHistoryEntry{ + Fragment: entry.Fragment, + EditedOn: entry.EditedOn, + Old: old, + EditedBy: editedBy, + }, nil +} + +func FragmentHistoryEntryToProto(entry *FragmentHistoryEntry) (*pb.FragmentHistoryEntry, error) { + old, err := FragmentToProto(entry.Old) + if err != nil { + return nil, err + } + editedBy, err := AuthenticatorInfoToProto(entry.EditedBy) + if err != nil { + return nil, err + } + return &pb.FragmentHistoryEntry{ + Fragment: entry.Fragment, + EditedOn: entry.EditedOn, + Old: old, + EditedBy: editedBy, + }, nil +} + From 6304af049a73781119c58d3d26dc26c8f0a863c8 Mon Sep 17 00:00:00 2001 From: purplenicole730 Date: Tue, 12 Nov 2024 14:26:21 -0500 Subject: [PATCH 26/75] add authorizedpermissions --- app/app_client.go | 16 +++++++++++++--- app/organization.go | 22 ++++++++++++++++++++++ 2 files changed, 35 insertions(+), 3 deletions(-) diff --git a/app/app_client.go b/app/app_client.go index aa506f5a8b5..058f4cc1e02 100644 --- a/app/app_client.go +++ b/app/app_client.go @@ -893,14 +893,24 @@ func (c *AppClient) ListAuthorizations(ctx context.Context, orgId string, resour } // CheckPermissions checks the validity of a list of permissions. -func (c *AppClient) CheckPermissions(ctx context.Context, permissions []*pb.AuthorizedPermissions) ([]*pb.AuthorizedPermissions, error) { +func (c *AppClient) CheckPermissions(ctx context.Context, permissions []*AuthorizedPermissions) ([]*AuthorizedPermissions, error) { + var pbPermissions []*pb.AuthorizedPermissions + for _, permission := range(permissions){ + pbPermissions = append(pbPermissions, AuthorizedPermissionsToProto(permission)) + } + resp, err := c.client.CheckPermissions(ctx, &pb.CheckPermissionsRequest{ - Permissions: permissions, + Permissions: pbPermissions, }) if err != nil { return nil, err } - return resp.AuthorizedPermissions, nil + + var authorizedPermissions []*AuthorizedPermissions + for _, permission := range(resp.AuthorizedPermissions){ + authorizedPermissions = append(authorizedPermissions, ProtoToAuthorizedPermissions(permission)) + } + return authorizedPermissions, nil } // GetRegistryItem gets a registry item. diff --git a/app/organization.go b/app/organization.go index 98fc1d607a4..53caa8bac79 100644 --- a/app/organization.go +++ b/app/organization.go @@ -165,3 +165,25 @@ func AuthorizationToProto(authorization *Authorization) *pb.Authorization { IdentityType: authorization.IdentityType, } } + +type AuthorizedPermissions struct { + ResourceType string + ResourceId string + Permissions []string +} + +func ProtoToAuthorizedPermissions(permissions *pb.AuthorizedPermissions) *AuthorizedPermissions { + return &AuthorizedPermissions{ + ResourceType: permissions.ResourceType, + ResourceId: permissions.ResourceId, + Permissions: permissions.Permissions, + } +} + +func AuthorizedPermissionsToProto(permissions *AuthorizedPermissions) *pb.AuthorizedPermissions { + return &pb.AuthorizedPermissions{ + ResourceType: permissions.ResourceType, + ResourceId: permissions.ResourceId, + Permissions: permissions.Permissions, + } +} From ab8ee89ba3ccef54f9889e62842c85c7a1ea675f Mon Sep 17 00:00:00 2001 From: purplenicole730 Date: Tue, 12 Nov 2024 17:22:39 -0500 Subject: [PATCH 27/75] add authorization and registry item proto wrappers --- app/app_client.go | 148 +++++---- app/authorization.go | 192 +++++++++++ app/registry_item.go | 735 +++++++++++++++++++++++++++++++++++++++++++ app/robot.go | 157 --------- 4 files changed, 1022 insertions(+), 210 deletions(-) create mode 100644 app/authorization.go create mode 100644 app/registry_item.go diff --git a/app/app_client.go b/app/app_client.go index 058f4cc1e02..a31b7d413df 100644 --- a/app/app_client.go +++ b/app/app_client.go @@ -2,8 +2,6 @@ package app import ( "context" - "errors" - "fmt" "sync" packages "go.viam.com/api/app/packages/v1" @@ -807,25 +805,6 @@ func (c *AppClient) GetFragmentHistory(ctx context.Context, id string, pageToken return history, resp.NextPageToken, nil } -func createAuthorization(orgId, identityId, identityType, role, resourceType, resourceId string) (*pb.Authorization, error) { - if role != "owner" && role != "operator" { - return nil, errors.New("role string must be 'owner' or 'operator'") - } - if resourceType != "organization" && resourceType != "location" && resourceType != "robot" { - return nil, errors.New("resourceType must be 'organization', 'location', or 'robot'") - } - - return &pb.Authorization{ - AuthorizationType: role, - AuthorizationId: fmt.Sprintf("%s_%s", resourceType, role), - ResourceType: resourceType, - ResourceId: resourceId, - IdentityId: identityId, - OrganizationId: orgId, - IdentityType: identityType, - }, nil -} - // AddRole creates an identity authorization. func (c *AppClient) AddRole(ctx context.Context, orgId, identityId, role, resourceType, resourceId string) error { authorization, err := createAuthorization(orgId, identityId, "", role, resourceType, resourceId) @@ -914,22 +893,30 @@ func (c *AppClient) CheckPermissions(ctx context.Context, permissions []*Authori } // GetRegistryItem gets a registry item. -func (c *AppClient) GetRegistryItem(ctx context.Context, itemId string) (*pb.RegistryItem, error) { +func (c *AppClient) GetRegistryItem(ctx context.Context, itemId string) (*RegistryItem, error) { resp, err := c.client.GetRegistryItem(ctx, &pb.GetRegistryItemRequest{ ItemId: itemId, }) if err != nil { return nil, err } - return resp.Item, nil + item, err := ProtoToRegistryItem(resp.Item) + if err != nil { + return nil, err + } + return item, nil } // CreateRegistryItem creates a registry item. -func (c *AppClient) CreateRegistryItem(ctx context.Context, orgId, name string, packageType packages.PackageType) error { - _, err := c.client.CreateRegistryItem(ctx, &pb.CreateRegistryItemRequest{ +func (c *AppClient) CreateRegistryItem(ctx context.Context, orgId, name string, packageType PackageType) error { + pbPackageType, err := PackageTypeToProto(packageType) + if err != nil { + return err + } + _, err = c.client.CreateRegistryItem(ctx, &pb.CreateRegistryItemRequest{ OrganizationId: orgId, Name: name, - Type: packageType, + Type: pbPackageType, }) if err != nil { return err @@ -938,12 +925,20 @@ func (c *AppClient) CreateRegistryItem(ctx context.Context, orgId, name string, } // UpdateRegistryItem updates a registry item. -func (c *AppClient) UpdateRegistryItem(ctx context.Context, itemId string, packageType packages.PackageType, description string, visibility pb.Visibility, url *string) error { - _, err := c.client.UpdateRegistryItem(ctx, &pb.UpdateRegistryItemRequest{ +func (c *AppClient) UpdateRegistryItem(ctx context.Context, itemId string, packageType PackageType, description string, visibility Visibility, url *string) error { + pbPackageType, err := PackageTypeToProto(packageType) + if err != nil { + return err + } + pbVisibility, err := VisibilityToProto(visibility) + if err != nil { + return err + } + _, err = c.client.UpdateRegistryItem(ctx, &pb.UpdateRegistryItemRequest{ ItemId: itemId, - Type: packageType, + Type: pbPackageType, Description: description, - Visibility: visibility, + Visibility: pbVisibility, Url: url, }) if err != nil { @@ -953,13 +948,37 @@ func (c *AppClient) UpdateRegistryItem(ctx context.Context, itemId string, packa } // ListRegistryItems lists the registry items in an organization. -func (c *AppClient) ListRegistryItems(ctx context.Context, orgId *string, types []packages.PackageType, visibilities []pb.Visibility, platforms []string, statuses []pb.RegistryItemStatus, searchTerm, pageToken *string, publicNamespaces []string) ([]*pb.RegistryItem, error) { +func (c *AppClient) ListRegistryItems(ctx context.Context, orgId *string, types []PackageType, visibilities []Visibility, platforms []string, statuses []RegistryItemStatus, searchTerm, pageToken *string, publicNamespaces []string) ([]*RegistryItem, error) { + var pbTypes []packages.PackageType + for _, packageType := range(types){ + t, err := PackageTypeToProto(packageType) + if err != nil { + return nil, err + } + pbTypes = append(pbTypes, t) + } + var pbVisibilities []pb.Visibility + for _, visibility := range(visibilities){ + v, err := VisibilityToProto(visibility) + if err != nil { + return nil, err + } + pbVisibilities = append(pbVisibilities, v) + } + var pbStatuses []pb.RegistryItemStatus + for _, status := range(statuses){ + s, err := RegistryItemStatusToProto(status) + if err != nil { + return nil, err + } + pbStatuses = append(pbStatuses, s) + } resp, err := c.client.ListRegistryItems(ctx, &pb.ListRegistryItemsRequest{ OrganizationId: orgId, - Types: types, - Visibilities: visibilities, + Types: pbTypes, + Visibilities: pbVisibilities, Platforms: platforms, - Statuses: statuses, + Statuses: pbStatuses, SearchTerm: searchTerm, PageToken: pageToken, PublicNamespaces: publicNamespaces, @@ -967,7 +986,15 @@ func (c *AppClient) ListRegistryItems(ctx context.Context, orgId *string, types if err != nil { return nil, err } - return resp.Items, nil + var items []*RegistryItem + for _, item := range(resp.Items){ + i, err := ProtoToRegistryItem(item) + if err != nil { + return nil, err + } + items = append(items, i) + } + return items, nil } // DeleteRegistryItem deletes a registry item given an ID that is formatted as `prefix:name“ where `prefix“ is the owner's organization ID or namespace. @@ -1006,13 +1033,21 @@ func (c *AppClient) CreateModule(ctx context.Context, orgId, name string) (strin } // UpdateModule updates the documentation URL, description, models, entrypoint, and/or the visibility of a module. A path to a setup script can be added that is run before a newly downloaded module starts. -func (c *AppClient) UpdateModule(ctx context.Context, moduleId string, visibility pb.Visibility, url, description string, models []*pb.Model, entrypoint string, firstRun *string) (string, error) { +func (c *AppClient) UpdateModule(ctx context.Context, moduleId string, visibility Visibility, url, description string, models []*Model, entrypoint string, firstRun *string) (string, error) { + pbVisibility, err := VisibilityToProto(visibility) + if err != nil { + return "", err + } + var pbModels []*pb.Model + for _, model := range(models) { + pbModels = append(pbModels, ModelToProto(model)) + } resp, err := c.client.UpdateModule(ctx, &pb.UpdateModuleRequest{ ModuleId: moduleId, - Visibility: visibility, + Visibility: pbVisibility, Url: url, Description: description, - Models: models, + Models: pbModels, Entrypoint: entrypoint, FirstRun: firstRun, }) @@ -1074,34 +1109,37 @@ func (c *AppClient) UpdateModule(ctx context.Context, moduleId string, visibilit // } // GetModule gets a module. -func (c *AppClient) GetModule(ctx context.Context, moduleId string) (*pb.Module, error) { +func (c *AppClient) GetModule(ctx context.Context, moduleId string) (*Module, error) { resp, err := c.client.GetModule(ctx, &pb.GetModuleRequest{ ModuleId: moduleId, }) if err != nil { return nil, err } - return resp.Module, nil + module, err := ProtoToModule(resp.Module) + if err != nil { + return nil, err + } + return module, nil } // ListModules lists the modules in the organization. -func (c *AppClient) ListModules(ctx context.Context, orgId *string) ([]*pb.Module, error) { +func (c *AppClient) ListModules(ctx context.Context, orgId *string) ([]*Module, error) { resp, err := c.client.ListModules(ctx, &pb.ListModulesRequest{ OrganizationId: orgId, }) if err != nil { return nil, err } - return resp.Modules, nil -} - -// APIKeyAuthorization is a struct with the necessary authorization data to create an API key. -type APIKeyAuthorization struct { - // `role`` must be "owner" or "operator" - role string - // `resourceType` must be "organization", "location", or "robot" - resourceType string - resourceId string + var modules []*Module + for _, module := range(resp.Modules){ + m, err := ProtoToModule(module) + if err != nil { + return nil, err + } + modules = append(modules, m) + } + return modules, nil } // CreateKey creates a new API key associated with a list of authorizations. @@ -1137,14 +1175,18 @@ func (c *AppClient) DeleteKey(ctx context.Context, id string) error { } // ListKeys lists all the keys for the organization. -func (c *AppClient) ListKeys(ctx context.Context, orgId string) ([]*pb.APIKeyWithAuthorizations, error) { +func (c *AppClient) ListKeys(ctx context.Context, orgId string) ([]APIKeyWithAuthorizations, error) { resp, err := c.client.ListKeys(ctx, &pb.ListKeysRequest{ OrgId: orgId, }) if err != nil { return nil, err } - return resp.ApiKeys, nil + var apiKeys []APIKeyWithAuthorizations + for _, key := range(resp.ApiKeys){ + apiKeys = append(apiKeys, *ProtoToAPIKeyWithAuthorizations(key)) + } + return apiKeys, nil } // RenameKey renames an API key. diff --git a/app/authorization.go b/app/authorization.go new file mode 100644 index 00000000000..ad7a9869f62 --- /dev/null +++ b/app/authorization.go @@ -0,0 +1,192 @@ +package app + +import ( + "errors" + "fmt" + + pb "go.viam.com/api/app/v1" + "google.golang.org/protobuf/types/known/timestamppb" +) + +func createAuthorization(orgId, identityId, identityType, role, resourceType, resourceId string) (*pb.Authorization, error) { + if role != "owner" && role != "operator" { + return nil, errors.New("role string must be 'owner' or 'operator'") + } + if resourceType != "organization" && resourceType != "location" && resourceType != "robot" { + return nil, errors.New("resourceType must be 'organization', 'location', or 'robot'") + } + + return &pb.Authorization{ + AuthorizationType: role, + AuthorizationId: fmt.Sprintf("%s_%s", resourceType, role), + ResourceType: resourceType, + ResourceId: resourceId, + IdentityId: identityId, + OrganizationId: orgId, + IdentityType: identityType, + }, nil +} + +type AuthenticatorInfo struct { + Type AuthenticationType + Value string + IsDeactivated bool +} + +func ProtoToAuthenticatorInfo(info *pb.AuthenticatorInfo) (*AuthenticatorInfo, error){ + authenticationType, err := ProtoToAuthenticationType(info.Type) + if err != nil { + return nil, err + } + return &AuthenticatorInfo{ + Type: authenticationType, + Value: info.Value, + IsDeactivated: info.IsDeactivated, + }, nil +} + +func AuthenticatorInfoToProto(info *AuthenticatorInfo) (*pb.AuthenticatorInfo, error){ + authenticationType, err := AuthenticationTypeToProto(info.Type) + if err != nil { + return nil, err + } + return &pb.AuthenticatorInfo{ + Type: authenticationType, + Value: info.Value, + IsDeactivated: info.IsDeactivated, + }, nil +} + +type AuthenticationType int32 + +const ( + AuthenticationType_AUTHENTICATION_TYPE_UNSPECIFIED AuthenticationType = 0 + AuthenticationType_AUTHENTICATION_TYPE_WEB_OAUTH AuthenticationType = 1 + AuthenticationType_AUTHENTICATION_TYPE_API_KEY AuthenticationType = 2 + AuthenticationType_AUTHENTICATION_TYPE_ROBOT_PART_SECRET AuthenticationType = 3 + AuthenticationType_AUTHENTICATION_TYPE_LOCATION_SECRET AuthenticationType = 4 +) + + +func ProtoToAuthenticationType(authenticationType pb.AuthenticationType) (AuthenticationType, error) { + switch authenticationType{ + case pb.AuthenticationType_AUTHENTICATION_TYPE_UNSPECIFIED: + return AuthenticationType_AUTHENTICATION_TYPE_UNSPECIFIED, nil + case pb.AuthenticationType_AUTHENTICATION_TYPE_WEB_OAUTH: + return AuthenticationType_AUTHENTICATION_TYPE_WEB_OAUTH, nil + case pb.AuthenticationType_AUTHENTICATION_TYPE_API_KEY: + return AuthenticationType_AUTHENTICATION_TYPE_API_KEY, nil + case pb.AuthenticationType_AUTHENTICATION_TYPE_ROBOT_PART_SECRET: + return AuthenticationType_AUTHENTICATION_TYPE_ROBOT_PART_SECRET, nil + case pb.AuthenticationType_AUTHENTICATION_TYPE_LOCATION_SECRET: + return AuthenticationType_AUTHENTICATION_TYPE_LOCATION_SECRET, nil + default: + return 0, fmt.Errorf("uknown authentication type: %v", authenticationType) + } +} + +func AuthenticationTypeToProto(authenticationType AuthenticationType) (pb.AuthenticationType, error) { + switch authenticationType{ + case AuthenticationType_AUTHENTICATION_TYPE_UNSPECIFIED: + return pb.AuthenticationType_AUTHENTICATION_TYPE_UNSPECIFIED, nil + case AuthenticationType_AUTHENTICATION_TYPE_WEB_OAUTH: + return pb.AuthenticationType_AUTHENTICATION_TYPE_WEB_OAUTH, nil + case AuthenticationType_AUTHENTICATION_TYPE_API_KEY: + return pb.AuthenticationType_AUTHENTICATION_TYPE_API_KEY, nil + case AuthenticationType_AUTHENTICATION_TYPE_ROBOT_PART_SECRET: + return pb.AuthenticationType_AUTHENTICATION_TYPE_ROBOT_PART_SECRET, nil + case AuthenticationType_AUTHENTICATION_TYPE_LOCATION_SECRET: + return pb.AuthenticationType_AUTHENTICATION_TYPE_LOCATION_SECRET, nil + default: + return 0, fmt.Errorf("unknown authentication type: %v", authenticationType) + } +} + +type APIKeyWithAuthorizations struct { + ApiKey *APIKey + Authorizations []*AuthorizationDetails +} + +func ProtoToAPIKeyWithAuthorizations(key *pb.APIKeyWithAuthorizations) *APIKeyWithAuthorizations { + var details []*AuthorizationDetails + for _, detail := range(key.Authorizations){ + details = append(details, ProtoToAuthorizationDetails(detail)) + } + return &APIKeyWithAuthorizations{ + ApiKey: ProtoToAPIKey(key.ApiKey), + Authorizations: details, + } +} + +func APIKeyWithAuthorizationsToProto(key *APIKeyWithAuthorizations) *pb.APIKeyWithAuthorizations { + var details []*pb.AuthorizationDetails + for _, detail := range(key.Authorizations){ + details = append(details, AuthorizationDetailsToProto(detail)) + } + return &pb.APIKeyWithAuthorizations{ + ApiKey: APIKeyToProto(key.ApiKey), + Authorizations: details, + } +} + +type APIKey struct { + Id string + Key string + Name string + CreatedOn *timestamppb.Timestamp +} + +func ProtoToAPIKey(key *pb.APIKey) *APIKey { + return &APIKey{ + Id: key.Id, + Key: key.Key, + Name: key.Name, + CreatedOn: key.CreatedOn, + } +} + +func APIKeyToProto(key *APIKey) *pb.APIKey { + return &pb.APIKey{ + Id: key.Id, + Key: key.Key, + Name: key.Name, + CreatedOn: key.CreatedOn, + } +} + +type AuthorizationDetails struct { + AuthorizationType string + AuthorizationId string + ResourceType string + ResourceId string + OrgId string +} + +func ProtoToAuthorizationDetails(details *pb.AuthorizationDetails) *AuthorizationDetails { + return &AuthorizationDetails{ + AuthorizationType: details.AuthorizationType, + AuthorizationId: details.AuthorizationId, + ResourceType: details.ResourceType, + ResourceId: details.ResourceId, + OrgId: details.OrgId, + } +} + +func AuthorizationDetailsToProto(details *AuthorizationDetails) *pb.AuthorizationDetails { + return &pb.AuthorizationDetails{ + AuthorizationType: details.AuthorizationType, + AuthorizationId: details.AuthorizationId, + ResourceType: details.ResourceType, + ResourceId: details.ResourceId, + OrgId: details.OrgId, + } +} + +// APIKeyAuthorization is a struct with the necessary authorization data to create an API key. +type APIKeyAuthorization struct { + // `role`` must be "owner" or "operator" + role string + // `resourceType` must be "organization", "location", or "robot" + resourceType string + resourceId string +} diff --git a/app/registry_item.go b/app/registry_item.go new file mode 100644 index 00000000000..22553f06040 --- /dev/null +++ b/app/registry_item.go @@ -0,0 +1,735 @@ +package app + +import ( + "fmt" + + mlTraining "go.viam.com/api/app/mltraining/v1" + packages "go.viam.com/api/app/packages/v1" + pb "go.viam.com/api/app/v1" + "google.golang.org/protobuf/types/known/timestamppb" +) + +type RegistryItem struct { + ItemId string + OrganizationId string + PublicNamespace string + Name string + Type PackageType + Visibility Visibility + Url string + Description string + TotalRobotUsage int64 + TotalExternalRobotUsage int64 + TotalOrganizationUsage int64 + TotalExternalOrganizationUsage int64 + Metadata isRegistryItem_Metadata + CreatedAt *timestamppb.Timestamp + UpdatedAt *timestamppb.Timestamp +} + +func ProtoToRegistryItem(item *pb.RegistryItem) (*RegistryItem, error) { + packageType, err := ProtoToPackageType(item.Type) + if err != nil { + return nil, err + } + visibility, err := ProtoToVisibility(item.Visibility) + if err != nil { + return nil, err + } + + var metadata isRegistryItem_Metadata + switch pbMetadata := item.Metadata.(type) { + case *pb.RegistryItem_ModuleMetadata: + md, err := ProtoToModuleMetadata(pbMetadata.ModuleMetadata) + if err != nil { + return nil, err + } + metadata = &RegistryItem_ModuleMetadata{ModuleMetadata: md} + case *pb.RegistryItem_MlModelMetadata: + md, err := ProtoToMLModelMetadata(pbMetadata.MlModelMetadata) + if err != nil { + return nil, err + } + metadata = &RegistryItem_MlModelMetadata{MlModelMetadata: md} + case *pb.RegistryItem_MlTrainingMetadata: + md, err := ProtoToMLTrainingMetadata(pbMetadata.MlTrainingMetadata) + if err != nil { + return nil, err + } + metadata = &RegistryItem_MlTrainingMetadata{MlTrainingMetadata: md} + default: + return nil, fmt.Errorf("unknown registry item metadata type: %T", item.Metadata) + } + + return &RegistryItem{ + ItemId: item.ItemId, + OrganizationId: item.OrganizationId, + PublicNamespace: item.PublicNamespace, + Name: item.Name, + Type: packageType, + Visibility: visibility, + Url: item.Url, + Description: item.Description, + TotalRobotUsage: item.TotalRobotUsage, + TotalExternalRobotUsage: item.TotalExternalRobotUsage, + TotalOrganizationUsage: item.TotalOrganizationUsage, + TotalExternalOrganizationUsage: item.TotalExternalOrganizationUsage, + Metadata: metadata, + CreatedAt: item.CreatedAt, + UpdatedAt: item.UpdatedAt, + }, nil +} + +func RegistryItemToProto(item *RegistryItem) (*pb.RegistryItem, error) { + packageType, err := PackageTypeToProto(item.Type) + if err != nil { + return nil, err + } + visibility, err := VisibilityToProto(item.Visibility) + if err != nil { + return nil, err + } + + switch md := item.Metadata.(type) { + case *RegistryItem_ModuleMetadata: + protoMetadata, err := ModuleMetadataToProto(md.ModuleMetadata) + if err != nil { + return nil, err + } + return &pb.RegistryItem{ + ItemId: item.ItemId, + OrganizationId: item.OrganizationId, + PublicNamespace: item.PublicNamespace, + Name: item.Name, + Type: packageType, + Visibility: visibility, + Url: item.Url, + Description: item.Description, + TotalRobotUsage: item.TotalRobotUsage, + TotalExternalRobotUsage: item.TotalExternalRobotUsage, + TotalOrganizationUsage: item.TotalOrganizationUsage, + TotalExternalOrganizationUsage: item.TotalExternalOrganizationUsage, + Metadata: &pb.RegistryItem_ModuleMetadata{ModuleMetadata: protoMetadata}, + CreatedAt: item.CreatedAt, + UpdatedAt: item.UpdatedAt, + }, nil + case *RegistryItem_MlModelMetadata: + protoMetadata, err := MLModelMetadataToProto(md.MlModelMetadata) + if err != nil { + return nil, err + } + return &pb.RegistryItem{ + ItemId: item.ItemId, + OrganizationId: item.OrganizationId, + PublicNamespace: item.PublicNamespace, + Name: item.Name, + Type: packageType, + Visibility: visibility, + Url: item.Url, + Description: item.Description, + TotalRobotUsage: item.TotalRobotUsage, + TotalExternalRobotUsage: item.TotalExternalRobotUsage, + TotalOrganizationUsage: item.TotalOrganizationUsage, + TotalExternalOrganizationUsage: item.TotalExternalOrganizationUsage, + Metadata: &pb.RegistryItem_MlModelMetadata{MlModelMetadata: protoMetadata}, + CreatedAt: item.CreatedAt, + UpdatedAt: item.UpdatedAt, + }, nil + case *RegistryItem_MlTrainingMetadata: + protoMetadata, err := MLTrainingMetadataToProto(md.MlTrainingMetadata) + if err != nil { + return nil, err + } + return &pb.RegistryItem{ + ItemId: item.ItemId, + OrganizationId: item.OrganizationId, + PublicNamespace: item.PublicNamespace, + Name: item.Name, + Type: packageType, + Visibility: visibility, + Url: item.Url, + Description: item.Description, + TotalRobotUsage: item.TotalRobotUsage, + TotalExternalRobotUsage: item.TotalExternalRobotUsage, + TotalOrganizationUsage: item.TotalOrganizationUsage, + TotalExternalOrganizationUsage: item.TotalExternalOrganizationUsage, + Metadata: &pb.RegistryItem_MlTrainingMetadata{MlTrainingMetadata: protoMetadata}, + CreatedAt: item.CreatedAt, + UpdatedAt: item.UpdatedAt, + }, nil + default: + return nil, fmt.Errorf("unknown registry item metadata type: %T", item.Metadata) + } +} + +type RegistryItemStatus int32 +const ( + RegistryItemStatus_REGISTRY_ITEM_STATUS_UNSPECIFIED RegistryItemStatus = 0 + RegistryItemStatus_REGISTRY_ITEM_STATUS_PUBLISHED RegistryItemStatus = 1 + RegistryItemStatus_REGISTRY_ITEM_STATUS_IN_DEVELOPMENT RegistryItemStatus = 2 +) + +func ProtoToRegistryItemStatus(status pb.RegistryItemStatus) (RegistryItemStatus, error) { + switch status{ + case pb.RegistryItemStatus_REGISTRY_ITEM_STATUS_UNSPECIFIED: + return RegistryItemStatus_REGISTRY_ITEM_STATUS_UNSPECIFIED, nil + case pb.RegistryItemStatus_REGISTRY_ITEM_STATUS_PUBLISHED: + return RegistryItemStatus_REGISTRY_ITEM_STATUS_PUBLISHED, nil + case pb.RegistryItemStatus_REGISTRY_ITEM_STATUS_IN_DEVELOPMENT: + return RegistryItemStatus_REGISTRY_ITEM_STATUS_IN_DEVELOPMENT, nil + default: + return 0, fmt.Errorf("unknown registry item status: %v", status) + } +} + +func RegistryItemStatusToProto(status RegistryItemStatus) (pb.RegistryItemStatus, error) { + switch status{ + case RegistryItemStatus_REGISTRY_ITEM_STATUS_UNSPECIFIED: + return pb.RegistryItemStatus_REGISTRY_ITEM_STATUS_UNSPECIFIED, nil + case RegistryItemStatus_REGISTRY_ITEM_STATUS_PUBLISHED: + return pb.RegistryItemStatus_REGISTRY_ITEM_STATUS_PUBLISHED, nil + case RegistryItemStatus_REGISTRY_ITEM_STATUS_IN_DEVELOPMENT: + return pb.RegistryItemStatus_REGISTRY_ITEM_STATUS_IN_DEVELOPMENT, nil + default: + return 0, fmt.Errorf("unknown registry item status: %v", status) + } +} + +type PackageType int32 +const ( + PackageType_PACKAGE_TYPE_UNSPECIFIED PackageType = 0 + PackageType_PACKAGE_TYPE_ARCHIVE PackageType = 1 + PackageType_PACKAGE_TYPE_ML_MODEL PackageType = 2 + PackageType_PACKAGE_TYPE_MODULE PackageType = 3 + PackageType_PACKAGE_TYPE_SLAM_MAP PackageType = 4 + PackageType_PACKAGE_TYPE_ML_TRAINING PackageType = 5 +) + +func ProtoToPackageType(packageType packages.PackageType) (PackageType, error) { + switch packageType{ + case packages.PackageType_PACKAGE_TYPE_UNSPECIFIED: + return PackageType_PACKAGE_TYPE_UNSPECIFIED, nil + case packages.PackageType_PACKAGE_TYPE_ARCHIVE: + return PackageType_PACKAGE_TYPE_ARCHIVE, nil + case packages.PackageType_PACKAGE_TYPE_ML_MODEL: + return PackageType_PACKAGE_TYPE_ML_MODEL, nil + case packages.PackageType_PACKAGE_TYPE_MODULE: + return PackageType_PACKAGE_TYPE_MODULE, nil + case packages.PackageType_PACKAGE_TYPE_SLAM_MAP: + return PackageType_PACKAGE_TYPE_SLAM_MAP, nil + case packages.PackageType_PACKAGE_TYPE_ML_TRAINING: + return PackageType_PACKAGE_TYPE_ML_TRAINING, nil + default: + return 0, fmt.Errorf("unknown fragment visibility: %v", packageType) + } +} + +func PackageTypeToProto(packageType PackageType) (packages.PackageType, error) { + switch packageType{ + case PackageType_PACKAGE_TYPE_UNSPECIFIED: + return packages.PackageType_PACKAGE_TYPE_UNSPECIFIED, nil + case PackageType_PACKAGE_TYPE_ARCHIVE: + return packages.PackageType_PACKAGE_TYPE_ARCHIVE, nil + case PackageType_PACKAGE_TYPE_ML_MODEL: + return packages.PackageType_PACKAGE_TYPE_ML_MODEL, nil + case PackageType_PACKAGE_TYPE_MODULE: + return packages.PackageType_PACKAGE_TYPE_MODULE, nil + case PackageType_PACKAGE_TYPE_SLAM_MAP: + return packages.PackageType_PACKAGE_TYPE_SLAM_MAP, nil + case PackageType_PACKAGE_TYPE_ML_TRAINING: + return packages.PackageType_PACKAGE_TYPE_ML_TRAINING, nil + default: + return 0, fmt.Errorf("unknown fragment visibility: %v", packageType) + } +} + + +type Visibility int32 +const ( + Visibility_VISIBILITY_UNSPECIFIED Visibility = 0 + Visibility_VISIBILITY_PRIVATE Visibility = 1 + Visibility_VISIBILITY_PUBLIC Visibility = 2 + Visibility_VISIBILITY_PUBLIC_UNLISTED Visibility = 3 +) + +func ProtoToVisibility(visibility pb.Visibility) (Visibility, error) { + switch visibility{ + case pb.Visibility_VISIBILITY_UNSPECIFIED: + return Visibility_VISIBILITY_UNSPECIFIED, nil + case pb.Visibility_VISIBILITY_PRIVATE: + return Visibility_VISIBILITY_PRIVATE, nil + case pb.Visibility_VISIBILITY_PUBLIC: + return Visibility_VISIBILITY_PUBLIC, nil + case pb.Visibility_VISIBILITY_PUBLIC_UNLISTED: + return Visibility_VISIBILITY_PUBLIC_UNLISTED, nil + default: + return 0, fmt.Errorf("unknown fragment visibility: %v", visibility) + } +} + +func VisibilityToProto(visibility Visibility) (pb.Visibility, error) { + switch visibility{ + case Visibility_VISIBILITY_UNSPECIFIED: + return pb.Visibility_VISIBILITY_UNSPECIFIED, nil + case Visibility_VISIBILITY_PRIVATE: + return pb.Visibility_VISIBILITY_PRIVATE, nil + case Visibility_VISIBILITY_PUBLIC: + return pb.Visibility_VISIBILITY_PUBLIC, nil + case Visibility_VISIBILITY_PUBLIC_UNLISTED: + return pb.Visibility_VISIBILITY_PUBLIC_UNLISTED, nil + default: + return 0, fmt.Errorf("unknown fragment visibility: %v", visibility) + } +} + +type isRegistryItem_Metadata interface { + isRegistryItem_Metadata() +} + +type RegistryItem_ModuleMetadata struct { + ModuleMetadata *ModuleMetadata +} + +type RegistryItem_MlModelMetadata struct { + MlModelMetadata *MLModelMetadata +} + +type RegistryItem_MlTrainingMetadata struct { + MlTrainingMetadata *MLTrainingMetadata +} + +func (*RegistryItem_ModuleMetadata) isRegistryItem_Metadata() {} + +func (*RegistryItem_MlModelMetadata) isRegistryItem_Metadata() {} + +func (*RegistryItem_MlTrainingMetadata) isRegistryItem_Metadata() {} + +type ModuleMetadata struct { + Models []*Model + Versions []*ModuleVersion + Entrypoint string + FirstRun *string +} + +func ProtoToModuleMetadata(md *pb.ModuleMetadata) (*ModuleMetadata, error) { + var models []*Model + for _, version := range(md.Models) { + models = append(models, ProtoToModel(version)) + } + var versions []*ModuleVersion + for _, version := range(md.Versions) { + versions = append(versions, ProtoToModuleVersion(version)) + } + return &ModuleMetadata{ + Models: models, + Versions: versions, + Entrypoint: md.Entrypoint, + FirstRun: md.FirstRun, + }, nil +} + +func ModuleMetadataToProto(md *ModuleMetadata) (*pb.ModuleMetadata, error) { + var models []*pb.Model + for _, version := range(md.Models) { + models = append(models, ModelToProto(version)) + } + var versions []*pb.ModuleVersion + for _, version := range(md.Versions) { + versions = append(versions, ModuleVersionToProto(version)) + } + return &pb.ModuleMetadata{ + Models: models, + Versions: versions, + Entrypoint: md.Entrypoint, + FirstRun: md.FirstRun, + }, nil +} + +type Model struct { + Api string + Model string +} + +func ProtoToModel(model *pb.Model) *Model { + return &Model{ + Api: model.Api, + Model: model.Model, + } +} + +func ModelToProto(model *Model) *pb.Model { + return &pb.Model{ + Api: model.Api, + Model: model.Model, + } +} + +type ModuleVersion struct { + Version string + Files []*Uploads + Models []*Model + Entrypoint string + FirstRun *string +} + +func ProtoToModuleVersion(version *pb.ModuleVersion) (*ModuleVersion) { + var files []*Uploads + for _, file := range(version.Files) { + files = append(files, ProtoToUploads(file)) + } + var models []*Model + for _, model := range(version.Models) { + models = append(models, ProtoToModel(model)) + } + return &ModuleVersion{ + Version: version.Version, + Files: files, + Models: models, + Entrypoint: version.Entrypoint, + FirstRun: version.FirstRun, + } +} + +func ModuleVersionToProto(version *ModuleVersion) (*pb.ModuleVersion) { + var files []*pb.Uploads + for _, file := range(version.Files) { + files = append(files, UploadsToProto(file)) + } + var models []*pb.Model + for _, model := range(version.Models) { + models = append(models, ModelToProto(model)) + } + return &pb.ModuleVersion{ + Version: version.Version, + Files: files, + Models: models, + Entrypoint: version.Entrypoint, + FirstRun: version.FirstRun, + } +} + +type Uploads struct { + Platform string + UploadedAt *timestamppb.Timestamp +} + +func ProtoToUploads(uploads *pb.Uploads) *Uploads { + return &Uploads{ + Platform: uploads.Platform, + UploadedAt: uploads.UploadedAt, + } +} + +func UploadsToProto(uploads *Uploads) *pb.Uploads { + return &pb.Uploads{ + Platform: uploads.Platform, + UploadedAt: uploads.UploadedAt, + } +} + +type MLModelMetadata struct { + Versions []string + ModelType ModelType + ModelFramework ModelFramework +} + +func ProtoToMLModelMetadata(md *pb.MLModelMetadata) (*MLModelMetadata, error) { + modelType, err := ProtoToModelType(md.ModelType) + if err != nil { + return nil, err + } + modelFramework, err := ProtoToModelFramework(md.ModelFramework) + if err != nil { + return nil, err + } + return &MLModelMetadata{ + Versions: md.Versions, + ModelType: modelType, + ModelFramework: modelFramework, + }, nil +} + +func MLModelMetadataToProto(md *MLModelMetadata) (*pb.MLModelMetadata, error) { + modelType, err := ModelTypeToProto(md.ModelType) + if err != nil { + return nil, err + } + modelFramework, err := ModelFrameworkToProto(md.ModelFramework) + if err != nil { + return nil, err + } + return &pb.MLModelMetadata{ + Versions: md.Versions, + ModelType: modelType, + ModelFramework: modelFramework, + }, nil +} + +type ModelType int32 +const ( + ModelType_MODEL_TYPE_UNSPECIFIED ModelType = 0 + ModelType_MODEL_TYPE_SINGLE_LABEL_CLASSIFICATION ModelType = 1 + ModelType_MODEL_TYPE_MULTI_LABEL_CLASSIFICATION ModelType = 2 + ModelType_MODEL_TYPE_OBJECT_DETECTION ModelType = 3 +) + +func ProtoToModelType(modelType mlTraining.ModelType) (ModelType, error) { + switch modelType{ + case mlTraining.ModelType_MODEL_TYPE_UNSPECIFIED: + return ModelType_MODEL_TYPE_UNSPECIFIED, nil + case mlTraining.ModelType_MODEL_TYPE_SINGLE_LABEL_CLASSIFICATION: + return ModelType_MODEL_TYPE_SINGLE_LABEL_CLASSIFICATION, nil + case mlTraining.ModelType_MODEL_TYPE_MULTI_LABEL_CLASSIFICATION: + return ModelType_MODEL_TYPE_MULTI_LABEL_CLASSIFICATION, nil + case mlTraining.ModelType_MODEL_TYPE_OBJECT_DETECTION: + return ModelType_MODEL_TYPE_OBJECT_DETECTION, nil + default: + return 0, fmt.Errorf("unknown model type: %v", modelType) + } +} + +func ModelTypeToProto(modelType ModelType) (mlTraining.ModelType, error) { + switch modelType{ + case ModelType_MODEL_TYPE_UNSPECIFIED: + return mlTraining.ModelType_MODEL_TYPE_UNSPECIFIED, nil + case ModelType_MODEL_TYPE_SINGLE_LABEL_CLASSIFICATION: + return mlTraining.ModelType_MODEL_TYPE_SINGLE_LABEL_CLASSIFICATION, nil + case ModelType_MODEL_TYPE_MULTI_LABEL_CLASSIFICATION: + return mlTraining.ModelType_MODEL_TYPE_MULTI_LABEL_CLASSIFICATION, nil + case ModelType_MODEL_TYPE_OBJECT_DETECTION: + return mlTraining.ModelType_MODEL_TYPE_OBJECT_DETECTION, nil + default: + return 0, fmt.Errorf("unknown model type: %v", modelType) + } +} + +type ModelFramework int32 +const ( + ModelFramework_MODEL_FRAMEWORK_UNSPECIFIED ModelFramework = 0 + ModelFramework_MODEL_FRAMEWORK_TFLITE ModelFramework = 1 + ModelFramework_MODEL_FRAMEWORK_TENSORFLOW ModelFramework = 2 + ModelFramework_MODEL_FRAMEWORK_PYTORCH ModelFramework = 3 + ModelFramework_MODEL_FRAMEWORK_ONNX ModelFramework = 4 +) + +func ProtoToModelFramework(framework mlTraining.ModelFramework) (ModelFramework, error) { + switch framework{ + case mlTraining.ModelFramework_MODEL_FRAMEWORK_UNSPECIFIED: + return ModelFramework_MODEL_FRAMEWORK_UNSPECIFIED, nil + case mlTraining.ModelFramework_MODEL_FRAMEWORK_TFLITE: + return ModelFramework_MODEL_FRAMEWORK_TFLITE, nil + case mlTraining.ModelFramework_MODEL_FRAMEWORK_TENSORFLOW: + return ModelFramework_MODEL_FRAMEWORK_TENSORFLOW, nil + case mlTraining.ModelFramework_MODEL_FRAMEWORK_PYTORCH: + return ModelFramework_MODEL_FRAMEWORK_PYTORCH, nil + case mlTraining.ModelFramework_MODEL_FRAMEWORK_ONNX: + return ModelFramework_MODEL_FRAMEWORK_ONNX, nil + default: + return 0, fmt.Errorf("unknown model framework: %v", framework) + } +} + +func ModelFrameworkToProto(framework ModelFramework) (mlTraining.ModelFramework, error) { + switch framework{ + case ModelFramework_MODEL_FRAMEWORK_UNSPECIFIED: + return mlTraining.ModelFramework_MODEL_FRAMEWORK_UNSPECIFIED, nil + case ModelFramework_MODEL_FRAMEWORK_TFLITE: + return mlTraining.ModelFramework_MODEL_FRAMEWORK_TFLITE, nil + case ModelFramework_MODEL_FRAMEWORK_TENSORFLOW: + return mlTraining.ModelFramework_MODEL_FRAMEWORK_TENSORFLOW, nil + case ModelFramework_MODEL_FRAMEWORK_PYTORCH: + return mlTraining.ModelFramework_MODEL_FRAMEWORK_PYTORCH, nil + case ModelFramework_MODEL_FRAMEWORK_ONNX: + return mlTraining.ModelFramework_MODEL_FRAMEWORK_ONNX, nil + default: + return 0, fmt.Errorf("unknown model framework: %v", framework) + } +} + +type MLTrainingMetadata struct { + Versions []*MLTrainingVersion + ModelType ModelType + ModelFramework ModelFramework + Draft bool +} + +func ProtoToMLTrainingMetadata(md *pb.MLTrainingMetadata) (*MLTrainingMetadata, error) { + var versions []*MLTrainingVersion + for _, version := range(md.Versions) { + versions = append(versions, ProtoToMLTrainingVersion(version)) + } + modelType, err := ProtoToModelType(md.ModelType) + if err != nil { + return nil, err + } + modelFramework, err := ProtoToModelFramework(md.ModelFramework) + if err != nil { + return nil, err + } + return &MLTrainingMetadata{ + Versions: versions, + ModelType: modelType, + ModelFramework: modelFramework, + Draft: md.Draft, + }, nil +} + +func MLTrainingMetadataToProto(md *MLTrainingMetadata) (*pb.MLTrainingMetadata, error) { + var versions []*pb.MLTrainingVersion + for _, version := range(md.Versions) { + versions = append(versions, MLTrainingVersionToProto(version)) + } + modelType, err := ModelTypeToProto(md.ModelType) + if err != nil { + return nil, err + } + modelFramework, err := ModelFrameworkToProto(md.ModelFramework) + if err != nil { + return nil, err + } + return &pb.MLTrainingMetadata{ + Versions: versions, + ModelType: modelType, + ModelFramework: modelFramework, + Draft: md.Draft, + }, nil +} + +type MLTrainingVersion struct { + Version string + CreatedOn *timestamppb.Timestamp +} + +func ProtoToMLTrainingVersion(version *pb.MLTrainingVersion) *MLTrainingVersion { + return &MLTrainingVersion{ + Version: version.Version, + CreatedOn: version.CreatedOn, + } +} + +func MLTrainingVersionToProto(version *MLTrainingVersion) *pb.MLTrainingVersion { + return &pb.MLTrainingVersion{ + Version: version.Version, + CreatedOn: version.CreatedOn, + } +} + +type Module struct { + ModuleId string + Name string + Visibility Visibility + Versions []*VersionHistory + Url string + Description string + Models []*Model + TotalRobotUsage int64 + TotalOrganizationUsage int64 + OrganizationId string + Entrypoint string + PublicNamespace string + FirstRun *string +} + +func ProtoToModule(module *pb.Module) (*Module, error) { + visibility, err := ProtoToVisibility(module.Visibility) + if err != nil { + return nil, err + } + var versions []*VersionHistory + for _, version := range(module.Versions){ + versions = append(versions, ProtoToVersionHistory(version)) + } + var models []*Model + for _, model := range(module.Models){ + models = append(models, ProtoToModel(model)) + } + return &Module{ + ModuleId: module.ModuleId, + Name: module.Name, + Visibility: visibility, + Versions: versions, + Url: module.Url, + Description: module.Description, + Models: models, + TotalRobotUsage: module.TotalRobotUsage, + TotalOrganizationUsage: module.TotalOrganizationUsage, + OrganizationId: module.OrganizationId, + Entrypoint: module.Entrypoint, + PublicNamespace: module.PublicNamespace, + FirstRun: module.FirstRun, + }, nil +} + +func ModuleToProto(module *Module) (*pb.Module, error) { + visibility, err := VisibilityToProto(module.Visibility) + if err != nil { + return nil, err + } + var versions []*pb.VersionHistory + for _, version := range(module.Versions){ + versions = append(versions, VersionHistoryToProto(version)) + } + var models []*pb.Model + for _, model := range(module.Models){ + models = append(models, ModelToProto(model)) + } + return &pb.Module{ + ModuleId: module.ModuleId, + Name: module.Name, + Visibility: visibility, + Versions: versions, + Url: module.Url, + Description: module.Description, + Models: models, + TotalRobotUsage: module.TotalRobotUsage, + TotalOrganizationUsage: module.TotalOrganizationUsage, + OrganizationId: module.OrganizationId, + Entrypoint: module.Entrypoint, + PublicNamespace: module.PublicNamespace, + FirstRun: module.FirstRun, + }, nil +} + +type VersionHistory struct { + Version string + Files []*Uploads + Models []*Model + Entrypoint string + FirstRun *string +} + +func ProtoToVersionHistory(history *pb.VersionHistory) *VersionHistory { + var files []*Uploads + for _, file := range(history.Files){ + files = append(files, ProtoToUploads(file)) + } + var models []*Model + for _, model := range(history.Models){ + models = append(models, ProtoToModel(model)) + } + return &VersionHistory{ + Version: history.Version, + Files: files, + Models: models, + Entrypoint: history.Entrypoint, + FirstRun: history.FirstRun, + } +} + +func VersionHistoryToProto(history *VersionHistory) *pb.VersionHistory { + var files []*pb.Uploads + for _, file := range(history.Files){ + files = append(files, UploadsToProto(file)) + } + var models []*pb.Model + for _, model := range(history.Models){ + models = append(models, ModelToProto(model)) + } + return &pb.VersionHistory{ + Version: history.Version, + Files: files, + Models: models, + Entrypoint: history.Entrypoint, + FirstRun: history.FirstRun, + } +} diff --git a/app/robot.go b/app/robot.go index a5a05648848..bb27dd343ea 100644 --- a/app/robot.go +++ b/app/robot.go @@ -1,8 +1,6 @@ package app import ( - "fmt" - pb "go.viam.com/api/app/v1" "go.viam.com/utils/protoutils" "google.golang.org/protobuf/types/known/timestamppb" @@ -170,158 +168,3 @@ func ProtoToRobotPartHistoryEntry(entry *pb.RobotPartHistoryEntry) (*RobotPartHi EditedBy: info, }, nil } - -type AuthenticatorInfo struct { - Type AuthenticationType - Value string - IsDeactivated bool -} - -func ProtoToAuthenticatorInfo(info *pb.AuthenticatorInfo) (*AuthenticatorInfo, error){ - authenticationType, err := ProtoToAuthenticationType(info.Type) - if err != nil { - return nil, err - } - return &AuthenticatorInfo{ - Type: authenticationType, - Value: info.Value, - IsDeactivated: info.IsDeactivated, - }, nil -} - -func AuthenticatorInfoToProto(info *AuthenticatorInfo) (*pb.AuthenticatorInfo, error){ - authenticationType, err := AuthenticationTypeToProto(info.Type) - if err != nil { - return nil, err - } - return &pb.AuthenticatorInfo{ - Type: authenticationType, - Value: info.Value, - IsDeactivated: info.IsDeactivated, - }, nil -} - -type AuthenticationType int32 - -const ( - AuthenticationType_AUTHENTICATION_TYPE_UNSPECIFIED AuthenticationType = 0 - AuthenticationType_AUTHENTICATION_TYPE_WEB_OAUTH AuthenticationType = 1 - AuthenticationType_AUTHENTICATION_TYPE_API_KEY AuthenticationType = 2 - AuthenticationType_AUTHENTICATION_TYPE_ROBOT_PART_SECRET AuthenticationType = 3 - AuthenticationType_AUTHENTICATION_TYPE_LOCATION_SECRET AuthenticationType = 4 -) - - -func ProtoToAuthenticationType(authenticationType pb.AuthenticationType) (AuthenticationType, error) { - switch authenticationType{ - case pb.AuthenticationType_AUTHENTICATION_TYPE_UNSPECIFIED: - return AuthenticationType_AUTHENTICATION_TYPE_UNSPECIFIED, nil - case pb.AuthenticationType_AUTHENTICATION_TYPE_WEB_OAUTH: - return AuthenticationType_AUTHENTICATION_TYPE_WEB_OAUTH, nil - case pb.AuthenticationType_AUTHENTICATION_TYPE_API_KEY: - return AuthenticationType_AUTHENTICATION_TYPE_API_KEY, nil - case pb.AuthenticationType_AUTHENTICATION_TYPE_ROBOT_PART_SECRET: - return AuthenticationType_AUTHENTICATION_TYPE_ROBOT_PART_SECRET, nil - case pb.AuthenticationType_AUTHENTICATION_TYPE_LOCATION_SECRET: - return AuthenticationType_AUTHENTICATION_TYPE_LOCATION_SECRET, nil - default: - return 0, fmt.Errorf("uknown authentication type: %v", authenticationType) - } -} - -func AuthenticationTypeToProto(authenticationType AuthenticationType) (pb.AuthenticationType, error) { - switch authenticationType{ - case AuthenticationType_AUTHENTICATION_TYPE_UNSPECIFIED: - return pb.AuthenticationType_AUTHENTICATION_TYPE_UNSPECIFIED, nil - case AuthenticationType_AUTHENTICATION_TYPE_WEB_OAUTH: - return pb.AuthenticationType_AUTHENTICATION_TYPE_WEB_OAUTH, nil - case AuthenticationType_AUTHENTICATION_TYPE_API_KEY: - return pb.AuthenticationType_AUTHENTICATION_TYPE_API_KEY, nil - case AuthenticationType_AUTHENTICATION_TYPE_ROBOT_PART_SECRET: - return pb.AuthenticationType_AUTHENTICATION_TYPE_ROBOT_PART_SECRET, nil - case AuthenticationType_AUTHENTICATION_TYPE_LOCATION_SECRET: - return pb.AuthenticationType_AUTHENTICATION_TYPE_LOCATION_SECRET, nil - default: - return 0, fmt.Errorf("unknown authentication type: %v", authenticationType) - } -} - -type APIKeyWithAuthorizations struct { - ApiKey *APIKey - Authorizations []*AuthorizationDetails -} - -func ProtoToAPIKeyWithAuthorizations(key *pb.APIKeyWithAuthorizations) *APIKeyWithAuthorizations { - var details []*AuthorizationDetails - for _, detail := range(key.Authorizations){ - details = append(details, ProtoToAuthorizationDetails(detail)) - } - return &APIKeyWithAuthorizations{ - ApiKey: ProtoToAPIKey(key.ApiKey), - Authorizations: details, - } -} - -func APIKeyWithAuthorizationsToProto(key *APIKeyWithAuthorizations) *pb.APIKeyWithAuthorizations { - var details []*pb.AuthorizationDetails - for _, detail := range(key.Authorizations){ - details = append(details, AuthorizationDetailsToProto(detail)) - } - return &pb.APIKeyWithAuthorizations{ - ApiKey: APIKeyToProto(key.ApiKey), - Authorizations: details, - } -} - -type APIKey struct { - Id string - Key string - Name string - CreatedOn *timestamppb.Timestamp -} - -func ProtoToAPIKey(key *pb.APIKey) *APIKey { - return &APIKey{ - Id: key.Id, - Key: key.Key, - Name: key.Name, - CreatedOn: key.CreatedOn, - } -} - -func APIKeyToProto(key *APIKey) *pb.APIKey { - return &pb.APIKey{ - Id: key.Id, - Key: key.Key, - Name: key.Name, - CreatedOn: key.CreatedOn, - } -} - -type AuthorizationDetails struct { - AuthorizationType string - AuthorizationId string - ResourceType string - ResourceId string - OrgId string -} - -func ProtoToAuthorizationDetails(details *pb.AuthorizationDetails) *AuthorizationDetails { - return &AuthorizationDetails{ - AuthorizationType: details.AuthorizationType, - AuthorizationId: details.AuthorizationId, - ResourceType: details.ResourceType, - ResourceId: details.ResourceId, - OrgId: details.OrgId, - } -} - -func AuthorizationDetailsToProto(details *AuthorizationDetails) *pb.AuthorizationDetails { - return &pb.AuthorizationDetails{ - AuthorizationType: details.AuthorizationType, - AuthorizationId: details.AuthorizationId, - ResourceType: details.ResourceType, - ResourceId: details.ResourceId, - OrgId: details.OrgId, - } -} From 63b0802038a6144290a417812d6bd7389e6687be Mon Sep 17 00:00:00 2001 From: purplenicole730 Date: Wed, 13 Nov 2024 11:58:30 -0500 Subject: [PATCH 28/75] make lint --- app/app_client.go | 402 ++++++++++++++++++------------- app/authorization.go | 114 ++++----- app/common.go | 46 ++-- app/fragment.go | 95 ++++---- app/location.go | 120 +++++----- app/log_stream.go | 9 +- app/organization.go | 124 +++++----- app/registry_item.go | 556 ++++++++++++++++++++++--------------------- app/robot.go | 152 ++++++------ 9 files changed, 841 insertions(+), 777 deletions(-) diff --git a/app/app_client.go b/app/app_client.go index a31b7d413df..e20a01ba130 100644 --- a/app/app_client.go +++ b/app/app_client.go @@ -6,10 +6,11 @@ import ( packages "go.viam.com/api/app/packages/v1" pb "go.viam.com/api/app/v1" - "go.viam.com/rdk/logging" "go.viam.com/utils/protoutils" "go.viam.com/utils/rpc" "google.golang.org/protobuf/types/known/timestamppb" + + "go.viam.com/rdk/logging" ) type AppClient struct { @@ -60,41 +61,41 @@ func (c *AppClient) ListOrganizations(ctx context.Context) ([]*Organization, err } // GetOrganizationsWithAccessToLocation gets all the organizations that have access to a location. -func (c *AppClient) GetOrganizationsWithAccessToLocation(ctx context.Context, locationId string) ([]*OrganizationIdentity, error) { +func (c *AppClient) GetOrganizationsWithAccessToLocation(ctx context.Context, locationID string) ([]*OrganizationIdentity, error) { resp, err := c.client.GetOrganizationsWithAccessToLocation(ctx, &pb.GetOrganizationsWithAccessToLocationRequest{ - LocationId: locationId, + LocationId: locationID, }) if err != nil { return nil, err } var organizations []*OrganizationIdentity - for _, org := range(resp.OrganizationIdentities) { + for _, org := range resp.OrganizationIdentities { organizations = append(organizations, ProtoToOrganizationIdentity(org)) } return organizations, nil } // ListOrganizationsByUser lists all the organizations that a user belongs to. -func (c *AppClient) ListOrganizationsByUser(ctx context.Context, userId string) ([]*OrgDetails, error) { +func (c *AppClient) ListOrganizationsByUser(ctx context.Context, userID string) ([]*OrgDetails, error) { resp, err := c.client.ListOrganizationsByUser(ctx, &pb.ListOrganizationsByUserRequest{ - UserId: userId, + UserId: userID, }) if err != nil { return nil, err } var organizations []*OrgDetails - for _, org := range(resp.Orgs) { + for _, org := range resp.Orgs { organizations = append(organizations, ProtoToOrgDetails(org)) } return organizations, nil } // GetOrganization gets an organization. -func (c *AppClient) GetOrganization(ctx context.Context, orgId string) (*Organization, error) { +func (c *AppClient) GetOrganization(ctx context.Context, orgID string) (*Organization, error) { resp, err := c.client.GetOrganization(ctx, &pb.GetOrganizationRequest{ - OrganizationId: orgId, + OrganizationId: orgID, }) if err != nil { return nil, err @@ -114,9 +115,9 @@ func (c *AppClient) GetOrganizationNamespaceAvailability(ctx context.Context, na } // UpdateOrganization updates an organization. -func (c *AppClient) UpdateOrganization(ctx context.Context, orgId string, name, namespace, region, cid *string) (*Organization, error) { +func (c *AppClient) UpdateOrganization(ctx context.Context, orgID string, name, namespace, region, cid *string) (*Organization, error) { resp, err := c.client.UpdateOrganization(ctx, &pb.UpdateOrganizationRequest{ - OrganizationId: orgId, + OrganizationId: orgID, Name: name, PublicNamespace: namespace, Region: region, @@ -129,9 +130,9 @@ func (c *AppClient) UpdateOrganization(ctx context.Context, orgId string, name, } // DeleteOrganization deletes an organization. -func (c *AppClient) DeleteOrganization(ctx context.Context, orgId string) error { +func (c *AppClient) DeleteOrganization(ctx context.Context, orgID string) error { _, err := c.client.DeleteOrganization(ctx, &pb.DeleteOrganizationRequest{ - OrganizationId: orgId, + OrganizationId: orgID, }) if err != nil { return err @@ -140,33 +141,35 @@ func (c *AppClient) DeleteOrganization(ctx context.Context, orgId string) error } // ListOrganizationMembers lists all members of an organization and all invited members to the organization. -func (c *AppClient) ListOrganizationMembers(ctx context.Context, orgId string) ([]*OrganizationMember, []*OrganizationInvite, error) { +func (c *AppClient) ListOrganizationMembers(ctx context.Context, orgID string) ([]*OrganizationMember, []*OrganizationInvite, error) { resp, err := c.client.ListOrganizationMembers(ctx, &pb.ListOrganizationMembersRequest{ - OrganizationId: orgId, + OrganizationId: orgID, }) if err != nil { return nil, nil, err } var members []*OrganizationMember - for _, member := range(resp.Members) { + for _, member := range resp.Members { members = append(members, ProtoToOrganizationMember(member)) } var invites []*OrganizationInvite - for _, invite := range(resp.Invites) { + for _, invite := range resp.Invites { invites = append(invites, ProtoToOrganizationInvite(invite)) } return members, invites, nil } // CreateOrganizaitonInvite creates an organization invite to an organization. -func (c *AppClient) CreateOrganizationInvite(ctx context.Context, orgId, email string, authorizations []*Authorization, sendEmailInvite *bool) (*OrganizationInvite, error) { +func (c *AppClient) CreateOrganizationInvite( + ctx context.Context, orgID, email string, authorizations []*Authorization, sendEmailInvite *bool, +) (*OrganizationInvite, error) { var pbAuthorizations []*pb.Authorization - for _, authorization := range(authorizations) { + for _, authorization := range authorizations { pbAuthorizations = append(pbAuthorizations, AuthorizationToProto(authorization)) } resp, err := c.client.CreateOrganizationInvite(ctx, &pb.CreateOrganizationInviteRequest{ - OrganizationId: orgId, + OrganizationId: orgID, Email: email, Authorizations: pbAuthorizations, SendEmailInvite: sendEmailInvite, @@ -178,17 +181,19 @@ func (c *AppClient) CreateOrganizationInvite(ctx context.Context, orgId, email s } // UpdateOrganizationInviteAuthorizations updates the authorizations attached to an organization invite. -func (c *AppClient) UpdateOrganizationInviteAuthorizations(ctx context.Context, orgId, email string, addAuthorizations, removeAuthorizations []*Authorization) (*OrganizationInvite, error) { +func (c *AppClient) UpdateOrganizationInviteAuthorizations( + ctx context.Context, orgID, email string, addAuthorizations, removeAuthorizations []*Authorization, +) (*OrganizationInvite, error) { var pbAddAuthorizations []*pb.Authorization - for _, authorization := range(addAuthorizations) { + for _, authorization := range addAuthorizations { pbAddAuthorizations = append(pbAddAuthorizations, AuthorizationToProto(authorization)) } var pbRemoveAuthorizations []*pb.Authorization - for _, authorization := range(removeAuthorizations) { + for _, authorization := range removeAuthorizations { pbRemoveAuthorizations = append(pbRemoveAuthorizations, AuthorizationToProto(authorization)) } resp, err := c.client.UpdateOrganizationInviteAuthorizations(ctx, &pb.UpdateOrganizationInviteAuthorizationsRequest{ - OrganizationId: orgId, + OrganizationId: orgID, Email: email, AddAuthorizations: pbAddAuthorizations, RemoveAuthorizations: pbRemoveAuthorizations, @@ -200,10 +205,10 @@ func (c *AppClient) UpdateOrganizationInviteAuthorizations(ctx context.Context, } // DeleteOrganizationMember deletes an organization member from an organization. -func (c *AppClient) DeleteOrganizationMember(ctx context.Context, orgId, userId string) error { +func (c *AppClient) DeleteOrganizationMember(ctx context.Context, orgID, userID string) error { _, err := c.client.DeleteOrganizationMember(ctx, &pb.DeleteOrganizationMemberRequest{ - OrganizationId: orgId, - UserId: userId, + OrganizationId: orgID, + UserId: userID, }) if err != nil { return err @@ -212,9 +217,9 @@ func (c *AppClient) DeleteOrganizationMember(ctx context.Context, orgId, userId } // DeleteOrganizationInvite deletes an organization invite. -func (c *AppClient) DeleteOrganizationInvite(ctx context.Context, orgId, email string) error { +func (c *AppClient) DeleteOrganizationInvite(ctx context.Context, orgID, email string) error { _, err := c.client.DeleteOrganizationInvite(ctx, &pb.DeleteOrganizationInviteRequest{ - OrganizationId: orgId, + OrganizationId: orgID, Email: email, }) if err != nil { @@ -224,9 +229,9 @@ func (c *AppClient) DeleteOrganizationInvite(ctx context.Context, orgId, email s } // ResendOrganizationInvite resends an organization invite. -func (c *AppClient) ResendOrganizationInvite(ctx context.Context, orgId, email string) (*OrganizationInvite, error) { +func (c *AppClient) ResendOrganizationInvite(ctx context.Context, orgID, email string) (*OrganizationInvite, error) { resp, err := c.client.ResendOrganizationInvite(ctx, &pb.ResendOrganizationInviteRequest{ - OrganizationId: orgId, + OrganizationId: orgID, Email: email, }) if err != nil { @@ -236,11 +241,11 @@ func (c *AppClient) ResendOrganizationInvite(ctx context.Context, orgId, email s } // CreateLocation creates a location. -func (c *AppClient) CreateLocation(ctx context.Context, orgId, name string, parentLocationId *string) (*Location, error) { +func (c *AppClient) CreateLocation(ctx context.Context, orgID, name string, parentLocationID *string) (*Location, error) { resp, err := c.client.CreateLocation(ctx, &pb.CreateLocationRequest{ - OrganizationId: orgId, + OrganizationId: orgID, Name: name, - ParentLocationId: parentLocationId, + ParentLocationId: parentLocationID, }) if err != nil { return nil, err @@ -253,9 +258,9 @@ func (c *AppClient) CreateLocation(ctx context.Context, orgId, name string, pare } // GetLocation gets a location. -func (c *AppClient) GetLocation(ctx context.Context, locationId string) (*Location, error) { +func (c *AppClient) GetLocation(ctx context.Context, locationID string) (*Location, error) { resp, err := c.client.GetLocation(ctx, &pb.GetLocationRequest{ - LocationId: locationId, + LocationId: locationID, }) if err != nil { return nil, err @@ -268,11 +273,11 @@ func (c *AppClient) GetLocation(ctx context.Context, locationId string) (*Locati } // UpdateLocation updates a location. -func (c *AppClient) UpdateLocation(ctx context.Context, locationId string, name, parentLocationId, region *string) (*Location, error) { +func (c *AppClient) UpdateLocation(ctx context.Context, locationID string, name, parentLocationID, region *string) (*Location, error) { resp, err := c.client.UpdateLocation(ctx, &pb.UpdateLocationRequest{ - LocationId: locationId, + LocationId: locationID, Name: name, - ParentLocationId: parentLocationId, + ParentLocationId: parentLocationID, Region: region, }) if err != nil { @@ -286,9 +291,9 @@ func (c *AppClient) UpdateLocation(ctx context.Context, locationId string, name, } // DeleteLocation deletes a location. -func (c *AppClient) DeleteLocation(ctx context.Context, locationId string) error { +func (c *AppClient) DeleteLocation(ctx context.Context, locationID string) error { _, err := c.client.DeleteLocation(ctx, &pb.DeleteLocationRequest{ - LocationId: locationId, + LocationId: locationID, }) if err != nil { return err @@ -297,16 +302,16 @@ func (c *AppClient) DeleteLocation(ctx context.Context, locationId string) error } // ListLocations gets a list of locations under the specified organization. -func (c *AppClient) ListLocations(ctx context.Context, orgId string) ([]*Location, error) { +func (c *AppClient) ListLocations(ctx context.Context, orgID string) ([]*Location, error) { resp, err := c.client.ListLocations(ctx, &pb.ListLocationsRequest{ - OrganizationId: orgId, + OrganizationId: orgID, }) if err != nil { return nil, err } var locations []*Location - for _, location := range(resp.Locations) { + for _, location := range resp.Locations { l, err := ProtoToLocation(location) if err != nil { return nil, err @@ -317,10 +322,10 @@ func (c *AppClient) ListLocations(ctx context.Context, orgId string) ([]*Locatio } // ShareLocation shares a location with an organization. -func (c *AppClient) ShareLocation(ctx context.Context, locationId, orgId string) error { +func (c *AppClient) ShareLocation(ctx context.Context, locationID, orgID string) error { _, err := c.client.ShareLocation(ctx, &pb.ShareLocationRequest{ - LocationId: locationId, - OrganizationId: orgId, + LocationId: locationID, + OrganizationId: orgID, }) if err != nil { return err @@ -329,10 +334,10 @@ func (c *AppClient) ShareLocation(ctx context.Context, locationId, orgId string) } // UnshareLocation stops sharing a location with an organization. -func (c *AppClient) UnshareLocation(ctx context.Context, locationId, orgId string) error { +func (c *AppClient) UnshareLocation(ctx context.Context, locationID, orgID string) error { _, err := c.client.UnshareLocation(ctx, &pb.UnshareLocationRequest{ - LocationId: locationId, - OrganizationId: orgId, + LocationId: locationID, + OrganizationId: orgID, }) if err != nil { return err @@ -341,9 +346,9 @@ func (c *AppClient) UnshareLocation(ctx context.Context, locationId, orgId strin } // LocationAuth gets a location's authorization secrets. -func (c *AppClient) LocationAuth(ctx context.Context, locationId string) (*LocationAuth, error) { +func (c *AppClient) LocationAuth(ctx context.Context, locationID string) (*LocationAuth, error) { resp, err := c.client.LocationAuth(ctx, &pb.LocationAuthRequest{ - LocationId: locationId, + LocationId: locationID, }) if err != nil { return nil, err @@ -356,9 +361,9 @@ func (c *AppClient) LocationAuth(ctx context.Context, locationId string) (*Locat } // CreateLocationSecret creates a new generated secret in the location. Succeeds if there are no more than 2 active secrets after creation. -func (c *AppClient) CreateLocationSecret(ctx context.Context, locationId string) (*LocationAuth, error) { +func (c *AppClient) CreateLocationSecret(ctx context.Context, locationID string) (*LocationAuth, error) { resp, err := c.client.CreateLocationSecret(ctx, &pb.CreateLocationSecretRequest{ - LocationId: locationId, + LocationId: locationID, }) if err != nil { return nil, err @@ -371,10 +376,10 @@ func (c *AppClient) CreateLocationSecret(ctx context.Context, locationId string) } // Delete a secret from the location. -func (c *AppClient) DeleteLocationSecret(ctx context.Context, locationId, secretId string) error { +func (c *AppClient) DeleteLocationSecret(ctx context.Context, locationID, secretID string) error { _, err := c.client.DeleteLocationSecret(ctx, &pb.DeleteLocationSecretRequest{ - LocationId: locationId, - SecretId: secretId, + LocationId: locationID, + SecretId: secretID, }) if err != nil { return err @@ -394,15 +399,15 @@ func (c *AppClient) GetRobot(ctx context.Context, id string) (*Robot, error) { } // GetRoverRentalRobots gets rover rental robots within an organization. -func (c *AppClient) GetRoverRentalRobots(ctx context.Context, orgId string) ([]*RoverRentalRobot, error) { +func (c *AppClient) GetRoverRentalRobots(ctx context.Context, orgID string) ([]*RoverRentalRobot, error) { resp, err := c.client.GetRoverRentalRobots(ctx, &pb.GetRoverRentalRobotsRequest{ - OrgId: orgId, + OrgId: orgID, }) if err != nil { return nil, err } var robots []*RoverRentalRobot - for _, robot := range(resp.Robots) { + for _, robot := range resp.Robots { robots = append(robots, ProtoToRoverRentalRobot(robot)) } return robots, nil @@ -410,14 +415,15 @@ func (c *AppClient) GetRoverRentalRobots(ctx context.Context, orgId string) ([]* // GetRobotParts gets a list of all the parts under a specific machine. func (c *AppClient) GetRobotParts(ctx context.Context, robotId string) ([]*RobotPart, error) { +func (c *AppClient) GetRobotParts(ctx context.Context, robotID string) ([]*RobotPart, error) { resp, err := c.client.GetRobotParts(ctx, &pb.GetRobotPartsRequest{ - RobotId: robotId, + RobotId: robotID, }) if err != nil { return nil, err } var parts []*RobotPart - for _, part := range(resp.Parts) { + for _, part := range resp.Parts { p, err := ProtoToRobotPart(part) if err != nil { return nil, err @@ -442,8 +448,19 @@ func (c *AppClient) GetRobotPart(ctx context.Context, id string) (*RobotPart, st return part, resp.ConfigJson, nil } -// GetRobotPartLogs gets the logs associated with a robot part from a page, defaulting to the most recent page if pageToken is empty. Logs of all levels are returned when levels is empty. -func (c *AppClient) GetRobotPartLogs(ctx context.Context, id string, filter, pageToken *string, levels []string, start, end *timestamppb.Timestamp, limit *int64, source *string) ([]*LogEntry, string, error) { +// GetRobotPartLogs gets the logs associated with a robot part from a page, defaulting to the most recent page if pageToken is empty. +// Logs of all levels are returned when levels is empty. +func (c *AppClient) GetRobotPartLogs( + ctx context.Context, + id string, + filter, + pageToken *string, + levels []string, + start, + end *timestamppb.Timestamp, + limit *int64, + source *string, +) ([]*LogEntry, string, error) { resp, err := c.client.GetRobotPartLogs(ctx, &pb.GetRobotPartLogsRequest{ Id: id, Filter: filter, @@ -458,7 +475,7 @@ func (c *AppClient) GetRobotPartLogs(ctx context.Context, id string, filter, pag return nil, "", err } var logs []*LogEntry - for _, log := range(resp.Logs){ + for _, log := range resp.Logs { l, err := ProtoToLogEntry(log) if err != nil { return nil, "", err @@ -470,7 +487,7 @@ func (c *AppClient) GetRobotPartLogs(ctx context.Context, id string, filter, pag // TailRobotPartLogs gets a stream of log entries for a specific robot part. Logs are ordered by newest first. func (c *AppClient) TailRobotPartLogs(ctx context.Context, id string, errorsOnly bool, filter *string, ch chan []*LogEntry) error { - stream := &logStream {client: c} + stream := &logStream{client: c} err := stream.startStream(ctx, id, errorsOnly, filter, ch) if err != nil { @@ -491,7 +508,7 @@ func (c *AppClient) GetRobotPartHistory(ctx context.Context, id string) ([]*Robo return nil, err } var history []*RobotPartHistoryEntry - for _, entry := range(resp.History){ + for _, entry := range resp.History { e, err := ProtoToRobotPartHistoryEntry(entry) if err != nil { return nil, err @@ -526,6 +543,7 @@ func (c *AppClient) UpdateRobotPart(ctx context.Context, id, name string, robotC func (c *AppClient) NewRobotPart(ctx context.Context, robotId, partName string) (string, error) { resp, err := c.client.NewRobotPart(ctx, &pb.NewRobotPartRequest{ RobotId: robotId, + RobotId: robotID, PartName: partName, }) if err != nil { @@ -537,7 +555,7 @@ func (c *AppClient) NewRobotPart(ctx context.Context, robotId, partName string) // DeleteRobotPart deletes a robot part. func (c *AppClient) DeleteRobotPart(ctx context.Context, partId string) error { _, err := c.client.DeleteRobotPart(ctx, &pb.DeleteRobotPartRequest{ - PartId: partId, + PartId: partID, }) if err != nil { return err @@ -546,24 +564,24 @@ func (c *AppClient) DeleteRobotPart(ctx context.Context, partId string) error { } // GetRobotAPIKeys gets the robot API keys for the robot. -func (c *AppClient) GetRobotAPIKeys(ctx context.Context, robotId string) ([]*APIKeyWithAuthorizations, error) { +func (c *AppClient) GetRobotAPIKeys(ctx context.Context, robotID string) ([]*APIKeyWithAuthorizations, error) { resp, err := c.client.GetRobotAPIKeys(ctx, &pb.GetRobotAPIKeysRequest{ - RobotId: robotId, + RobotId: robotID, }) if err != nil { return nil, err } var keys []*APIKeyWithAuthorizations - for _, key := range(resp.ApiKeys) { + for _, key := range resp.ApiKeys { keys = append(keys, ProtoToAPIKeyWithAuthorizations(key)) } return keys, nil } // MarkPartAsMain marks the given part as the main part, and all the others as not. -func (c *AppClient) MarkPartAsMain(ctx context.Context, partId string) error { +func (c *AppClient) MarkPartAsMain(ctx context.Context, partID string) error { _, err := c.client.MarkPartAsMain(ctx, &pb.MarkPartAsMainRequest{ - PartId: partId, + PartId: partID, }) if err != nil { return err @@ -571,10 +589,12 @@ func (c *AppClient) MarkPartAsMain(ctx context.Context, partId string) error { return nil } -// MarkPartForRestart marks the given part for restart. Once the robot part checks-in with the app the flag is reset on the robot part. Calling this multiple times before a robot part checks-in has no effect. -func (c *AppClient) MarkPartForRestart(ctx context.Context, partId string) error { +// MarkPartForRestart marks the given part for restart. +// Once the robot part checks-in with the app the flag is reset on the robot part. +// Calling this multiple times before a robot part checks-in has no effect. +func (c *AppClient) MarkPartForRestart(ctx context.Context, partID string) error { _, err := c.client.MarkPartForRestart(ctx, &pb.MarkPartForRestartRequest{ - PartId: partId, + PartId: partID, }) if err != nil { return err @@ -582,7 +602,8 @@ func (c *AppClient) MarkPartForRestart(ctx context.Context, partId string) error return nil } -// CreateRobotPartSecret creates a new generated secret in the robot part. Succeeds if there are no more than 2 active secrets after creation. +// CreateRobotPartSecret creates a new generated secret in the robot part. +// Succeeds if there are no more than 2 active secrets after creation. func (c *AppClient) CreateRobotPartSecret(ctx context.Context, partId string) (*RobotPart, error) { resp, err := c.client.CreateRobotPartSecret(ctx, &pb.CreateRobotPartSecretRequest{ PartId: partId, @@ -598,9 +619,9 @@ func (c *AppClient) CreateRobotPartSecret(ctx context.Context, partId string) (* } // DeleteRobotPartSecret deletes a secret from the robot part. -func (c *AppClient) DeleteRobotPartSecret(ctx context.Context, partId, secretId string) error { +func (c *AppClient) DeleteRobotPartSecret(ctx context.Context, partID, secretId string) error { _, err := c.client.DeleteRobotPartSecret(ctx, &pb.DeleteRobotPartSecretRequest{ - PartId: partId, + PartId: partID, SecretId: secretId, }) if err != nil { @@ -610,15 +631,15 @@ func (c *AppClient) DeleteRobotPartSecret(ctx context.Context, partId, secretId } // ListRobots gets a list of robots under a location. -func (c *AppClient) ListRobots(ctx context.Context, locationId string) ([]*Robot, error) { +func (c *AppClient) ListRobots(ctx context.Context, locationID string) ([]*Robot, error) { resp, err := c.client.ListRobots(ctx, &pb.ListRobotsRequest{ - LocationId: locationId, + LocationId: locationID, }) if err != nil { return nil, err } var robots []*Robot - for _, robot := range(resp.Robots) { + for _, robot := range resp.Robots { robots = append(robots, ProtoToRobot(robot)) } return robots, nil @@ -661,9 +682,11 @@ func (c *AppClient) DeleteRobot(ctx context.Context, id string) error { } // ListFragments gets a list of fragments. -func (c *AppClient) ListFragments(ctx context.Context, orgId string, showPublic bool, fragmentVisibility []FragmentVisibility) ([]*Fragment, error) { +func (c *AppClient) ListFragments( + ctx context.Context, orgId string, showPublic bool, fragmentVisibility []FragmentVisibility, +) ([]*Fragment, error) { var visibilities []pb.FragmentVisibility - for _, visibility := range(fragmentVisibility) { + for _, visibility := range fragmentVisibility { v, err := FragmentVisibilityToProto(visibility) if err != nil { return nil, err @@ -679,7 +702,7 @@ func (c *AppClient) ListFragments(ctx context.Context, orgId string, showPublic return nil, err } var fragments []*Fragment - for _, fragment := range(resp.Fragments) { + for _, fragment := range resp.Fragments { f, err := ProtoToFragment(fragment) if err != nil { return nil, err @@ -705,7 +728,9 @@ func (c *AppClient) GetFragment(ctx context.Context, id string) (*Fragment, erro } // CreateFragment creates a fragment. -func (c *AppClient) CreateFragment(ctx context.Context, name string, config interface{}, orgId string, visibility *FragmentVisibility) (*Fragment, error) { +func (c *AppClient) CreateFragment( + ctx context.Context, name string, config interface{}, orgID string, visibility *FragmentVisibility, +) (*Fragment, error) { cfg, err := protoutils.StructToStructPb(config) if err != nil { return nil, err @@ -717,7 +742,7 @@ func (c *AppClient) CreateFragment(ctx context.Context, name string, config inte resp, err := c.client.CreateFragment(ctx, &pb.CreateFragmentRequest{ Name: name, Config: cfg, - OrganizationId: orgId, + OrganizationId: orgID, Visibility: &v, }) if err != nil { @@ -731,7 +756,9 @@ func (c *AppClient) CreateFragment(ctx context.Context, name string, config inte } // UpdateFragment updates a fragment. -func (c *AppClient) UpdateFragment(ctx context.Context, id, name string, config interface{}, public *bool, visibility *pb.FragmentVisibility) (*Fragment, error) { +func (c *AppClient) UpdateFragment( + ctx context.Context, id, name string, config interface{}, public *bool, visibility *pb.FragmentVisibility, +) (*Fragment, error) { cfg, err := protoutils.StructToStructPb(config) if err != nil { return nil, err @@ -764,17 +791,18 @@ func (c *AppClient) DeleteFragment(ctx context.Context, id string) error { return nil } -// ListMachineFragments gets top level and nested fragments for a amchine, as well as any other fragments specified by IDs. Additional fragments are useful when needing to view fragments that will be provisionally added to the machine alongside existing fragments. -func (c *AppClient) ListMachineFragments(ctx context.Context, machineId string, additionalFragmentIds []string) ([]*Fragment, error) { +// ListMachineFragments gets top level and nested fragments for a amchine, as well as any other fragments specified by IDs. Additional +// fragments are useful when needing to view fragments that will be provisionally added to the machine alongside existing fragments. +func (c *AppClient) ListMachineFragments(ctx context.Context, machineID string, additionalFragmentIds []string) ([]*Fragment, error) { resp, err := c.client.ListMachineFragments(ctx, &pb.ListMachineFragmentsRequest{ - MachineId: machineId, + MachineId: machineID, AdditionalFragmentIds: additionalFragmentIds, }) if err != nil { return nil, err } var fragments []*Fragment - for _, fragment := range(resp.Fragments) { + for _, fragment := range resp.Fragments { f, err := ProtoToFragment(fragment) if err != nil { return nil, err @@ -785,7 +813,9 @@ func (c *AppClient) ListMachineFragments(ctx context.Context, machineId string, } // GetFragmentHistory gets the fragment's history. -func (c *AppClient) GetFragmentHistory(ctx context.Context, id string, pageToken *string, pageLimit *int64) ([]*FragmentHistoryEntry, string, error) { +func (c *AppClient) GetFragmentHistory( + ctx context.Context, id string, pageToken *string, pageLimit *int64, +) ([]*FragmentHistoryEntry, string, error) { resp, err := c.client.GetFragmentHistory(ctx, &pb.GetFragmentHistoryRequest{ Id: id, PageToken: pageToken, @@ -795,7 +825,7 @@ func (c *AppClient) GetFragmentHistory(ctx context.Context, id string, pageToken return nil, "", err } var history []*FragmentHistoryEntry - for _, entry := range(resp.History) { + for _, entry := range resp.History { e, err := ProtoToFragmentHistoryEntry(entry) if err != nil { return nil, "", err @@ -806,8 +836,8 @@ func (c *AppClient) GetFragmentHistory(ctx context.Context, id string, pageToken } // AddRole creates an identity authorization. -func (c *AppClient) AddRole(ctx context.Context, orgId, identityId, role, resourceType, resourceId string) error { - authorization, err := createAuthorization(orgId, identityId, "", role, resourceType, resourceId) +func (c *AppClient) AddRole(ctx context.Context, orgID, identityId, role, resourceType, resourceId string) error { + authorization, err := createAuthorization(orgID, identityId, "", role, resourceType, resourceId) if err != nil { return err } @@ -821,8 +851,8 @@ func (c *AppClient) AddRole(ctx context.Context, orgId, identityId, role, resour } // RemoveRole deletes an identity authorization. -func (c *AppClient) RemoveRole(ctx context.Context, orgId, identityId, role, resourceType, resourceId string) error { - authorization, err := createAuthorization(orgId, identityId, "", role, resourceType, resourceId) +func (c *AppClient) RemoveRole(ctx context.Context, orgID, identityId, role, resourceType, resourceId string) error { + authorization, err := createAuthorization(orgID, identityId, "", role, resourceType, resourceId) if err != nil { return err } @@ -836,12 +866,24 @@ func (c *AppClient) RemoveRole(ctx context.Context, orgId, identityId, role, res } // ChangeRole changes an identity authorization to a new identity authorization. -func (c *AppClient) ChangeRole(ctx context.Context, oldOrgId, oldIdentityId, oldRole, oldResourceType, oldResourceId, newOrgId, newIdentityId, newRole, newResourceType, newResourceId string) error { - oldAuthorization, err := createAuthorization(oldOrgId, oldIdentityId, "", oldRole, oldResourceType, oldResourceId) +func (c *AppClient) ChangeRole( + ctx context.Context, + oldOrgID, + oldIdentityId, + oldRole, + oldResourceType, + oldResourceID, + newOrgID, + newIdentityID, + newRole, + newResourceType, + newResourceID string, +) error { + oldAuthorization, err := createAuthorization(oldOrgID, oldIdentityId, "", oldRole, oldResourceType, oldResourceID) if err != nil { return err } - newAuthorization, err := createAuthorization(newOrgId, newIdentityId, "", newRole, newResourceType, newResourceId) + newAuthorization, err := createAuthorization(newOrgID, newIdentityID, "", newRole, newResourceType, newResourceID) if err != nil { return err } @@ -855,17 +897,18 @@ func (c *AppClient) ChangeRole(ctx context.Context, oldOrgId, oldIdentityId, old return nil } -// listAuthorizations returns all authorization roles for any given resources. If no resources are given, all resources within the organization will be included. -func (c *AppClient) ListAuthorizations(ctx context.Context, orgId string, resourceIds []string) ([]*Authorization, error) { +// ListAuthorizations returns all authorization roles for any given resources. +// If no resources are given, all resources within the organization will be included. +func (c *AppClient) ListAuthorizations(ctx context.Context, orgID string, resourceIds []string) ([]*Authorization, error) { resp, err := c.client.ListAuthorizations(ctx, &pb.ListAuthorizationsRequest{ - OrganizationId: orgId, + OrganizationId: orgID, ResourceIds: resourceIds, }) if err != nil { return nil, err } var authorizations []*Authorization - for _, authorization := range(resp.Authorizations) { + for _, authorization := range resp.Authorizations { authorizations = append(authorizations, ProtoToAuthorization(authorization)) } return authorizations, nil @@ -874,10 +917,10 @@ func (c *AppClient) ListAuthorizations(ctx context.Context, orgId string, resour // CheckPermissions checks the validity of a list of permissions. func (c *AppClient) CheckPermissions(ctx context.Context, permissions []*AuthorizedPermissions) ([]*AuthorizedPermissions, error) { var pbPermissions []*pb.AuthorizedPermissions - for _, permission := range(permissions){ + for _, permission := range permissions { pbPermissions = append(pbPermissions, AuthorizedPermissionsToProto(permission)) } - + resp, err := c.client.CheckPermissions(ctx, &pb.CheckPermissionsRequest{ Permissions: pbPermissions, }) @@ -886,16 +929,16 @@ func (c *AppClient) CheckPermissions(ctx context.Context, permissions []*Authori } var authorizedPermissions []*AuthorizedPermissions - for _, permission := range(resp.AuthorizedPermissions){ + for _, permission := range resp.AuthorizedPermissions { authorizedPermissions = append(authorizedPermissions, ProtoToAuthorizedPermissions(permission)) } return authorizedPermissions, nil } // GetRegistryItem gets a registry item. -func (c *AppClient) GetRegistryItem(ctx context.Context, itemId string) (*RegistryItem, error) { +func (c *AppClient) GetRegistryItem(ctx context.Context, itemID string) (*RegistryItem, error) { resp, err := c.client.GetRegistryItem(ctx, &pb.GetRegistryItemRequest{ - ItemId: itemId, + ItemId: itemID, }) if err != nil { return nil, err @@ -908,13 +951,13 @@ func (c *AppClient) GetRegistryItem(ctx context.Context, itemId string) (*Regist } // CreateRegistryItem creates a registry item. -func (c *AppClient) CreateRegistryItem(ctx context.Context, orgId, name string, packageType PackageType) error { +func (c *AppClient) CreateRegistryItem(ctx context.Context, orgID, name string, packageType PackageType) error { pbPackageType, err := PackageTypeToProto(packageType) if err != nil { return err } _, err = c.client.CreateRegistryItem(ctx, &pb.CreateRegistryItemRequest{ - OrganizationId: orgId, + OrganizationId: orgID, Name: name, Type: pbPackageType, }) @@ -925,7 +968,9 @@ func (c *AppClient) CreateRegistryItem(ctx context.Context, orgId, name string, } // UpdateRegistryItem updates a registry item. -func (c *AppClient) UpdateRegistryItem(ctx context.Context, itemId string, packageType PackageType, description string, visibility Visibility, url *string) error { +func (c *AppClient) UpdateRegistryItem( + ctx context.Context, itemID string, packageType PackageType, description string, visibility Visibility, url *string, +) error { pbPackageType, err := PackageTypeToProto(packageType) if err != nil { return err @@ -935,7 +980,7 @@ func (c *AppClient) UpdateRegistryItem(ctx context.Context, itemId string, packa return err } _, err = c.client.UpdateRegistryItem(ctx, &pb.UpdateRegistryItemRequest{ - ItemId: itemId, + ItemId: itemID, Type: pbPackageType, Description: description, Visibility: pbVisibility, @@ -948,9 +993,19 @@ func (c *AppClient) UpdateRegistryItem(ctx context.Context, itemId string, packa } // ListRegistryItems lists the registry items in an organization. -func (c *AppClient) ListRegistryItems(ctx context.Context, orgId *string, types []PackageType, visibilities []Visibility, platforms []string, statuses []RegistryItemStatus, searchTerm, pageToken *string, publicNamespaces []string) ([]*RegistryItem, error) { +func (c *AppClient) ListRegistryItems( + ctx context.Context, + orgID *string, + types []PackageType, + visibilities []Visibility, + platforms []string, + statuses []RegistryItemStatus, + searchTerm, + pageToken *string, + publicNamespaces []string, +) ([]*RegistryItem, error) { var pbTypes []packages.PackageType - for _, packageType := range(types){ + for _, packageType := range types { t, err := PackageTypeToProto(packageType) if err != nil { return nil, err @@ -958,7 +1013,7 @@ func (c *AppClient) ListRegistryItems(ctx context.Context, orgId *string, types pbTypes = append(pbTypes, t) } var pbVisibilities []pb.Visibility - for _, visibility := range(visibilities){ + for _, visibility := range visibilities { v, err := VisibilityToProto(visibility) if err != nil { return nil, err @@ -966,7 +1021,7 @@ func (c *AppClient) ListRegistryItems(ctx context.Context, orgId *string, types pbVisibilities = append(pbVisibilities, v) } var pbStatuses []pb.RegistryItemStatus - for _, status := range(statuses){ + for _, status := range statuses { s, err := RegistryItemStatusToProto(status) if err != nil { return nil, err @@ -974,7 +1029,7 @@ func (c *AppClient) ListRegistryItems(ctx context.Context, orgId *string, types pbStatuses = append(pbStatuses, s) } resp, err := c.client.ListRegistryItems(ctx, &pb.ListRegistryItemsRequest{ - OrganizationId: orgId, + OrganizationId: orgID, Types: pbTypes, Visibilities: pbVisibilities, Platforms: platforms, @@ -987,7 +1042,7 @@ func (c *AppClient) ListRegistryItems(ctx context.Context, orgId *string, types return nil, err } var items []*RegistryItem - for _, item := range(resp.Items){ + for _, item := range resp.Items { i, err := ProtoToRegistryItem(item) if err != nil { return nil, err @@ -997,10 +1052,11 @@ func (c *AppClient) ListRegistryItems(ctx context.Context, orgId *string, types return items, nil } -// DeleteRegistryItem deletes a registry item given an ID that is formatted as `prefix:name“ where `prefix“ is the owner's organization ID or namespace. -func (c *AppClient) DeleteRegistryItem(ctx context.Context, itemId string) error { +// DeleteRegistryItem deletes a registry item given an ID that is formatted as `prefix:name“ +// where `prefix“ is the owner's organization ID or namespace. +func (c *AppClient) DeleteRegistryItem(ctx context.Context, itemID string) error { _, err := c.client.DeleteRegistryItem(ctx, &pb.DeleteRegistryItemRequest{ - ItemId: itemId, + ItemId: itemID, }) if err != nil { return err @@ -1009,9 +1065,9 @@ func (c *AppClient) DeleteRegistryItem(ctx context.Context, itemId string) error } // TransferRegistryItem transfers a registry item to a namespace. -func (c *AppClient) TransferRegistryItem(ctx context.Context, itemId, newPublicNamespace string) error { +func (c *AppClient) TransferRegistryItem(ctx context.Context, itemID, newPublicNamespace string) error { _, err := c.client.TransferRegistryItem(ctx, &pb.TransferRegistryItemRequest{ - ItemId: itemId, + ItemId: itemID, NewPublicNamespace: newPublicNamespace, }) if err != nil { @@ -1021,9 +1077,9 @@ func (c *AppClient) TransferRegistryItem(ctx context.Context, itemId, newPublicN } // CreateModule creates a module. -func (c *AppClient) CreateModule(ctx context.Context, orgId, name string) (string, string, error) { +func (c *AppClient) CreateModule(ctx context.Context, orgID, name string) (string, string, error) { resp, err := c.client.CreateModule(ctx, &pb.CreateModuleRequest{ - OrganizationId: orgId, + OrganizationId: orgID, Name: name, }) if err != nil { @@ -1032,18 +1088,21 @@ func (c *AppClient) CreateModule(ctx context.Context, orgId, name string) (strin return resp.ModuleId, resp.Url, nil } -// UpdateModule updates the documentation URL, description, models, entrypoint, and/or the visibility of a module. A path to a setup script can be added that is run before a newly downloaded module starts. -func (c *AppClient) UpdateModule(ctx context.Context, moduleId string, visibility Visibility, url, description string, models []*Model, entrypoint string, firstRun *string) (string, error) { +// UpdateModule updates the documentation URL, description, models, entrypoint, and/or the visibility of a module. +// A path to a setup script can be added that is run before a newly downloaded module starts. +func (c *AppClient) UpdateModule( + ctx context.Context, moduleID string, visibility Visibility, url, description string, models []*Model, entrypoint string, firstRun *string, +) (string, error) { pbVisibility, err := VisibilityToProto(visibility) if err != nil { return "", err } var pbModels []*pb.Model - for _, model := range(models) { - pbModels = append(pbModels, ModelToProto(model)) + for _, model := range models { + pbModels = append(pbModels, ModelToProto(model)) } resp, err := c.client.UpdateModule(ctx, &pb.UpdateModuleRequest{ - ModuleId: moduleId, + ModuleId: moduleID, Visibility: pbVisibility, Url: url, Description: description, @@ -1079,39 +1138,39 @@ func (c *AppClient) UpdateModule(ctx context.Context, moduleId string, visibilit // func (c *AppClient) UploadModuleFile(ctx context.Context, moduleFile isModuleFile, ch ) (string, error) { // c.mu.Lock() -// streamCtx, stream, - - // stream := &uploadStream{client: c} - - // err = stream.startStream(ctx, moduleFile, ch) - - // var req *pb.UploadModuleFileRequest - // switch moduleFileInfo := moduleFile.(type) { - // case UploadModuleFileRequest_ModuleFileInfo: - // req = &pb.UploadModuleFileRequest{ - // ModuleFile: &pb.UploadModuleFileRequest_ModuleFileInfo{ - // ModuleFileInfo: moduleFileInfo.ModuleFileInfo, - // }, - // } - // case UploadModuleFileRequest_File: - // req = &pb.UploadModuleFileRequest{ - // ModuleFile: &pb.UploadModuleFileRequest_File{ - // File: moduleFileInfo.File, - // }, - // } - // } - - // resp, err := c.client.UploadModuleFile(ctx, req) - // if err != nil { - // return "", err - // } - // return resp.Url, nil +// streamCtx, stream, + +// stream := &uploadStream{client: c} + +// err = stream.startStream(ctx, moduleFile, ch) + +// var req *pb.UploadModuleFileRequest +// switch moduleFileInfo := moduleFile.(type) { +// case UploadModuleFileRequest_ModuleFileInfo: +// req = &pb.UploadModuleFileRequest{ +// ModuleFile: &pb.UploadModuleFileRequest_ModuleFileInfo{ +// ModuleFileInfo: moduleFileInfo.ModuleFileInfo, +// }, +// } +// case UploadModuleFileRequest_File: +// req = &pb.UploadModuleFileRequest{ +// ModuleFile: &pb.UploadModuleFileRequest_File{ +// File: moduleFileInfo.File, +// }, +// } +// } + +// resp, err := c.client.UploadModuleFile(ctx, req) +// if err != nil { +// return "", err +// } +// return resp.Url, nil // } // GetModule gets a module. -func (c *AppClient) GetModule(ctx context.Context, moduleId string) (*Module, error) { +func (c *AppClient) GetModule(ctx context.Context, moduleID string) (*Module, error) { resp, err := c.client.GetModule(ctx, &pb.GetModuleRequest{ - ModuleId: moduleId, + ModuleId: moduleID, }) if err != nil { return nil, err @@ -1124,15 +1183,15 @@ func (c *AppClient) GetModule(ctx context.Context, moduleId string) (*Module, er } // ListModules lists the modules in the organization. -func (c *AppClient) ListModules(ctx context.Context, orgId *string) ([]*Module, error) { +func (c *AppClient) ListModules(ctx context.Context, orgID *string) ([]*Module, error) { resp, err := c.client.ListModules(ctx, &pb.ListModulesRequest{ - OrganizationId: orgId, + OrganizationId: orgID, }) if err != nil { return nil, err } var modules []*Module - for _, module := range(resp.Modules){ + for _, module := range resp.Modules { m, err := ProtoToModule(module) if err != nil { return nil, err @@ -1143,12 +1202,15 @@ func (c *AppClient) ListModules(ctx context.Context, orgId *string) ([]*Module, } // CreateKey creates a new API key associated with a list of authorizations. -func (c *AppClient) CreateKey(ctx context.Context, orgId string, keyAuthorizations []APIKeyAuthorization, name string) (string, string, error) { +func (c *AppClient) CreateKey( + ctx context.Context, orgID string, keyAuthorizations []APIKeyAuthorization, name string, +) (string, string, error) { var authorizations []*pb.Authorization for _, keyAuthorization := range keyAuthorizations { - authorization, err := createAuthorization(orgId, "", "api-key", keyAuthorization.role, keyAuthorization.resourceType, keyAuthorization.resourceId) + authorization, err := createAuthorization( + orgID, "", "api-key", keyAuthorization.role, keyAuthorization.resourceType, keyAuthorization.resourceID) if err != nil { - return "", "", nil + return "", "", err } authorizations = append(authorizations, authorization) } @@ -1175,15 +1237,15 @@ func (c *AppClient) DeleteKey(ctx context.Context, id string) error { } // ListKeys lists all the keys for the organization. -func (c *AppClient) ListKeys(ctx context.Context, orgId string) ([]APIKeyWithAuthorizations, error) { +func (c *AppClient) ListKeys(ctx context.Context, orgID string) ([]APIKeyWithAuthorizations, error) { resp, err := c.client.ListKeys(ctx, &pb.ListKeysRequest{ - OrgId: orgId, + OrgId: orgID, }) if err != nil { return nil, err } var apiKeys []APIKeyWithAuthorizations - for _, key := range(resp.ApiKeys){ + for _, key := range resp.ApiKeys { apiKeys = append(apiKeys, *ProtoToAPIKeyWithAuthorizations(key)) } return apiKeys, nil diff --git a/app/authorization.go b/app/authorization.go index ad7a9869f62..de78fec7385 100644 --- a/app/authorization.go +++ b/app/authorization.go @@ -8,7 +8,7 @@ import ( "google.golang.org/protobuf/types/known/timestamppb" ) -func createAuthorization(orgId, identityId, identityType, role, resourceType, resourceId string) (*pb.Authorization, error) { +func createAuthorization(orgID, identityID, identityType, role, resourceType, resourceID string) (*pb.Authorization, error) { if role != "owner" && role != "operator" { return nil, errors.New("role string must be 'owner' or 'operator'") } @@ -20,39 +20,39 @@ func createAuthorization(orgId, identityId, identityType, role, resourceType, re AuthorizationType: role, AuthorizationId: fmt.Sprintf("%s_%s", resourceType, role), ResourceType: resourceType, - ResourceId: resourceId, - IdentityId: identityId, - OrganizationId: orgId, + ResourceId: resourceID, + IdentityId: identityID, + OrganizationId: orgID, IdentityType: identityType, }, nil } type AuthenticatorInfo struct { - Type AuthenticationType - Value string + Type AuthenticationType + Value string IsDeactivated bool } -func ProtoToAuthenticatorInfo(info *pb.AuthenticatorInfo) (*AuthenticatorInfo, error){ +func ProtoToAuthenticatorInfo(info *pb.AuthenticatorInfo) (*AuthenticatorInfo, error) { authenticationType, err := ProtoToAuthenticationType(info.Type) if err != nil { return nil, err } return &AuthenticatorInfo{ - Type: authenticationType, - Value: info.Value, + Type: authenticationType, + Value: info.Value, IsDeactivated: info.IsDeactivated, }, nil } -func AuthenticatorInfoToProto(info *AuthenticatorInfo) (*pb.AuthenticatorInfo, error){ +func AuthenticatorInfoToProto(info *AuthenticatorInfo) (*pb.AuthenticatorInfo, error) { authenticationType, err := AuthenticationTypeToProto(info.Type) if err != nil { return nil, err } return &pb.AuthenticatorInfo{ - Type: authenticationType, - Value: info.Value, + Type: authenticationType, + Value: info.Value, IsDeactivated: info.IsDeactivated, }, nil } @@ -60,42 +60,41 @@ func AuthenticatorInfoToProto(info *AuthenticatorInfo) (*pb.AuthenticatorInfo, e type AuthenticationType int32 const ( - AuthenticationType_AUTHENTICATION_TYPE_UNSPECIFIED AuthenticationType = 0 - AuthenticationType_AUTHENTICATION_TYPE_WEB_OAUTH AuthenticationType = 1 - AuthenticationType_AUTHENTICATION_TYPE_API_KEY AuthenticationType = 2 - AuthenticationType_AUTHENTICATION_TYPE_ROBOT_PART_SECRET AuthenticationType = 3 - AuthenticationType_AUTHENTICATION_TYPE_LOCATION_SECRET AuthenticationType = 4 + AuthenticationTypeUnspecified AuthenticationType = 0 + AuthenticationTypeWebOAuth AuthenticationType = 1 + AuthenticationTypeAPIKey AuthenticationType = 2 + AuthenticationTypeRobotPartSecret AuthenticationType = 3 + AuthenticationTypeLocationSecret AuthenticationType = 4 ) - func ProtoToAuthenticationType(authenticationType pb.AuthenticationType) (AuthenticationType, error) { - switch authenticationType{ + switch authenticationType { case pb.AuthenticationType_AUTHENTICATION_TYPE_UNSPECIFIED: - return AuthenticationType_AUTHENTICATION_TYPE_UNSPECIFIED, nil + return AuthenticationTypeUnspecified, nil case pb.AuthenticationType_AUTHENTICATION_TYPE_WEB_OAUTH: - return AuthenticationType_AUTHENTICATION_TYPE_WEB_OAUTH, nil + return AuthenticationTypeWebOAuth, nil case pb.AuthenticationType_AUTHENTICATION_TYPE_API_KEY: - return AuthenticationType_AUTHENTICATION_TYPE_API_KEY, nil + return AuthenticationTypeAPIKey, nil case pb.AuthenticationType_AUTHENTICATION_TYPE_ROBOT_PART_SECRET: - return AuthenticationType_AUTHENTICATION_TYPE_ROBOT_PART_SECRET, nil + return AuthenticationTypeRobotPartSecret, nil case pb.AuthenticationType_AUTHENTICATION_TYPE_LOCATION_SECRET: - return AuthenticationType_AUTHENTICATION_TYPE_LOCATION_SECRET, nil + return AuthenticationTypeLocationSecret, nil default: return 0, fmt.Errorf("uknown authentication type: %v", authenticationType) } } func AuthenticationTypeToProto(authenticationType AuthenticationType) (pb.AuthenticationType, error) { - switch authenticationType{ - case AuthenticationType_AUTHENTICATION_TYPE_UNSPECIFIED: + switch authenticationType { + case AuthenticationTypeUnspecified: return pb.AuthenticationType_AUTHENTICATION_TYPE_UNSPECIFIED, nil - case AuthenticationType_AUTHENTICATION_TYPE_WEB_OAUTH: + case AuthenticationTypeWebOAuth: return pb.AuthenticationType_AUTHENTICATION_TYPE_WEB_OAUTH, nil - case AuthenticationType_AUTHENTICATION_TYPE_API_KEY: + case AuthenticationTypeAPIKey: return pb.AuthenticationType_AUTHENTICATION_TYPE_API_KEY, nil - case AuthenticationType_AUTHENTICATION_TYPE_ROBOT_PART_SECRET: + case AuthenticationTypeRobotPartSecret: return pb.AuthenticationType_AUTHENTICATION_TYPE_ROBOT_PART_SECRET, nil - case AuthenticationType_AUTHENTICATION_TYPE_LOCATION_SECRET: + case AuthenticationTypeLocationSecret: return pb.AuthenticationType_AUTHENTICATION_TYPE_LOCATION_SECRET, nil default: return 0, fmt.Errorf("unknown authentication type: %v", authenticationType) @@ -103,82 +102,83 @@ func AuthenticationTypeToProto(authenticationType AuthenticationType) (pb.Authen } type APIKeyWithAuthorizations struct { - ApiKey *APIKey + APIKey *APIKey Authorizations []*AuthorizationDetails } func ProtoToAPIKeyWithAuthorizations(key *pb.APIKeyWithAuthorizations) *APIKeyWithAuthorizations { var details []*AuthorizationDetails - for _, detail := range(key.Authorizations){ + for _, detail := range key.Authorizations { details = append(details, ProtoToAuthorizationDetails(detail)) } return &APIKeyWithAuthorizations{ - ApiKey: ProtoToAPIKey(key.ApiKey), + APIKey: ProtoToAPIKey(key.ApiKey), Authorizations: details, } } func APIKeyWithAuthorizationsToProto(key *APIKeyWithAuthorizations) *pb.APIKeyWithAuthorizations { var details []*pb.AuthorizationDetails - for _, detail := range(key.Authorizations){ + for _, detail := range key.Authorizations { details = append(details, AuthorizationDetailsToProto(detail)) } return &pb.APIKeyWithAuthorizations{ - ApiKey: APIKeyToProto(key.ApiKey), + ApiKey: APIKeyToProto(key.APIKey), Authorizations: details, } } type APIKey struct { - Id string - Key string - Name string + ID string + Key string + Name string CreatedOn *timestamppb.Timestamp } func ProtoToAPIKey(key *pb.APIKey) *APIKey { return &APIKey{ - Id: key.Id, - Key: key.Key, - Name: key.Name, + ID: key.Id, + Key: key.Key, + Name: key.Name, CreatedOn: key.CreatedOn, } } func APIKeyToProto(key *APIKey) *pb.APIKey { return &pb.APIKey{ - Id: key.Id, - Key: key.Key, - Name: key.Name, + Id: key.ID, + Key: key.Key, + Name: key.Name, CreatedOn: key.CreatedOn, } } type AuthorizationDetails struct { AuthorizationType string - AuthorizationId string - ResourceType string - ResourceId string - OrgId string + AuthorizationID string + ResourceType string + ResourceID string + OrgID string } func ProtoToAuthorizationDetails(details *pb.AuthorizationDetails) *AuthorizationDetails { return &AuthorizationDetails{ AuthorizationType: details.AuthorizationType, - AuthorizationId: details.AuthorizationId, - ResourceType: details.ResourceType, - ResourceId: details.ResourceId, - OrgId: details.OrgId, + AuthorizationID: details.AuthorizationId, + ResourceType: details.ResourceType, + ResourceID: details.ResourceId, + OrgID: details.OrgId, } } +// AuthorizationDetailsToProto converts a AuthorizationDetails struct to protobuf. func AuthorizationDetailsToProto(details *AuthorizationDetails) *pb.AuthorizationDetails { return &pb.AuthorizationDetails{ AuthorizationType: details.AuthorizationType, - AuthorizationId: details.AuthorizationId, - ResourceType: details.ResourceType, - ResourceId: details.ResourceId, - OrgId: details.OrgId, + AuthorizationId: details.AuthorizationID, + ResourceType: details.ResourceType, + ResourceId: details.ResourceID, + OrgId: details.OrgID, } } @@ -188,5 +188,5 @@ type APIKeyAuthorization struct { role string // `resourceType` must be "organization", "location", or "robot" resourceType string - resourceId string + resourceID string } diff --git a/app/common.go b/app/common.go index dcfbcec6b1e..81995b51b08 100644 --- a/app/common.go +++ b/app/common.go @@ -8,38 +8,38 @@ import ( ) type LogEntry struct { - Host string - Level string - Time *timestamppb.Timestamp + Host string + Level string + Time *timestamppb.Timestamp LoggerName string - Message string - Caller *map[string]interface{} - Stack string - Fields []*map[string]interface{} + Message string + Caller *map[string]interface{} + Stack string + Fields []*map[string]interface{} } func ProtoToLogEntry(logEntry *common.LogEntry) (*LogEntry, error) { var fields []*map[string]interface{} - for _, field := range(logEntry.Fields) { + for _, field := range logEntry.Fields { f := field.AsMap() fields = append(fields, &f) } caller := logEntry.Caller.AsMap() return &LogEntry{ - Host: logEntry.Host, - Level: logEntry.Level, - Time: logEntry.Time, + Host: logEntry.Host, + Level: logEntry.Level, + Time: logEntry.Time, LoggerName: logEntry.LoggerName, - Message: logEntry.Message, - Caller: &caller, - Stack: logEntry.Stack, - Fields: fields, + Message: logEntry.Message, + Caller: &caller, + Stack: logEntry.Stack, + Fields: fields, }, nil } func LogEntryToProto(logEntry *LogEntry) (*common.LogEntry, error) { var fields []*structpb.Struct - for _, field := range(logEntry.Fields) { + for _, field := range logEntry.Fields { f, err := protoutils.StructToStructPb(field) if err != nil { return nil, err @@ -51,13 +51,13 @@ func LogEntryToProto(logEntry *LogEntry) (*common.LogEntry, error) { return nil, err } return &common.LogEntry{ - Host: logEntry.Host, - Level: logEntry.Level, - Time: logEntry.Time, + Host: logEntry.Host, + Level: logEntry.Level, + Time: logEntry.Time, LoggerName: logEntry.LoggerName, - Message: logEntry.Message, - Caller: caller, - Stack: logEntry.Stack, - Fields: fields, + Message: logEntry.Message, + Caller: caller, + Stack: logEntry.Stack, + Fields: fields, }, nil } diff --git a/app/fragment.go b/app/fragment.go index fbda3621471..1a524e6b333 100644 --- a/app/fragment.go +++ b/app/fragment.go @@ -9,18 +9,18 @@ import ( ) type Fragment struct { - Id string - Name string - Fragment *map[string]interface{} + ID string + Name string + Fragment *map[string]interface{} OrganizationOwner string - Public bool - CreatedOn *timestamppb.Timestamp - OrganizationName string - RobotPartCount int32 + Public bool + CreatedOn *timestamppb.Timestamp + OrganizationName string + RobotPartCount int32 OrganizationCount int32 - OnlyUsedByOwner bool - Visibility FragmentVisibility - LastUpdated *timestamppb.Timestamp + OnlyUsedByOwner bool + Visibility FragmentVisibility + LastUpdated *timestamppb.Timestamp } func ProtoToFragment(fragment *pb.Fragment) (*Fragment, error) { @@ -30,18 +30,18 @@ func ProtoToFragment(fragment *pb.Fragment) (*Fragment, error) { return nil, err } return &Fragment{ - Id: fragment.Id, - Name: fragment.Name, - Fragment: &f, + ID: fragment.Id, + Name: fragment.Name, + Fragment: &f, OrganizationOwner: fragment.OrganizationOwner, - Public: fragment.Public, - CreatedOn: fragment.CreatedOn, - OrganizationName: fragment.OrganizationName, - RobotPartCount: fragment.RobotPartCount, + Public: fragment.Public, + CreatedOn: fragment.CreatedOn, + OrganizationName: fragment.OrganizationName, + RobotPartCount: fragment.RobotPartCount, OrganizationCount: fragment.OrganizationCount, - OnlyUsedByOwner: fragment.OnlyUsedByOwner, - Visibility: visibility, - LastUpdated: fragment.LastUpdated, + OnlyUsedByOwner: fragment.OnlyUsedByOwner, + Visibility: visibility, + LastUpdated: fragment.LastUpdated, }, nil } @@ -55,54 +55,54 @@ func FragmentToProto(fragment *Fragment) (*pb.Fragment, error) { return nil, err } return &pb.Fragment{ - Id: fragment.Id, - Name: fragment.Name, - Fragment: f, + Id: fragment.ID, + Name: fragment.Name, + Fragment: f, OrganizationOwner: fragment.OrganizationOwner, - Public: fragment.Public, - CreatedOn: fragment.CreatedOn, - OrganizationName: fragment.OrganizationName, - RobotPartCount: fragment.RobotPartCount, + Public: fragment.Public, + CreatedOn: fragment.CreatedOn, + OrganizationName: fragment.OrganizationName, + RobotPartCount: fragment.RobotPartCount, OrganizationCount: fragment.OrganizationCount, - OnlyUsedByOwner: fragment.OnlyUsedByOwner, - Visibility: visibility, - LastUpdated: fragment.LastUpdated, + OnlyUsedByOwner: fragment.OnlyUsedByOwner, + Visibility: visibility, + LastUpdated: fragment.LastUpdated, }, nil } type FragmentVisibility int32 const ( - FragmentVisibility_FRAGMENT_VISIBILITY_UNSPECIFIED FragmentVisibility = 0 - FragmentVisibility_FRAGMENT_VISIBILITY_PRIVATE FragmentVisibility = 1 - FragmentVisibility_FRAGMENT_VISIBILITY_PUBLIC FragmentVisibility = 2 - FragmentVisibility_FRAGMENT_VISIBILITY_PUBLIC_UNLISTED FragmentVisibility = 3 + FragmentVisibilityUnspecified FragmentVisibility = 0 + FragmentVisibilityPrivate FragmentVisibility = 1 + FragmentVisibilityPublic FragmentVisibility = 2 + FragmentVisibilityPublicUnlisted FragmentVisibility = 3 ) func ProtoToFragmentVisibility(visibility pb.FragmentVisibility) (FragmentVisibility, error) { - switch visibility{ + switch visibility { case pb.FragmentVisibility_FRAGMENT_VISIBILITY_UNSPECIFIED: - return FragmentVisibility_FRAGMENT_VISIBILITY_UNSPECIFIED, nil + return FragmentVisibilityUnspecified, nil case pb.FragmentVisibility_FRAGMENT_VISIBILITY_PRIVATE: - return FragmentVisibility_FRAGMENT_VISIBILITY_PRIVATE, nil + return FragmentVisibilityPrivate, nil case pb.FragmentVisibility_FRAGMENT_VISIBILITY_PUBLIC: - return FragmentVisibility_FRAGMENT_VISIBILITY_PUBLIC, nil + return FragmentVisibilityPublic, nil case pb.FragmentVisibility_FRAGMENT_VISIBILITY_PUBLIC_UNLISTED: - return FragmentVisibility_FRAGMENT_VISIBILITY_PUBLIC_UNLISTED, nil + return FragmentVisibilityPublicUnlisted, nil default: return 0, fmt.Errorf("uknown fragment visibililty: %v", visibility) } } func FragmentVisibilityToProto(visibility FragmentVisibility) (pb.FragmentVisibility, error) { - switch visibility{ - case FragmentVisibility_FRAGMENT_VISIBILITY_UNSPECIFIED: + switch visibility { + case FragmentVisibilityUnspecified: return pb.FragmentVisibility_FRAGMENT_VISIBILITY_UNSPECIFIED, nil - case FragmentVisibility_FRAGMENT_VISIBILITY_PRIVATE: + case FragmentVisibilityPrivate: return pb.FragmentVisibility_FRAGMENT_VISIBILITY_PRIVATE, nil - case FragmentVisibility_FRAGMENT_VISIBILITY_PUBLIC: + case FragmentVisibilityPublic: return pb.FragmentVisibility_FRAGMENT_VISIBILITY_PUBLIC, nil - case FragmentVisibility_FRAGMENT_VISIBILITY_PUBLIC_UNLISTED: + case FragmentVisibilityPublicUnlisted: return pb.FragmentVisibility_FRAGMENT_VISIBILITY_PUBLIC_UNLISTED, nil default: return 0, fmt.Errorf("unknown fragment visibility: %v", visibility) @@ -112,7 +112,7 @@ func FragmentVisibilityToProto(visibility FragmentVisibility) (pb.FragmentVisibi type FragmentHistoryEntry struct { Fragment string EditedOn *timestamppb.Timestamp - Old *Fragment + Old *Fragment EditedBy *AuthenticatorInfo } @@ -128,7 +128,7 @@ func ProtoToFragmentHistoryEntry(entry *pb.FragmentHistoryEntry) (*FragmentHisto return &FragmentHistoryEntry{ Fragment: entry.Fragment, EditedOn: entry.EditedOn, - Old: old, + Old: old, EditedBy: editedBy, }, nil } @@ -145,8 +145,7 @@ func FragmentHistoryEntryToProto(entry *FragmentHistoryEntry) (*pb.FragmentHisto return &pb.FragmentHistoryEntry{ Fragment: entry.Fragment, EditedOn: entry.EditedOn, - Old: old, + Old: old, EditedBy: editedBy, }, nil } - diff --git a/app/location.go b/app/location.go index 8a252ef07a0..c628eea28ba 100644 --- a/app/location.go +++ b/app/location.go @@ -8,19 +8,19 @@ import ( ) type Location struct { - Id string - Name string - ParentLocationId string - Auth *LocationAuth - Organizations []*LocationOrganization - CreatedOn *timestamppb.Timestamp - RobotCount int32 - Config *StorageConfig + ID string + Name string + ParentLocationID string + Auth *LocationAuth + Organizations []*LocationOrganization + CreatedOn *timestamppb.Timestamp + RobotCount int32 + Config *StorageConfig } func ProtoToLocation(location *pb.Location) (*Location, error) { var organizations []*LocationOrganization - for _, organization := range(location.Organizations) { + for _, organization := range location.Organizations { organizations = append(organizations, ProtoToLocationOrganization(organization)) } auth, err := ProtoToLocationAuth(location.Auth) @@ -28,20 +28,20 @@ func ProtoToLocation(location *pb.Location) (*Location, error) { return nil, err } return &Location{ - Id: location.Id, - Name: location.Name, - ParentLocationId: location.ParentLocationId, - Auth: auth, - Organizations: organizations, - CreatedOn: location.CreatedOn, - RobotCount: location.RobotCount, - Config: ProtoToStorageConfig(location.Config), + ID: location.Id, + Name: location.Name, + ParentLocationID: location.ParentLocationId, + Auth: auth, + Organizations: organizations, + CreatedOn: location.CreatedOn, + RobotCount: location.RobotCount, + Config: ProtoToStorageConfig(location.Config), }, nil } func LocationToProto(location *Location) (*pb.Location, error) { var organizations []*pb.LocationOrganization - for _, organization := range(location.Organizations) { + for _, organization := range location.Organizations { organizations = append(organizations, LocationOrganizationToProto(organization)) } auth, err := LocationAuthToProto(location.Auth) @@ -49,33 +49,33 @@ func LocationToProto(location *Location) (*pb.Location, error) { return nil, err } return &pb.Location{ - Id: location.Id, - Name: location.Name, - ParentLocationId: location.ParentLocationId, - Auth: auth, - Organizations: organizations, - CreatedOn: location.CreatedOn, - RobotCount: location.RobotCount, - Config: StorageConfigToProto(location.Config), + Id: location.ID, + Name: location.Name, + ParentLocationId: location.ParentLocationID, + Auth: auth, + Organizations: organizations, + CreatedOn: location.CreatedOn, + RobotCount: location.RobotCount, + Config: StorageConfigToProto(location.Config), }, nil } type LocationOrganization struct { - OrganizationId string - Primary bool + OrganizationID string + Primary bool } func ProtoToLocationOrganization(locationOrganization *pb.LocationOrganization) *LocationOrganization { return &LocationOrganization{ - OrganizationId: locationOrganization.OrganizationId, - Primary: locationOrganization.Primary, + OrganizationID: locationOrganization.OrganizationId, + Primary: locationOrganization.Primary, } } func LocationOrganizationToProto(locationOrganization *LocationOrganization) *pb.LocationOrganization { return &pb.LocationOrganization{ - OrganizationId: locationOrganization.OrganizationId, - Primary: locationOrganization.Primary, + OrganizationId: locationOrganization.OrganizationID, + Primary: locationOrganization.Primary, } } @@ -92,13 +92,13 @@ func StorageConfigToProto(config *StorageConfig) *pb.StorageConfig { } type LocationAuth struct { - LocationId string - Secrets []*SharedSecret + LocationID string + Secrets []*SharedSecret } func ProtoToLocationAuth(locationAuth *pb.LocationAuth) (*LocationAuth, error) { var secrets []*SharedSecret - for _, secret := range(locationAuth.Secrets) { + for _, secret := range locationAuth.Secrets { s, err := ProtoToSharedSecret(secret) if err != nil { return nil, err @@ -106,14 +106,14 @@ func ProtoToLocationAuth(locationAuth *pb.LocationAuth) (*LocationAuth, error) { secrets = append(secrets, s) } return &LocationAuth{ - LocationId: locationAuth.LocationId, - Secrets: secrets, + LocationID: locationAuth.LocationId, + Secrets: secrets, }, nil } func LocationAuthToProto(locationAuth *LocationAuth) (*pb.LocationAuth, error) { var secrets []*pb.SharedSecret - for _, secret := range(locationAuth.Secrets) { + for _, secret := range locationAuth.Secrets { s, err := SharedSecretToProto(secret) if err != nil { return nil, err @@ -121,15 +121,15 @@ func LocationAuthToProto(locationAuth *LocationAuth) (*pb.LocationAuth, error) { secrets = append(secrets, s) } return &pb.LocationAuth{ - LocationId: locationAuth.LocationId, - Secrets: secrets, + LocationId: locationAuth.LocationID, + Secrets: secrets, }, nil } type SharedSecret struct { - Id string + ID string CreatedOn *timestamppb.Timestamp - State SharedSecret_State + State SharedSecretState } func ProtoToSharedSecret(sharedSecret *pb.SharedSecret) (*SharedSecret, error) { @@ -138,9 +138,9 @@ func ProtoToSharedSecret(sharedSecret *pb.SharedSecret) (*SharedSecret, error) { return nil, err } return &SharedSecret{ - Id: sharedSecret.Id, + ID: sharedSecret.Id, CreatedOn: sharedSecret.CreatedOn, - State: state, + State: state, }, nil } @@ -150,40 +150,40 @@ func SharedSecretToProto(sharedSecret *SharedSecret) (*pb.SharedSecret, error) { return nil, err } return &pb.SharedSecret{ - Id: sharedSecret.Id, + Id: sharedSecret.ID, CreatedOn: sharedSecret.CreatedOn, - State: state, + State: state, }, nil } -type SharedSecret_State int32 +type SharedSecretState int32 const ( - SharedSecret_STATE_UNSPECIFIED SharedSecret_State = 0 - SharedSecret_STATE_ENABLED SharedSecret_State = 1 - SharedSecret_STATE_DISABLED SharedSecret_State = 2 + SharedSecretUnspecified SharedSecretState = 0 + SharedSecretEnabled SharedSecretState = 1 + SharedSecretDisabled SharedSecretState = 2 ) -func ProtoToSharedSecretState(state pb.SharedSecret_State) (SharedSecret_State, error) { - switch state{ +func ProtoToSharedSecretState(state pb.SharedSecret_State) (SharedSecretState, error) { + switch state { case pb.SharedSecret_STATE_UNSPECIFIED: - return SharedSecret_STATE_UNSPECIFIED, nil + return SharedSecretUnspecified, nil case pb.SharedSecret_STATE_ENABLED: - return SharedSecret_STATE_ENABLED, nil + return SharedSecretEnabled, nil case pb.SharedSecret_STATE_DISABLED: - return SharedSecret_STATE_DISABLED, nil + return SharedSecretDisabled, nil default: return 0, fmt.Errorf("uknown secret state: %v", state) } } -func SharedSecretStateToProto(state SharedSecret_State) (pb.SharedSecret_State, error) { - switch state{ - case SharedSecret_STATE_UNSPECIFIED: +func SharedSecretStateToProto(state SharedSecretState) (pb.SharedSecret_State, error) { + switch state { + case SharedSecretUnspecified: return pb.SharedSecret_STATE_UNSPECIFIED, nil - case SharedSecret_STATE_ENABLED: + case SharedSecretEnabled: return pb.SharedSecret_STATE_ENABLED, nil - case SharedSecret_STATE_DISABLED: + case SharedSecretDisabled: return pb.SharedSecret_STATE_DISABLED, nil default: return 0, fmt.Errorf("unknown secret state: %v", state) diff --git a/app/log_stream.go b/app/log_stream.go index a7f31e2496a..5b9055c58d9 100644 --- a/app/log_stream.go +++ b/app/log_stream.go @@ -9,14 +9,13 @@ import ( ) type logStream struct { - client *AppClient + client *AppClient streamCancel context.CancelFunc streamMu sync.Mutex activeBackgroundWorkers sync.WaitGroup } - func (s *logStream) startStream(ctx context.Context, id string, errorsOnly bool, filter *string, ch chan []*LogEntry) error { s.streamMu.Lock() defer s.streamMu.Unlock() @@ -35,9 +34,9 @@ func (s *logStream) startStream(ctx context.Context, id string, errorsOnly bool, } req := &pb.TailRobotPartLogsRequest{ - Id: id, + Id: id, ErrorsOnly: errorsOnly, - Filter: filter, + Filter: filter, } // This call won't return any errors it had until the client tries to receive. @@ -79,7 +78,7 @@ func (s *logStream) receiveFromStream(ctx context.Context, stream pb.AppService_ } // If there is a response, send to the logs channel. var logs []*LogEntry - for _, log := range(streamResp.Logs) { + for _, log := range streamResp.Logs { l, err := ProtoToLogEntry(log) if err != nil { s.client.logger.Debug(err) diff --git a/app/organization.go b/app/organization.go index 53caa8bac79..f34184e462c 100644 --- a/app/organization.go +++ b/app/organization.go @@ -6,85 +6,85 @@ import ( ) type Organization struct { - Id string - Name string - CreatedOn *timestamppb.Timestamp + ID string + Name string + CreatedOn *timestamppb.Timestamp PublicNamespace string - DefaultRegion string - Cid *string + DefaultRegion string + Cid *string } func ProtoToOrganization(organization *pb.Organization) *Organization { return &Organization{ - Id: organization.Id, - Name: organization.Name, - CreatedOn: organization.CreatedOn, + ID: organization.Id, + Name: organization.Name, + CreatedOn: organization.CreatedOn, PublicNamespace: organization.PublicNamespace, - DefaultRegion: organization.DefaultRegion, - Cid: organization.Cid, + DefaultRegion: organization.DefaultRegion, + Cid: organization.Cid, } } func OrganizationToProto(organization *Organization) *pb.Organization { return &pb.Organization{ - Id: organization.Id, - Name: organization.Name, - CreatedOn: organization.CreatedOn, + Id: organization.ID, + Name: organization.Name, + CreatedOn: organization.CreatedOn, PublicNamespace: organization.PublicNamespace, - DefaultRegion: organization.DefaultRegion, - Cid: organization.Cid, + DefaultRegion: organization.DefaultRegion, + Cid: organization.Cid, } } type OrganizationIdentity struct { - Id string + ID string Name string } func ProtoToOrganizationIdentity(organizationIdentity *pb.OrganizationIdentity) *OrganizationIdentity { return &OrganizationIdentity{ - Id: organizationIdentity.Id, + ID: organizationIdentity.Id, Name: organizationIdentity.Name, } } func OrganizationIdentityToProto(organizationIdentity *OrganizationIdentity) (*pb.OrganizationIdentity, error) { return &pb.OrganizationIdentity{ - Id: organizationIdentity.Id, + Id: organizationIdentity.ID, Name: organizationIdentity.Name, }, nil } type OrgDetails struct { - OrgId string + OrgID string OrgName string } func ProtoToOrgDetails(orgDetails *pb.OrgDetails) *OrgDetails { return &OrgDetails{ - OrgId: orgDetails.OrgId, + OrgID: orgDetails.OrgId, OrgName: orgDetails.OrgName, } } func OrgDetailsToProto(orgDetails *OrgDetails) (*pb.OrgDetails, error) { return &pb.OrgDetails{ - OrgId: orgDetails.OrgId, + OrgId: orgDetails.OrgID, OrgName: orgDetails.OrgName, }, nil } type OrganizationMember struct { - UserId string - Emails []string + UserID string + Emails []string DateAdded *timestamppb.Timestamp LastLogin *timestamppb.Timestamp } func ProtoToOrganizationMember(organizationMemOrganizationMember *pb.OrganizationMember) *OrganizationMember { return &OrganizationMember{ - UserId: organizationMemOrganizationMember.UserId, - Emails: organizationMemOrganizationMember.Emails, + UserID: organizationMemOrganizationMember.UserId, + Emails: organizationMemOrganizationMember.Emails, DateAdded: organizationMemOrganizationMember.DateAdded, LastLogin: organizationMemOrganizationMember.LastLogin, } @@ -92,98 +92,98 @@ func ProtoToOrganizationMember(organizationMemOrganizationMember *pb.Organizatio func OrganizationMemberToProto(organizationMemOrganizationMember *OrganizationMember) (*pb.OrganizationMember, error) { return &pb.OrganizationMember{ - UserId: organizationMemOrganizationMember.UserId, - Emails: organizationMemOrganizationMember.Emails, + UserId: organizationMemOrganizationMember.UserID, + Emails: organizationMemOrganizationMember.Emails, DateAdded: organizationMemOrganizationMember.DateAdded, LastLogin: organizationMemOrganizationMember.LastLogin, }, nil } type OrganizationInvite struct { - OrganizationId string - Email string - CreatedOn *timestamppb.Timestamp + OrganizationID string + Email string + CreatedOn *timestamppb.Timestamp Authorizations []*Authorization } func ProtoToOrganizationInvite(organizationInvite *pb.OrganizationInvite) *OrganizationInvite { var authorizations []*Authorization - for _, authorization := range(organizationInvite.Authorizations) { + for _, authorization := range organizationInvite.Authorizations { authorizations = append(authorizations, ProtoToAuthorization(authorization)) } return &OrganizationInvite{ - OrganizationId: organizationInvite.OrganizationId, - Email: organizationInvite.Email, - CreatedOn: organizationInvite.CreatedOn, + OrganizationID: organizationInvite.OrganizationId, + Email: organizationInvite.Email, + CreatedOn: organizationInvite.CreatedOn, Authorizations: authorizations, } } func OrganizationInviteToProto(organizationInvite *OrganizationInvite) (*pb.OrganizationInvite, error) { var authorizations []*pb.Authorization - for _, authorization := range(organizationInvite.Authorizations) { + for _, authorization := range organizationInvite.Authorizations { authorizations = append(authorizations, AuthorizationToProto(authorization)) } return &pb.OrganizationInvite{ - OrganizationId: organizationInvite.OrganizationId, - Email: organizationInvite.Email, - CreatedOn: organizationInvite.CreatedOn, + OrganizationId: organizationInvite.OrganizationID, + Email: organizationInvite.Email, + CreatedOn: organizationInvite.CreatedOn, Authorizations: authorizations, }, nil } type Authorization struct { AuthorizationType string - AuthorizationId string - ResourceType string - ResourceId string - IdentityId string - OrganizationId string - IdentityType string + AuthorizationID string + ResourceType string + ResourceID string + IdentityID string + OrganizationID string + IdentityType string } func ProtoToAuthorization(authorization *pb.Authorization) *Authorization { return &Authorization{ AuthorizationType: authorization.AuthorizationType, - AuthorizationId: authorization.AuthorizationId, - ResourceType: authorization.ResourceType, - ResourceId: authorization.ResourceId, - IdentityId: authorization.IdentityId, - OrganizationId: authorization.OrganizationId, - IdentityType: authorization.IdentityType, + AuthorizationID: authorization.AuthorizationId, + ResourceType: authorization.ResourceType, + ResourceID: authorization.ResourceId, + IdentityID: authorization.IdentityId, + OrganizationID: authorization.OrganizationId, + IdentityType: authorization.IdentityType, } } func AuthorizationToProto(authorization *Authorization) *pb.Authorization { return &pb.Authorization{ AuthorizationType: authorization.AuthorizationType, - AuthorizationId: authorization.AuthorizationId, - ResourceType: authorization.ResourceType, - ResourceId: authorization.ResourceId, - IdentityId: authorization.IdentityId, - OrganizationId: authorization.OrganizationId, - IdentityType: authorization.IdentityType, + AuthorizationId: authorization.AuthorizationID, + ResourceType: authorization.ResourceType, + ResourceId: authorization.ResourceID, + IdentityId: authorization.IdentityID, + OrganizationId: authorization.OrganizationID, + IdentityType: authorization.IdentityType, } } type AuthorizedPermissions struct { ResourceType string - ResourceId string - Permissions []string + ResourceID string + Permissions []string } func ProtoToAuthorizedPermissions(permissions *pb.AuthorizedPermissions) *AuthorizedPermissions { return &AuthorizedPermissions{ ResourceType: permissions.ResourceType, - ResourceId: permissions.ResourceId, - Permissions: permissions.Permissions, + ResourceID: permissions.ResourceId, + Permissions: permissions.Permissions, } } func AuthorizedPermissionsToProto(permissions *AuthorizedPermissions) *pb.AuthorizedPermissions { return &pb.AuthorizedPermissions{ ResourceType: permissions.ResourceType, - ResourceId: permissions.ResourceId, - Permissions: permissions.Permissions, + ResourceId: permissions.ResourceID, + Permissions: permissions.Permissions, } } diff --git a/app/registry_item.go b/app/registry_item.go index 22553f06040..98029da564e 100644 --- a/app/registry_item.go +++ b/app/registry_item.go @@ -10,21 +10,21 @@ import ( ) type RegistryItem struct { - ItemId string - OrganizationId string - PublicNamespace string - Name string - Type PackageType - Visibility Visibility - Url string - Description string - TotalRobotUsage int64 - TotalExternalRobotUsage int64 - TotalOrganizationUsage int64 + ItemID string + OrganizationID string + PublicNamespace string + Name string + Type PackageType + Visibility Visibility + URL string + Description string + TotalRobotUsage int64 + TotalExternalRobotUsage int64 + TotalOrganizationUsage int64 TotalExternalOrganizationUsage int64 - Metadata isRegistryItem_Metadata - CreatedAt *timestamppb.Timestamp - UpdatedAt *timestamppb.Timestamp + Metadata isRegistryItemMetadata + CreatedAt *timestamppb.Timestamp + UpdatedAt *timestamppb.Timestamp } func ProtoToRegistryItem(item *pb.RegistryItem) (*RegistryItem, error) { @@ -37,46 +37,46 @@ func ProtoToRegistryItem(item *pb.RegistryItem) (*RegistryItem, error) { return nil, err } - var metadata isRegistryItem_Metadata + var metadata isRegistryItemMetadata switch pbMetadata := item.Metadata.(type) { case *pb.RegistryItem_ModuleMetadata: md, err := ProtoToModuleMetadata(pbMetadata.ModuleMetadata) if err != nil { return nil, err } - metadata = &RegistryItem_ModuleMetadata{ModuleMetadata: md} + metadata = &RegistryItemModuleMetadata{ModuleMetadata: md} case *pb.RegistryItem_MlModelMetadata: md, err := ProtoToMLModelMetadata(pbMetadata.MlModelMetadata) if err != nil { return nil, err } - metadata = &RegistryItem_MlModelMetadata{MlModelMetadata: md} + metadata = &RegistryItemMLModelMetadata{MlModelMetadata: md} case *pb.RegistryItem_MlTrainingMetadata: md, err := ProtoToMLTrainingMetadata(pbMetadata.MlTrainingMetadata) if err != nil { return nil, err } - metadata = &RegistryItem_MlTrainingMetadata{MlTrainingMetadata: md} + metadata = &RegistryItemMLTrainingMetadata{MlTrainingMetadata: md} default: return nil, fmt.Errorf("unknown registry item metadata type: %T", item.Metadata) } return &RegistryItem{ - ItemId: item.ItemId, - OrganizationId: item.OrganizationId, - PublicNamespace: item.PublicNamespace, - Name: item.Name, - Type: packageType, - Visibility: visibility, - Url: item.Url, - Description: item.Description, - TotalRobotUsage: item.TotalRobotUsage, - TotalExternalRobotUsage: item.TotalExternalRobotUsage, - TotalOrganizationUsage: item.TotalOrganizationUsage, + ItemID: item.ItemId, + OrganizationID: item.OrganizationId, + PublicNamespace: item.PublicNamespace, + Name: item.Name, + Type: packageType, + Visibility: visibility, + URL: item.Url, + Description: item.Description, + TotalRobotUsage: item.TotalRobotUsage, + TotalExternalRobotUsage: item.TotalExternalRobotUsage, + TotalOrganizationUsage: item.TotalOrganizationUsage, TotalExternalOrganizationUsage: item.TotalExternalOrganizationUsage, - Metadata: metadata, - CreatedAt: item.CreatedAt, - UpdatedAt: item.UpdatedAt, + Metadata: metadata, + CreatedAt: item.CreatedAt, + UpdatedAt: item.UpdatedAt, }, nil } @@ -91,71 +91,71 @@ func RegistryItemToProto(item *RegistryItem) (*pb.RegistryItem, error) { } switch md := item.Metadata.(type) { - case *RegistryItem_ModuleMetadata: + case *RegistryItemModuleMetadata: protoMetadata, err := ModuleMetadataToProto(md.ModuleMetadata) if err != nil { return nil, err } return &pb.RegistryItem{ - ItemId: item.ItemId, - OrganizationId: item.OrganizationId, - PublicNamespace: item.PublicNamespace, - Name: item.Name, - Type: packageType, - Visibility: visibility, - Url: item.Url, - Description: item.Description, - TotalRobotUsage: item.TotalRobotUsage, - TotalExternalRobotUsage: item.TotalExternalRobotUsage, - TotalOrganizationUsage: item.TotalOrganizationUsage, + ItemId: item.ItemID, + OrganizationId: item.OrganizationID, + PublicNamespace: item.PublicNamespace, + Name: item.Name, + Type: packageType, + Visibility: visibility, + Url: item.URL, + Description: item.Description, + TotalRobotUsage: item.TotalRobotUsage, + TotalExternalRobotUsage: item.TotalExternalRobotUsage, + TotalOrganizationUsage: item.TotalOrganizationUsage, TotalExternalOrganizationUsage: item.TotalExternalOrganizationUsage, - Metadata: &pb.RegistryItem_ModuleMetadata{ModuleMetadata: protoMetadata}, - CreatedAt: item.CreatedAt, - UpdatedAt: item.UpdatedAt, + Metadata: &pb.RegistryItem_ModuleMetadata{ModuleMetadata: protoMetadata}, + CreatedAt: item.CreatedAt, + UpdatedAt: item.UpdatedAt, }, nil - case *RegistryItem_MlModelMetadata: + case *RegistryItemMLModelMetadata: protoMetadata, err := MLModelMetadataToProto(md.MlModelMetadata) if err != nil { return nil, err } return &pb.RegistryItem{ - ItemId: item.ItemId, - OrganizationId: item.OrganizationId, - PublicNamespace: item.PublicNamespace, - Name: item.Name, - Type: packageType, - Visibility: visibility, - Url: item.Url, - Description: item.Description, - TotalRobotUsage: item.TotalRobotUsage, - TotalExternalRobotUsage: item.TotalExternalRobotUsage, - TotalOrganizationUsage: item.TotalOrganizationUsage, + ItemId: item.ItemID, + OrganizationId: item.OrganizationID, + PublicNamespace: item.PublicNamespace, + Name: item.Name, + Type: packageType, + Visibility: visibility, + Url: item.URL, + Description: item.Description, + TotalRobotUsage: item.TotalRobotUsage, + TotalExternalRobotUsage: item.TotalExternalRobotUsage, + TotalOrganizationUsage: item.TotalOrganizationUsage, TotalExternalOrganizationUsage: item.TotalExternalOrganizationUsage, - Metadata: &pb.RegistryItem_MlModelMetadata{MlModelMetadata: protoMetadata}, - CreatedAt: item.CreatedAt, - UpdatedAt: item.UpdatedAt, + Metadata: &pb.RegistryItem_MlModelMetadata{MlModelMetadata: protoMetadata}, + CreatedAt: item.CreatedAt, + UpdatedAt: item.UpdatedAt, }, nil - case *RegistryItem_MlTrainingMetadata: + case *RegistryItemMLTrainingMetadata: protoMetadata, err := MLTrainingMetadataToProto(md.MlTrainingMetadata) if err != nil { return nil, err } return &pb.RegistryItem{ - ItemId: item.ItemId, - OrganizationId: item.OrganizationId, - PublicNamespace: item.PublicNamespace, - Name: item.Name, - Type: packageType, - Visibility: visibility, - Url: item.Url, - Description: item.Description, - TotalRobotUsage: item.TotalRobotUsage, - TotalExternalRobotUsage: item.TotalExternalRobotUsage, - TotalOrganizationUsage: item.TotalOrganizationUsage, + ItemId: item.ItemID, + OrganizationId: item.OrganizationID, + PublicNamespace: item.PublicNamespace, + Name: item.Name, + Type: packageType, + Visibility: visibility, + Url: item.URL, + Description: item.Description, + TotalRobotUsage: item.TotalRobotUsage, + TotalExternalRobotUsage: item.TotalExternalRobotUsage, + TotalOrganizationUsage: item.TotalOrganizationUsage, TotalExternalOrganizationUsage: item.TotalExternalOrganizationUsage, - Metadata: &pb.RegistryItem_MlTrainingMetadata{MlTrainingMetadata: protoMetadata}, - CreatedAt: item.CreatedAt, - UpdatedAt: item.UpdatedAt, + Metadata: &pb.RegistryItem_MlTrainingMetadata{MlTrainingMetadata: protoMetadata}, + CreatedAt: item.CreatedAt, + UpdatedAt: item.UpdatedAt, }, nil default: return nil, fmt.Errorf("unknown registry item metadata type: %T", item.Metadata) @@ -163,32 +163,33 @@ func RegistryItemToProto(item *RegistryItem) (*pb.RegistryItem, error) { } type RegistryItemStatus int32 + const ( - RegistryItemStatus_REGISTRY_ITEM_STATUS_UNSPECIFIED RegistryItemStatus = 0 - RegistryItemStatus_REGISTRY_ITEM_STATUS_PUBLISHED RegistryItemStatus = 1 - RegistryItemStatus_REGISTRY_ITEM_STATUS_IN_DEVELOPMENT RegistryItemStatus = 2 + RegistryItemStatusUnspecified RegistryItemStatus = 0 + RegistryItemStatusPublished RegistryItemStatus = 1 + RegistryItemStatusInDevelopment RegistryItemStatus = 2 ) func ProtoToRegistryItemStatus(status pb.RegistryItemStatus) (RegistryItemStatus, error) { - switch status{ + switch status { case pb.RegistryItemStatus_REGISTRY_ITEM_STATUS_UNSPECIFIED: - return RegistryItemStatus_REGISTRY_ITEM_STATUS_UNSPECIFIED, nil + return RegistryItemStatusUnspecified, nil case pb.RegistryItemStatus_REGISTRY_ITEM_STATUS_PUBLISHED: - return RegistryItemStatus_REGISTRY_ITEM_STATUS_PUBLISHED, nil + return RegistryItemStatusPublished, nil case pb.RegistryItemStatus_REGISTRY_ITEM_STATUS_IN_DEVELOPMENT: - return RegistryItemStatus_REGISTRY_ITEM_STATUS_IN_DEVELOPMENT, nil + return RegistryItemStatusInDevelopment, nil default: return 0, fmt.Errorf("unknown registry item status: %v", status) } } func RegistryItemStatusToProto(status RegistryItemStatus) (pb.RegistryItemStatus, error) { - switch status{ - case RegistryItemStatus_REGISTRY_ITEM_STATUS_UNSPECIFIED: + switch status { + case RegistryItemStatusUnspecified: return pb.RegistryItemStatus_REGISTRY_ITEM_STATUS_UNSPECIFIED, nil - case RegistryItemStatus_REGISTRY_ITEM_STATUS_PUBLISHED: + case RegistryItemStatusPublished: return pb.RegistryItemStatus_REGISTRY_ITEM_STATUS_PUBLISHED, nil - case RegistryItemStatus_REGISTRY_ITEM_STATUS_IN_DEVELOPMENT: + case RegistryItemStatusInDevelopment: return pb.RegistryItemStatus_REGISTRY_ITEM_STATUS_IN_DEVELOPMENT, nil default: return 0, fmt.Errorf("unknown registry item status: %v", status) @@ -196,240 +197,241 @@ func RegistryItemStatusToProto(status RegistryItemStatus) (pb.RegistryItemStatus } type PackageType int32 + const ( - PackageType_PACKAGE_TYPE_UNSPECIFIED PackageType = 0 - PackageType_PACKAGE_TYPE_ARCHIVE PackageType = 1 - PackageType_PACKAGE_TYPE_ML_MODEL PackageType = 2 - PackageType_PACKAGE_TYPE_MODULE PackageType = 3 - PackageType_PACKAGE_TYPE_SLAM_MAP PackageType = 4 - PackageType_PACKAGE_TYPE_ML_TRAINING PackageType = 5 + PackageTypeUnspecified PackageType = 0 + PackageTypeArchive PackageType = 1 + PackageTypeMLModel PackageType = 2 + PackageTypeModule PackageType = 3 + PackageTypeSLAMMap PackageType = 4 + PackageTypeMLTraining PackageType = 5 ) func ProtoToPackageType(packageType packages.PackageType) (PackageType, error) { - switch packageType{ + switch packageType { case packages.PackageType_PACKAGE_TYPE_UNSPECIFIED: - return PackageType_PACKAGE_TYPE_UNSPECIFIED, nil + return PackageTypeUnspecified, nil case packages.PackageType_PACKAGE_TYPE_ARCHIVE: - return PackageType_PACKAGE_TYPE_ARCHIVE, nil + return PackageTypeArchive, nil case packages.PackageType_PACKAGE_TYPE_ML_MODEL: - return PackageType_PACKAGE_TYPE_ML_MODEL, nil + return PackageTypeMLModel, nil case packages.PackageType_PACKAGE_TYPE_MODULE: - return PackageType_PACKAGE_TYPE_MODULE, nil + return PackageTypeModule, nil case packages.PackageType_PACKAGE_TYPE_SLAM_MAP: - return PackageType_PACKAGE_TYPE_SLAM_MAP, nil + return PackageTypeSLAMMap, nil case packages.PackageType_PACKAGE_TYPE_ML_TRAINING: - return PackageType_PACKAGE_TYPE_ML_TRAINING, nil + return PackageTypeMLTraining, nil default: return 0, fmt.Errorf("unknown fragment visibility: %v", packageType) } } func PackageTypeToProto(packageType PackageType) (packages.PackageType, error) { - switch packageType{ - case PackageType_PACKAGE_TYPE_UNSPECIFIED: + switch packageType { + case PackageTypeUnspecified: return packages.PackageType_PACKAGE_TYPE_UNSPECIFIED, nil - case PackageType_PACKAGE_TYPE_ARCHIVE: + case PackageTypeArchive: return packages.PackageType_PACKAGE_TYPE_ARCHIVE, nil - case PackageType_PACKAGE_TYPE_ML_MODEL: + case PackageTypeMLModel: return packages.PackageType_PACKAGE_TYPE_ML_MODEL, nil - case PackageType_PACKAGE_TYPE_MODULE: + case PackageTypeModule: return packages.PackageType_PACKAGE_TYPE_MODULE, nil - case PackageType_PACKAGE_TYPE_SLAM_MAP: + case PackageTypeSLAMMap: return packages.PackageType_PACKAGE_TYPE_SLAM_MAP, nil - case PackageType_PACKAGE_TYPE_ML_TRAINING: + case PackageTypeMLTraining: return packages.PackageType_PACKAGE_TYPE_ML_TRAINING, nil default: return 0, fmt.Errorf("unknown fragment visibility: %v", packageType) } } - type Visibility int32 + const ( - Visibility_VISIBILITY_UNSPECIFIED Visibility = 0 - Visibility_VISIBILITY_PRIVATE Visibility = 1 - Visibility_VISIBILITY_PUBLIC Visibility = 2 - Visibility_VISIBILITY_PUBLIC_UNLISTED Visibility = 3 + VisibilityUnspecified Visibility = 0 + VisibilityPrivate Visibility = 1 + VisibilityPublic Visibility = 2 + VisibilityPublicUnlisted Visibility = 3 ) func ProtoToVisibility(visibility pb.Visibility) (Visibility, error) { - switch visibility{ + switch visibility { case pb.Visibility_VISIBILITY_UNSPECIFIED: - return Visibility_VISIBILITY_UNSPECIFIED, nil + return VisibilityUnspecified, nil case pb.Visibility_VISIBILITY_PRIVATE: - return Visibility_VISIBILITY_PRIVATE, nil + return VisibilityPrivate, nil case pb.Visibility_VISIBILITY_PUBLIC: - return Visibility_VISIBILITY_PUBLIC, nil + return VisibilityPublic, nil case pb.Visibility_VISIBILITY_PUBLIC_UNLISTED: - return Visibility_VISIBILITY_PUBLIC_UNLISTED, nil + return VisibilityPublicUnlisted, nil default: return 0, fmt.Errorf("unknown fragment visibility: %v", visibility) } } func VisibilityToProto(visibility Visibility) (pb.Visibility, error) { - switch visibility{ - case Visibility_VISIBILITY_UNSPECIFIED: + switch visibility { + case VisibilityUnspecified: return pb.Visibility_VISIBILITY_UNSPECIFIED, nil - case Visibility_VISIBILITY_PRIVATE: + case VisibilityPrivate: return pb.Visibility_VISIBILITY_PRIVATE, nil - case Visibility_VISIBILITY_PUBLIC: + case VisibilityPublic: return pb.Visibility_VISIBILITY_PUBLIC, nil - case Visibility_VISIBILITY_PUBLIC_UNLISTED: + case VisibilityPublicUnlisted: return pb.Visibility_VISIBILITY_PUBLIC_UNLISTED, nil default: return 0, fmt.Errorf("unknown fragment visibility: %v", visibility) } } -type isRegistryItem_Metadata interface { - isRegistryItem_Metadata() +type isRegistryItemMetadata interface { + isRegistryItemMetadata() } -type RegistryItem_ModuleMetadata struct { +type RegistryItemModuleMetadata struct { ModuleMetadata *ModuleMetadata } -type RegistryItem_MlModelMetadata struct { +type RegistryItemMLModelMetadata struct { MlModelMetadata *MLModelMetadata } -type RegistryItem_MlTrainingMetadata struct { +type RegistryItemMLTrainingMetadata struct { MlTrainingMetadata *MLTrainingMetadata } -func (*RegistryItem_ModuleMetadata) isRegistryItem_Metadata() {} +func (*RegistryItemModuleMetadata) isRegistryItemMetadata() {} -func (*RegistryItem_MlModelMetadata) isRegistryItem_Metadata() {} +func (*RegistryItemMLModelMetadata) isRegistryItemMetadata() {} -func (*RegistryItem_MlTrainingMetadata) isRegistryItem_Metadata() {} +func (*RegistryItemMLTrainingMetadata) isRegistryItemMetadata() {} type ModuleMetadata struct { - Models []*Model - Versions []*ModuleVersion + Models []*Model + Versions []*ModuleVersion Entrypoint string - FirstRun *string + FirstRun *string } func ProtoToModuleMetadata(md *pb.ModuleMetadata) (*ModuleMetadata, error) { var models []*Model - for _, version := range(md.Models) { + for _, version := range md.Models { models = append(models, ProtoToModel(version)) } var versions []*ModuleVersion - for _, version := range(md.Versions) { + for _, version := range md.Versions { versions = append(versions, ProtoToModuleVersion(version)) } return &ModuleMetadata{ - Models: models, - Versions: versions, + Models: models, + Versions: versions, Entrypoint: md.Entrypoint, - FirstRun: md.FirstRun, + FirstRun: md.FirstRun, }, nil } func ModuleMetadataToProto(md *ModuleMetadata) (*pb.ModuleMetadata, error) { var models []*pb.Model - for _, version := range(md.Models) { + for _, version := range md.Models { models = append(models, ModelToProto(version)) } var versions []*pb.ModuleVersion - for _, version := range(md.Versions) { + for _, version := range md.Versions { versions = append(versions, ModuleVersionToProto(version)) } return &pb.ModuleMetadata{ - Models: models, - Versions: versions, + Models: models, + Versions: versions, Entrypoint: md.Entrypoint, - FirstRun: md.FirstRun, + FirstRun: md.FirstRun, }, nil } type Model struct { - Api string + API string Model string } func ProtoToModel(model *pb.Model) *Model { return &Model{ - Api: model.Api, + API: model.Api, Model: model.Model, } } func ModelToProto(model *Model) *pb.Model { return &pb.Model{ - Api: model.Api, + Api: model.API, Model: model.Model, } } type ModuleVersion struct { - Version string - Files []*Uploads - Models []*Model + Version string + Files []*Uploads + Models []*Model Entrypoint string - FirstRun *string + FirstRun *string } -func ProtoToModuleVersion(version *pb.ModuleVersion) (*ModuleVersion) { +func ProtoToModuleVersion(version *pb.ModuleVersion) *ModuleVersion { var files []*Uploads - for _, file := range(version.Files) { + for _, file := range version.Files { files = append(files, ProtoToUploads(file)) } var models []*Model - for _, model := range(version.Models) { + for _, model := range version.Models { models = append(models, ProtoToModel(model)) } return &ModuleVersion{ - Version: version.Version, - Files: files, - Models: models, + Version: version.Version, + Files: files, + Models: models, Entrypoint: version.Entrypoint, - FirstRun: version.FirstRun, + FirstRun: version.FirstRun, } } -func ModuleVersionToProto(version *ModuleVersion) (*pb.ModuleVersion) { +func ModuleVersionToProto(version *ModuleVersion) *pb.ModuleVersion { var files []*pb.Uploads - for _, file := range(version.Files) { + for _, file := range version.Files { files = append(files, UploadsToProto(file)) } var models []*pb.Model - for _, model := range(version.Models) { + for _, model := range version.Models { models = append(models, ModelToProto(model)) } return &pb.ModuleVersion{ - Version: version.Version, - Files: files, - Models: models, + Version: version.Version, + Files: files, + Models: models, Entrypoint: version.Entrypoint, - FirstRun: version.FirstRun, + FirstRun: version.FirstRun, } } type Uploads struct { - Platform string + Platform string UploadedAt *timestamppb.Timestamp } func ProtoToUploads(uploads *pb.Uploads) *Uploads { return &Uploads{ - Platform: uploads.Platform, + Platform: uploads.Platform, UploadedAt: uploads.UploadedAt, } } func UploadsToProto(uploads *Uploads) *pb.Uploads { return &pb.Uploads{ - Platform: uploads.Platform, + Platform: uploads.Platform, UploadedAt: uploads.UploadedAt, } } - + type MLModelMetadata struct { - Versions []string - ModelType ModelType + Versions []string + ModelType ModelType ModelFramework ModelFramework } @@ -443,8 +445,8 @@ func ProtoToMLModelMetadata(md *pb.MLModelMetadata) (*MLModelMetadata, error) { return nil, err } return &MLModelMetadata{ - Versions: md.Versions, - ModelType: modelType, + Versions: md.Versions, + ModelType: modelType, ModelFramework: modelFramework, }, nil } @@ -459,44 +461,45 @@ func MLModelMetadataToProto(md *MLModelMetadata) (*pb.MLModelMetadata, error) { return nil, err } return &pb.MLModelMetadata{ - Versions: md.Versions, - ModelType: modelType, + Versions: md.Versions, + ModelType: modelType, ModelFramework: modelFramework, }, nil } type ModelType int32 + const ( - ModelType_MODEL_TYPE_UNSPECIFIED ModelType = 0 - ModelType_MODEL_TYPE_SINGLE_LABEL_CLASSIFICATION ModelType = 1 - ModelType_MODEL_TYPE_MULTI_LABEL_CLASSIFICATION ModelType = 2 - ModelType_MODEL_TYPE_OBJECT_DETECTION ModelType = 3 + ModelTypeUnspecified ModelType = 0 + ModelTypeSingleLabelClassification ModelType = 1 + ModelTypeMultiLabelClassification ModelType = 2 + ModelTypeObjectDetection ModelType = 3 ) func ProtoToModelType(modelType mlTraining.ModelType) (ModelType, error) { - switch modelType{ + switch modelType { case mlTraining.ModelType_MODEL_TYPE_UNSPECIFIED: - return ModelType_MODEL_TYPE_UNSPECIFIED, nil + return ModelTypeUnspecified, nil case mlTraining.ModelType_MODEL_TYPE_SINGLE_LABEL_CLASSIFICATION: - return ModelType_MODEL_TYPE_SINGLE_LABEL_CLASSIFICATION, nil + return ModelTypeSingleLabelClassification, nil case mlTraining.ModelType_MODEL_TYPE_MULTI_LABEL_CLASSIFICATION: - return ModelType_MODEL_TYPE_MULTI_LABEL_CLASSIFICATION, nil + return ModelTypeMultiLabelClassification, nil case mlTraining.ModelType_MODEL_TYPE_OBJECT_DETECTION: - return ModelType_MODEL_TYPE_OBJECT_DETECTION, nil + return ModelTypeObjectDetection, nil default: return 0, fmt.Errorf("unknown model type: %v", modelType) } } func ModelTypeToProto(modelType ModelType) (mlTraining.ModelType, error) { - switch modelType{ - case ModelType_MODEL_TYPE_UNSPECIFIED: + switch modelType { + case ModelTypeUnspecified: return mlTraining.ModelType_MODEL_TYPE_UNSPECIFIED, nil - case ModelType_MODEL_TYPE_SINGLE_LABEL_CLASSIFICATION: + case ModelTypeSingleLabelClassification: return mlTraining.ModelType_MODEL_TYPE_SINGLE_LABEL_CLASSIFICATION, nil - case ModelType_MODEL_TYPE_MULTI_LABEL_CLASSIFICATION: + case ModelTypeMultiLabelClassification: return mlTraining.ModelType_MODEL_TYPE_MULTI_LABEL_CLASSIFICATION, nil - case ModelType_MODEL_TYPE_OBJECT_DETECTION: + case ModelTypeObjectDetection: return mlTraining.ModelType_MODEL_TYPE_OBJECT_DETECTION, nil default: return 0, fmt.Errorf("unknown model type: %v", modelType) @@ -504,42 +507,43 @@ func ModelTypeToProto(modelType ModelType) (mlTraining.ModelType, error) { } type ModelFramework int32 + const ( - ModelFramework_MODEL_FRAMEWORK_UNSPECIFIED ModelFramework = 0 - ModelFramework_MODEL_FRAMEWORK_TFLITE ModelFramework = 1 - ModelFramework_MODEL_FRAMEWORK_TENSORFLOW ModelFramework = 2 - ModelFramework_MODEL_FRAMEWORK_PYTORCH ModelFramework = 3 - ModelFramework_MODEL_FRAMEWORK_ONNX ModelFramework = 4 + ModelFrameworkUnspecified ModelFramework = 0 + ModelFrameworkTFLite ModelFramework = 1 + ModelFrameworkTensorFlow ModelFramework = 2 + ModelFrameworkPyTorch ModelFramework = 3 + ModelFrameworkONNX ModelFramework = 4 ) func ProtoToModelFramework(framework mlTraining.ModelFramework) (ModelFramework, error) { - switch framework{ + switch framework { case mlTraining.ModelFramework_MODEL_FRAMEWORK_UNSPECIFIED: - return ModelFramework_MODEL_FRAMEWORK_UNSPECIFIED, nil + return ModelFrameworkUnspecified, nil case mlTraining.ModelFramework_MODEL_FRAMEWORK_TFLITE: - return ModelFramework_MODEL_FRAMEWORK_TFLITE, nil + return ModelFrameworkTFLite, nil case mlTraining.ModelFramework_MODEL_FRAMEWORK_TENSORFLOW: - return ModelFramework_MODEL_FRAMEWORK_TENSORFLOW, nil + return ModelFrameworkTensorFlow, nil case mlTraining.ModelFramework_MODEL_FRAMEWORK_PYTORCH: - return ModelFramework_MODEL_FRAMEWORK_PYTORCH, nil + return ModelFrameworkPyTorch, nil case mlTraining.ModelFramework_MODEL_FRAMEWORK_ONNX: - return ModelFramework_MODEL_FRAMEWORK_ONNX, nil + return ModelFrameworkONNX, nil default: return 0, fmt.Errorf("unknown model framework: %v", framework) } } func ModelFrameworkToProto(framework ModelFramework) (mlTraining.ModelFramework, error) { - switch framework{ - case ModelFramework_MODEL_FRAMEWORK_UNSPECIFIED: + switch framework { + case ModelFrameworkUnspecified: return mlTraining.ModelFramework_MODEL_FRAMEWORK_UNSPECIFIED, nil - case ModelFramework_MODEL_FRAMEWORK_TFLITE: + case ModelFrameworkTFLite: return mlTraining.ModelFramework_MODEL_FRAMEWORK_TFLITE, nil - case ModelFramework_MODEL_FRAMEWORK_TENSORFLOW: + case ModelFrameworkTensorFlow: return mlTraining.ModelFramework_MODEL_FRAMEWORK_TENSORFLOW, nil - case ModelFramework_MODEL_FRAMEWORK_PYTORCH: + case ModelFrameworkPyTorch: return mlTraining.ModelFramework_MODEL_FRAMEWORK_PYTORCH, nil - case ModelFramework_MODEL_FRAMEWORK_ONNX: + case ModelFrameworkONNX: return mlTraining.ModelFramework_MODEL_FRAMEWORK_ONNX, nil default: return 0, fmt.Errorf("unknown model framework: %v", framework) @@ -547,15 +551,15 @@ func ModelFrameworkToProto(framework ModelFramework) (mlTraining.ModelFramework, } type MLTrainingMetadata struct { - Versions []*MLTrainingVersion - ModelType ModelType + Versions []*MLTrainingVersion + ModelType ModelType ModelFramework ModelFramework - Draft bool + Draft bool } func ProtoToMLTrainingMetadata(md *pb.MLTrainingMetadata) (*MLTrainingMetadata, error) { var versions []*MLTrainingVersion - for _, version := range(md.Versions) { + for _, version := range md.Versions { versions = append(versions, ProtoToMLTrainingVersion(version)) } modelType, err := ProtoToModelType(md.ModelType) @@ -567,16 +571,16 @@ func ProtoToMLTrainingMetadata(md *pb.MLTrainingMetadata) (*MLTrainingMetadata, return nil, err } return &MLTrainingMetadata{ - Versions: versions, - ModelType: modelType, + Versions: versions, + ModelType: modelType, ModelFramework: modelFramework, - Draft: md.Draft, + Draft: md.Draft, }, nil } func MLTrainingMetadataToProto(md *MLTrainingMetadata) (*pb.MLTrainingMetadata, error) { var versions []*pb.MLTrainingVersion - for _, version := range(md.Versions) { + for _, version := range md.Versions { versions = append(versions, MLTrainingVersionToProto(version)) } modelType, err := ModelTypeToProto(md.ModelType) @@ -588,46 +592,46 @@ func MLTrainingMetadataToProto(md *MLTrainingMetadata) (*pb.MLTrainingMetadata, return nil, err } return &pb.MLTrainingMetadata{ - Versions: versions, - ModelType: modelType, + Versions: versions, + ModelType: modelType, ModelFramework: modelFramework, - Draft: md.Draft, + Draft: md.Draft, }, nil } type MLTrainingVersion struct { - Version string + Version string CreatedOn *timestamppb.Timestamp } func ProtoToMLTrainingVersion(version *pb.MLTrainingVersion) *MLTrainingVersion { return &MLTrainingVersion{ - Version: version.Version, + Version: version.Version, CreatedOn: version.CreatedOn, } } func MLTrainingVersionToProto(version *MLTrainingVersion) *pb.MLTrainingVersion { return &pb.MLTrainingVersion{ - Version: version.Version, + Version: version.Version, CreatedOn: version.CreatedOn, } } type Module struct { - ModuleId string - Name string - Visibility Visibility - Versions []*VersionHistory - Url string - Description string - Models []*Model - TotalRobotUsage int64 + ModuleID string + Name string + Visibility Visibility + Versions []*VersionHistory + URL string + Description string + Models []*Model + TotalRobotUsage int64 TotalOrganizationUsage int64 - OrganizationId string - Entrypoint string - PublicNamespace string - FirstRun *string + OrganizationID string + Entrypoint string + PublicNamespace string + FirstRun *string } func ProtoToModule(module *pb.Module) (*Module, error) { @@ -636,27 +640,27 @@ func ProtoToModule(module *pb.Module) (*Module, error) { return nil, err } var versions []*VersionHistory - for _, version := range(module.Versions){ + for _, version := range module.Versions { versions = append(versions, ProtoToVersionHistory(version)) } var models []*Model - for _, model := range(module.Models){ + for _, model := range module.Models { models = append(models, ProtoToModel(model)) } return &Module{ - ModuleId: module.ModuleId, - Name: module.Name, - Visibility: visibility, - Versions: versions, - Url: module.Url, - Description: module.Description, - Models: models, - TotalRobotUsage: module.TotalRobotUsage, + ModuleID: module.ModuleId, + Name: module.Name, + Visibility: visibility, + Versions: versions, + URL: module.Url, + Description: module.Description, + Models: models, + TotalRobotUsage: module.TotalRobotUsage, TotalOrganizationUsage: module.TotalOrganizationUsage, - OrganizationId: module.OrganizationId, - Entrypoint: module.Entrypoint, - PublicNamespace: module.PublicNamespace, - FirstRun: module.FirstRun, + OrganizationID: module.OrganizationId, + Entrypoint: module.Entrypoint, + PublicNamespace: module.PublicNamespace, + FirstRun: module.FirstRun, }, nil } @@ -666,70 +670,70 @@ func ModuleToProto(module *Module) (*pb.Module, error) { return nil, err } var versions []*pb.VersionHistory - for _, version := range(module.Versions){ + for _, version := range module.Versions { versions = append(versions, VersionHistoryToProto(version)) } var models []*pb.Model - for _, model := range(module.Models){ + for _, model := range module.Models { models = append(models, ModelToProto(model)) } return &pb.Module{ - ModuleId: module.ModuleId, - Name: module.Name, - Visibility: visibility, - Versions: versions, - Url: module.Url, - Description: module.Description, - Models: models, - TotalRobotUsage: module.TotalRobotUsage, + ModuleId: module.ModuleID, + Name: module.Name, + Visibility: visibility, + Versions: versions, + Url: module.URL, + Description: module.Description, + Models: models, + TotalRobotUsage: module.TotalRobotUsage, TotalOrganizationUsage: module.TotalOrganizationUsage, - OrganizationId: module.OrganizationId, - Entrypoint: module.Entrypoint, - PublicNamespace: module.PublicNamespace, - FirstRun: module.FirstRun, + OrganizationId: module.OrganizationID, + Entrypoint: module.Entrypoint, + PublicNamespace: module.PublicNamespace, + FirstRun: module.FirstRun, }, nil } type VersionHistory struct { - Version string - Files []*Uploads - Models []*Model + Version string + Files []*Uploads + Models []*Model Entrypoint string - FirstRun *string + FirstRun *string } func ProtoToVersionHistory(history *pb.VersionHistory) *VersionHistory { var files []*Uploads - for _, file := range(history.Files){ + for _, file := range history.Files { files = append(files, ProtoToUploads(file)) } var models []*Model - for _, model := range(history.Models){ + for _, model := range history.Models { models = append(models, ProtoToModel(model)) } return &VersionHistory{ - Version: history.Version, - Files: files, - Models: models, + Version: history.Version, + Files: files, + Models: models, Entrypoint: history.Entrypoint, - FirstRun: history.FirstRun, + FirstRun: history.FirstRun, } } func VersionHistoryToProto(history *VersionHistory) *pb.VersionHistory { var files []*pb.Uploads - for _, file := range(history.Files){ + for _, file := range history.Files { files = append(files, UploadsToProto(file)) } var models []*pb.Model - for _, model := range(history.Models){ + for _, model := range history.Models { models = append(models, ModelToProto(model)) } return &pb.VersionHistory{ - Version: history.Version, - Files: files, - Models: models, + Version: history.Version, + Files: files, + Models: models, Entrypoint: history.Entrypoint, - FirstRun: history.FirstRun, + FirstRun: history.FirstRun, } } diff --git a/app/robot.go b/app/robot.go index bb27dd343ea..c0df29f13dc 100644 --- a/app/robot.go +++ b/app/robot.go @@ -7,79 +7,79 @@ import ( ) type Robot struct { - Id string - Name string - Location string + ID string + Name string + Location string LastAccess *timestamppb.Timestamp - CreatedOn *timestamppb.Timestamp + CreatedOn *timestamppb.Timestamp } func ProtoToRobot(robot *pb.Robot) *Robot { return &Robot{ - Id: robot.Id, - Name: robot.Name, - Location: robot.Location, + ID: robot.Id, + Name: robot.Name, + Location: robot.Location, LastAccess: robot.LastAccess, - CreatedOn: robot.CreatedOn, + CreatedOn: robot.CreatedOn, } } func RobotToProto(robot *Robot) *pb.Robot { return &pb.Robot{ - Id: robot.Id, - Name: robot.Name, - Location: robot.Location, + Id: robot.ID, + Name: robot.Name, + Location: robot.Location, LastAccess: robot.LastAccess, - CreatedOn: robot.CreatedOn, + CreatedOn: robot.CreatedOn, } } type RoverRentalRobot struct { - RobotId string - LocationId string - RobotName string - RobotMainPartId string + RobotID string + LocationID string + RobotName string + RobotMainPartID string } func ProtoToRoverRentalRobot(rrRobot *pb.RoverRentalRobot) *RoverRentalRobot { return &RoverRentalRobot{ - RobotId: rrRobot.RobotId, - LocationId: rrRobot.LocationId, - RobotName: rrRobot.RobotName, - RobotMainPartId: rrRobot.RobotMainPartId, + RobotID: rrRobot.RobotId, + LocationID: rrRobot.LocationId, + RobotName: rrRobot.RobotName, + RobotMainPartID: rrRobot.RobotMainPartId, } } func RoverRentalRobotToProto(rrRobot *RoverRentalRobot) *pb.RoverRentalRobot { return &pb.RoverRentalRobot{ - RobotId: rrRobot.RobotId, - LocationId: rrRobot.LocationId, - RobotName: rrRobot.RobotName, - RobotMainPartId: rrRobot.RobotMainPartId, + RobotId: rrRobot.RobotID, + LocationId: rrRobot.LocationID, + RobotName: rrRobot.RobotName, + RobotMainPartId: rrRobot.RobotMainPartID, } } type RobotPart struct { - Id string - Name string - DnsName string - Secret string - Robot string - LocationId string - RobotConfig *map[string]interface{} - LastAccess *timestamppb.Timestamp + ID string + Name string + DNSName string + Secret string + Robot string + LocationID string + RobotConfig *map[string]interface{} + LastAccess *timestamppb.Timestamp UserSuppliedInfo *map[string]interface{} - MainPart bool - Fqdn string - LocalFqdn string - CreatedOn *timestamppb.Timestamp - Secrets []*SharedSecret - LastUpdated *timestamppb.Timestamp + MainPart bool + Fqdn string + LocalFqdn string + CreatedOn *timestamppb.Timestamp + Secrets []*SharedSecret + LastUpdated *timestamppb.Timestamp } func ProtoToRobotPart(robotPart *pb.RobotPart) (*RobotPart, error) { var secrets []*SharedSecret - for _, secret := range(robotPart.Secrets) { + for _, secret := range robotPart.Secrets { s, err := ProtoToSharedSecret(secret) if err != nil { return nil, err @@ -89,27 +89,27 @@ func ProtoToRobotPart(robotPart *pb.RobotPart) (*RobotPart, error) { cfg := robotPart.RobotConfig.AsMap() info := robotPart.UserSuppliedInfo.AsMap() return &RobotPart{ - Id: robotPart.Id, - Name: robotPart.Name, - DnsName: robotPart.DnsName, - Secret: robotPart.Secret, - Robot: robotPart.DnsName, - LocationId: robotPart.LocationId, - RobotConfig: &cfg, - LastAccess: robotPart.LastAccess, + ID: robotPart.Id, + Name: robotPart.Name, + DNSName: robotPart.DnsName, + Secret: robotPart.Secret, + Robot: robotPart.DnsName, + LocationID: robotPart.LocationId, + RobotConfig: &cfg, + LastAccess: robotPart.LastAccess, UserSuppliedInfo: &info, - MainPart: robotPart.MainPart, - Fqdn: robotPart.Fqdn, - LocalFqdn: robotPart.LocalFqdn, - CreatedOn: robotPart.CreatedOn, - Secrets: secrets, - LastUpdated: robotPart.LastUpdated, + MainPart: robotPart.MainPart, + Fqdn: robotPart.Fqdn, + LocalFqdn: robotPart.LocalFqdn, + CreatedOn: robotPart.CreatedOn, + Secrets: secrets, + LastUpdated: robotPart.LastUpdated, }, nil } func RobotPartToProto(robotPart *RobotPart) (*pb.RobotPart, error) { var secrets []*pb.SharedSecret - for _, secret := range(robotPart.Secrets) { + for _, secret := range robotPart.Secrets { s, err := SharedSecretToProto(secret) if err != nil { return nil, err @@ -125,29 +125,29 @@ func RobotPartToProto(robotPart *RobotPart) (*pb.RobotPart, error) { return nil, err } return &pb.RobotPart{ - Id: robotPart.Id, - Name: robotPart.Name, - DnsName: robotPart.DnsName, - Secret: robotPart.Secret, - Robot: robotPart.DnsName, - LocationId: robotPart.LocationId, - RobotConfig: robotConfig, - LastAccess: robotPart.LastAccess, + Id: robotPart.ID, + Name: robotPart.Name, + DnsName: robotPart.DNSName, + Secret: robotPart.Secret, + Robot: robotPart.DNSName, + LocationId: robotPart.LocationID, + RobotConfig: robotConfig, + LastAccess: robotPart.LastAccess, UserSuppliedInfo: userSuppliedInfo, - MainPart: robotPart.MainPart, - Fqdn: robotPart.Fqdn, - LocalFqdn: robotPart.LocalFqdn, - CreatedOn: robotPart.CreatedOn, - Secrets: secrets, - LastUpdated: robotPart.LastUpdated, + MainPart: robotPart.MainPart, + Fqdn: robotPart.Fqdn, + LocalFqdn: robotPart.LocalFqdn, + CreatedOn: robotPart.CreatedOn, + Secrets: secrets, + LastUpdated: robotPart.LastUpdated, }, nil } type RobotPartHistoryEntry struct { - Part string - Robot string - When *timestamppb.Timestamp - Old *RobotPart + Part string + Robot string + When *timestamppb.Timestamp + Old *RobotPart EditedBy *AuthenticatorInfo } @@ -161,10 +161,10 @@ func ProtoToRobotPartHistoryEntry(entry *pb.RobotPartHistoryEntry) (*RobotPartHi return nil, err } return &RobotPartHistoryEntry{ - Part: entry.Part, - Robot: entry.Robot, - When: entry.When, - Old: old, + Part: entry.Part, + Robot: entry.Robot, + When: entry.When, + Old: old, EditedBy: info, }, nil } From 2f63521dc5e2ebad0a3f4d1397070a27821ac8d0 Mon Sep 17 00:00:00 2001 From: purplenicole730 Date: Wed, 13 Nov 2024 12:17:46 -0500 Subject: [PATCH 29/75] make lint --- app/app_client.go | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/app/app_client.go b/app/app_client.go index e20a01ba130..0a4ed29868a 100644 --- a/app/app_client.go +++ b/app/app_client.go @@ -1,3 +1,6 @@ +// Package app defines the interfaces that manage a machine fleet with code instead of with the graphical interface of the Viam App. +// +// [fleet management docs]: https://docs.viam.com/appendix/apis/fleet/ package app import ( @@ -414,7 +417,6 @@ func (c *AppClient) GetRoverRentalRobots(ctx context.Context, orgID string) ([]* } // GetRobotParts gets a list of all the parts under a specific machine. -func (c *AppClient) GetRobotParts(ctx context.Context, robotId string) ([]*RobotPart, error) { func (c *AppClient) GetRobotParts(ctx context.Context, robotID string) ([]*RobotPart, error) { resp, err := c.client.GetRobotParts(ctx, &pb.GetRobotPartsRequest{ RobotId: robotID, @@ -540,9 +542,8 @@ func (c *AppClient) UpdateRobotPart(ctx context.Context, id, name string, robotC } // NewRobotPart creates a new robot part. -func (c *AppClient) NewRobotPart(ctx context.Context, robotId, partName string) (string, error) { +func (c *AppClient) NewRobotPart(ctx context.Context, robotID, partName string) (string, error) { resp, err := c.client.NewRobotPart(ctx, &pb.NewRobotPartRequest{ - RobotId: robotId, RobotId: robotID, PartName: partName, }) @@ -553,7 +554,7 @@ func (c *AppClient) NewRobotPart(ctx context.Context, robotId, partName string) } // DeleteRobotPart deletes a robot part. -func (c *AppClient) DeleteRobotPart(ctx context.Context, partId string) error { +func (c *AppClient) DeleteRobotPart(ctx context.Context, partID string) error { _, err := c.client.DeleteRobotPart(ctx, &pb.DeleteRobotPartRequest{ PartId: partID, }) From 100343678a5017e7e1ed3b51f71d25816ed1f7c3 Mon Sep 17 00:00:00 2001 From: purplenicole730 Date: Wed, 13 Nov 2024 14:17:05 -0500 Subject: [PATCH 30/75] make lint --- app/app_client.go | 292 +++++++++++++++--------------- app/authorization.go | 212 +++++++++++++--------- app/common.go | 30 +--- app/fragment.go | 70 ++------ app/location.go | 133 ++------------ app/log_stream.go | 9 +- app/organization.go | 120 ++----------- app/registry_item.go | 412 ++++++++++--------------------------------- app/robot.go | 74 ++------ 9 files changed, 426 insertions(+), 926 deletions(-) diff --git a/app/app_client.go b/app/app_client.go index 0a4ed29868a..809eed0616a 100644 --- a/app/app_client.go +++ b/app/app_client.go @@ -16,19 +16,21 @@ import ( "go.viam.com/rdk/logging" ) -type AppClient struct { +// Client is a gRPC client for method calls to the App API. +type Client struct { client pb.AppServiceClient logger logging.Logger mu sync.Mutex } -func NewClientFromConn(conn rpc.ClientConn, logger logging.Logger) AppClient { - return AppClient{client: pb.NewAppServiceClient(conn), logger: logger} +// NewClientFromConn uses a connection to create a new AppClient. +func NewClientFromConn(conn rpc.ClientConn, logger logging.Logger) Client { + return Client{client: pb.NewAppServiceClient(conn), logger: logger} } // GetUserIDByEmail gets the ID of the user with the given email. -func (c *AppClient) GetUserIDByEmail(ctx context.Context, email string) (string, error) { +func (c *Client) GetUserIDByEmail(ctx context.Context, email string) (string, error) { resp, err := c.client.GetUserIDByEmail(ctx, &pb.GetUserIDByEmailRequest{ Email: email, }) @@ -39,18 +41,18 @@ func (c *AppClient) GetUserIDByEmail(ctx context.Context, email string) (string, } // CreateOrganization creates a new organization. -func (c *AppClient) CreateOrganization(ctx context.Context, name string) (*Organization, error) { +func (c *Client) CreateOrganization(ctx context.Context, name string) (*Organization, error) { resp, err := c.client.CreateOrganization(ctx, &pb.CreateOrganizationRequest{ Name: name, }) if err != nil { return nil, err } - return ProtoToOrganization(resp.Organization), nil + return organizationFromProto(resp.Organization), nil } // ListOrganizations lists all the organizations. -func (c *AppClient) ListOrganizations(ctx context.Context) ([]*Organization, error) { +func (c *Client) ListOrganizations(ctx context.Context) ([]*Organization, error) { resp, err := c.client.ListOrganizations(ctx, &pb.ListOrganizationsRequest{}) if err != nil { return nil, err @@ -58,13 +60,13 @@ func (c *AppClient) ListOrganizations(ctx context.Context) ([]*Organization, err var organizations []*Organization for _, org := range resp.Organizations { - organizations = append(organizations, ProtoToOrganization(org)) + organizations = append(organizations, organizationFromProto(org)) } return organizations, nil } // GetOrganizationsWithAccessToLocation gets all the organizations that have access to a location. -func (c *AppClient) GetOrganizationsWithAccessToLocation(ctx context.Context, locationID string) ([]*OrganizationIdentity, error) { +func (c *Client) GetOrganizationsWithAccessToLocation(ctx context.Context, locationID string) ([]*OrganizationIdentity, error) { resp, err := c.client.GetOrganizationsWithAccessToLocation(ctx, &pb.GetOrganizationsWithAccessToLocationRequest{ LocationId: locationID, }) @@ -74,13 +76,13 @@ func (c *AppClient) GetOrganizationsWithAccessToLocation(ctx context.Context, lo var organizations []*OrganizationIdentity for _, org := range resp.OrganizationIdentities { - organizations = append(organizations, ProtoToOrganizationIdentity(org)) + organizations = append(organizations, organizationIdentityFromProto(org)) } return organizations, nil } // ListOrganizationsByUser lists all the organizations that a user belongs to. -func (c *AppClient) ListOrganizationsByUser(ctx context.Context, userID string) ([]*OrgDetails, error) { +func (c *Client) ListOrganizationsByUser(ctx context.Context, userID string) ([]*OrgDetails, error) { resp, err := c.client.ListOrganizationsByUser(ctx, &pb.ListOrganizationsByUserRequest{ UserId: userID, }) @@ -90,24 +92,24 @@ func (c *AppClient) ListOrganizationsByUser(ctx context.Context, userID string) var organizations []*OrgDetails for _, org := range resp.Orgs { - organizations = append(organizations, ProtoToOrgDetails(org)) + organizations = append(organizations, orgDetailsFromProto(org)) } return organizations, nil } // GetOrganization gets an organization. -func (c *AppClient) GetOrganization(ctx context.Context, orgID string) (*Organization, error) { +func (c *Client) GetOrganization(ctx context.Context, orgID string) (*Organization, error) { resp, err := c.client.GetOrganization(ctx, &pb.GetOrganizationRequest{ OrganizationId: orgID, }) if err != nil { return nil, err } - return ProtoToOrganization(resp.Organization), nil + return organizationFromProto(resp.Organization), nil } // GetOrganizationNamespaceAvailability checks for namespace availability throughout all organizations. -func (c *AppClient) GetOrganizationNamespaceAvailability(ctx context.Context, namespace string) (bool, error) { +func (c *Client) GetOrganizationNamespaceAvailability(ctx context.Context, namespace string) (bool, error) { resp, err := c.client.GetOrganizationNamespaceAvailability(ctx, &pb.GetOrganizationNamespaceAvailabilityRequest{ PublicNamespace: namespace, }) @@ -118,7 +120,7 @@ func (c *AppClient) GetOrganizationNamespaceAvailability(ctx context.Context, na } // UpdateOrganization updates an organization. -func (c *AppClient) UpdateOrganization(ctx context.Context, orgID string, name, namespace, region, cid *string) (*Organization, error) { +func (c *Client) UpdateOrganization(ctx context.Context, orgID string, name, namespace, region, cid *string) (*Organization, error) { resp, err := c.client.UpdateOrganization(ctx, &pb.UpdateOrganizationRequest{ OrganizationId: orgID, Name: name, @@ -129,11 +131,11 @@ func (c *AppClient) UpdateOrganization(ctx context.Context, orgID string, name, if err != nil { return nil, err } - return ProtoToOrganization(resp.Organization), nil + return organizationFromProto(resp.Organization), nil } // DeleteOrganization deletes an organization. -func (c *AppClient) DeleteOrganization(ctx context.Context, orgID string) error { +func (c *Client) DeleteOrganization(ctx context.Context, orgID string) error { _, err := c.client.DeleteOrganization(ctx, &pb.DeleteOrganizationRequest{ OrganizationId: orgID, }) @@ -144,7 +146,7 @@ func (c *AppClient) DeleteOrganization(ctx context.Context, orgID string) error } // ListOrganizationMembers lists all members of an organization and all invited members to the organization. -func (c *AppClient) ListOrganizationMembers(ctx context.Context, orgID string) ([]*OrganizationMember, []*OrganizationInvite, error) { +func (c *Client) ListOrganizationMembers(ctx context.Context, orgID string) ([]*OrganizationMember, []*OrganizationInvite, error) { resp, err := c.client.ListOrganizationMembers(ctx, &pb.ListOrganizationMembersRequest{ OrganizationId: orgID, }) @@ -154,22 +156,22 @@ func (c *AppClient) ListOrganizationMembers(ctx context.Context, orgID string) ( var members []*OrganizationMember for _, member := range resp.Members { - members = append(members, ProtoToOrganizationMember(member)) + members = append(members, organizationMemberFromProto(member)) } var invites []*OrganizationInvite for _, invite := range resp.Invites { - invites = append(invites, ProtoToOrganizationInvite(invite)) + invites = append(invites, organizationInviteFromProto(invite)) } return members, invites, nil } -// CreateOrganizaitonInvite creates an organization invite to an organization. -func (c *AppClient) CreateOrganizationInvite( +// CreateOrganizationInvite creates an organization invite to an organization. +func (c *Client) CreateOrganizationInvite( ctx context.Context, orgID, email string, authorizations []*Authorization, sendEmailInvite *bool, ) (*OrganizationInvite, error) { var pbAuthorizations []*pb.Authorization for _, authorization := range authorizations { - pbAuthorizations = append(pbAuthorizations, AuthorizationToProto(authorization)) + pbAuthorizations = append(pbAuthorizations, authorizationToProto(authorization)) } resp, err := c.client.CreateOrganizationInvite(ctx, &pb.CreateOrganizationInviteRequest{ OrganizationId: orgID, @@ -180,20 +182,20 @@ func (c *AppClient) CreateOrganizationInvite( if err != nil { return nil, err } - return ProtoToOrganizationInvite(resp.Invite), nil + return organizationInviteFromProto(resp.Invite), nil } // UpdateOrganizationInviteAuthorizations updates the authorizations attached to an organization invite. -func (c *AppClient) UpdateOrganizationInviteAuthorizations( +func (c *Client) UpdateOrganizationInviteAuthorizations( ctx context.Context, orgID, email string, addAuthorizations, removeAuthorizations []*Authorization, ) (*OrganizationInvite, error) { var pbAddAuthorizations []*pb.Authorization for _, authorization := range addAuthorizations { - pbAddAuthorizations = append(pbAddAuthorizations, AuthorizationToProto(authorization)) + pbAddAuthorizations = append(pbAddAuthorizations, authorizationToProto(authorization)) } var pbRemoveAuthorizations []*pb.Authorization for _, authorization := range removeAuthorizations { - pbRemoveAuthorizations = append(pbRemoveAuthorizations, AuthorizationToProto(authorization)) + pbRemoveAuthorizations = append(pbRemoveAuthorizations, authorizationToProto(authorization)) } resp, err := c.client.UpdateOrganizationInviteAuthorizations(ctx, &pb.UpdateOrganizationInviteAuthorizationsRequest{ OrganizationId: orgID, @@ -204,11 +206,11 @@ func (c *AppClient) UpdateOrganizationInviteAuthorizations( if err != nil { return nil, err } - return ProtoToOrganizationInvite(resp.Invite), nil + return organizationInviteFromProto(resp.Invite), nil } // DeleteOrganizationMember deletes an organization member from an organization. -func (c *AppClient) DeleteOrganizationMember(ctx context.Context, orgID, userID string) error { +func (c *Client) DeleteOrganizationMember(ctx context.Context, orgID, userID string) error { _, err := c.client.DeleteOrganizationMember(ctx, &pb.DeleteOrganizationMemberRequest{ OrganizationId: orgID, UserId: userID, @@ -220,7 +222,7 @@ func (c *AppClient) DeleteOrganizationMember(ctx context.Context, orgID, userID } // DeleteOrganizationInvite deletes an organization invite. -func (c *AppClient) DeleteOrganizationInvite(ctx context.Context, orgID, email string) error { +func (c *Client) DeleteOrganizationInvite(ctx context.Context, orgID, email string) error { _, err := c.client.DeleteOrganizationInvite(ctx, &pb.DeleteOrganizationInviteRequest{ OrganizationId: orgID, Email: email, @@ -232,7 +234,7 @@ func (c *AppClient) DeleteOrganizationInvite(ctx context.Context, orgID, email s } // ResendOrganizationInvite resends an organization invite. -func (c *AppClient) ResendOrganizationInvite(ctx context.Context, orgID, email string) (*OrganizationInvite, error) { +func (c *Client) ResendOrganizationInvite(ctx context.Context, orgID, email string) (*OrganizationInvite, error) { resp, err := c.client.ResendOrganizationInvite(ctx, &pb.ResendOrganizationInviteRequest{ OrganizationId: orgID, Email: email, @@ -240,11 +242,11 @@ func (c *AppClient) ResendOrganizationInvite(ctx context.Context, orgID, email s if err != nil { return nil, err } - return ProtoToOrganizationInvite(resp.Invite), nil + return organizationInviteFromProto(resp.Invite), nil } // CreateLocation creates a location. -func (c *AppClient) CreateLocation(ctx context.Context, orgID, name string, parentLocationID *string) (*Location, error) { +func (c *Client) CreateLocation(ctx context.Context, orgID, name string, parentLocationID *string) (*Location, error) { resp, err := c.client.CreateLocation(ctx, &pb.CreateLocationRequest{ OrganizationId: orgID, Name: name, @@ -253,7 +255,7 @@ func (c *AppClient) CreateLocation(ctx context.Context, orgID, name string, pare if err != nil { return nil, err } - location, err := ProtoToLocation(resp.Location) + location, err := locationFromProto(resp.Location) if err != nil { return nil, err } @@ -261,14 +263,14 @@ func (c *AppClient) CreateLocation(ctx context.Context, orgID, name string, pare } // GetLocation gets a location. -func (c *AppClient) GetLocation(ctx context.Context, locationID string) (*Location, error) { +func (c *Client) GetLocation(ctx context.Context, locationID string) (*Location, error) { resp, err := c.client.GetLocation(ctx, &pb.GetLocationRequest{ LocationId: locationID, }) if err != nil { return nil, err } - location, err := ProtoToLocation(resp.Location) + location, err := locationFromProto(resp.Location) if err != nil { return nil, err } @@ -276,7 +278,7 @@ func (c *AppClient) GetLocation(ctx context.Context, locationID string) (*Locati } // UpdateLocation updates a location. -func (c *AppClient) UpdateLocation(ctx context.Context, locationID string, name, parentLocationID, region *string) (*Location, error) { +func (c *Client) UpdateLocation(ctx context.Context, locationID string, name, parentLocationID, region *string) (*Location, error) { resp, err := c.client.UpdateLocation(ctx, &pb.UpdateLocationRequest{ LocationId: locationID, Name: name, @@ -286,7 +288,7 @@ func (c *AppClient) UpdateLocation(ctx context.Context, locationID string, name, if err != nil { return nil, err } - location, err := ProtoToLocation(resp.Location) + location, err := locationFromProto(resp.Location) if err != nil { return nil, err } @@ -294,7 +296,7 @@ func (c *AppClient) UpdateLocation(ctx context.Context, locationID string, name, } // DeleteLocation deletes a location. -func (c *AppClient) DeleteLocation(ctx context.Context, locationID string) error { +func (c *Client) DeleteLocation(ctx context.Context, locationID string) error { _, err := c.client.DeleteLocation(ctx, &pb.DeleteLocationRequest{ LocationId: locationID, }) @@ -305,7 +307,7 @@ func (c *AppClient) DeleteLocation(ctx context.Context, locationID string) error } // ListLocations gets a list of locations under the specified organization. -func (c *AppClient) ListLocations(ctx context.Context, orgID string) ([]*Location, error) { +func (c *Client) ListLocations(ctx context.Context, orgID string) ([]*Location, error) { resp, err := c.client.ListLocations(ctx, &pb.ListLocationsRequest{ OrganizationId: orgID, }) @@ -315,7 +317,7 @@ func (c *AppClient) ListLocations(ctx context.Context, orgID string) ([]*Locatio var locations []*Location for _, location := range resp.Locations { - l, err := ProtoToLocation(location) + l, err := locationFromProto(location) if err != nil { return nil, err } @@ -325,7 +327,7 @@ func (c *AppClient) ListLocations(ctx context.Context, orgID string) ([]*Locatio } // ShareLocation shares a location with an organization. -func (c *AppClient) ShareLocation(ctx context.Context, locationID, orgID string) error { +func (c *Client) ShareLocation(ctx context.Context, locationID, orgID string) error { _, err := c.client.ShareLocation(ctx, &pb.ShareLocationRequest{ LocationId: locationID, OrganizationId: orgID, @@ -337,7 +339,7 @@ func (c *AppClient) ShareLocation(ctx context.Context, locationID, orgID string) } // UnshareLocation stops sharing a location with an organization. -func (c *AppClient) UnshareLocation(ctx context.Context, locationID, orgID string) error { +func (c *Client) UnshareLocation(ctx context.Context, locationID, orgID string) error { _, err := c.client.UnshareLocation(ctx, &pb.UnshareLocationRequest{ LocationId: locationID, OrganizationId: orgID, @@ -349,14 +351,14 @@ func (c *AppClient) UnshareLocation(ctx context.Context, locationID, orgID strin } // LocationAuth gets a location's authorization secrets. -func (c *AppClient) LocationAuth(ctx context.Context, locationID string) (*LocationAuth, error) { +func (c *Client) LocationAuth(ctx context.Context, locationID string) (*LocationAuth, error) { resp, err := c.client.LocationAuth(ctx, &pb.LocationAuthRequest{ LocationId: locationID, }) if err != nil { return nil, err } - auth, err := ProtoToLocationAuth(resp.Auth) + auth, err := locationAuthFromProto(resp.Auth) if err != nil { return nil, err } @@ -364,22 +366,22 @@ func (c *AppClient) LocationAuth(ctx context.Context, locationID string) (*Locat } // CreateLocationSecret creates a new generated secret in the location. Succeeds if there are no more than 2 active secrets after creation. -func (c *AppClient) CreateLocationSecret(ctx context.Context, locationID string) (*LocationAuth, error) { +func (c *Client) CreateLocationSecret(ctx context.Context, locationID string) (*LocationAuth, error) { resp, err := c.client.CreateLocationSecret(ctx, &pb.CreateLocationSecretRequest{ LocationId: locationID, }) if err != nil { return nil, err } - auth, err := ProtoToLocationAuth(resp.Auth) + auth, err := locationAuthFromProto(resp.Auth) if err != nil { return nil, err } return auth, nil } -// Delete a secret from the location. -func (c *AppClient) DeleteLocationSecret(ctx context.Context, locationID, secretID string) error { +// DeleteLocationSecret deletes a secret from the location. +func (c *Client) DeleteLocationSecret(ctx context.Context, locationID, secretID string) error { _, err := c.client.DeleteLocationSecret(ctx, &pb.DeleteLocationSecretRequest{ LocationId: locationID, SecretId: secretID, @@ -391,18 +393,18 @@ func (c *AppClient) DeleteLocationSecret(ctx context.Context, locationID, secret } // GetRobot gets a specific robot by ID. -func (c *AppClient) GetRobot(ctx context.Context, id string) (*Robot, error) { +func (c *Client) GetRobot(ctx context.Context, id string) (*Robot, error) { resp, err := c.client.GetRobot(ctx, &pb.GetRobotRequest{ Id: id, }) if err != nil { return nil, err } - return ProtoToRobot(resp.Robot), nil + return robotFromProto(resp.Robot), nil } // GetRoverRentalRobots gets rover rental robots within an organization. -func (c *AppClient) GetRoverRentalRobots(ctx context.Context, orgID string) ([]*RoverRentalRobot, error) { +func (c *Client) GetRoverRentalRobots(ctx context.Context, orgID string) ([]*RoverRentalRobot, error) { resp, err := c.client.GetRoverRentalRobots(ctx, &pb.GetRoverRentalRobotsRequest{ OrgId: orgID, }) @@ -411,13 +413,13 @@ func (c *AppClient) GetRoverRentalRobots(ctx context.Context, orgID string) ([]* } var robots []*RoverRentalRobot for _, robot := range resp.Robots { - robots = append(robots, ProtoToRoverRentalRobot(robot)) + robots = append(robots, roverRentalRobotFromProto(robot)) } return robots, nil } // GetRobotParts gets a list of all the parts under a specific machine. -func (c *AppClient) GetRobotParts(ctx context.Context, robotID string) ([]*RobotPart, error) { +func (c *Client) GetRobotParts(ctx context.Context, robotID string) ([]*RobotPart, error) { resp, err := c.client.GetRobotParts(ctx, &pb.GetRobotPartsRequest{ RobotId: robotID, }) @@ -426,7 +428,7 @@ func (c *AppClient) GetRobotParts(ctx context.Context, robotID string) ([]*Robot } var parts []*RobotPart for _, part := range resp.Parts { - p, err := ProtoToRobotPart(part) + p, err := robotPartFromProto(part) if err != nil { return nil, err } @@ -436,14 +438,14 @@ func (c *AppClient) GetRobotParts(ctx context.Context, robotID string) ([]*Robot } // GetRobotPart gets a specific robot part and its config by ID. -func (c *AppClient) GetRobotPart(ctx context.Context, id string) (*RobotPart, string, error) { +func (c *Client) GetRobotPart(ctx context.Context, id string) (*RobotPart, string, error) { resp, err := c.client.GetRobotPart(ctx, &pb.GetRobotPartRequest{ Id: id, }) if err != nil { return nil, "", err } - part, err := ProtoToRobotPart(resp.Part) + part, err := robotPartFromProto(resp.Part) if err != nil { return nil, "", err } @@ -452,7 +454,7 @@ func (c *AppClient) GetRobotPart(ctx context.Context, id string) (*RobotPart, st // GetRobotPartLogs gets the logs associated with a robot part from a page, defaulting to the most recent page if pageToken is empty. // Logs of all levels are returned when levels is empty. -func (c *AppClient) GetRobotPartLogs( +func (c *Client) GetRobotPartLogs( ctx context.Context, id string, filter, @@ -478,17 +480,13 @@ func (c *AppClient) GetRobotPartLogs( } var logs []*LogEntry for _, log := range resp.Logs { - l, err := ProtoToLogEntry(log) - if err != nil { - return nil, "", err - } - logs = append(logs, l) + logs = append(logs, logEntryFromProto(log)) } return logs, resp.NextPageToken, nil } // TailRobotPartLogs gets a stream of log entries for a specific robot part. Logs are ordered by newest first. -func (c *AppClient) TailRobotPartLogs(ctx context.Context, id string, errorsOnly bool, filter *string, ch chan []*LogEntry) error { +func (c *Client) TailRobotPartLogs(ctx context.Context, id string, errorsOnly bool, filter *string, ch chan []*LogEntry) error { stream := &logStream{client: c} err := stream.startStream(ctx, id, errorsOnly, filter, ch) @@ -502,7 +500,7 @@ func (c *AppClient) TailRobotPartLogs(ctx context.Context, id string, errorsOnly } // GetRobotPartHistory gets a specific robot part history by ID. -func (c *AppClient) GetRobotPartHistory(ctx context.Context, id string) ([]*RobotPartHistoryEntry, error) { +func (c *Client) GetRobotPartHistory(ctx context.Context, id string) ([]*RobotPartHistoryEntry, error) { resp, err := c.client.GetRobotPartHistory(ctx, &pb.GetRobotPartHistoryRequest{ Id: id, }) @@ -511,7 +509,7 @@ func (c *AppClient) GetRobotPartHistory(ctx context.Context, id string) ([]*Robo } var history []*RobotPartHistoryEntry for _, entry := range resp.History { - e, err := ProtoToRobotPartHistoryEntry(entry) + e, err := robotPartHistoryEntryFromProto(entry) if err != nil { return nil, err } @@ -520,8 +518,8 @@ func (c *AppClient) GetRobotPartHistory(ctx context.Context, id string) ([]*Robo return history, nil } -// UpdaetRobotPart updates a robot part. -func (c *AppClient) UpdateRobotPart(ctx context.Context, id, name string, robotConfig interface{}) (*RobotPart, error) { +// UpdateRobotPart updates a robot part. +func (c *Client) UpdateRobotPart(ctx context.Context, id, name string, robotConfig interface{}) (*RobotPart, error) { config, err := protoutils.StructToStructPb(robotConfig) if err != nil { return nil, err @@ -534,7 +532,7 @@ func (c *AppClient) UpdateRobotPart(ctx context.Context, id, name string, robotC if err != nil { return nil, err } - part, err := ProtoToRobotPart(resp.Part) + part, err := robotPartFromProto(resp.Part) if err != nil { return nil, err } @@ -542,7 +540,7 @@ func (c *AppClient) UpdateRobotPart(ctx context.Context, id, name string, robotC } // NewRobotPart creates a new robot part. -func (c *AppClient) NewRobotPart(ctx context.Context, robotID, partName string) (string, error) { +func (c *Client) NewRobotPart(ctx context.Context, robotID, partName string) (string, error) { resp, err := c.client.NewRobotPart(ctx, &pb.NewRobotPartRequest{ RobotId: robotID, PartName: partName, @@ -554,7 +552,7 @@ func (c *AppClient) NewRobotPart(ctx context.Context, robotID, partName string) } // DeleteRobotPart deletes a robot part. -func (c *AppClient) DeleteRobotPart(ctx context.Context, partID string) error { +func (c *Client) DeleteRobotPart(ctx context.Context, partID string) error { _, err := c.client.DeleteRobotPart(ctx, &pb.DeleteRobotPartRequest{ PartId: partID, }) @@ -565,7 +563,7 @@ func (c *AppClient) DeleteRobotPart(ctx context.Context, partID string) error { } // GetRobotAPIKeys gets the robot API keys for the robot. -func (c *AppClient) GetRobotAPIKeys(ctx context.Context, robotID string) ([]*APIKeyWithAuthorizations, error) { +func (c *Client) GetRobotAPIKeys(ctx context.Context, robotID string) ([]*APIKeyWithAuthorizations, error) { resp, err := c.client.GetRobotAPIKeys(ctx, &pb.GetRobotAPIKeysRequest{ RobotId: robotID, }) @@ -574,13 +572,13 @@ func (c *AppClient) GetRobotAPIKeys(ctx context.Context, robotID string) ([]*API } var keys []*APIKeyWithAuthorizations for _, key := range resp.ApiKeys { - keys = append(keys, ProtoToAPIKeyWithAuthorizations(key)) + keys = append(keys, apiKeyWithAuthorizationsFromProto(key)) } return keys, nil } // MarkPartAsMain marks the given part as the main part, and all the others as not. -func (c *AppClient) MarkPartAsMain(ctx context.Context, partID string) error { +func (c *Client) MarkPartAsMain(ctx context.Context, partID string) error { _, err := c.client.MarkPartAsMain(ctx, &pb.MarkPartAsMainRequest{ PartId: partID, }) @@ -593,7 +591,7 @@ func (c *AppClient) MarkPartAsMain(ctx context.Context, partID string) error { // MarkPartForRestart marks the given part for restart. // Once the robot part checks-in with the app the flag is reset on the robot part. // Calling this multiple times before a robot part checks-in has no effect. -func (c *AppClient) MarkPartForRestart(ctx context.Context, partID string) error { +func (c *Client) MarkPartForRestart(ctx context.Context, partID string) error { _, err := c.client.MarkPartForRestart(ctx, &pb.MarkPartForRestartRequest{ PartId: partID, }) @@ -605,14 +603,14 @@ func (c *AppClient) MarkPartForRestart(ctx context.Context, partID string) error // CreateRobotPartSecret creates a new generated secret in the robot part. // Succeeds if there are no more than 2 active secrets after creation. -func (c *AppClient) CreateRobotPartSecret(ctx context.Context, partId string) (*RobotPart, error) { +func (c *Client) CreateRobotPartSecret(ctx context.Context, partID string) (*RobotPart, error) { resp, err := c.client.CreateRobotPartSecret(ctx, &pb.CreateRobotPartSecretRequest{ - PartId: partId, + PartId: partID, }) if err != nil { return nil, err } - part, err := ProtoToRobotPart(resp.Part) + part, err := robotPartFromProto(resp.Part) if err != nil { return nil, err } @@ -620,10 +618,10 @@ func (c *AppClient) CreateRobotPartSecret(ctx context.Context, partId string) (* } // DeleteRobotPartSecret deletes a secret from the robot part. -func (c *AppClient) DeleteRobotPartSecret(ctx context.Context, partID, secretId string) error { +func (c *Client) DeleteRobotPartSecret(ctx context.Context, partID, secretID string) error { _, err := c.client.DeleteRobotPartSecret(ctx, &pb.DeleteRobotPartSecretRequest{ PartId: partID, - SecretId: secretId, + SecretId: secretID, }) if err != nil { return err @@ -632,7 +630,7 @@ func (c *AppClient) DeleteRobotPartSecret(ctx context.Context, partID, secretId } // ListRobots gets a list of robots under a location. -func (c *AppClient) ListRobots(ctx context.Context, locationID string) ([]*Robot, error) { +func (c *Client) ListRobots(ctx context.Context, locationID string) ([]*Robot, error) { resp, err := c.client.ListRobots(ctx, &pb.ListRobotsRequest{ LocationId: locationID, }) @@ -641,13 +639,13 @@ func (c *AppClient) ListRobots(ctx context.Context, locationID string) ([]*Robot } var robots []*Robot for _, robot := range resp.Robots { - robots = append(robots, ProtoToRobot(robot)) + robots = append(robots, robotFromProto(robot)) } return robots, nil } // NewRobot creates a new robot. -func (c *AppClient) NewRobot(ctx context.Context, name, location string) (string, error) { +func (c *Client) NewRobot(ctx context.Context, name, location string) (string, error) { resp, err := c.client.NewRobot(ctx, &pb.NewRobotRequest{ Name: name, Location: location, @@ -659,7 +657,7 @@ func (c *AppClient) NewRobot(ctx context.Context, name, location string) (string } // UpdateRobot updates a robot. -func (c *AppClient) UpdateRobot(ctx context.Context, id, name, location string) (*Robot, error) { +func (c *Client) UpdateRobot(ctx context.Context, id, name, location string) (*Robot, error) { resp, err := c.client.UpdateRobot(ctx, &pb.UpdateRobotRequest{ Id: id, Name: name, @@ -668,11 +666,11 @@ func (c *AppClient) UpdateRobot(ctx context.Context, id, name, location string) if err != nil { return nil, err } - return ProtoToRobot(resp.Robot), nil + return robotFromProto(resp.Robot), nil } // DeleteRobot deletes a robot. -func (c *AppClient) DeleteRobot(ctx context.Context, id string) error { +func (c *Client) DeleteRobot(ctx context.Context, id string) error { _, err := c.client.DeleteRobot(ctx, &pb.DeleteRobotRequest{ Id: id, }) @@ -683,19 +681,19 @@ func (c *AppClient) DeleteRobot(ctx context.Context, id string) error { } // ListFragments gets a list of fragments. -func (c *AppClient) ListFragments( - ctx context.Context, orgId string, showPublic bool, fragmentVisibility []FragmentVisibility, +func (c *Client) ListFragments( + ctx context.Context, orgID string, showPublic bool, fragmentVisibility []FragmentVisibility, ) ([]*Fragment, error) { var visibilities []pb.FragmentVisibility for _, visibility := range fragmentVisibility { - v, err := FragmentVisibilityToProto(visibility) + v, err := fragmentVisibilityToProto(visibility) if err != nil { return nil, err } visibilities = append(visibilities, v) } resp, err := c.client.ListFragments(ctx, &pb.ListFragmentsRequest{ - OrganizationId: orgId, + OrganizationId: orgID, ShowPublic: showPublic, FragmentVisibility: visibilities, }) @@ -704,7 +702,7 @@ func (c *AppClient) ListFragments( } var fragments []*Fragment for _, fragment := range resp.Fragments { - f, err := ProtoToFragment(fragment) + f, err := fragmentFromProto(fragment) if err != nil { return nil, err } @@ -714,14 +712,14 @@ func (c *AppClient) ListFragments( } // GetFragment gets a single fragment. -func (c *AppClient) GetFragment(ctx context.Context, id string) (*Fragment, error) { +func (c *Client) GetFragment(ctx context.Context, id string) (*Fragment, error) { resp, err := c.client.GetFragment(ctx, &pb.GetFragmentRequest{ Id: id, }) if err != nil { return nil, err } - fragment, err := ProtoToFragment(resp.Fragment) + fragment, err := fragmentFromProto(resp.Fragment) if err != nil { return nil, err } @@ -729,14 +727,14 @@ func (c *AppClient) GetFragment(ctx context.Context, id string) (*Fragment, erro } // CreateFragment creates a fragment. -func (c *AppClient) CreateFragment( +func (c *Client) CreateFragment( ctx context.Context, name string, config interface{}, orgID string, visibility *FragmentVisibility, ) (*Fragment, error) { cfg, err := protoutils.StructToStructPb(config) if err != nil { return nil, err } - v, err := FragmentVisibilityToProto(*visibility) + v, err := fragmentVisibilityToProto(*visibility) if err != nil { return nil, err } @@ -749,7 +747,7 @@ func (c *AppClient) CreateFragment( if err != nil { return nil, err } - fragment, err := ProtoToFragment(resp.Fragment) + fragment, err := fragmentFromProto(resp.Fragment) if err != nil { return nil, err } @@ -757,7 +755,7 @@ func (c *AppClient) CreateFragment( } // UpdateFragment updates a fragment. -func (c *AppClient) UpdateFragment( +func (c *Client) UpdateFragment( ctx context.Context, id, name string, config interface{}, public *bool, visibility *pb.FragmentVisibility, ) (*Fragment, error) { cfg, err := protoutils.StructToStructPb(config) @@ -774,7 +772,7 @@ func (c *AppClient) UpdateFragment( if err != nil { return nil, err } - fragment, err := ProtoToFragment(resp.Fragment) + fragment, err := fragmentFromProto(resp.Fragment) if err != nil { return nil, err } @@ -782,7 +780,7 @@ func (c *AppClient) UpdateFragment( } // DeleteFragment deletes a fragment. -func (c *AppClient) DeleteFragment(ctx context.Context, id string) error { +func (c *Client) DeleteFragment(ctx context.Context, id string) error { _, err := c.client.DeleteFragment(ctx, &pb.DeleteFragmentRequest{ Id: id, }) @@ -794,17 +792,17 @@ func (c *AppClient) DeleteFragment(ctx context.Context, id string) error { // ListMachineFragments gets top level and nested fragments for a amchine, as well as any other fragments specified by IDs. Additional // fragments are useful when needing to view fragments that will be provisionally added to the machine alongside existing fragments. -func (c *AppClient) ListMachineFragments(ctx context.Context, machineID string, additionalFragmentIds []string) ([]*Fragment, error) { +func (c *Client) ListMachineFragments(ctx context.Context, machineID string, additionalFragmentIDs []string) ([]*Fragment, error) { resp, err := c.client.ListMachineFragments(ctx, &pb.ListMachineFragmentsRequest{ MachineId: machineID, - AdditionalFragmentIds: additionalFragmentIds, + AdditionalFragmentIds: additionalFragmentIDs, }) if err != nil { return nil, err } var fragments []*Fragment for _, fragment := range resp.Fragments { - f, err := ProtoToFragment(fragment) + f, err := fragmentFromProto(fragment) if err != nil { return nil, err } @@ -814,7 +812,7 @@ func (c *AppClient) ListMachineFragments(ctx context.Context, machineID string, } // GetFragmentHistory gets the fragment's history. -func (c *AppClient) GetFragmentHistory( +func (c *Client) GetFragmentHistory( ctx context.Context, id string, pageToken *string, pageLimit *int64, ) ([]*FragmentHistoryEntry, string, error) { resp, err := c.client.GetFragmentHistory(ctx, &pb.GetFragmentHistoryRequest{ @@ -827,7 +825,7 @@ func (c *AppClient) GetFragmentHistory( } var history []*FragmentHistoryEntry for _, entry := range resp.History { - e, err := ProtoToFragmentHistoryEntry(entry) + e, err := fragmentHistoryEntryFromProto(entry) if err != nil { return nil, "", err } @@ -837,8 +835,8 @@ func (c *AppClient) GetFragmentHistory( } // AddRole creates an identity authorization. -func (c *AppClient) AddRole(ctx context.Context, orgID, identityId, role, resourceType, resourceId string) error { - authorization, err := createAuthorization(orgID, identityId, "", role, resourceType, resourceId) +func (c *Client) AddRole(ctx context.Context, orgID, identityID, role, resourceType, resourceID string) error { + authorization, err := createAuthorization(orgID, identityID, "", role, resourceType, resourceID) if err != nil { return err } @@ -852,8 +850,8 @@ func (c *AppClient) AddRole(ctx context.Context, orgID, identityId, role, resour } // RemoveRole deletes an identity authorization. -func (c *AppClient) RemoveRole(ctx context.Context, orgID, identityId, role, resourceType, resourceId string) error { - authorization, err := createAuthorization(orgID, identityId, "", role, resourceType, resourceId) +func (c *Client) RemoveRole(ctx context.Context, orgID, identityID, role, resourceType, resourceID string) error { + authorization, err := createAuthorization(orgID, identityID, "", role, resourceType, resourceID) if err != nil { return err } @@ -867,10 +865,10 @@ func (c *AppClient) RemoveRole(ctx context.Context, orgID, identityId, role, res } // ChangeRole changes an identity authorization to a new identity authorization. -func (c *AppClient) ChangeRole( +func (c *Client) ChangeRole( ctx context.Context, oldOrgID, - oldIdentityId, + oldIdentityID, oldRole, oldResourceType, oldResourceID, @@ -880,7 +878,7 @@ func (c *AppClient) ChangeRole( newResourceType, newResourceID string, ) error { - oldAuthorization, err := createAuthorization(oldOrgID, oldIdentityId, "", oldRole, oldResourceType, oldResourceID) + oldAuthorization, err := createAuthorization(oldOrgID, oldIdentityID, "", oldRole, oldResourceType, oldResourceID) if err != nil { return err } @@ -900,26 +898,26 @@ func (c *AppClient) ChangeRole( // ListAuthorizations returns all authorization roles for any given resources. // If no resources are given, all resources within the organization will be included. -func (c *AppClient) ListAuthorizations(ctx context.Context, orgID string, resourceIds []string) ([]*Authorization, error) { +func (c *Client) ListAuthorizations(ctx context.Context, orgID string, resourceIDs []string) ([]*Authorization, error) { resp, err := c.client.ListAuthorizations(ctx, &pb.ListAuthorizationsRequest{ OrganizationId: orgID, - ResourceIds: resourceIds, + ResourceIds: resourceIDs, }) if err != nil { return nil, err } var authorizations []*Authorization for _, authorization := range resp.Authorizations { - authorizations = append(authorizations, ProtoToAuthorization(authorization)) + authorizations = append(authorizations, authorizationFromProto(authorization)) } return authorizations, nil } // CheckPermissions checks the validity of a list of permissions. -func (c *AppClient) CheckPermissions(ctx context.Context, permissions []*AuthorizedPermissions) ([]*AuthorizedPermissions, error) { +func (c *Client) CheckPermissions(ctx context.Context, permissions []*AuthorizedPermissions) ([]*AuthorizedPermissions, error) { var pbPermissions []*pb.AuthorizedPermissions for _, permission := range permissions { - pbPermissions = append(pbPermissions, AuthorizedPermissionsToProto(permission)) + pbPermissions = append(pbPermissions, authorizedPermissionsToProto(permission)) } resp, err := c.client.CheckPermissions(ctx, &pb.CheckPermissionsRequest{ @@ -931,20 +929,20 @@ func (c *AppClient) CheckPermissions(ctx context.Context, permissions []*Authori var authorizedPermissions []*AuthorizedPermissions for _, permission := range resp.AuthorizedPermissions { - authorizedPermissions = append(authorizedPermissions, ProtoToAuthorizedPermissions(permission)) + authorizedPermissions = append(authorizedPermissions, authorizedPermissionsFromProto(permission)) } return authorizedPermissions, nil } // GetRegistryItem gets a registry item. -func (c *AppClient) GetRegistryItem(ctx context.Context, itemID string) (*RegistryItem, error) { +func (c *Client) GetRegistryItem(ctx context.Context, itemID string) (*RegistryItem, error) { resp, err := c.client.GetRegistryItem(ctx, &pb.GetRegistryItemRequest{ ItemId: itemID, }) if err != nil { return nil, err } - item, err := ProtoToRegistryItem(resp.Item) + item, err := registryItemFromProto(resp.Item) if err != nil { return nil, err } @@ -952,8 +950,8 @@ func (c *AppClient) GetRegistryItem(ctx context.Context, itemID string) (*Regist } // CreateRegistryItem creates a registry item. -func (c *AppClient) CreateRegistryItem(ctx context.Context, orgID, name string, packageType PackageType) error { - pbPackageType, err := PackageTypeToProto(packageType) +func (c *Client) CreateRegistryItem(ctx context.Context, orgID, name string, packageType PackageType) error { + pbPackageType, err := packageTypeToProto(packageType) if err != nil { return err } @@ -969,14 +967,14 @@ func (c *AppClient) CreateRegistryItem(ctx context.Context, orgID, name string, } // UpdateRegistryItem updates a registry item. -func (c *AppClient) UpdateRegistryItem( +func (c *Client) UpdateRegistryItem( ctx context.Context, itemID string, packageType PackageType, description string, visibility Visibility, url *string, ) error { - pbPackageType, err := PackageTypeToProto(packageType) + pbPackageType, err := packageTypeToProto(packageType) if err != nil { return err } - pbVisibility, err := VisibilityToProto(visibility) + pbVisibility, err := visibilityToProto(visibility) if err != nil { return err } @@ -994,7 +992,7 @@ func (c *AppClient) UpdateRegistryItem( } // ListRegistryItems lists the registry items in an organization. -func (c *AppClient) ListRegistryItems( +func (c *Client) ListRegistryItems( ctx context.Context, orgID *string, types []PackageType, @@ -1007,7 +1005,7 @@ func (c *AppClient) ListRegistryItems( ) ([]*RegistryItem, error) { var pbTypes []packages.PackageType for _, packageType := range types { - t, err := PackageTypeToProto(packageType) + t, err := packageTypeToProto(packageType) if err != nil { return nil, err } @@ -1015,7 +1013,7 @@ func (c *AppClient) ListRegistryItems( } var pbVisibilities []pb.Visibility for _, visibility := range visibilities { - v, err := VisibilityToProto(visibility) + v, err := visibilityToProto(visibility) if err != nil { return nil, err } @@ -1023,7 +1021,7 @@ func (c *AppClient) ListRegistryItems( } var pbStatuses []pb.RegistryItemStatus for _, status := range statuses { - s, err := RegistryItemStatusToProto(status) + s, err := registryItemStatusToProto(status) if err != nil { return nil, err } @@ -1044,7 +1042,7 @@ func (c *AppClient) ListRegistryItems( } var items []*RegistryItem for _, item := range resp.Items { - i, err := ProtoToRegistryItem(item) + i, err := registryItemFromProto(item) if err != nil { return nil, err } @@ -1055,7 +1053,7 @@ func (c *AppClient) ListRegistryItems( // DeleteRegistryItem deletes a registry item given an ID that is formatted as `prefix:name“ // where `prefix“ is the owner's organization ID or namespace. -func (c *AppClient) DeleteRegistryItem(ctx context.Context, itemID string) error { +func (c *Client) DeleteRegistryItem(ctx context.Context, itemID string) error { _, err := c.client.DeleteRegistryItem(ctx, &pb.DeleteRegistryItemRequest{ ItemId: itemID, }) @@ -1066,7 +1064,7 @@ func (c *AppClient) DeleteRegistryItem(ctx context.Context, itemID string) error } // TransferRegistryItem transfers a registry item to a namespace. -func (c *AppClient) TransferRegistryItem(ctx context.Context, itemID, newPublicNamespace string) error { +func (c *Client) TransferRegistryItem(ctx context.Context, itemID, newPublicNamespace string) error { _, err := c.client.TransferRegistryItem(ctx, &pb.TransferRegistryItemRequest{ ItemId: itemID, NewPublicNamespace: newPublicNamespace, @@ -1078,7 +1076,7 @@ func (c *AppClient) TransferRegistryItem(ctx context.Context, itemID, newPublicN } // CreateModule creates a module. -func (c *AppClient) CreateModule(ctx context.Context, orgID, name string) (string, string, error) { +func (c *Client) CreateModule(ctx context.Context, orgID, name string) (string, string, error) { resp, err := c.client.CreateModule(ctx, &pb.CreateModuleRequest{ OrganizationId: orgID, Name: name, @@ -1091,16 +1089,16 @@ func (c *AppClient) CreateModule(ctx context.Context, orgID, name string) (strin // UpdateModule updates the documentation URL, description, models, entrypoint, and/or the visibility of a module. // A path to a setup script can be added that is run before a newly downloaded module starts. -func (c *AppClient) UpdateModule( +func (c *Client) UpdateModule( ctx context.Context, moduleID string, visibility Visibility, url, description string, models []*Model, entrypoint string, firstRun *string, ) (string, error) { - pbVisibility, err := VisibilityToProto(visibility) + pbVisibility, err := visibilityToProto(visibility) if err != nil { return "", err } var pbModels []*pb.Model for _, model := range models { - pbModels = append(pbModels, ModelToProto(model)) + pbModels = append(pbModels, modelToProto(model)) } resp, err := c.client.UpdateModule(ctx, &pb.UpdateModuleRequest{ ModuleId: moduleID, @@ -1169,14 +1167,14 @@ func (c *AppClient) UpdateModule( // } // GetModule gets a module. -func (c *AppClient) GetModule(ctx context.Context, moduleID string) (*Module, error) { +func (c *Client) GetModule(ctx context.Context, moduleID string) (*Module, error) { resp, err := c.client.GetModule(ctx, &pb.GetModuleRequest{ ModuleId: moduleID, }) if err != nil { return nil, err } - module, err := ProtoToModule(resp.Module) + module, err := moduleFromProto(resp.Module) if err != nil { return nil, err } @@ -1184,7 +1182,7 @@ func (c *AppClient) GetModule(ctx context.Context, moduleID string) (*Module, er } // ListModules lists the modules in the organization. -func (c *AppClient) ListModules(ctx context.Context, orgID *string) ([]*Module, error) { +func (c *Client) ListModules(ctx context.Context, orgID *string) ([]*Module, error) { resp, err := c.client.ListModules(ctx, &pb.ListModulesRequest{ OrganizationId: orgID, }) @@ -1193,7 +1191,7 @@ func (c *AppClient) ListModules(ctx context.Context, orgID *string) ([]*Module, } var modules []*Module for _, module := range resp.Modules { - m, err := ProtoToModule(module) + m, err := moduleFromProto(module) if err != nil { return nil, err } @@ -1203,7 +1201,7 @@ func (c *AppClient) ListModules(ctx context.Context, orgID *string) ([]*Module, } // CreateKey creates a new API key associated with a list of authorizations. -func (c *AppClient) CreateKey( +func (c *Client) CreateKey( ctx context.Context, orgID string, keyAuthorizations []APIKeyAuthorization, name string, ) (string, string, error) { var authorizations []*pb.Authorization @@ -1227,7 +1225,7 @@ func (c *AppClient) CreateKey( } // DeleteKey deletes an API key. -func (c *AppClient) DeleteKey(ctx context.Context, id string) error { +func (c *Client) DeleteKey(ctx context.Context, id string) error { _, err := c.client.DeleteKey(ctx, &pb.DeleteKeyRequest{ Id: id, }) @@ -1238,7 +1236,7 @@ func (c *AppClient) DeleteKey(ctx context.Context, id string) error { } // ListKeys lists all the keys for the organization. -func (c *AppClient) ListKeys(ctx context.Context, orgID string) ([]APIKeyWithAuthorizations, error) { +func (c *Client) ListKeys(ctx context.Context, orgID string) ([]APIKeyWithAuthorizations, error) { resp, err := c.client.ListKeys(ctx, &pb.ListKeysRequest{ OrgId: orgID, }) @@ -1247,13 +1245,13 @@ func (c *AppClient) ListKeys(ctx context.Context, orgID string) ([]APIKeyWithAut } var apiKeys []APIKeyWithAuthorizations for _, key := range resp.ApiKeys { - apiKeys = append(apiKeys, *ProtoToAPIKeyWithAuthorizations(key)) + apiKeys = append(apiKeys, *apiKeyWithAuthorizationsFromProto(key)) } return apiKeys, nil } // RenameKey renames an API key. -func (c *AppClient) RenameKey(ctx context.Context, id, name string) (string, string, error) { +func (c *Client) RenameKey(ctx context.Context, id, name string) (string, string, error) { resp, err := c.client.RenameKey(ctx, &pb.RenameKeyRequest{ Id: id, Name: name, @@ -1265,7 +1263,7 @@ func (c *AppClient) RenameKey(ctx context.Context, id, name string) (string, str } // RotateKey rotates an API key. -func (c *AppClient) RotateKey(ctx context.Context, id string) (string, string, error) { +func (c *Client) RotateKey(ctx context.Context, id string) (string, string, error) { resp, err := c.client.RotateKey(ctx, &pb.RotateKeyRequest{ Id: id, }) @@ -1276,7 +1274,7 @@ func (c *AppClient) RotateKey(ctx context.Context, id string) (string, string, e } // CreateKeyFromExistingKeyAuthorizations creates a new API key with an existing key's authorizations. -func (c *AppClient) CreateKeyFromExistingKeyAuthorizations(ctx context.Context, id string) (string, string, error) { +func (c *Client) CreateKeyFromExistingKeyAuthorizations(ctx context.Context, id string) (string, string, error) { resp, err := c.client.CreateKeyFromExistingKeyAuthorizations(ctx, &pb.CreateKeyFromExistingKeyAuthorizationsRequest{ Id: id, }) diff --git a/app/authorization.go b/app/authorization.go index de78fec7385..5041b2e5833 100644 --- a/app/authorization.go +++ b/app/authorization.go @@ -8,6 +8,73 @@ import ( "google.golang.org/protobuf/types/known/timestamppb" ) +// Authorization has the information about a specific authorization. +type Authorization struct { + AuthorizationType string + AuthorizationID string + ResourceType string + ResourceID string + IdentityID string + OrganizationID string + IdentityType string +} + +func authorizationFromProto(authorization *pb.Authorization) *Authorization { + return &Authorization{ + AuthorizationType: authorization.AuthorizationType, + AuthorizationID: authorization.AuthorizationId, + ResourceType: authorization.ResourceType, + ResourceID: authorization.ResourceId, + IdentityID: authorization.IdentityId, + OrganizationID: authorization.OrganizationId, + IdentityType: authorization.IdentityType, + } +} + +func authorizationToProto(authorization *Authorization) *pb.Authorization { + return &pb.Authorization{ + AuthorizationType: authorization.AuthorizationType, + AuthorizationId: authorization.AuthorizationID, + ResourceType: authorization.ResourceType, + ResourceId: authorization.ResourceID, + IdentityId: authorization.IdentityID, + OrganizationId: authorization.OrganizationID, + IdentityType: authorization.IdentityType, + } +} + +// AuthorizedPermissions is authorized permissions. +type AuthorizedPermissions struct { + ResourceType string + ResourceID string + Permissions []string +} + +func authorizedPermissionsFromProto(permissions *pb.AuthorizedPermissions) *AuthorizedPermissions { + return &AuthorizedPermissions{ + ResourceType: permissions.ResourceType, + ResourceID: permissions.ResourceId, + Permissions: permissions.Permissions, + } +} + +func authorizedPermissionsToProto(permissions *AuthorizedPermissions) *pb.AuthorizedPermissions { + return &pb.AuthorizedPermissions{ + ResourceType: permissions.ResourceType, + ResourceId: permissions.ResourceID, + Permissions: permissions.Permissions, + } +} + +// APIKeyAuthorization is a struct with the necessary authorization data to create an API key. +type APIKeyAuthorization struct { + // `role`` must be "owner" or "operator" + role string + // `resourceType` must be "organization", "location", or "robot" + resourceType string + resourceID string +} + func createAuthorization(orgID, identityID, identityType, role, resourceType, resourceID string) (*pb.Authorization, error) { if role != "owner" && role != "operator" { return nil, errors.New("role string must be 'owner' or 'operator'") @@ -27,47 +94,86 @@ func createAuthorization(orgID, identityID, identityType, role, resourceType, re }, nil } -type AuthenticatorInfo struct { - Type AuthenticationType - Value string - IsDeactivated bool +// SharedSecret is a secret used for LocationAuth and RobotParts. +type SharedSecret struct { + ID string + CreatedOn *timestamppb.Timestamp + State SharedSecretState } -func ProtoToAuthenticatorInfo(info *pb.AuthenticatorInfo) (*AuthenticatorInfo, error) { - authenticationType, err := ProtoToAuthenticationType(info.Type) +func sharedSecretFromProto(sharedSecret *pb.SharedSecret) (*SharedSecret, error) { + state, err := sharedSecretStateFromProto(sharedSecret.State) if err != nil { return nil, err } - return &AuthenticatorInfo{ - Type: authenticationType, - Value: info.Value, - IsDeactivated: info.IsDeactivated, + return &SharedSecret{ + ID: sharedSecret.Id, + CreatedOn: sharedSecret.CreatedOn, + State: state, }, nil } -func AuthenticatorInfoToProto(info *AuthenticatorInfo) (*pb.AuthenticatorInfo, error) { - authenticationType, err := AuthenticationTypeToProto(info.Type) +// SharedSecretState specifies if the secret is enabled, disabled, or unspecified. +type SharedSecretState int32 + +const ( + // SharedSecretUnspecified represents an unspecified shared secret state. + SharedSecretUnspecified SharedSecretState = 0 + // SharedSecretEnabled represents an enabled secret that can be used in authentication. + SharedSecretEnabled SharedSecretState = 1 + // SharedSecretDisabled represents a disabled secret that must not be used to authenticate to rpc. + SharedSecretDisabled SharedSecretState = 2 +) + +func sharedSecretStateFromProto(state pb.SharedSecret_State) (SharedSecretState, error) { + switch state { + case pb.SharedSecret_STATE_UNSPECIFIED: + return SharedSecretUnspecified, nil + case pb.SharedSecret_STATE_ENABLED: + return SharedSecretEnabled, nil + case pb.SharedSecret_STATE_DISABLED: + return SharedSecretDisabled, nil + default: + return 0, fmt.Errorf("uknown secret state: %v", state) + } +} + +// AuthenticatorInfo holds the information of an authenticator. +type AuthenticatorInfo struct { + Type AuthenticationType + Value string + IsDeactivated bool +} + +func authenticatorInfoFromProto(info *pb.AuthenticatorInfo) (*AuthenticatorInfo, error) { + authenticationType, err := authenticationTypeFromProto(info.Type) if err != nil { return nil, err } - return &pb.AuthenticatorInfo{ + return &AuthenticatorInfo{ Type: authenticationType, Value: info.Value, IsDeactivated: info.IsDeactivated, }, nil } +// AuthenticationType specifies the type of authentication. type AuthenticationType int32 const ( - AuthenticationTypeUnspecified AuthenticationType = 0 - AuthenticationTypeWebOAuth AuthenticationType = 1 - AuthenticationTypeAPIKey AuthenticationType = 2 + // AuthenticationTypeUnspecified represents an unspecified authentication. + AuthenticationTypeUnspecified AuthenticationType = 0 + // AuthenticationTypeWebOAuth represents authentication using Web OAuth. + AuthenticationTypeWebOAuth AuthenticationType = 1 + // AuthenticationTypeAPIKey represents authentication using an API key. + AuthenticationTypeAPIKey AuthenticationType = 2 + // AuthenticationTypeRobotPartSecret represents authentication using a robot part secret. AuthenticationTypeRobotPartSecret AuthenticationType = 3 - AuthenticationTypeLocationSecret AuthenticationType = 4 + // AuthenticationTypeLocationSecret represents authentication using a location secret. + AuthenticationTypeLocationSecret AuthenticationType = 4 ) -func ProtoToAuthenticationType(authenticationType pb.AuthenticationType) (AuthenticationType, error) { +func authenticationTypeFromProto(authenticationType pb.AuthenticationType) (AuthenticationType, error) { switch authenticationType { case pb.AuthenticationType_AUTHENTICATION_TYPE_UNSPECIFIED: return AuthenticationTypeUnspecified, nil @@ -84,50 +190,24 @@ func ProtoToAuthenticationType(authenticationType pb.AuthenticationType) (Authen } } -func AuthenticationTypeToProto(authenticationType AuthenticationType) (pb.AuthenticationType, error) { - switch authenticationType { - case AuthenticationTypeUnspecified: - return pb.AuthenticationType_AUTHENTICATION_TYPE_UNSPECIFIED, nil - case AuthenticationTypeWebOAuth: - return pb.AuthenticationType_AUTHENTICATION_TYPE_WEB_OAUTH, nil - case AuthenticationTypeAPIKey: - return pb.AuthenticationType_AUTHENTICATION_TYPE_API_KEY, nil - case AuthenticationTypeRobotPartSecret: - return pb.AuthenticationType_AUTHENTICATION_TYPE_ROBOT_PART_SECRET, nil - case AuthenticationTypeLocationSecret: - return pb.AuthenticationType_AUTHENTICATION_TYPE_LOCATION_SECRET, nil - default: - return 0, fmt.Errorf("unknown authentication type: %v", authenticationType) - } -} - +// APIKeyWithAuthorizations is an API Key with its authorizations. type APIKeyWithAuthorizations struct { APIKey *APIKey Authorizations []*AuthorizationDetails } -func ProtoToAPIKeyWithAuthorizations(key *pb.APIKeyWithAuthorizations) *APIKeyWithAuthorizations { +func apiKeyWithAuthorizationsFromProto(key *pb.APIKeyWithAuthorizations) *APIKeyWithAuthorizations { var details []*AuthorizationDetails for _, detail := range key.Authorizations { - details = append(details, ProtoToAuthorizationDetails(detail)) + details = append(details, authorizationDetailsFromProto(detail)) } return &APIKeyWithAuthorizations{ - APIKey: ProtoToAPIKey(key.ApiKey), - Authorizations: details, - } -} - -func APIKeyWithAuthorizationsToProto(key *APIKeyWithAuthorizations) *pb.APIKeyWithAuthorizations { - var details []*pb.AuthorizationDetails - for _, detail := range key.Authorizations { - details = append(details, AuthorizationDetailsToProto(detail)) - } - return &pb.APIKeyWithAuthorizations{ - ApiKey: APIKeyToProto(key.APIKey), + APIKey: apiKeyFromProto(key.ApiKey), Authorizations: details, } } +// APIKey is a API key to make a request to an API. type APIKey struct { ID string Key string @@ -135,7 +215,7 @@ type APIKey struct { CreatedOn *timestamppb.Timestamp } -func ProtoToAPIKey(key *pb.APIKey) *APIKey { +func apiKeyFromProto(key *pb.APIKey) *APIKey { return &APIKey{ ID: key.Id, Key: key.Key, @@ -144,15 +224,7 @@ func ProtoToAPIKey(key *pb.APIKey) *APIKey { } } -func APIKeyToProto(key *APIKey) *pb.APIKey { - return &pb.APIKey{ - Id: key.ID, - Key: key.Key, - Name: key.Name, - CreatedOn: key.CreatedOn, - } -} - +// AuthorizationDetails has the details for an authorization. type AuthorizationDetails struct { AuthorizationType string AuthorizationID string @@ -161,7 +233,7 @@ type AuthorizationDetails struct { OrgID string } -func ProtoToAuthorizationDetails(details *pb.AuthorizationDetails) *AuthorizationDetails { +func authorizationDetailsFromProto(details *pb.AuthorizationDetails) *AuthorizationDetails { return &AuthorizationDetails{ AuthorizationType: details.AuthorizationType, AuthorizationID: details.AuthorizationId, @@ -170,23 +242,3 @@ func ProtoToAuthorizationDetails(details *pb.AuthorizationDetails) *Authorizatio OrgID: details.OrgId, } } - -// AuthorizationDetailsToProto converts a AuthorizationDetails struct to protobuf. -func AuthorizationDetailsToProto(details *AuthorizationDetails) *pb.AuthorizationDetails { - return &pb.AuthorizationDetails{ - AuthorizationType: details.AuthorizationType, - AuthorizationId: details.AuthorizationID, - ResourceType: details.ResourceType, - ResourceId: details.ResourceID, - OrgId: details.OrgID, - } -} - -// APIKeyAuthorization is a struct with the necessary authorization data to create an API key. -type APIKeyAuthorization struct { - // `role`` must be "owner" or "operator" - role string - // `resourceType` must be "organization", "location", or "robot" - resourceType string - resourceID string -} diff --git a/app/common.go b/app/common.go index 81995b51b08..e0f31711f8b 100644 --- a/app/common.go +++ b/app/common.go @@ -2,11 +2,10 @@ package app import ( common "go.viam.com/api/common/v1" - "go.viam.com/utils/protoutils" - "google.golang.org/protobuf/types/known/structpb" "google.golang.org/protobuf/types/known/timestamppb" ) +// LogEntry holds the information of a single log entry. type LogEntry struct { Host string Level string @@ -18,7 +17,7 @@ type LogEntry struct { Fields []*map[string]interface{} } -func ProtoToLogEntry(logEntry *common.LogEntry) (*LogEntry, error) { +func logEntryFromProto(logEntry *common.LogEntry) *LogEntry { var fields []*map[string]interface{} for _, field := range logEntry.Fields { f := field.AsMap() @@ -34,30 +33,5 @@ func ProtoToLogEntry(logEntry *common.LogEntry) (*LogEntry, error) { Caller: &caller, Stack: logEntry.Stack, Fields: fields, - }, nil -} - -func LogEntryToProto(logEntry *LogEntry) (*common.LogEntry, error) { - var fields []*structpb.Struct - for _, field := range logEntry.Fields { - f, err := protoutils.StructToStructPb(field) - if err != nil { - return nil, err - } - fields = append(fields, f) } - caller, err := protoutils.StructToStructPb(logEntry.Caller) - if err != nil { - return nil, err - } - return &common.LogEntry{ - Host: logEntry.Host, - Level: logEntry.Level, - Time: logEntry.Time, - LoggerName: logEntry.LoggerName, - Message: logEntry.Message, - Caller: caller, - Stack: logEntry.Stack, - Fields: fields, - }, nil } diff --git a/app/fragment.go b/app/fragment.go index 1a524e6b333..6c10c4ffa3f 100644 --- a/app/fragment.go +++ b/app/fragment.go @@ -4,10 +4,10 @@ import ( "fmt" pb "go.viam.com/api/app/v1" - "go.viam.com/utils/protoutils" "google.golang.org/protobuf/types/known/timestamppb" ) +// Fragment stores the information of a fragment. type Fragment struct { ID string Name string @@ -23,9 +23,9 @@ type Fragment struct { LastUpdated *timestamppb.Timestamp } -func ProtoToFragment(fragment *pb.Fragment) (*Fragment, error) { +func fragmentFromProto(fragment *pb.Fragment) (*Fragment, error) { f := fragment.Fragment.AsMap() - visibility, err := ProtoToFragmentVisibility(fragment.Visibility) + visibility, err := fragmentVisibilityFromProto(fragment.Visibility) if err != nil { return nil, err } @@ -45,41 +45,21 @@ func ProtoToFragment(fragment *pb.Fragment) (*Fragment, error) { }, nil } -func FragmentToProto(fragment *Fragment) (*pb.Fragment, error) { - f, err := protoutils.StructToStructPb(fragment.Fragment) - if err != nil { - return nil, err - } - visibility, err := FragmentVisibilityToProto(fragment.Visibility) - if err != nil { - return nil, err - } - return &pb.Fragment{ - Id: fragment.ID, - Name: fragment.Name, - Fragment: f, - OrganizationOwner: fragment.OrganizationOwner, - Public: fragment.Public, - CreatedOn: fragment.CreatedOn, - OrganizationName: fragment.OrganizationName, - RobotPartCount: fragment.RobotPartCount, - OrganizationCount: fragment.OrganizationCount, - OnlyUsedByOwner: fragment.OnlyUsedByOwner, - Visibility: visibility, - LastUpdated: fragment.LastUpdated, - }, nil -} - +// FragmentVisibility specifies the kind of visibility a fragment has. type FragmentVisibility int32 const ( - FragmentVisibilityUnspecified FragmentVisibility = 0 - FragmentVisibilityPrivate FragmentVisibility = 1 - FragmentVisibilityPublic FragmentVisibility = 2 + // FragmentVisibilityUnspecified is an unspecified visibility. + FragmentVisibilityUnspecified FragmentVisibility = 0 + // FragmentVisibilityPrivate restricts access to a fragment to its organization. + FragmentVisibilityPrivate FragmentVisibility = 1 + // FragmentVisibilityPublic allows the fragment to be accessible to everyone. + FragmentVisibilityPublic FragmentVisibility = 2 + // FragmentVisibilityPublicUnlisted allows the fragment to be accessible to everyone but is hidden from public listings like it is private. FragmentVisibilityPublicUnlisted FragmentVisibility = 3 ) -func ProtoToFragmentVisibility(visibility pb.FragmentVisibility) (FragmentVisibility, error) { +func fragmentVisibilityFromProto(visibility pb.FragmentVisibility) (FragmentVisibility, error) { switch visibility { case pb.FragmentVisibility_FRAGMENT_VISIBILITY_UNSPECIFIED: return FragmentVisibilityUnspecified, nil @@ -94,7 +74,7 @@ func ProtoToFragmentVisibility(visibility pb.FragmentVisibility) (FragmentVisibi } } -func FragmentVisibilityToProto(visibility FragmentVisibility) (pb.FragmentVisibility, error) { +func fragmentVisibilityToProto(visibility FragmentVisibility) (pb.FragmentVisibility, error) { switch visibility { case FragmentVisibilityUnspecified: return pb.FragmentVisibility_FRAGMENT_VISIBILITY_UNSPECIFIED, nil @@ -109,6 +89,7 @@ func FragmentVisibilityToProto(visibility FragmentVisibility) (pb.FragmentVisibi } } +// FragmentHistoryEntry is an entry of a fragment's history. type FragmentHistoryEntry struct { Fragment string EditedOn *timestamppb.Timestamp @@ -116,12 +97,12 @@ type FragmentHistoryEntry struct { EditedBy *AuthenticatorInfo } -func ProtoToFragmentHistoryEntry(entry *pb.FragmentHistoryEntry) (*FragmentHistoryEntry, error) { - old, err := ProtoToFragment(entry.Old) +func fragmentHistoryEntryFromProto(entry *pb.FragmentHistoryEntry) (*FragmentHistoryEntry, error) { + old, err := fragmentFromProto(entry.Old) if err != nil { return nil, err } - editedBy, err := ProtoToAuthenticatorInfo(entry.EditedBy) + editedBy, err := authenticatorInfoFromProto(entry.EditedBy) if err != nil { return nil, err } @@ -132,20 +113,3 @@ func ProtoToFragmentHistoryEntry(entry *pb.FragmentHistoryEntry) (*FragmentHisto EditedBy: editedBy, }, nil } - -func FragmentHistoryEntryToProto(entry *FragmentHistoryEntry) (*pb.FragmentHistoryEntry, error) { - old, err := FragmentToProto(entry.Old) - if err != nil { - return nil, err - } - editedBy, err := AuthenticatorInfoToProto(entry.EditedBy) - if err != nil { - return nil, err - } - return &pb.FragmentHistoryEntry{ - Fragment: entry.Fragment, - EditedOn: entry.EditedOn, - Old: old, - EditedBy: editedBy, - }, nil -} diff --git a/app/location.go b/app/location.go index c628eea28ba..f750389b700 100644 --- a/app/location.go +++ b/app/location.go @@ -1,12 +1,11 @@ package app import ( - "fmt" - pb "go.viam.com/api/app/v1" "google.golang.org/protobuf/types/known/timestamppb" ) +// Location holds the information of a specific location. type Location struct { ID string Name string @@ -18,12 +17,12 @@ type Location struct { Config *StorageConfig } -func ProtoToLocation(location *pb.Location) (*Location, error) { +func locationFromProto(location *pb.Location) (*Location, error) { var organizations []*LocationOrganization for _, organization := range location.Organizations { - organizations = append(organizations, ProtoToLocationOrganization(organization)) + organizations = append(organizations, locationOrganizationFromProto(organization)) } - auth, err := ProtoToLocationAuth(location.Auth) + auth, err := locationAuthFromProto(location.Auth) if err != nil { return nil, err } @@ -35,71 +34,42 @@ func ProtoToLocation(location *pb.Location) (*Location, error) { Organizations: organizations, CreatedOn: location.CreatedOn, RobotCount: location.RobotCount, - Config: ProtoToStorageConfig(location.Config), - }, nil -} - -func LocationToProto(location *Location) (*pb.Location, error) { - var organizations []*pb.LocationOrganization - for _, organization := range location.Organizations { - organizations = append(organizations, LocationOrganizationToProto(organization)) - } - auth, err := LocationAuthToProto(location.Auth) - if err != nil { - return nil, err - } - return &pb.Location{ - Id: location.ID, - Name: location.Name, - ParentLocationId: location.ParentLocationID, - Auth: auth, - Organizations: organizations, - CreatedOn: location.CreatedOn, - RobotCount: location.RobotCount, - Config: StorageConfigToProto(location.Config), + Config: storageConfigFromProto(location.Config), }, nil } +// LocationOrganization holds information of an organization the location is shared with. type LocationOrganization struct { OrganizationID string Primary bool } -func ProtoToLocationOrganization(locationOrganization *pb.LocationOrganization) *LocationOrganization { +func locationOrganizationFromProto(locationOrganization *pb.LocationOrganization) *LocationOrganization { return &LocationOrganization{ OrganizationID: locationOrganization.OrganizationId, Primary: locationOrganization.Primary, } } -func LocationOrganizationToProto(locationOrganization *LocationOrganization) *pb.LocationOrganization { - return &pb.LocationOrganization{ - OrganizationId: locationOrganization.OrganizationID, - Primary: locationOrganization.Primary, - } -} - +// StorageConfig holds the GCS region that data is stored in. type StorageConfig struct { Region string } -func ProtoToStorageConfig(config *pb.StorageConfig) *StorageConfig { +func storageConfigFromProto(config *pb.StorageConfig) *StorageConfig { return &StorageConfig{Region: config.Region} } -func StorageConfigToProto(config *StorageConfig) *pb.StorageConfig { - return &pb.StorageConfig{Region: config.Region} -} - +// LocationAuth holds the secrets used to authenticate to a location. type LocationAuth struct { LocationID string Secrets []*SharedSecret } -func ProtoToLocationAuth(locationAuth *pb.LocationAuth) (*LocationAuth, error) { +func locationAuthFromProto(locationAuth *pb.LocationAuth) (*LocationAuth, error) { var secrets []*SharedSecret for _, secret := range locationAuth.Secrets { - s, err := ProtoToSharedSecret(secret) + s, err := sharedSecretFromProto(secret) if err != nil { return nil, err } @@ -110,82 +80,3 @@ func ProtoToLocationAuth(locationAuth *pb.LocationAuth) (*LocationAuth, error) { Secrets: secrets, }, nil } - -func LocationAuthToProto(locationAuth *LocationAuth) (*pb.LocationAuth, error) { - var secrets []*pb.SharedSecret - for _, secret := range locationAuth.Secrets { - s, err := SharedSecretToProto(secret) - if err != nil { - return nil, err - } - secrets = append(secrets, s) - } - return &pb.LocationAuth{ - LocationId: locationAuth.LocationID, - Secrets: secrets, - }, nil -} - -type SharedSecret struct { - ID string - CreatedOn *timestamppb.Timestamp - State SharedSecretState -} - -func ProtoToSharedSecret(sharedSecret *pb.SharedSecret) (*SharedSecret, error) { - state, err := ProtoToSharedSecretState(sharedSecret.State) - if err != nil { - return nil, err - } - return &SharedSecret{ - ID: sharedSecret.Id, - CreatedOn: sharedSecret.CreatedOn, - State: state, - }, nil -} - -func SharedSecretToProto(sharedSecret *SharedSecret) (*pb.SharedSecret, error) { - state, err := SharedSecretStateToProto(sharedSecret.State) - if err != nil { - return nil, err - } - return &pb.SharedSecret{ - Id: sharedSecret.ID, - CreatedOn: sharedSecret.CreatedOn, - State: state, - }, nil -} - -type SharedSecretState int32 - -const ( - SharedSecretUnspecified SharedSecretState = 0 - SharedSecretEnabled SharedSecretState = 1 - SharedSecretDisabled SharedSecretState = 2 -) - -func ProtoToSharedSecretState(state pb.SharedSecret_State) (SharedSecretState, error) { - switch state { - case pb.SharedSecret_STATE_UNSPECIFIED: - return SharedSecretUnspecified, nil - case pb.SharedSecret_STATE_ENABLED: - return SharedSecretEnabled, nil - case pb.SharedSecret_STATE_DISABLED: - return SharedSecretDisabled, nil - default: - return 0, fmt.Errorf("uknown secret state: %v", state) - } -} - -func SharedSecretStateToProto(state SharedSecretState) (pb.SharedSecret_State, error) { - switch state { - case SharedSecretUnspecified: - return pb.SharedSecret_STATE_UNSPECIFIED, nil - case SharedSecretEnabled: - return pb.SharedSecret_STATE_ENABLED, nil - case SharedSecretDisabled: - return pb.SharedSecret_STATE_DISABLED, nil - default: - return 0, fmt.Errorf("unknown secret state: %v", state) - } -} diff --git a/app/log_stream.go b/app/log_stream.go index 5b9055c58d9..8044772ba88 100644 --- a/app/log_stream.go +++ b/app/log_stream.go @@ -9,7 +9,7 @@ import ( ) type logStream struct { - client *AppClient + client *Client streamCancel context.CancelFunc streamMu sync.Mutex @@ -79,12 +79,7 @@ func (s *logStream) receiveFromStream(ctx context.Context, stream pb.AppService_ // If there is a response, send to the logs channel. var logs []*LogEntry for _, log := range streamResp.Logs { - l, err := ProtoToLogEntry(log) - if err != nil { - s.client.logger.Debug(err) - return - } - logs = append(logs, l) + logs = append(logs, logEntryFromProto(log)) } ch <- logs } diff --git a/app/organization.go b/app/organization.go index f34184e462c..e1160ce5b52 100644 --- a/app/organization.go +++ b/app/organization.go @@ -5,6 +5,7 @@ import ( "google.golang.org/protobuf/types/known/timestamppb" ) +// Organization holds the information of an organization. type Organization struct { ID string Name string @@ -14,7 +15,7 @@ type Organization struct { Cid *string } -func ProtoToOrganization(organization *pb.Organization) *Organization { +func organizationFromProto(organization *pb.Organization) *Organization { return &Organization{ ID: organization.Id, Name: organization.Name, @@ -25,55 +26,33 @@ func ProtoToOrganization(organization *pb.Organization) *Organization { } } -func OrganizationToProto(organization *Organization) *pb.Organization { - return &pb.Organization{ - Id: organization.ID, - Name: organization.Name, - CreatedOn: organization.CreatedOn, - PublicNamespace: organization.PublicNamespace, - DefaultRegion: organization.DefaultRegion, - Cid: organization.Cid, - } -} - +// OrganizationIdentity is used to render an organization's information on the frontend. type OrganizationIdentity struct { ID string Name string } -func ProtoToOrganizationIdentity(organizationIdentity *pb.OrganizationIdentity) *OrganizationIdentity { +func organizationIdentityFromProto(organizationIdentity *pb.OrganizationIdentity) *OrganizationIdentity { return &OrganizationIdentity{ ID: organizationIdentity.Id, Name: organizationIdentity.Name, } } -func OrganizationIdentityToProto(organizationIdentity *OrganizationIdentity) (*pb.OrganizationIdentity, error) { - return &pb.OrganizationIdentity{ - Id: organizationIdentity.ID, - Name: organizationIdentity.Name, - }, nil -} - +// OrgDetails holds the ID and name of the organization. type OrgDetails struct { OrgID string OrgName string } -func ProtoToOrgDetails(orgDetails *pb.OrgDetails) *OrgDetails { +func orgDetailsFromProto(orgDetails *pb.OrgDetails) *OrgDetails { return &OrgDetails{ OrgID: orgDetails.OrgId, OrgName: orgDetails.OrgName, } } -func OrgDetailsToProto(orgDetails *OrgDetails) (*pb.OrgDetails, error) { - return &pb.OrgDetails{ - OrgId: orgDetails.OrgID, - OrgName: orgDetails.OrgName, - }, nil -} - +// OrganizationMember holds the information of a member of an organization. type OrganizationMember struct { UserID string Emails []string @@ -81,7 +60,7 @@ type OrganizationMember struct { LastLogin *timestamppb.Timestamp } -func ProtoToOrganizationMember(organizationMemOrganizationMember *pb.OrganizationMember) *OrganizationMember { +func organizationMemberFromProto(organizationMemOrganizationMember *pb.OrganizationMember) *OrganizationMember { return &OrganizationMember{ UserID: organizationMemOrganizationMember.UserId, Emails: organizationMemOrganizationMember.Emails, @@ -90,15 +69,7 @@ func ProtoToOrganizationMember(organizationMemOrganizationMember *pb.Organizatio } } -func OrganizationMemberToProto(organizationMemOrganizationMember *OrganizationMember) (*pb.OrganizationMember, error) { - return &pb.OrganizationMember{ - UserId: organizationMemOrganizationMember.UserID, - Emails: organizationMemOrganizationMember.Emails, - DateAdded: organizationMemOrganizationMember.DateAdded, - LastLogin: organizationMemOrganizationMember.LastLogin, - }, nil -} - +// OrganizationInvite is the invite to an organization. type OrganizationInvite struct { OrganizationID string Email string @@ -106,10 +77,10 @@ type OrganizationInvite struct { Authorizations []*Authorization } -func ProtoToOrganizationInvite(organizationInvite *pb.OrganizationInvite) *OrganizationInvite { +func organizationInviteFromProto(organizationInvite *pb.OrganizationInvite) *OrganizationInvite { var authorizations []*Authorization for _, authorization := range organizationInvite.Authorizations { - authorizations = append(authorizations, ProtoToAuthorization(authorization)) + authorizations = append(authorizations, authorizationFromProto(authorization)) } return &OrganizationInvite{ OrganizationID: organizationInvite.OrganizationId, @@ -118,72 +89,3 @@ func ProtoToOrganizationInvite(organizationInvite *pb.OrganizationInvite) *Organ Authorizations: authorizations, } } - -func OrganizationInviteToProto(organizationInvite *OrganizationInvite) (*pb.OrganizationInvite, error) { - var authorizations []*pb.Authorization - for _, authorization := range organizationInvite.Authorizations { - authorizations = append(authorizations, AuthorizationToProto(authorization)) - } - return &pb.OrganizationInvite{ - OrganizationId: organizationInvite.OrganizationID, - Email: organizationInvite.Email, - CreatedOn: organizationInvite.CreatedOn, - Authorizations: authorizations, - }, nil -} - -type Authorization struct { - AuthorizationType string - AuthorizationID string - ResourceType string - ResourceID string - IdentityID string - OrganizationID string - IdentityType string -} - -func ProtoToAuthorization(authorization *pb.Authorization) *Authorization { - return &Authorization{ - AuthorizationType: authorization.AuthorizationType, - AuthorizationID: authorization.AuthorizationId, - ResourceType: authorization.ResourceType, - ResourceID: authorization.ResourceId, - IdentityID: authorization.IdentityId, - OrganizationID: authorization.OrganizationId, - IdentityType: authorization.IdentityType, - } -} - -func AuthorizationToProto(authorization *Authorization) *pb.Authorization { - return &pb.Authorization{ - AuthorizationType: authorization.AuthorizationType, - AuthorizationId: authorization.AuthorizationID, - ResourceType: authorization.ResourceType, - ResourceId: authorization.ResourceID, - IdentityId: authorization.IdentityID, - OrganizationId: authorization.OrganizationID, - IdentityType: authorization.IdentityType, - } -} - -type AuthorizedPermissions struct { - ResourceType string - ResourceID string - Permissions []string -} - -func ProtoToAuthorizedPermissions(permissions *pb.AuthorizedPermissions) *AuthorizedPermissions { - return &AuthorizedPermissions{ - ResourceType: permissions.ResourceType, - ResourceID: permissions.ResourceId, - Permissions: permissions.Permissions, - } -} - -func AuthorizedPermissionsToProto(permissions *AuthorizedPermissions) *pb.AuthorizedPermissions { - return &pb.AuthorizedPermissions{ - ResourceType: permissions.ResourceType, - ResourceId: permissions.ResourceID, - Permissions: permissions.Permissions, - } -} diff --git a/app/registry_item.go b/app/registry_item.go index 98029da564e..6029e002a9d 100644 --- a/app/registry_item.go +++ b/app/registry_item.go @@ -9,6 +9,7 @@ import ( "google.golang.org/protobuf/types/known/timestamppb" ) +// RegistryItem has the information of an item in the registry. type RegistryItem struct { ItemID string OrganizationID string @@ -27,12 +28,12 @@ type RegistryItem struct { UpdatedAt *timestamppb.Timestamp } -func ProtoToRegistryItem(item *pb.RegistryItem) (*RegistryItem, error) { - packageType, err := ProtoToPackageType(item.Type) +func registryItemFromProto(item *pb.RegistryItem) (*RegistryItem, error) { + packageType, err := packageTypeFromProto(item.Type) if err != nil { return nil, err } - visibility, err := ProtoToVisibility(item.Visibility) + visibility, err := visibilityFromProto(item.Visibility) if err != nil { return nil, err } @@ -40,19 +41,16 @@ func ProtoToRegistryItem(item *pb.RegistryItem) (*RegistryItem, error) { var metadata isRegistryItemMetadata switch pbMetadata := item.Metadata.(type) { case *pb.RegistryItem_ModuleMetadata: - md, err := ProtoToModuleMetadata(pbMetadata.ModuleMetadata) - if err != nil { - return nil, err - } + md := moduleMetadataFromProto(pbMetadata.ModuleMetadata) metadata = &RegistryItemModuleMetadata{ModuleMetadata: md} case *pb.RegistryItem_MlModelMetadata: - md, err := ProtoToMLModelMetadata(pbMetadata.MlModelMetadata) + md, err := mlModelMetadataFromProto(pbMetadata.MlModelMetadata) if err != nil { return nil, err } metadata = &RegistryItemMLModelMetadata{MlModelMetadata: md} case *pb.RegistryItem_MlTrainingMetadata: - md, err := ProtoToMLTrainingMetadata(pbMetadata.MlTrainingMetadata) + md, err := mlTrainingMetadataFromProto(pbMetadata.MlTrainingMetadata) if err != nil { return nil, err } @@ -80,110 +78,19 @@ func ProtoToRegistryItem(item *pb.RegistryItem) (*RegistryItem, error) { }, nil } -func RegistryItemToProto(item *RegistryItem) (*pb.RegistryItem, error) { - packageType, err := PackageTypeToProto(item.Type) - if err != nil { - return nil, err - } - visibility, err := VisibilityToProto(item.Visibility) - if err != nil { - return nil, err - } - - switch md := item.Metadata.(type) { - case *RegistryItemModuleMetadata: - protoMetadata, err := ModuleMetadataToProto(md.ModuleMetadata) - if err != nil { - return nil, err - } - return &pb.RegistryItem{ - ItemId: item.ItemID, - OrganizationId: item.OrganizationID, - PublicNamespace: item.PublicNamespace, - Name: item.Name, - Type: packageType, - Visibility: visibility, - Url: item.URL, - Description: item.Description, - TotalRobotUsage: item.TotalRobotUsage, - TotalExternalRobotUsage: item.TotalExternalRobotUsage, - TotalOrganizationUsage: item.TotalOrganizationUsage, - TotalExternalOrganizationUsage: item.TotalExternalOrganizationUsage, - Metadata: &pb.RegistryItem_ModuleMetadata{ModuleMetadata: protoMetadata}, - CreatedAt: item.CreatedAt, - UpdatedAt: item.UpdatedAt, - }, nil - case *RegistryItemMLModelMetadata: - protoMetadata, err := MLModelMetadataToProto(md.MlModelMetadata) - if err != nil { - return nil, err - } - return &pb.RegistryItem{ - ItemId: item.ItemID, - OrganizationId: item.OrganizationID, - PublicNamespace: item.PublicNamespace, - Name: item.Name, - Type: packageType, - Visibility: visibility, - Url: item.URL, - Description: item.Description, - TotalRobotUsage: item.TotalRobotUsage, - TotalExternalRobotUsage: item.TotalExternalRobotUsage, - TotalOrganizationUsage: item.TotalOrganizationUsage, - TotalExternalOrganizationUsage: item.TotalExternalOrganizationUsage, - Metadata: &pb.RegistryItem_MlModelMetadata{MlModelMetadata: protoMetadata}, - CreatedAt: item.CreatedAt, - UpdatedAt: item.UpdatedAt, - }, nil - case *RegistryItemMLTrainingMetadata: - protoMetadata, err := MLTrainingMetadataToProto(md.MlTrainingMetadata) - if err != nil { - return nil, err - } - return &pb.RegistryItem{ - ItemId: item.ItemID, - OrganizationId: item.OrganizationID, - PublicNamespace: item.PublicNamespace, - Name: item.Name, - Type: packageType, - Visibility: visibility, - Url: item.URL, - Description: item.Description, - TotalRobotUsage: item.TotalRobotUsage, - TotalExternalRobotUsage: item.TotalExternalRobotUsage, - TotalOrganizationUsage: item.TotalOrganizationUsage, - TotalExternalOrganizationUsage: item.TotalExternalOrganizationUsage, - Metadata: &pb.RegistryItem_MlTrainingMetadata{MlTrainingMetadata: protoMetadata}, - CreatedAt: item.CreatedAt, - UpdatedAt: item.UpdatedAt, - }, nil - default: - return nil, fmt.Errorf("unknown registry item metadata type: %T", item.Metadata) - } -} - +// RegistryItemStatus specifies if a registry item is published or in development. type RegistryItemStatus int32 const ( - RegistryItemStatusUnspecified RegistryItemStatus = 0 - RegistryItemStatusPublished RegistryItemStatus = 1 + // RegistryItemStatusUnspecified is an unspecified registry item status. + RegistryItemStatusUnspecified RegistryItemStatus = 0 + // RegistryItemStatusPublished represents a published registry item. + RegistryItemStatusPublished RegistryItemStatus = 1 + // RegistryItemStatusInDevelopment represents a registry item still in development. RegistryItemStatusInDevelopment RegistryItemStatus = 2 ) -func ProtoToRegistryItemStatus(status pb.RegistryItemStatus) (RegistryItemStatus, error) { - switch status { - case pb.RegistryItemStatus_REGISTRY_ITEM_STATUS_UNSPECIFIED: - return RegistryItemStatusUnspecified, nil - case pb.RegistryItemStatus_REGISTRY_ITEM_STATUS_PUBLISHED: - return RegistryItemStatusPublished, nil - case pb.RegistryItemStatus_REGISTRY_ITEM_STATUS_IN_DEVELOPMENT: - return RegistryItemStatusInDevelopment, nil - default: - return 0, fmt.Errorf("unknown registry item status: %v", status) - } -} - -func RegistryItemStatusToProto(status RegistryItemStatus) (pb.RegistryItemStatus, error) { +func registryItemStatusToProto(status RegistryItemStatus) (pb.RegistryItemStatus, error) { switch status { case RegistryItemStatusUnspecified: return pb.RegistryItemStatus_REGISTRY_ITEM_STATUS_UNSPECIFIED, nil @@ -196,18 +103,25 @@ func RegistryItemStatusToProto(status RegistryItemStatus) (pb.RegistryItemStatus } } +// PackageType is the type of package being used. type PackageType int32 const ( + // PackageTypeUnspecified represents an unspecified package type. PackageTypeUnspecified PackageType = 0 - PackageTypeArchive PackageType = 1 - PackageTypeMLModel PackageType = 2 - PackageTypeModule PackageType = 3 - PackageTypeSLAMMap PackageType = 4 - PackageTypeMLTraining PackageType = 5 + // PackageTypeArchive represents an archive package type. + PackageTypeArchive PackageType = 1 + // PackageTypeMLModel represents a ML model package type. + PackageTypeMLModel PackageType = 2 + // PackageTypeModule represents a module package type. + PackageTypeModule PackageType = 3 + // PackageTypeSLAMMap represents a SLAM map package type. + PackageTypeSLAMMap PackageType = 4 + // PackageTypeMLTraining represents a ML training package type. + PackageTypeMLTraining PackageType = 5 ) -func ProtoToPackageType(packageType packages.PackageType) (PackageType, error) { +func packageTypeFromProto(packageType packages.PackageType) (PackageType, error) { switch packageType { case packages.PackageType_PACKAGE_TYPE_UNSPECIFIED: return PackageTypeUnspecified, nil @@ -226,7 +140,7 @@ func ProtoToPackageType(packageType packages.PackageType) (PackageType, error) { } } -func PackageTypeToProto(packageType PackageType) (packages.PackageType, error) { +func packageTypeToProto(packageType PackageType) (packages.PackageType, error) { switch packageType { case PackageTypeUnspecified: return packages.PackageType_PACKAGE_TYPE_UNSPECIFIED, nil @@ -245,16 +159,21 @@ func PackageTypeToProto(packageType PackageType) (packages.PackageType, error) { } } +// Visibility specifies the type of visibility of a registry item. type Visibility int32 const ( - VisibilityUnspecified Visibility = 0 - VisibilityPrivate Visibility = 1 - VisibilityPublic Visibility = 2 + // VisibilityUnspecified represents an unspecified visibility. + VisibilityUnspecified Visibility = 0 + // VisibilityPrivate are for registry items visible only within the owning org. + VisibilityPrivate Visibility = 1 + // VisibilityPublic are for registry items that are visible to everyone. + VisibilityPublic Visibility = 2 + // VisibilityPublicUnlisted are for registry items usable in everyone's robot but are hidden from the registry page as if they are private. VisibilityPublicUnlisted Visibility = 3 ) -func ProtoToVisibility(visibility pb.Visibility) (Visibility, error) { +func visibilityFromProto(visibility pb.Visibility) (Visibility, error) { switch visibility { case pb.Visibility_VISIBILITY_UNSPECIFIED: return VisibilityUnspecified, nil @@ -269,7 +188,7 @@ func ProtoToVisibility(visibility pb.Visibility) (Visibility, error) { } } -func VisibilityToProto(visibility Visibility) (pb.Visibility, error) { +func visibilityToProto(visibility Visibility) (pb.Visibility, error) { switch visibility { case VisibilityUnspecified: return pb.Visibility_VISIBILITY_UNSPECIFIED, nil @@ -288,14 +207,17 @@ type isRegistryItemMetadata interface { isRegistryItemMetadata() } +// RegistryItemModuleMetadata is a registry item's module metadata. type RegistryItemModuleMetadata struct { ModuleMetadata *ModuleMetadata } +// RegistryItemMLModelMetadata is a registry item's ML model metadata. type RegistryItemMLModelMetadata struct { MlModelMetadata *MLModelMetadata } +// RegistryItemMLTrainingMetadata is a registry item's ML Training metadata. type RegistryItemMLTrainingMetadata struct { MlTrainingMetadata *MLTrainingMetadata } @@ -306,6 +228,7 @@ func (*RegistryItemMLModelMetadata) isRegistryItemMetadata() {} func (*RegistryItemMLTrainingMetadata) isRegistryItemMetadata() {} +// ModuleMetadata holds the metadata of a module. type ModuleMetadata struct { Models []*Model Versions []*ModuleVersion @@ -313,59 +236,44 @@ type ModuleMetadata struct { FirstRun *string } -func ProtoToModuleMetadata(md *pb.ModuleMetadata) (*ModuleMetadata, error) { +func moduleMetadataFromProto(md *pb.ModuleMetadata) *ModuleMetadata { var models []*Model for _, version := range md.Models { - models = append(models, ProtoToModel(version)) + models = append(models, modelFromProto(version)) } var versions []*ModuleVersion for _, version := range md.Versions { - versions = append(versions, ProtoToModuleVersion(version)) + versions = append(versions, moduleVersionFromProto(version)) } return &ModuleMetadata{ Models: models, Versions: versions, Entrypoint: md.Entrypoint, FirstRun: md.FirstRun, - }, nil -} - -func ModuleMetadataToProto(md *ModuleMetadata) (*pb.ModuleMetadata, error) { - var models []*pb.Model - for _, version := range md.Models { - models = append(models, ModelToProto(version)) } - var versions []*pb.ModuleVersion - for _, version := range md.Versions { - versions = append(versions, ModuleVersionToProto(version)) - } - return &pb.ModuleMetadata{ - Models: models, - Versions: versions, - Entrypoint: md.Entrypoint, - FirstRun: md.FirstRun, - }, nil } +// Model has the API and model of a model. type Model struct { API string Model string } -func ProtoToModel(model *pb.Model) *Model { +func modelFromProto(model *pb.Model) *Model { return &Model{ API: model.Api, Model: model.Model, } } -func ModelToProto(model *Model) *pb.Model { +func modelToProto(model *Model) *pb.Model { return &pb.Model{ Api: model.API, Model: model.Model, } } +// ModuleVersion holds the information of a module version. type ModuleVersion struct { Version string Files []*Uploads @@ -374,14 +282,14 @@ type ModuleVersion struct { FirstRun *string } -func ProtoToModuleVersion(version *pb.ModuleVersion) *ModuleVersion { +func moduleVersionFromProto(version *pb.ModuleVersion) *ModuleVersion { var files []*Uploads for _, file := range version.Files { - files = append(files, ProtoToUploads(file)) + files = append(files, uploadsFromProto(file)) } var models []*Model for _, model := range version.Models { - models = append(models, ProtoToModel(model)) + models = append(models, modelFromProto(model)) } return &ModuleVersion{ Version: version.Version, @@ -392,55 +300,32 @@ func ProtoToModuleVersion(version *pb.ModuleVersion) *ModuleVersion { } } -func ModuleVersionToProto(version *ModuleVersion) *pb.ModuleVersion { - var files []*pb.Uploads - for _, file := range version.Files { - files = append(files, UploadsToProto(file)) - } - var models []*pb.Model - for _, model := range version.Models { - models = append(models, ModelToProto(model)) - } - return &pb.ModuleVersion{ - Version: version.Version, - Files: files, - Models: models, - Entrypoint: version.Entrypoint, - FirstRun: version.FirstRun, - } -} - +// Uploads holds the time the file was uploaded and the OS and architecture a module is built to run on. type Uploads struct { Platform string UploadedAt *timestamppb.Timestamp } -func ProtoToUploads(uploads *pb.Uploads) *Uploads { +func uploadsFromProto(uploads *pb.Uploads) *Uploads { return &Uploads{ Platform: uploads.Platform, UploadedAt: uploads.UploadedAt, } } -func UploadsToProto(uploads *Uploads) *pb.Uploads { - return &pb.Uploads{ - Platform: uploads.Platform, - UploadedAt: uploads.UploadedAt, - } -} - +// MLModelMetadata holds the metadata for a ML model. type MLModelMetadata struct { Versions []string ModelType ModelType ModelFramework ModelFramework } -func ProtoToMLModelMetadata(md *pb.MLModelMetadata) (*MLModelMetadata, error) { - modelType, err := ProtoToModelType(md.ModelType) +func mlModelMetadataFromProto(md *pb.MLModelMetadata) (*MLModelMetadata, error) { + modelType, err := modelTypeFromProto(md.ModelType) if err != nil { return nil, err } - modelFramework, err := ProtoToModelFramework(md.ModelFramework) + modelFramework, err := modelFrameworkFromProto(md.ModelFramework) if err != nil { return nil, err } @@ -451,32 +336,21 @@ func ProtoToMLModelMetadata(md *pb.MLModelMetadata) (*MLModelMetadata, error) { }, nil } -func MLModelMetadataToProto(md *MLModelMetadata) (*pb.MLModelMetadata, error) { - modelType, err := ModelTypeToProto(md.ModelType) - if err != nil { - return nil, err - } - modelFramework, err := ModelFrameworkToProto(md.ModelFramework) - if err != nil { - return nil, err - } - return &pb.MLModelMetadata{ - Versions: md.Versions, - ModelType: modelType, - ModelFramework: modelFramework, - }, nil -} - +// ModelType specifies the type of model used for classification or detection. type ModelType int32 const ( - ModelTypeUnspecified ModelType = 0 + // ModelTypeUnspecified represents an unspecified model. + ModelTypeUnspecified ModelType = 0 + // ModelTypeSingleLabelClassification represents a single-label classification model. ModelTypeSingleLabelClassification ModelType = 1 - ModelTypeMultiLabelClassification ModelType = 2 - ModelTypeObjectDetection ModelType = 3 + // ModelTypeMultiLabelClassification represents a multi-label classification model. + ModelTypeMultiLabelClassification ModelType = 2 + // ModelTypeObjectDetection represents an object detection model. + ModelTypeObjectDetection ModelType = 3 ) -func ProtoToModelType(modelType mlTraining.ModelType) (ModelType, error) { +func modelTypeFromProto(modelType mlTraining.ModelType) (ModelType, error) { switch modelType { case mlTraining.ModelType_MODEL_TYPE_UNSPECIFIED: return ModelTypeUnspecified, nil @@ -491,32 +365,23 @@ func ProtoToModelType(modelType mlTraining.ModelType) (ModelType, error) { } } -func ModelTypeToProto(modelType ModelType) (mlTraining.ModelType, error) { - switch modelType { - case ModelTypeUnspecified: - return mlTraining.ModelType_MODEL_TYPE_UNSPECIFIED, nil - case ModelTypeSingleLabelClassification: - return mlTraining.ModelType_MODEL_TYPE_SINGLE_LABEL_CLASSIFICATION, nil - case ModelTypeMultiLabelClassification: - return mlTraining.ModelType_MODEL_TYPE_MULTI_LABEL_CLASSIFICATION, nil - case ModelTypeObjectDetection: - return mlTraining.ModelType_MODEL_TYPE_OBJECT_DETECTION, nil - default: - return 0, fmt.Errorf("unknown model type: %v", modelType) - } -} - +// ModelFramework is the framework type of a model. type ModelFramework int32 const ( + // ModelFrameworkUnspecified is an unspecified model framework. ModelFrameworkUnspecified ModelFramework = 0 - ModelFrameworkTFLite ModelFramework = 1 - ModelFrameworkTensorFlow ModelFramework = 2 - ModelFrameworkPyTorch ModelFramework = 3 - ModelFrameworkONNX ModelFramework = 4 + // ModelFrameworkTFLite specifies a TFLite model framework. + ModelFrameworkTFLite ModelFramework = 1 + // ModelFrameworkTensorFlow specifies a TensorFlow model framework. + ModelFrameworkTensorFlow ModelFramework = 2 + // ModelFrameworkPyTorch specifies a PyTorch model framework. + ModelFrameworkPyTorch ModelFramework = 3 + // ModelFrameworkONNX specifies a ONNX model framework. + ModelFrameworkONNX ModelFramework = 4 ) -func ProtoToModelFramework(framework mlTraining.ModelFramework) (ModelFramework, error) { +func modelFrameworkFromProto(framework mlTraining.ModelFramework) (ModelFramework, error) { switch framework { case mlTraining.ModelFramework_MODEL_FRAMEWORK_UNSPECIFIED: return ModelFrameworkUnspecified, nil @@ -533,23 +398,7 @@ func ProtoToModelFramework(framework mlTraining.ModelFramework) (ModelFramework, } } -func ModelFrameworkToProto(framework ModelFramework) (mlTraining.ModelFramework, error) { - switch framework { - case ModelFrameworkUnspecified: - return mlTraining.ModelFramework_MODEL_FRAMEWORK_UNSPECIFIED, nil - case ModelFrameworkTFLite: - return mlTraining.ModelFramework_MODEL_FRAMEWORK_TFLITE, nil - case ModelFrameworkTensorFlow: - return mlTraining.ModelFramework_MODEL_FRAMEWORK_TENSORFLOW, nil - case ModelFrameworkPyTorch: - return mlTraining.ModelFramework_MODEL_FRAMEWORK_PYTORCH, nil - case ModelFrameworkONNX: - return mlTraining.ModelFramework_MODEL_FRAMEWORK_ONNX, nil - default: - return 0, fmt.Errorf("unknown model framework: %v", framework) - } -} - +// MLTrainingMetadata is the metadata of an ML Training. type MLTrainingMetadata struct { Versions []*MLTrainingVersion ModelType ModelType @@ -557,16 +406,16 @@ type MLTrainingMetadata struct { Draft bool } -func ProtoToMLTrainingMetadata(md *pb.MLTrainingMetadata) (*MLTrainingMetadata, error) { +func mlTrainingMetadataFromProto(md *pb.MLTrainingMetadata) (*MLTrainingMetadata, error) { var versions []*MLTrainingVersion for _, version := range md.Versions { - versions = append(versions, ProtoToMLTrainingVersion(version)) + versions = append(versions, mlTrainingVersionFromProto(version)) } - modelType, err := ProtoToModelType(md.ModelType) + modelType, err := modelTypeFromProto(md.ModelType) if err != nil { return nil, err } - modelFramework, err := ProtoToModelFramework(md.ModelFramework) + modelFramework, err := modelFrameworkFromProto(md.ModelFramework) if err != nil { return nil, err } @@ -578,46 +427,20 @@ func ProtoToMLTrainingMetadata(md *pb.MLTrainingMetadata) (*MLTrainingMetadata, }, nil } -func MLTrainingMetadataToProto(md *MLTrainingMetadata) (*pb.MLTrainingMetadata, error) { - var versions []*pb.MLTrainingVersion - for _, version := range md.Versions { - versions = append(versions, MLTrainingVersionToProto(version)) - } - modelType, err := ModelTypeToProto(md.ModelType) - if err != nil { - return nil, err - } - modelFramework, err := ModelFrameworkToProto(md.ModelFramework) - if err != nil { - return nil, err - } - return &pb.MLTrainingMetadata{ - Versions: versions, - ModelType: modelType, - ModelFramework: modelFramework, - Draft: md.Draft, - }, nil -} - +// MLTrainingVersion is the version of ML Training. type MLTrainingVersion struct { Version string CreatedOn *timestamppb.Timestamp } -func ProtoToMLTrainingVersion(version *pb.MLTrainingVersion) *MLTrainingVersion { +func mlTrainingVersionFromProto(version *pb.MLTrainingVersion) *MLTrainingVersion { return &MLTrainingVersion{ Version: version.Version, CreatedOn: version.CreatedOn, } } -func MLTrainingVersionToProto(version *MLTrainingVersion) *pb.MLTrainingVersion { - return &pb.MLTrainingVersion{ - Version: version.Version, - CreatedOn: version.CreatedOn, - } -} - +// Module holds the information of a module. type Module struct { ModuleID string Name string @@ -634,18 +457,18 @@ type Module struct { FirstRun *string } -func ProtoToModule(module *pb.Module) (*Module, error) { - visibility, err := ProtoToVisibility(module.Visibility) +func moduleFromProto(module *pb.Module) (*Module, error) { + visibility, err := visibilityFromProto(module.Visibility) if err != nil { return nil, err } var versions []*VersionHistory for _, version := range module.Versions { - versions = append(versions, ProtoToVersionHistory(version)) + versions = append(versions, versionHistoryFromProto(version)) } var models []*Model for _, model := range module.Models { - models = append(models, ProtoToModel(model)) + models = append(models, modelFromProto(model)) } return &Module{ ModuleID: module.ModuleId, @@ -664,36 +487,7 @@ func ProtoToModule(module *pb.Module) (*Module, error) { }, nil } -func ModuleToProto(module *Module) (*pb.Module, error) { - visibility, err := VisibilityToProto(module.Visibility) - if err != nil { - return nil, err - } - var versions []*pb.VersionHistory - for _, version := range module.Versions { - versions = append(versions, VersionHistoryToProto(version)) - } - var models []*pb.Model - for _, model := range module.Models { - models = append(models, ModelToProto(model)) - } - return &pb.Module{ - ModuleId: module.ModuleID, - Name: module.Name, - Visibility: visibility, - Versions: versions, - Url: module.URL, - Description: module.Description, - Models: models, - TotalRobotUsage: module.TotalRobotUsage, - TotalOrganizationUsage: module.TotalOrganizationUsage, - OrganizationId: module.OrganizationID, - Entrypoint: module.Entrypoint, - PublicNamespace: module.PublicNamespace, - FirstRun: module.FirstRun, - }, nil -} - +// VersionHistory holds the history of a version. type VersionHistory struct { Version string Files []*Uploads @@ -702,14 +496,14 @@ type VersionHistory struct { FirstRun *string } -func ProtoToVersionHistory(history *pb.VersionHistory) *VersionHistory { +func versionHistoryFromProto(history *pb.VersionHistory) *VersionHistory { var files []*Uploads for _, file := range history.Files { - files = append(files, ProtoToUploads(file)) + files = append(files, uploadsFromProto(file)) } var models []*Model for _, model := range history.Models { - models = append(models, ProtoToModel(model)) + models = append(models, modelFromProto(model)) } return &VersionHistory{ Version: history.Version, @@ -719,21 +513,3 @@ func ProtoToVersionHistory(history *pb.VersionHistory) *VersionHistory { FirstRun: history.FirstRun, } } - -func VersionHistoryToProto(history *VersionHistory) *pb.VersionHistory { - var files []*pb.Uploads - for _, file := range history.Files { - files = append(files, UploadsToProto(file)) - } - var models []*pb.Model - for _, model := range history.Models { - models = append(models, ModelToProto(model)) - } - return &pb.VersionHistory{ - Version: history.Version, - Files: files, - Models: models, - Entrypoint: history.Entrypoint, - FirstRun: history.FirstRun, - } -} diff --git a/app/robot.go b/app/robot.go index c0df29f13dc..e657498c564 100644 --- a/app/robot.go +++ b/app/robot.go @@ -2,10 +2,10 @@ package app import ( pb "go.viam.com/api/app/v1" - "go.viam.com/utils/protoutils" "google.golang.org/protobuf/types/known/timestamppb" ) +// Robot holds the information of a machine. type Robot struct { ID string Name string @@ -14,7 +14,7 @@ type Robot struct { CreatedOn *timestamppb.Timestamp } -func ProtoToRobot(robot *pb.Robot) *Robot { +func robotFromProto(robot *pb.Robot) *Robot { return &Robot{ ID: robot.Id, Name: robot.Name, @@ -24,16 +24,7 @@ func ProtoToRobot(robot *pb.Robot) *Robot { } } -func RobotToProto(robot *Robot) *pb.Robot { - return &pb.Robot{ - Id: robot.ID, - Name: robot.Name, - Location: robot.Location, - LastAccess: robot.LastAccess, - CreatedOn: robot.CreatedOn, - } -} - +// RoverRentalRobot holds the information of a rover rental robot. type RoverRentalRobot struct { RobotID string LocationID string @@ -41,7 +32,7 @@ type RoverRentalRobot struct { RobotMainPartID string } -func ProtoToRoverRentalRobot(rrRobot *pb.RoverRentalRobot) *RoverRentalRobot { +func roverRentalRobotFromProto(rrRobot *pb.RoverRentalRobot) *RoverRentalRobot { return &RoverRentalRobot{ RobotID: rrRobot.RobotId, LocationID: rrRobot.LocationId, @@ -50,15 +41,7 @@ func ProtoToRoverRentalRobot(rrRobot *pb.RoverRentalRobot) *RoverRentalRobot { } } -func RoverRentalRobotToProto(rrRobot *RoverRentalRobot) *pb.RoverRentalRobot { - return &pb.RoverRentalRobot{ - RobotId: rrRobot.RobotID, - LocationId: rrRobot.LocationID, - RobotName: rrRobot.RobotName, - RobotMainPartId: rrRobot.RobotMainPartID, - } -} - +// RobotPart is a specific machine part. type RobotPart struct { ID string Name string @@ -77,10 +60,10 @@ type RobotPart struct { LastUpdated *timestamppb.Timestamp } -func ProtoToRobotPart(robotPart *pb.RobotPart) (*RobotPart, error) { +func robotPartFromProto(robotPart *pb.RobotPart) (*RobotPart, error) { var secrets []*SharedSecret for _, secret := range robotPart.Secrets { - s, err := ProtoToSharedSecret(secret) + s, err := sharedSecretFromProto(secret) if err != nil { return nil, err } @@ -107,42 +90,7 @@ func ProtoToRobotPart(robotPart *pb.RobotPart) (*RobotPart, error) { }, nil } -func RobotPartToProto(robotPart *RobotPart) (*pb.RobotPart, error) { - var secrets []*pb.SharedSecret - for _, secret := range robotPart.Secrets { - s, err := SharedSecretToProto(secret) - if err != nil { - return nil, err - } - secrets = append(secrets, s) - } - robotConfig, err := protoutils.StructToStructPb(robotPart.RobotConfig) - if err != nil { - return nil, err - } - userSuppliedInfo, err := protoutils.StructToStructPb(robotPart.UserSuppliedInfo) - if err != nil { - return nil, err - } - return &pb.RobotPart{ - Id: robotPart.ID, - Name: robotPart.Name, - DnsName: robotPart.DNSName, - Secret: robotPart.Secret, - Robot: robotPart.DNSName, - LocationId: robotPart.LocationID, - RobotConfig: robotConfig, - LastAccess: robotPart.LastAccess, - UserSuppliedInfo: userSuppliedInfo, - MainPart: robotPart.MainPart, - Fqdn: robotPart.Fqdn, - LocalFqdn: robotPart.LocalFqdn, - CreatedOn: robotPart.CreatedOn, - Secrets: secrets, - LastUpdated: robotPart.LastUpdated, - }, nil -} - +// RobotPartHistoryEntry is a history entry of a robot part. type RobotPartHistoryEntry struct { Part string Robot string @@ -151,12 +99,12 @@ type RobotPartHistoryEntry struct { EditedBy *AuthenticatorInfo } -func ProtoToRobotPartHistoryEntry(entry *pb.RobotPartHistoryEntry) (*RobotPartHistoryEntry, error) { - old, err := ProtoToRobotPart(entry.Old) +func robotPartHistoryEntryFromProto(entry *pb.RobotPartHistoryEntry) (*RobotPartHistoryEntry, error) { + old, err := robotPartFromProto(entry.Old) if err != nil { return nil, err } - info, err := ProtoToAuthenticatorInfo(entry.EditedBy) + info, err := authenticatorInfoFromProto(entry.EditedBy) if err != nil { return nil, err } From 92bf79d45543381955c17b474db4716912e7a8e0 Mon Sep 17 00:00:00 2001 From: purplenicole730 Date: Thu, 14 Nov 2024 10:29:48 -0500 Subject: [PATCH 31/75] add missing wrappers --- app/app_client.go | 59 +++++++++++++++++++++++++++++++++++++++++++++ app/organization.go | 17 +++++++++++++ 2 files changed, 76 insertions(+) diff --git a/app/app_client.go b/app/app_client.go index 809eed0616a..b9c36d4a1e1 100644 --- a/app/app_client.go +++ b/app/app_client.go @@ -245,6 +245,65 @@ func (c *Client) ResendOrganizationInvite(ctx context.Context, orgID, email stri return organizationInviteFromProto(resp.Invite), nil } +// EnableBillingService enables a billing service to an address in an organization. +func (c *Client) EnableBillingService(ctx context.Context, orgID string, billingAddress *BillingAddress) error { + _, err := c.client.EnableBillingService(ctx, &pb.EnableBillingServiceRequest{ + OrgId: orgID, + BillingAddress: billingAddressToProto(billingAddress), + }) + if err != nil { + return err + } + return nil +} + +// DisableBillingService disables the billing service for an organization. +func (c *Client) DisableBillingService(ctx context.Context, orgID string) error { + _, err := c.client.DisableBillingService(ctx, &pb.DisableBillingServiceRequest{ + OrgId: orgID, + }) + if err != nil { + return err + } + return nil +} + +// UpdateBillingService updates the billing service of an organization. +func (c *Client) UpdateBillingService(ctx context.Context, orgID string, billingAddress *BillingAddress, billingSupportEmail string) error { + _, err := c.client.UpdateBillingService(ctx, &pb.UpdateBillingServiceRequest{ + OrgId: orgID, + BillingAddress: billingAddressToProto(billingAddress), + BillingSupportEmail: billingSupportEmail, + }) + if err != nil { + return err + } + return nil +} + +// OrganizationSetSupportEmail sets an organization's support email. +func (c *Client) OrganizationSetSupportEmail(ctx context.Context, orgID, email string) error { + _, err := c.client.OrganizationSetSupportEmail(ctx, &pb.OrganizationSetSupportEmailRequest{ + OrgId: orgID, + Email: email, + }) + if err != nil { + return err + } + return nil +} + +// OrganizationGetSupportEmail gets an organization's support email. +func (c *Client) OrganizationGetSupportEmail(ctx context.Context, orgID string) (string, error) { + resp, err := c.client.OrganizationGetSupportEmail(ctx, &pb.OrganizationGetSupportEmailRequest{ + OrgId: orgID, + }) + if err != nil { + return "", err + } + return resp.Email, nil +} + // CreateLocation creates a location. func (c *Client) CreateLocation(ctx context.Context, orgID, name string, parentLocationID *string) (*Location, error) { resp, err := c.client.CreateLocation(ctx, &pb.CreateLocationRequest{ diff --git a/app/organization.go b/app/organization.go index e1160ce5b52..3645790080a 100644 --- a/app/organization.go +++ b/app/organization.go @@ -89,3 +89,20 @@ func organizationInviteFromProto(organizationInvite *pb.OrganizationInvite) *Org Authorizations: authorizations, } } + +// BillingAddress contains billing address details. +type BillingAddress struct { + AddressLine_1 string + AddressLine_2 *string + City string + State string +} + +func billingAddressToProto(addr *BillingAddress) *pb.BillingAddress { + return &pb.BillingAddress{ + AddressLine_1: addr.AddressLine_1, + AddressLine_2: addr.AddressLine_2, + City: addr.City, + State: addr.State, + } +} From 0f5c9340c2579530134ff5e78440dbffca2abe48 Mon Sep 17 00:00:00 2001 From: purplenicole730 Date: Thu, 14 Nov 2024 10:50:18 -0500 Subject: [PATCH 32/75] add all methods to testutils inject --- testutils/inject/app_service_client.go | 904 +++++++++++++++++++++++-- 1 file changed, 866 insertions(+), 38 deletions(-) diff --git a/testutils/inject/app_service_client.go b/testutils/inject/app_service_client.go index 5cffed32d2f..c52884b95ae 100644 --- a/testutils/inject/app_service_client.go +++ b/testutils/inject/app_service_client.go @@ -10,24 +10,182 @@ import ( // AppServiceClient represents a fake instance of an app service client. type AppServiceClient struct { apppb.AppServiceClient + GetUserIDByEmailFunc func(ctx context.Context, in *apppb.GetUserIDByEmailRequest, + opts ...grpc.CallOption) (*apppb.GetUserIDByEmailResponse, error) + CreateOrganizationFunc func(ctx context.Context, in *apppb.CreateOrganizationRequest, + opts ...grpc.CallOption) (*apppb.CreateOrganizationResponse, error) ListOrganizationsFunc func(ctx context.Context, in *apppb.ListOrganizationsRequest, opts ...grpc.CallOption) (*apppb.ListOrganizationsResponse, error) + GetOrganizationsWithAccessToLocationFunc func(ctx context.Context, in *apppb.GetOrganizationsWithAccessToLocationRequest, + opts ...grpc.CallOption) (*apppb.GetOrganizationsWithAccessToLocationResponse, error) + ListOrganizationsByUserFunc func(ctx context.Context, in *apppb.ListOrganizationsByUserRequest, + opts ...grpc.CallOption) (*apppb.ListOrganizationsByUserResponse, error) + GetOrganizationFunc func(ctx context.Context, in *apppb.GetOrganizationRequest, + opts ...grpc.CallOption) (*apppb.GetOrganizationResponse, error) + GetOrganizationNamespaceAvailabilityFunc func(ctx context.Context, in *apppb.GetOrganizationNamespaceAvailabilityRequest, + opts ...grpc.CallOption) (*apppb.GetOrganizationNamespaceAvailabilityResponse, error) + UpdateOrganizationFunc func(ctx context.Context, in *apppb.UpdateOrganizationRequest, + opts ...grpc.CallOption) (*apppb.UpdateOrganizationResponse, error) + DeleteOrganizationFunc func(ctx context.Context, in *apppb.DeleteOrganizationRequest, + opts ...grpc.CallOption) (*apppb.DeleteOrganizationResponse, error) + ListOrganizationMembersFunc func(ctx context.Context, in *apppb.ListOrganizationMembersRequest, + opts ...grpc.CallOption) (*apppb.ListOrganizationMembersResponse, error) + CreateOrganizationInviteFunc func(ctx context.Context, in *apppb.CreateOrganizationInviteRequest, + opts ...grpc.CallOption) (*apppb.CreateOrganizationInviteResponse, error) + UpdateOrganizationInviteAuthorizationsFunc func(ctx context.Context, in *apppb.UpdateOrganizationInviteAuthorizationsRequest, + opts ...grpc.CallOption) (*apppb.UpdateOrganizationInviteAuthorizationsResponse, error) + DeleteOrganizationMemberFunc func(ctx context.Context, in *apppb.DeleteOrganizationMemberRequest, + opts ...grpc.CallOption) (*apppb.DeleteOrganizationMemberResponse, error) + DeleteOrganizationInviteFunc func(ctx context.Context, in *apppb.DeleteOrganizationInviteRequest, + opts ...grpc.CallOption) (*apppb.DeleteOrganizationInviteResponse, error) + ResendOrganizationInviteFunc func(ctx context.Context, in *apppb.ResendOrganizationInviteRequest, + opts ...grpc.CallOption) (*apppb.ResendOrganizationInviteResponse, error) + EnableBillingServiceFunc func(ctx context.Context, in *apppb.EnableBillingServiceRequest, + opts ...grpc.CallOption) (*apppb.EnableBillingServiceResponse, error) + DisableBillingServiceFunc func(ctx context.Context, in *apppb.DisableBillingServiceRequest, + opts ...grpc.CallOption) (*apppb.DisableBillingServiceResponse, error) + UpdateBillingServiceFunc func(ctx context.Context, in *apppb.UpdateBillingServiceRequest, + opts ...grpc.CallOption) (*apppb.UpdateBillingServiceResponse, error) + OrganizationSetSupportEmailFunc func(ctx context.Context, in *apppb.OrganizationSetSupportEmailRequest, + opts ...grpc.CallOption) (*apppb.OrganizationSetSupportEmailResponse, error) + OrganizationGetSupportEmailFunc func(ctx context.Context, in *apppb.OrganizationGetSupportEmailRequest, + opts ...grpc.CallOption) (*apppb.OrganizationGetSupportEmailResponse, error) + CreateLocationFunc func(ctx context.Context, in *apppb.CreateLocationRequest, + opts ...grpc.CallOption) (*apppb.CreateLocationResponse, error) + GetLocationFunc func(ctx context.Context, in *apppb.GetLocationRequest, + opts ...grpc.CallOption) (*apppb.GetLocationResponse, error) + UpdateLocationFunc func(ctx context.Context, in *apppb.UpdateLocationRequest, + opts ...grpc.CallOption) (*apppb.UpdateLocationResponse, error) + DeleteLocationFunc func(ctx context.Context, in *apppb.DeleteLocationRequest, + opts ...grpc.CallOption) (*apppb.DeleteLocationResponse, error) ListLocationsFunc func(ctx context.Context, in *apppb.ListLocationsRequest, opts ...grpc.CallOption) (*apppb.ListLocationsResponse, error) - ListRobotsFunc func(ctx context.Context, in *apppb.ListRobotsRequest, - opts ...grpc.CallOption) (*apppb.ListRobotsResponse, error) - CreateKeyFunc func(ctx context.Context, in *apppb.CreateKeyRequest, - opts ...grpc.CallOption) (*apppb.CreateKeyResponse, error) - GetRobotAPIKeysFunc func(ctx context.Context, in *apppb.GetRobotAPIKeysRequest, - opts ...grpc.CallOption) (*apppb.GetRobotAPIKeysResponse, error) - GetRobotPartFunc func(ctx context.Context, in *apppb.GetRobotPartRequest, - opts ...grpc.CallOption) (*apppb.GetRobotPartResponse, error) + ShareLocationFunc func(ctx context.Context, in *apppb.ShareLocationRequest, + opts ...grpc.CallOption) (*apppb.ShareLocationResponse, error) + UnshareLocationFunc func(ctx context.Context, in *apppb.UnshareLocationRequest, + opts ...grpc.CallOption) (*apppb.UnshareLocationResponse, error) + LocationAuthFunc func(ctx context.Context, in *apppb.LocationAuthRequest, + opts ...grpc.CallOption) (*apppb.LocationAuthResponse, error) + CreateLocationSecretFunc func(ctx context.Context, in *apppb.CreateLocationSecretRequest, + opts ...grpc.CallOption) (*apppb.CreateLocationSecretResponse, error) + DeleteLocationSecretFunc func(ctx context.Context, in *apppb.DeleteLocationSecretRequest, + opts ...grpc.CallOption) (*apppb.DeleteLocationSecretResponse, error) + GetRobotFunc func(ctx context.Context, in *apppb.GetRobotRequest, + opts ...grpc.CallOption) (*apppb.GetRobotResponse, error) + GetRoverRentalRobotsFunc func(ctx context.Context, in *apppb.GetRoverRentalRobotsRequest, + opts ...grpc.CallOption) (*apppb.GetRoverRentalRobotsResponse, error) GetRobotPartsFunc func(ctx context.Context, in *apppb.GetRobotPartsRequest, opts ...grpc.CallOption) (*apppb.GetRobotPartsResponse, error) + GetRobotPartFunc func(ctx context.Context, in *apppb.GetRobotPartRequest, + opts ...grpc.CallOption) (*apppb.GetRobotPartResponse, error) GetRobotPartLogsFunc func(ctx context.Context, in *apppb.GetRobotPartLogsRequest, opts ...grpc.CallOption) (*apppb.GetRobotPartLogsResponse, error) + TailRobotPartLogsFunc func(ctx context.Context, in *apppb.TailRobotPartLogsRequest, + opts ...grpc.CallOption) (*apppb.TailRobotPartLogsRequest, error) + GetRobotPartHistoryFunc func(ctx context.Context, in *apppb.GetRobotPartHistoryRequest, + opts ...grpc.CallOption) (*apppb.GetRobotPartHistoryResponse, error) UpdateRobotPartFunc func(ctx context.Context, in *apppb.UpdateRobotPartRequest, opts ...grpc.CallOption) (*apppb.UpdateRobotPartResponse, error) + NewRobotPartFunc func(ctx context.Context, in *apppb.NewRobotPartRequest, + opts ...grpc.CallOption) (*apppb.NewRobotPartResponse, error) + DeleteRobotPartFunc func(ctx context.Context, in *apppb.DeleteRobotPartRequest, + opts ...grpc.CallOption) (*apppb.DeleteRobotPartResponse, error) + GetRobotAPIKeysFunc func(ctx context.Context, in *apppb.GetRobotAPIKeysRequest, + opts ...grpc.CallOption) (*apppb.GetRobotAPIKeysResponse, error) + MarkPartAsMainFunc func(ctx context.Context, in *apppb.MarkPartAsMainRequest, + opts ...grpc.CallOption) (*apppb.MarkPartAsMainResponse, error) + MarkPartForRestartFunc func(ctx context.Context, in *apppb.MarkPartForRestartRequest, + opts ...grpc.CallOption) (*apppb.MarkPartForRestartResponse, error) + CreateRobotPartSecretFunc func(ctx context.Context, in *apppb.CreateRobotPartSecretRequest, + opts ...grpc.CallOption) (*apppb.CreateRobotPartSecretResponse, error) + DeleteRobotPartSecretFunc func(ctx context.Context, in *apppb.DeleteRobotPartSecretRequest, + opts ...grpc.CallOption) (*apppb.DeleteRobotPartSecretResponse, error) + ListRobotsFunc func(ctx context.Context, in *apppb.ListRobotsRequest, + opts ...grpc.CallOption) (*apppb.ListRobotsResponse, error) + NewRobotFunc func(ctx context.Context, in *apppb.NewRobotRequest, + opts ...grpc.CallOption) (*apppb.NewRobotResponse, error) + UpdateRobotFunc func(ctx context.Context, in *apppb.UpdateRobotRequest, + opts ...grpc.CallOption) (*apppb.UpdateRobotResponse, error) + DeleteRobotFunc func(ctx context.Context, in *apppb.DeleteRobotRequest, + opts ...grpc.CallOption) (*apppb.DeleteRobotResponse, error) + ListFragmentsFunc func(ctx context.Context, in *apppb.ListFragmentsRequest, + opts ...grpc.CallOption) (*apppb.ListFragmentsResponse, error) + GetFragmentFunc func(ctx context.Context, in *apppb.GetFragmentRequest, + opts ...grpc.CallOption) (*apppb.GetFragmentResponse, error) + CreateFragmentFunc func(ctx context.Context, in *apppb.CreateFragmentRequest, + opts ...grpc.CallOption) (*apppb.CreateFragmentResponse, error) + UpdateFragmentFunc func(ctx context.Context, in *apppb.UpdateFragmentRequest, + opts ...grpc.CallOption) (*apppb.UpdateFragmentResponse, error) + DeleteFragmentFunc func(ctx context.Context, in *apppb.DeleteFragmentRequest, + opts ...grpc.CallOption) (*apppb.DeleteFragmentResponse, error) + ListMachineFragmentsFunc func(ctx context.Context, in *apppb.ListMachineFragmentsRequest, + opts ...grpc.CallOption) (*apppb.ListMachineFragmentsResponse, error) + GetFragmentHistoryFunc func(ctx context.Context, in *apppb.GetFragmentHistoryRequest, + opts ...grpc.CallOption) (*apppb.GetFragmentHistoryResponse, error) + AddRoleFunc func(ctx context.Context, in *apppb.AddRoleRequest, + opts ...grpc.CallOption) (*apppb.AddRoleResponse, error) + RemoveRoleFunc func(ctx context.Context, in *apppb.RemoveRoleRequest, + opts ...grpc.CallOption) (*apppb.RemoveRoleResponse, error) + ChangeRoleFunc func(ctx context.Context, in *apppb.ChangeRoleRequest, + opts ...grpc.CallOption) (*apppb.ChangeRoleResponse, error) + ListAuthorizationsFunc func(ctx context.Context, in *apppb.ListAuthorizationsRequest, + opts ...grpc.CallOption) (*apppb.ListAuthorizationsResponse, error) + CheckPermissionsFunc func(ctx context.Context, in *apppb.CheckPermissionsRequest, + opts ...grpc.CallOption) (*apppb.CheckPermissionsResponse, error) + GetRegistryItemFunc func(ctx context.Context, in *apppb.GetRegistryItemRequest, + opts ...grpc.CallOption) (*apppb.GetRegistryItemResponse, error) + CreateRegistryItemFunc func(ctx context.Context, in *apppb.CreateRegistryItemRequest, + opts ...grpc.CallOption) (*apppb.CreateRegistryItemResponse, error) + UpdateRegistryItemFunc func(ctx context.Context, in *apppb.UpdateRegistryItemRequest, + opts ...grpc.CallOption) (*apppb.UpdateRegistryItemResponse, error) + ListRegistryItemsFunc func(ctx context.Context, in *apppb.ListRegistryItemsRequest, + opts ...grpc.CallOption) (*apppb.ListRegistryItemsResponse, error) + DeleteRegistryItemFunc func(ctx context.Context, in *apppb.DeleteRegistryItemRequest, + opts ...grpc.CallOption) (*apppb.DeleteRegistryItemResponse, error) + TransferRegistryItemFunc func(ctx context.Context, in *apppb.TransferRegistryItemRequest, + opts ...grpc.CallOption) (*apppb.TransferRegistryItemResponse, error) + CreateModuleFunc func(ctx context.Context, in *apppb.CreateModuleRequest, + opts ...grpc.CallOption) (*apppb.CreateModuleResponse, error) + UpdateModuleFunc func(ctx context.Context, in *apppb.UpdateModuleRequest, + opts ...grpc.CallOption) (*apppb.UpdateModuleResponse, error) + UploadModuleFileFunc func(ctx context.Context, in *apppb.UploadModuleFileRequest, + opts ...grpc.CallOption) (*apppb.UploadModuleFileRequest, error) + GetModuleFunc func(ctx context.Context, in *apppb.GetModuleRequest, + opts ...grpc.CallOption) (*apppb.GetModuleResponse, error) + ListModulesFunc func(ctx context.Context, in *apppb.ListModulesRequest, + opts ...grpc.CallOption) (*apppb.ListModulesResponse, error) + CreateKeyFunc func(ctx context.Context, in *apppb.CreateKeyRequest, + opts ...grpc.CallOption) (*apppb.CreateKeyResponse, error) + DeleteKeyFunc func(ctx context.Context, in *apppb.DeleteKeyRequest, + opts ...grpc.CallOption) (*apppb.DeleteKeyResponse, error) + ListKeysFunc func(ctx context.Context, in *apppb.ListKeysRequest, + opts ...grpc.CallOption) (*apppb.ListKeysResponse, error) + RenameKeyFunc func(ctx context.Context, in *apppb.RenameKeyRequest, + opts ...grpc.CallOption) (*apppb.RenameKeyResponse, error) + RotateKeyFunc func(ctx context.Context, in *apppb.RotateKeyRequest, + opts ...grpc.CallOption) (*apppb.RotateKeyResponse, error) + CreateKeyFromExistingKeyAuthorizationsFunc func(ctx context.Context, in *apppb.CreateKeyFromExistingKeyAuthorizationsRequest, + opts ...grpc.CallOption) (*apppb.CreateKeyFromExistingKeyAuthorizationsResponse, error) + } + +// GetUserIDByEmail calls the injected GetUserIDByEmailFunc or the real version. +func (asc *AppServiceClient) GetUserIDByEmail(ctx context.Context, in *apppb.GetUserIDByEmailRequest, + opts ...grpc.CallOption, +) (*apppb.GetUserIDByEmailResponse, error) { + if asc.GetUserIDByEmailFunc == nil { + return asc.AppServiceClient.GetUserIDByEmail(ctx, in, opts...) + } + return asc.GetUserIDByEmailFunc(ctx, in, opts...) +} + +// CreateOrganization calls the injected CreateOrganizationFunc or the real version. +func (asc *AppServiceClient) CreateOrganization(ctx context.Context, in *apppb.CreateOrganizationRequest, + opts ...grpc.CallOption, +) (*apppb.CreateOrganizationResponse, error) { + if asc.CreateOrganizationFunc == nil { + return asc.AppServiceClient.CreateOrganization(ctx, in, opts...) + } + return asc.CreateOrganizationFunc(ctx, in, opts...) } // ListOrganizations calls the injected ListOrganizationsFunc or the real version. @@ -40,6 +198,216 @@ func (asc *AppServiceClient) ListOrganizations(ctx context.Context, in *apppb.Li return asc.ListOrganizationsFunc(ctx, in, opts...) } +// GetOrganizationsWithAccessToLocation calls the injected GetOrganizationsWithAccessToLocationFunc or the real version. +func (asc *AppServiceClient) GetOrganizationsWithAccessToLocation(ctx context.Context, in *apppb.GetOrganizationsWithAccessToLocationRequest, + opts ...grpc.CallOption, +) (*apppb.GetOrganizationsWithAccessToLocationResponse, error) { + if asc.GetOrganizationsWithAccessToLocationFunc == nil { + return asc.AppServiceClient.GetOrganizationsWithAccessToLocation(ctx, in, opts...) + } + return asc.GetOrganizationsWithAccessToLocationFunc(ctx, in, opts...) +} + +// ListOrganizationsByUser calls the injected ListOrganizationsByUserFunc or the real version. +func (asc *AppServiceClient) ListOrganizationsByUser(ctx context.Context, in *apppb.ListOrganizationsByUserRequest, + opts ...grpc.CallOption, +) (*apppb.ListOrganizationsByUserResponse, error) { + if asc.ListOrganizationsByUserFunc == nil { + return asc.AppServiceClient.ListOrganizationsByUser(ctx, in, opts...) + } + return asc.ListOrganizationsByUserFunc(ctx, in, opts...) +} + +// GetOrganization calls the injected GetOrganizationFunc or the real version. +func (asc *AppServiceClient) GetOrganization(ctx context.Context, in *apppb.GetOrganizationRequest, + opts ...grpc.CallOption, +) (*apppb.GetOrganizationResponse, error) { + if asc.GetOrganizationFunc == nil { + return asc.AppServiceClient.GetOrganization(ctx, in, opts...) + } + return asc.GetOrganizationFunc(ctx, in, opts...) +} + +// GetOrganizationNamespaceAvailability calls the injected GetOrganizationNamespaceAvailabilityFunc or the real version. +func (asc *AppServiceClient) GetOrganizationNamespaceAvailability(ctx context.Context, in *apppb.GetOrganizationNamespaceAvailabilityRequest, + opts ...grpc.CallOption, +) (*apppb.GetOrganizationNamespaceAvailabilityResponse, error) { + if asc.GetOrganizationNamespaceAvailabilityFunc == nil { + return asc.AppServiceClient.GetOrganizationNamespaceAvailability(ctx, in, opts...) + } + return asc.GetOrganizationNamespaceAvailabilityFunc(ctx, in, opts...) +} + +// UpdateOrganization calls the injected UpdateOrganizationFunc or the real version. +func (asc *AppServiceClient) UpdateOrganization(ctx context.Context, in *apppb.UpdateOrganizationRequest, + opts ...grpc.CallOption, +) (*apppb.UpdateOrganizationResponse, error) { + if asc.UpdateOrganizationFunc == nil { + return asc.AppServiceClient.UpdateOrganization(ctx, in, opts...) + } + return asc.UpdateOrganizationFunc(ctx, in, opts...) +} + +// DeleteOrganization calls the injected DeleteOrganizationFunc or the real version. +func (asc *AppServiceClient) DeleteOrganization(ctx context.Context, in *apppb.DeleteOrganizationRequest, + opts ...grpc.CallOption, +) (*apppb.DeleteOrganizationResponse, error) { + if asc.DeleteOrganizationFunc == nil { + return asc.AppServiceClient.DeleteOrganization(ctx, in, opts...) + } + return asc.DeleteOrganizationFunc(ctx, in, opts...) +} + +// ListOrganizationMembers calls the injected ListOrganizationMembersFunc or the real version. +func (asc *AppServiceClient) ListOrganizationMembers(ctx context.Context, in *apppb.ListOrganizationMembersRequest, + opts ...grpc.CallOption, +) (*apppb.ListOrganizationMembersResponse, error) { + if asc.ListOrganizationMembersFunc == nil { + return asc.AppServiceClient.ListOrganizationMembers(ctx, in, opts...) + } + return asc.ListOrganizationMembersFunc(ctx, in, opts...) +} + +// CreateOrganizationInvite calls the injected CreateOrganizationInviteFunc or the real version. +func (asc *AppServiceClient) CreateOrganizationInvite(ctx context.Context, in *apppb.CreateOrganizationInviteRequest, + opts ...grpc.CallOption, +) (*apppb.CreateOrganizationInviteResponse, error) { + if asc.CreateOrganizationInviteFunc == nil { + return asc.AppServiceClient.CreateOrganizationInvite(ctx, in, opts...) + } + return asc.CreateOrganizationInviteFunc(ctx, in, opts...) +} + +// UpdateOrganizationInviteAuthorizations calls the injected UpdateOrganizationInviteAuthorizationsFunc or the real version. +func (asc *AppServiceClient) UpdateOrganizationInviteAuthorizations(ctx context.Context, in *apppb.UpdateOrganizationInviteAuthorizationsRequest, + opts ...grpc.CallOption, +) (*apppb.UpdateOrganizationInviteAuthorizationsResponse, error) { + if asc.UpdateOrganizationInviteAuthorizationsFunc == nil { + return asc.AppServiceClient.UpdateOrganizationInviteAuthorizations(ctx, in, opts...) + } + return asc.UpdateOrganizationInviteAuthorizationsFunc(ctx, in, opts...) +} + +// DeleteOrganizationMember calls the injected DeleteOrganizationMemberFunc or the real version. +func (asc *AppServiceClient) DeleteOrganizationMember(ctx context.Context, in *apppb.DeleteOrganizationMemberRequest, + opts ...grpc.CallOption, +) (*apppb.DeleteOrganizationMemberResponse, error) { + if asc.DeleteOrganizationMemberFunc == nil { + return asc.AppServiceClient.DeleteOrganizationMember(ctx, in, opts...) + } + return asc.DeleteOrganizationMemberFunc(ctx, in, opts...) +} + +// DeleteOrganizationInvite calls the injected DeleteOrganizationInviteFunc or the real version. +func (asc *AppServiceClient) DeleteOrganizationInvite(ctx context.Context, in *apppb.DeleteOrganizationInviteRequest, + opts ...grpc.CallOption, +) (*apppb.DeleteOrganizationInviteResponse, error) { + if asc.DeleteOrganizationInviteFunc == nil { + return asc.AppServiceClient.DeleteOrganizationInvite(ctx, in, opts...) + } + return asc.DeleteOrganizationInviteFunc(ctx, in, opts...) +} + +// ResendOrganizationInvite calls the injected ResendOrganizationInviteFunc or the real version. +func (asc *AppServiceClient) ResendOrganizationInvite(ctx context.Context, in *apppb.ResendOrganizationInviteRequest, + opts ...grpc.CallOption, +) (*apppb.ResendOrganizationInviteResponse, error) { + if asc.ResendOrganizationInviteFunc == nil { + return asc.AppServiceClient.ResendOrganizationInvite(ctx, in, opts...) + } + return asc.ResendOrganizationInviteFunc(ctx, in, opts...) +} + +// EnableBillingService calls the injected EnableBillingServiceFunc or the real version. +func (asc *AppServiceClient) EnableBillingService(ctx context.Context, in *apppb.EnableBillingServiceRequest, + opts ...grpc.CallOption, +) (*apppb.EnableBillingServiceResponse, error) { + if asc.EnableBillingServiceFunc == nil { + return asc.AppServiceClient.EnableBillingService(ctx, in, opts...) + } + return asc.EnableBillingServiceFunc(ctx, in, opts...) +} + +// DisableBillingService calls the injected DisableBillingServiceFunc or the real version. +func (asc *AppServiceClient) DisableBillingService(ctx context.Context, in *apppb.DisableBillingServiceRequest, + opts ...grpc.CallOption, +) (*apppb.DisableBillingServiceResponse, error) { + if asc.DisableBillingServiceFunc == nil { + return asc.AppServiceClient.DisableBillingService(ctx, in, opts...) + } + return asc.DisableBillingServiceFunc(ctx, in, opts...) +} + +// UpdateBillingService calls the injected UpdateBillingServiceFunc or the real version. +func (asc *AppServiceClient) UpdateBillingService(ctx context.Context, in *apppb.UpdateBillingServiceRequest, + opts ...grpc.CallOption, +) (*apppb.UpdateBillingServiceResponse, error) { + if asc.UpdateBillingServiceFunc == nil { + return asc.AppServiceClient.UpdateBillingService(ctx, in, opts...) + } + return asc.UpdateBillingServiceFunc(ctx, in, opts...) +} + +// OrganizationSetSupportEmail calls the injected OrganizationSetSupportEmailFunc or the real version. +func (asc *AppServiceClient) OrganizationSetSupportEmail(ctx context.Context, in *apppb.OrganizationSetSupportEmailRequest, + opts ...grpc.CallOption, +) (*apppb.OrganizationSetSupportEmailResponse, error) { + if asc.OrganizationSetSupportEmailFunc == nil { + return asc.AppServiceClient.OrganizationSetSupportEmail(ctx, in, opts...) + } + return asc.OrganizationSetSupportEmailFunc(ctx, in, opts...) +} + +// OrganizationGetSupportEmail calls the injected OrganizationGetSupportEmailFunc or the real version. +func (asc *AppServiceClient) OrganizationGetSupportEmail(ctx context.Context, in *apppb.OrganizationGetSupportEmailRequest, + opts ...grpc.CallOption, +) (*apppb.OrganizationGetSupportEmailResponse, error) { + if asc.OrganizationGetSupportEmailFunc == nil { + return asc.AppServiceClient.OrganizationGetSupportEmail(ctx, in, opts...) + } + return asc.OrganizationGetSupportEmailFunc(ctx, in, opts...) +} + +// CreateLocation calls the injected CreateLocationFunc or the real version. +func (asc *AppServiceClient) CreateLocation(ctx context.Context, in *apppb.CreateLocationRequest, + opts ...grpc.CallOption, +) (*apppb.CreateLocationResponse, error) { + if asc.CreateLocationFunc == nil { + return asc.AppServiceClient.CreateLocation(ctx, in, opts...) + } + return asc.CreateLocationFunc(ctx, in, opts...) +} + +// GetLocation calls the injected GetLocationFunc or the real version. +func (asc *AppServiceClient) GetLocation(ctx context.Context, in *apppb.GetLocationRequest, + opts ...grpc.CallOption, +) (*apppb.GetLocationResponse, error) { + if asc.GetLocationFunc == nil { + return asc.AppServiceClient.GetLocation(ctx, in, opts...) + } + return asc.GetLocationFunc(ctx, in, opts...) +} + +// UpdateLocation calls the injected UpdateLocationFunc or the real version. +func (asc *AppServiceClient) UpdateLocation(ctx context.Context, in *apppb.UpdateLocationRequest, + opts ...grpc.CallOption, +) (*apppb.UpdateLocationResponse, error) { + if asc.UpdateLocationFunc == nil { + return asc.AppServiceClient.UpdateLocation(ctx, in, opts...) + } + return asc.UpdateLocationFunc(ctx, in, opts...) +} + +// DeleteLocation calls the injected DeleteLocationFunc or the real version. +func (asc *AppServiceClient) DeleteLocation(ctx context.Context, in *apppb.DeleteLocationRequest, + opts ...grpc.CallOption, +) (*apppb.DeleteLocationResponse, error) { + if asc.DeleteLocationFunc == nil { + return asc.AppServiceClient.DeleteLocation(ctx, in, opts...) + } + return asc.DeleteLocationFunc(ctx, in, opts...) +} + // ListLocations calls the injected ListLocationsFunc or the real version. func (asc *AppServiceClient) ListLocations(ctx context.Context, in *apppb.ListLocationsRequest, opts ...grpc.CallOption, @@ -50,54 +418,74 @@ func (asc *AppServiceClient) ListLocations(ctx context.Context, in *apppb.ListLo return asc.ListLocationsFunc(ctx, in, opts...) } -// ListRobots calls the injected ListRobotsFunc or the real version. -func (asc *AppServiceClient) ListRobots(ctx context.Context, in *apppb.ListRobotsRequest, +// ShareLocation calls the injected ShareLocationFunc or the real version. +func (asc *AppServiceClient) ShareLocation(ctx context.Context, in *apppb.ShareLocationRequest, opts ...grpc.CallOption, -) (*apppb.ListRobotsResponse, error) { - if asc.ListRobotsFunc == nil { - return asc.AppServiceClient.ListRobots(ctx, in, opts...) +) (*apppb.ShareLocationResponse, error) { + if asc.ShareLocationFunc == nil { + return asc.AppServiceClient.ShareLocation(ctx, in, opts...) } - return asc.ListRobotsFunc(ctx, in, opts...) + return asc.ShareLocationFunc(ctx, in, opts...) } -// CreateKey calls the injected CreateKeyFunc or the real version. -func (asc *AppServiceClient) CreateKey(ctx context.Context, in *apppb.CreateKeyRequest, +// UnshareLocation calls the injected UnshareLocationFunc or the real version. +func (asc *AppServiceClient) UnshareLocation(ctx context.Context, in *apppb.UnshareLocationRequest, opts ...grpc.CallOption, -) (*apppb.CreateKeyResponse, error) { - if asc.CreateKeyFunc == nil { - return asc.AppServiceClient.CreateKey(ctx, in, opts...) +) (*apppb.UnshareLocationResponse, error) { + if asc.UnshareLocationFunc == nil { + return asc.AppServiceClient.UnshareLocation(ctx, in, opts...) } - return asc.CreateKeyFunc(ctx, in, opts...) + return asc.UnshareLocationFunc(ctx, in, opts...) } -// GetRobotAPIKeys wraps GetRobotAPIKeys. -func (asc *AppServiceClient) GetRobotAPIKeys(ctx context.Context, in *apppb.GetRobotAPIKeysRequest, +// LocationAuth calls the injected LocationAuthFunc or the real version. +func (asc *AppServiceClient) LocationAuth(ctx context.Context, in *apppb.LocationAuthRequest, opts ...grpc.CallOption, -) (*apppb.GetRobotAPIKeysResponse, error) { - if asc.GetRobotAPIKeysFunc == nil { - return asc.AppServiceClient.GetRobotAPIKeys(ctx, in, opts...) +) (*apppb.LocationAuthResponse, error) { + if asc.LocationAuthFunc == nil { + return asc.AppServiceClient.LocationAuth(ctx, in, opts...) } - return asc.GetRobotAPIKeysFunc(ctx, in, opts...) + return asc.LocationAuthFunc(ctx, in, opts...) } -// GetRobotPart wraps GetRobotPart. -func (asc *AppServiceClient) GetRobotPart(ctx context.Context, in *apppb.GetRobotPartRequest, +// CreateLocationSecret calls the injected CreateLocationSecretFunc or the real version. +func (asc *AppServiceClient) CreateLocationSecret(ctx context.Context, in *apppb.CreateLocationSecretRequest, opts ...grpc.CallOption, -) (*apppb.GetRobotPartResponse, error) { - if asc.GetRobotPartFunc == nil { - return asc.AppServiceClient.GetRobotPart(ctx, in, opts...) +) (*apppb.CreateLocationSecretResponse, error) { + if asc.CreateLocationSecretFunc == nil { + return asc.AppServiceClient.CreateLocationSecret(ctx, in, opts...) } - return asc.GetRobotPartFunc(ctx, in, opts...) + return asc.CreateLocationSecretFunc(ctx, in, opts...) } -// UpdateRobotPart wraps UpdateRobotPart. -func (asc *AppServiceClient) UpdateRobotPart(ctx context.Context, in *apppb.UpdateRobotPartRequest, +// DeleteLocationSecret calls the injected DeleteLocationSecretFunc or the real version. +func (asc *AppServiceClient) DeleteLocationSecret(ctx context.Context, in *apppb.DeleteLocationSecretRequest, opts ...grpc.CallOption, -) (*apppb.UpdateRobotPartResponse, error) { - if asc.GetRobotPartFunc == nil { - return asc.AppServiceClient.UpdateRobotPart(ctx, in, opts...) +) (*apppb.DeleteLocationSecretResponse, error) { + if asc.DeleteLocationSecretFunc == nil { + return asc.AppServiceClient.DeleteLocationSecret(ctx, in, opts...) } - return asc.UpdateRobotPartFunc(ctx, in, opts...) + return asc.DeleteLocationSecretFunc(ctx, in, opts...) +} + +// GetRobot calls the injected GetRobotFunc or the real version. +func (asc *AppServiceClient) GetRobot(ctx context.Context, in *apppb.GetRobotRequest, + opts ...grpc.CallOption, +) (*apppb.GetRobotResponse, error) { + if asc.GetRobotFunc == nil { + return asc.AppServiceClient.GetRobot(ctx, in, opts...) + } + return asc.GetRobotFunc(ctx, in, opts...) +} + +// GetRoverRentalRobots calls the injected GetRoverRentalRobotsFunc or the real version. +func (asc *AppServiceClient) GetRoverRentalRobots(ctx context.Context, in *apppb.GetRoverRentalRobotsRequest, + opts ...grpc.CallOption, +) (*apppb.GetRoverRentalRobotsResponse, error) { + if asc.GetRoverRentalRobotsFunc == nil { + return asc.AppServiceClient.GetRoverRentalRobots(ctx, in, opts...) + } + return asc.GetRoverRentalRobotsFunc(ctx, in, opts...) } // GetRobotParts calls the injected GetRobotPartsFunc or the real version. @@ -110,6 +498,16 @@ func (asc *AppServiceClient) GetRobotParts(ctx context.Context, in *apppb.GetRob return asc.GetRobotPartsFunc(ctx, in, opts...) } +// GetRobotPart calls the injected GetRobotPartFunc or the real version. +func (asc *AppServiceClient) GetRobotPart(ctx context.Context, in *apppb.GetRobotPartRequest, + opts ...grpc.CallOption, +) (*apppb.GetRobotPartResponse, error) { + if asc.GetRobotPartFunc == nil { + return asc.AppServiceClient.GetRobotPart(ctx, in, opts...) + } + return asc.GetRobotPartFunc(ctx, in, opts...) +} + // GetRobotPartLogs calls the injected GetRobotPartLogsFunc or the real version. func (asc *AppServiceClient) GetRobotPartLogs(ctx context.Context, in *apppb.GetRobotPartLogsRequest, opts ...grpc.CallOption, @@ -119,3 +517,433 @@ func (asc *AppServiceClient) GetRobotPartLogs(ctx context.Context, in *apppb.Get } return asc.GetRobotPartLogsFunc(ctx, in, opts...) } + +// // TailRobotPartLogs calls the injected TailRobotPartLogsFunc or the real version. +// func (asc *AppServiceClient) TailRobotPartLogs(ctx context.Context, in *apppb.TailRobotPartLogsRequest, +// opts ...grpc.CallOption, +// ) (*apppb.TailRobotPartLogsResponse, error) { +// if asc.TailRobotPartLogsFunc == nil { +// return asc.AppServiceClient.TailRobotPartLogs(ctx, in, opts...) +// } +// return asc.TailRobotPartLogsFunc(ctx, in, opts...) +// } + +// GetRobotPartHistory calls the injected GetRobotPartHistoryFunc or the real version. +func (asc *AppServiceClient) GetRobotPartHistory(ctx context.Context, in *apppb.GetRobotPartHistoryRequest, + opts ...grpc.CallOption, +) (*apppb.GetRobotPartHistoryResponse, error) { + if asc.GetRobotPartHistoryFunc == nil { + return asc.AppServiceClient.GetRobotPartHistory(ctx, in, opts...) + } + return asc.GetRobotPartHistoryFunc(ctx, in, opts...) +} + +// UpdateRobotPart calls the injected UpdateRobotPartFunc or the real version. +func (asc *AppServiceClient) UpdateRobotPart(ctx context.Context, in *apppb.UpdateRobotPartRequest, + opts ...grpc.CallOption, +) (*apppb.UpdateRobotPartResponse, error) { + if asc.UpdateRobotPartFunc == nil { + return asc.AppServiceClient.UpdateRobotPart(ctx, in, opts...) + } + return asc.UpdateRobotPartFunc(ctx, in, opts...) +} + +// NewRobotPart calls the injected NewRobotPartFunc or the real version. +func (asc *AppServiceClient) NewRobotPart(ctx context.Context, in *apppb.NewRobotPartRequest, + opts ...grpc.CallOption, +) (*apppb.NewRobotPartResponse, error) { + if asc.NewRobotPartFunc == nil { + return asc.AppServiceClient.NewRobotPart(ctx, in, opts...) + } + return asc.NewRobotPartFunc(ctx, in, opts...) +} + +// DeleteRobotPart calls the injected DeleteRobotPartFunc or the real version. +func (asc *AppServiceClient) DeleteRobotPart(ctx context.Context, in *apppb.DeleteRobotPartRequest, + opts ...grpc.CallOption, +) (*apppb.DeleteRobotPartResponse, error) { + if asc.DeleteRobotPartFunc == nil { + return asc.AppServiceClient.DeleteRobotPart(ctx, in, opts...) + } + return asc.DeleteRobotPartFunc(ctx, in, opts...) +} + +// GetRobotAPIKeys calls the injected GetRobotAPIKeysFunc or the real version. +func (asc *AppServiceClient) GetRobotAPIKeys(ctx context.Context, in *apppb.GetRobotAPIKeysRequest, + opts ...grpc.CallOption, +) (*apppb.GetRobotAPIKeysResponse, error) { + if asc.GetRobotAPIKeysFunc == nil { + return asc.AppServiceClient.GetRobotAPIKeys(ctx, in, opts...) + } + return asc.GetRobotAPIKeysFunc(ctx, in, opts...) +} + +// MarkPartAsMain calls the injected MarkPartAsMainFunc or the real version. +func (asc *AppServiceClient) MarkPartAsMain(ctx context.Context, in *apppb.MarkPartAsMainRequest, + opts ...grpc.CallOption, +) (*apppb.MarkPartAsMainResponse, error) { + if asc.MarkPartAsMainFunc == nil { + return asc.AppServiceClient.MarkPartAsMain(ctx, in, opts...) + } + return asc.MarkPartAsMainFunc(ctx, in, opts...) +} + +// MarkPartForRestart calls the injected MarkPartForRestartFunc or the real version. +func (asc *AppServiceClient) MarkPartForRestart(ctx context.Context, in *apppb.MarkPartForRestartRequest, + opts ...grpc.CallOption, +) (*apppb.MarkPartForRestartResponse, error) { + if asc.MarkPartForRestartFunc == nil { + return asc.AppServiceClient.MarkPartForRestart(ctx, in, opts...) + } + return asc.MarkPartForRestartFunc(ctx, in, opts...) +} + +// CreateRobotPartSecret calls the injected CreateRobotPartSecretFunc or the real version. +func (asc *AppServiceClient) CreateRobotPartSecret(ctx context.Context, in *apppb.CreateRobotPartSecretRequest, + opts ...grpc.CallOption, +) (*apppb.CreateRobotPartSecretResponse, error) { + if asc.CreateRobotPartSecretFunc == nil { + return asc.AppServiceClient.CreateRobotPartSecret(ctx, in, opts...) + } + return asc.CreateRobotPartSecretFunc(ctx, in, opts...) +} + +// DeleteRobotPartSecret calls the injected DeleteRobotPartSecretFunc or the real version. +func (asc *AppServiceClient) DeleteRobotPartSecret(ctx context.Context, in *apppb.DeleteRobotPartSecretRequest, + opts ...grpc.CallOption, +) (*apppb.DeleteRobotPartSecretResponse, error) { + if asc.DeleteRobotPartSecretFunc == nil { + return asc.AppServiceClient.DeleteRobotPartSecret(ctx, in, opts...) + } + return asc.DeleteRobotPartSecretFunc(ctx, in, opts...) +} + +// ListRobots calls the injected ListRobotsFunc or the real version. +func (asc *AppServiceClient) ListRobots(ctx context.Context, in *apppb.ListRobotsRequest, + opts ...grpc.CallOption, +) (*apppb.ListRobotsResponse, error) { + if asc.ListRobotsFunc == nil { + return asc.AppServiceClient.ListRobots(ctx, in, opts...) + } + return asc.ListRobotsFunc(ctx, in, opts...) +} + +// NewRobot calls the injected NewRobotFunc or the real version. +func (asc *AppServiceClient) NewRobot(ctx context.Context, in *apppb.NewRobotRequest, + opts ...grpc.CallOption, +) (*apppb.NewRobotResponse, error) { + if asc.NewRobotFunc == nil { + return asc.AppServiceClient.NewRobot(ctx, in, opts...) + } + return asc.NewRobotFunc(ctx, in, opts...) +} + +// UpdateRobot calls the injected UpdateRobotFunc or the real version. +func (asc *AppServiceClient) UpdateRobot(ctx context.Context, in *apppb.UpdateRobotRequest, + opts ...grpc.CallOption, +) (*apppb.UpdateRobotResponse, error) { + if asc.UpdateRobotFunc == nil { + return asc.AppServiceClient.UpdateRobot(ctx, in, opts...) + } + return asc.UpdateRobotFunc(ctx, in, opts...) +} + +// DeleteRobot calls the injected DeleteRobotFunc or the real version. +func (asc *AppServiceClient) DeleteRobot(ctx context.Context, in *apppb.DeleteRobotRequest, + opts ...grpc.CallOption, +) (*apppb.DeleteRobotResponse, error) { + if asc.DeleteRobotFunc == nil { + return asc.AppServiceClient.DeleteRobot(ctx, in, opts...) + } + return asc.DeleteRobotFunc(ctx, in, opts...) +} + +// ListFragments calls the injected ListFragmentsFunc or the real version. +func (asc *AppServiceClient) ListFragments(ctx context.Context, in *apppb.ListFragmentsRequest, + opts ...grpc.CallOption, +) (*apppb.ListFragmentsResponse, error) { + if asc.ListFragmentsFunc == nil { + return asc.AppServiceClient.ListFragments(ctx, in, opts...) + } + return asc.ListFragmentsFunc(ctx, in, opts...) +} + +// GetFragment calls the injected GetFragmentFunc or the real version. +func (asc *AppServiceClient) GetFragment(ctx context.Context, in *apppb.GetFragmentRequest, + opts ...grpc.CallOption, +) (*apppb.GetFragmentResponse, error) { + if asc.GetFragmentFunc == nil { + return asc.AppServiceClient.GetFragment(ctx, in, opts...) + } + return asc.GetFragmentFunc(ctx, in, opts...) +} + +// CreateFragment calls the injected CreateFragmentFunc or the real version. +func (asc *AppServiceClient) CreateFragment(ctx context.Context, in *apppb.CreateFragmentRequest, + opts ...grpc.CallOption, +) (*apppb.CreateFragmentResponse, error) { + if asc.CreateFragmentFunc == nil { + return asc.AppServiceClient.CreateFragment(ctx, in, opts...) + } + return asc.CreateFragmentFunc(ctx, in, opts...) +} + +// UpdateFragment calls the injected UpdateFragmentFunc or the real version. +func (asc *AppServiceClient) UpdateFragment(ctx context.Context, in *apppb.UpdateFragmentRequest, + opts ...grpc.CallOption, +) (*apppb.UpdateFragmentResponse, error) { + if asc.UpdateFragmentFunc == nil { + return asc.AppServiceClient.UpdateFragment(ctx, in, opts...) + } + return asc.UpdateFragmentFunc(ctx, in, opts...) +} + +// DeleteFragment calls the injected DeleteFragmentFunc or the real version. +func (asc *AppServiceClient) DeleteFragment(ctx context.Context, in *apppb.DeleteFragmentRequest, + opts ...grpc.CallOption, +) (*apppb.DeleteFragmentResponse, error) { + if asc.DeleteFragmentFunc == nil { + return asc.AppServiceClient.DeleteFragment(ctx, in, opts...) + } + return asc.DeleteFragmentFunc(ctx, in, opts...) +} + +// ListMachineFragments calls the injected ListMachineFragmentsFunc or the real version. +func (asc *AppServiceClient) ListMachineFragments(ctx context.Context, in *apppb.ListMachineFragmentsRequest, + opts ...grpc.CallOption, +) (*apppb.ListMachineFragmentsResponse, error) { + if asc.ListMachineFragmentsFunc == nil { + return asc.AppServiceClient.ListMachineFragments(ctx, in, opts...) + } + return asc.ListMachineFragmentsFunc(ctx, in, opts...) +} + +// GetFragmentHistory calls the injected GetFragmentHistoryFunc or the real version. +func (asc *AppServiceClient) GetFragmentHistory(ctx context.Context, in *apppb.GetFragmentHistoryRequest, + opts ...grpc.CallOption, +) (*apppb.GetFragmentHistoryResponse, error) { + if asc.GetFragmentHistoryFunc == nil { + return asc.AppServiceClient.GetFragmentHistory(ctx, in, opts...) + } + return asc.GetFragmentHistoryFunc(ctx, in, opts...) +} + +// AddRole calls the injected AddRoleFunc or the real version. +func (asc *AppServiceClient) AddRole(ctx context.Context, in *apppb.AddRoleRequest, + opts ...grpc.CallOption, +) (*apppb.AddRoleResponse, error) { + if asc.AddRoleFunc == nil { + return asc.AppServiceClient.AddRole(ctx, in, opts...) + } + return asc.AddRoleFunc(ctx, in, opts...) +} + +// RemoveRole calls the injected RemoveRoleFunc or the real version. +func (asc *AppServiceClient) RemoveRole(ctx context.Context, in *apppb.RemoveRoleRequest, + opts ...grpc.CallOption, +) (*apppb.RemoveRoleResponse, error) { + if asc.RemoveRoleFunc == nil { + return asc.AppServiceClient.RemoveRole(ctx, in, opts...) + } + return asc.RemoveRoleFunc(ctx, in, opts...) +} + +// ChangeRole calls the injected ChangeRoleFunc or the real version. +func (asc *AppServiceClient) ChangeRole(ctx context.Context, in *apppb.ChangeRoleRequest, + opts ...grpc.CallOption, +) (*apppb.ChangeRoleResponse, error) { + if asc.ChangeRoleFunc == nil { + return asc.AppServiceClient.ChangeRole(ctx, in, opts...) + } + return asc.ChangeRoleFunc(ctx, in, opts...) +} + +// ListAuthorizations calls the injected ListAuthorizationsFunc or the real version. +func (asc *AppServiceClient) ListAuthorizations(ctx context.Context, in *apppb.ListAuthorizationsRequest, + opts ...grpc.CallOption, +) (*apppb.ListAuthorizationsResponse, error) { + if asc.ListAuthorizationsFunc == nil { + return asc.AppServiceClient.ListAuthorizations(ctx, in, opts...) + } + return asc.ListAuthorizationsFunc(ctx, in, opts...) +} + +// CheckPermissions calls the injected CheckPermissionsFunc or the real version. +func (asc *AppServiceClient) CheckPermissions(ctx context.Context, in *apppb.CheckPermissionsRequest, + opts ...grpc.CallOption, +) (*apppb.CheckPermissionsResponse, error) { + if asc.CheckPermissionsFunc == nil { + return asc.AppServiceClient.CheckPermissions(ctx, in, opts...) + } + return asc.CheckPermissionsFunc(ctx, in, opts...) +} + +// GetRegistryItem calls the injected GetRegistryItemFunc or the real version. +func (asc *AppServiceClient) GetRegistryItem(ctx context.Context, in *apppb.GetRegistryItemRequest, + opts ...grpc.CallOption, +) (*apppb.GetRegistryItemResponse, error) { + if asc.GetRegistryItemFunc == nil { + return asc.AppServiceClient.GetRegistryItem(ctx, in, opts...) + } + return asc.GetRegistryItemFunc(ctx, in, opts...) +} + +// CreateRegistryItem calls the injected CreateRegistryItemFunc or the real version. +func (asc *AppServiceClient) CreateRegistryItem(ctx context.Context, in *apppb.CreateRegistryItemRequest, + opts ...grpc.CallOption, +) (*apppb.CreateRegistryItemResponse, error) { + if asc.CreateRegistryItemFunc == nil { + return asc.AppServiceClient.CreateRegistryItem(ctx, in, opts...) + } + return asc.CreateRegistryItemFunc(ctx, in, opts...) +} + +// UpdateRegistryItem calls the injected UpdateRegistryItemFunc or the real version. +func (asc *AppServiceClient) UpdateRegistryItem(ctx context.Context, in *apppb.UpdateRegistryItemRequest, + opts ...grpc.CallOption, +) (*apppb.UpdateRegistryItemResponse, error) { + if asc.UpdateRegistryItemFunc == nil { + return asc.AppServiceClient.UpdateRegistryItem(ctx, in, opts...) + } + return asc.UpdateRegistryItemFunc(ctx, in, opts...) +} + +// ListRegistryItems calls the injected ListRegistryItemsFunc or the real version. +func (asc *AppServiceClient) ListRegistryItems(ctx context.Context, in *apppb.ListRegistryItemsRequest, + opts ...grpc.CallOption, +) (*apppb.ListRegistryItemsResponse, error) { + if asc.ListRegistryItemsFunc == nil { + return asc.AppServiceClient.ListRegistryItems(ctx, in, opts...) + } + return asc.ListRegistryItemsFunc(ctx, in, opts...) +} + +// DeleteRegistryItem calls the injected DeleteRegistryItemFunc or the real version. +func (asc *AppServiceClient) DeleteRegistryItem(ctx context.Context, in *apppb.DeleteRegistryItemRequest, + opts ...grpc.CallOption, +) (*apppb.DeleteRegistryItemResponse, error) { + if asc.DeleteRegistryItemFunc == nil { + return asc.AppServiceClient.DeleteRegistryItem(ctx, in, opts...) + } + return asc.DeleteRegistryItemFunc(ctx, in, opts...) +} + +// TransferRegistryItem calls the injected TransferRegistryItemFunc or the real version. +func (asc *AppServiceClient) TransferRegistryItem(ctx context.Context, in *apppb.TransferRegistryItemRequest, + opts ...grpc.CallOption, +) (*apppb.TransferRegistryItemResponse, error) { + if asc.TransferRegistryItemFunc == nil { + return asc.AppServiceClient.TransferRegistryItem(ctx, in, opts...) + } + return asc.TransferRegistryItemFunc(ctx, in, opts...) +} + +// CreateModule calls the injected CreateModuleFunc or the real version. +func (asc *AppServiceClient) CreateModule(ctx context.Context, in *apppb.CreateModuleRequest, + opts ...grpc.CallOption, +) (*apppb.CreateModuleResponse, error) { + if asc.CreateModuleFunc == nil { + return asc.AppServiceClient.CreateModule(ctx, in, opts...) + } + return asc.CreateModuleFunc(ctx, in, opts...) +} + +// UpdateModule calls the injected UpdateModuleFunc or the real version. +func (asc *AppServiceClient) UpdateModule(ctx context.Context, in *apppb.UpdateModuleRequest, + opts ...grpc.CallOption, +) (*apppb.UpdateModuleResponse, error) { + if asc.UpdateModuleFunc == nil { + return asc.AppServiceClient.UpdateModule(ctx, in, opts...) + } + return asc.UpdateModuleFunc(ctx, in, opts...) +} + +// // UploadModuleFile calls the injected UploadModuleFileFunc or the real version. +// func (asc *AppServiceClient) UploadModuleFile(ctx context.Context, in *apppb.UploadModuleFileRequest, +// opts ...grpc.CallOption, +// ) (*apppb.UploadModuleFileResponse, error) { +// if asc.UploadModuleFileFunc == nil { +// return asc.AppServiceClient.UploadModuleFile(ctx, in, opts...) +// } +// return asc.UploadModuleFileFunc(ctx, in, opts...) +// } + +// GetModule calls the injected GetModuleFunc or the real version. +func (asc *AppServiceClient) GetModule(ctx context.Context, in *apppb.GetModuleRequest, + opts ...grpc.CallOption, +) (*apppb.GetModuleResponse, error) { + if asc.GetModuleFunc == nil { + return asc.AppServiceClient.GetModule(ctx, in, opts...) + } + return asc.GetModuleFunc(ctx, in, opts...) +} + +// ListModules calls the injected ListModulesFunc or the real version. +func (asc *AppServiceClient) ListModules(ctx context.Context, in *apppb.ListModulesRequest, + opts ...grpc.CallOption, +) (*apppb.ListModulesResponse, error) { + if asc.ListModulesFunc == nil { + return asc.AppServiceClient.ListModules(ctx, in, opts...) + } + return asc.ListModulesFunc(ctx, in, opts...) +} + +// CreateKey calls the injected CreateKeyFunc or the real version. +func (asc *AppServiceClient) CreateKey(ctx context.Context, in *apppb.CreateKeyRequest, + opts ...grpc.CallOption, +) (*apppb.CreateKeyResponse, error) { + if asc.CreateKeyFunc == nil { + return asc.AppServiceClient.CreateKey(ctx, in, opts...) + } + return asc.CreateKeyFunc(ctx, in, opts...) +} + +// DeleteKey calls the injected DeleteKeyFunc or the real version. +func (asc *AppServiceClient) DeleteKey(ctx context.Context, in *apppb.DeleteKeyRequest, + opts ...grpc.CallOption, +) (*apppb.DeleteKeyResponse, error) { + if asc.DeleteKeyFunc == nil { + return asc.AppServiceClient.DeleteKey(ctx, in, opts...) + } + return asc.DeleteKeyFunc(ctx, in, opts...) +} + +// ListKeys calls the injected ListKeysFunc or the real version. +func (asc *AppServiceClient) ListKeys(ctx context.Context, in *apppb.ListKeysRequest, + opts ...grpc.CallOption, +) (*apppb.ListKeysResponse, error) { + if asc.ListKeysFunc == nil { + return asc.AppServiceClient.ListKeys(ctx, in, opts...) + } + return asc.ListKeysFunc(ctx, in, opts...) +} + +// RenameKey calls the injected RenameKeyFunc or the real version. +func (asc *AppServiceClient) RenameKey(ctx context.Context, in *apppb.RenameKeyRequest, + opts ...grpc.CallOption, +) (*apppb.RenameKeyResponse, error) { + if asc.RenameKeyFunc == nil { + return asc.AppServiceClient.RenameKey(ctx, in, opts...) + } + return asc.RenameKeyFunc(ctx, in, opts...) +} + +// RotateKey calls the injected RotateKeyFunc or the real version. +func (asc *AppServiceClient) RotateKey(ctx context.Context, in *apppb.RotateKeyRequest, + opts ...grpc.CallOption, +) (*apppb.RotateKeyResponse, error) { + if asc.RotateKeyFunc == nil { + return asc.AppServiceClient.RotateKey(ctx, in, opts...) + } + return asc.RotateKeyFunc(ctx, in, opts...) +} + +// CreateKeyFromExistingKeyAuthorizations calls the injected CreateKeyFromExistingKeyAuthorizationsFunc or the real version. +func (asc *AppServiceClient) CreateKeyFromExistingKeyAuthorizations(ctx context.Context, in *apppb.CreateKeyFromExistingKeyAuthorizationsRequest, + opts ...grpc.CallOption, +) (*apppb.CreateKeyFromExistingKeyAuthorizationsResponse, error) { + if asc.CreateKeyFromExistingKeyAuthorizationsFunc == nil { + return asc.AppServiceClient.CreateKeyFromExistingKeyAuthorizations(ctx, in, opts...) + } + return asc.CreateKeyFromExistingKeyAuthorizationsFunc(ctx, in, opts...) +} From 6503fdde76a97ba6ac6d093fc66d871414c5b9b5 Mon Sep 17 00:00:00 2001 From: purplenicole730 Date: Thu, 14 Nov 2024 13:51:14 -0500 Subject: [PATCH 33/75] add organization tests --- app/app_client_test.go | 393 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 393 insertions(+) create mode 100644 app/app_client_test.go diff --git a/app/app_client_test.go b/app/app_client_test.go new file mode 100644 index 00000000000..96dcf320cac --- /dev/null +++ b/app/app_client_test.go @@ -0,0 +1,393 @@ +package app + +import ( + "context" + "testing" + + pb "go.viam.com/api/app/v1" + "go.viam.com/rdk/testutils/inject" + "go.viam.com/test" + "google.golang.org/grpc" + "google.golang.org/protobuf/types/known/timestamppb" +) + +const ( + organizationID = "organization_id" + email = "email" + userID = "user_id" + locationID = "location_id" + available = true + authorizationType = "authorization_type" + authorizationID = "authorization_id" + resourceType = "resource_type" + resourceID = "resource_id" + identityID = "identity_id" + identityType = "identity_type" +) + +var ( + name = "name" + region = "region" + namespace = "public_namespace" + cid = "cid" + dateAdded = timestamppb.Timestamp{Seconds: 0, Nanos: 50} + organization = Organization{ + ID: organizationID, + Name: name, + CreatedOn: &dateAdded, + PublicNamespace: namespace, + DefaultRegion: region, + Cid: &cid, + } + pbOrganization = pb.Organization{ + Id: organization.ID, + Name: organization.Name, + CreatedOn: organization.CreatedOn, + PublicNamespace: organization.PublicNamespace, + DefaultRegion: organization.DefaultRegion, + Cid: organization.Cid, + } + organizationIdentity = OrganizationIdentity{ + ID: organizationID, + Name: name, + } + orgDetails = OrgDetails{ + OrgID: organizationID, + OrgName: name, + } + lastLogin = timestamppb.Timestamp{Seconds: 0, Nanos: 100} + createdOn = timestamppb.Timestamp{Seconds: 0, Nanos: 0} + authorization = Authorization{ + AuthorizationType: authorizationType, + AuthorizationID: authorizationID, + ResourceType: resourceType, + ResourceID: resourceID, + IdentityID: identityID, + OrganizationID: organizationID, + IdentityType: identityType, + } + pbAuthorization = pb.Authorization{ + AuthorizationType: authorization.AuthorizationType, + AuthorizationId: authorization.AuthorizationID, + ResourceType: authorization.ResourceType, + ResourceId: authorization.ResourceID, + IdentityId: authorization.IdentityID, + OrganizationId: authorization.OrganizationID, + IdentityType: authorization.IdentityType, + } + authorizations = []*Authorization{&authorization} + pbAuthorizations = []*pb.Authorization{&pbAuthorization} + member = OrganizationMember{ + UserID: userID, + Emails: []string{email}, + DateAdded: &dateAdded, + LastLogin: &lastLogin, + } + invite = OrganizationInvite{ + OrganizationID: organizationID, + Email: email, + CreatedOn: &createdOn, + Authorizations: authorizations, + } + pbInvite = pb.OrganizationInvite{ + OrganizationId: invite.OrganizationID, + Email: invite.Email, + CreatedOn: invite.CreatedOn, + Authorizations: pbAuthorizations, + } + sendEmailInvite = true + addressLine2 = "address_line_2" + address = BillingAddress{ + AddressLine_1: "address_line_1", + AddressLine_2: &addressLine2, + City: "city", + State: "state", + } + pbAddress = pb.BillingAddress{ + AddressLine_1: address.AddressLine_1, + AddressLine_2: address.AddressLine_2, + City: address.City, + State: address.State, + } +) + + +func createGrpcClient() *inject.AppServiceClient { + return &inject.AppServiceClient{} +} + +func TestAppClient(t *testing.T) { + grpcClient := createGrpcClient() + client := Client{client: grpcClient} + + t.Run("GetUserIDByEmail", func(t *testing.T) { + grpcClient.GetUserIDByEmailFunc = func(ctx context.Context, in *pb.GetUserIDByEmailRequest, opts ...grpc.CallOption) (*pb.GetUserIDByEmailResponse, error) { + test.That(t, in.Email, test.ShouldEqual, email) + return &pb.GetUserIDByEmailResponse{ + UserId: userID, + }, nil + } + resp, _ := client.GetUserIDByEmail(context.Background(), email) + test.That(t, resp, test.ShouldEqual, userID) + }) + + t.Run("CreateOrganization", func(t *testing.T) { + grpcClient.CreateOrganizationFunc = func(ctx context.Context, in *pb.CreateOrganizationRequest, opts ...grpc.CallOption) (*pb.CreateOrganizationResponse, error) { + test.That(t, in.Name, test.ShouldEqual, name) + return &pb.CreateOrganizationResponse{ + Organization: &pbOrganization, + }, nil + } + resp, _ := client.CreateOrganization(context.Background(), name) + test.That(t, resp.ID, test.ShouldEqual, organization.ID) + test.That(t, resp.Name, test.ShouldEqual, organization.Name) + test.That(t, resp.PublicNamespace, test.ShouldEqual, organization.PublicNamespace) + test.That(t, resp.DefaultRegion, test.ShouldEqual, organization.DefaultRegion) + test.That(t, resp.Cid, test.ShouldEqual, organization.Cid) + }) + + t.Run("ListOrganizations", func(t *testing.T) { + organizations := []Organization{organization} + grpcClient.ListOrganizationsFunc = func(ctx context.Context, in *pb.ListOrganizationsRequest, opts ...grpc.CallOption) (*pb.ListOrganizationsResponse, error) { + return &pb.ListOrganizationsResponse{ + Organizations: []*pb.Organization{&pbOrganization}, + }, nil + } + resp, _ := client.ListOrganizations(context.Background()) + test.That(t, len(resp), test.ShouldEqual, 1) + test.That(t, resp[0].ID, test.ShouldEqual, organizations[0].ID) + test.That(t, resp[0].Name, test.ShouldEqual, organizations[0].Name) + test.That(t, resp[0].PublicNamespace, test.ShouldEqual, organizations[0].PublicNamespace) + test.That(t, resp[0].DefaultRegion, test.ShouldEqual, organizations[0].DefaultRegion) + test.That(t, resp[0].Cid, test.ShouldEqual, organizations[0].Cid) + }) + + t.Run("GetOrganizationsWithAccessToLocation", func(t *testing.T) { + pbOrganizationIdentity := pb.OrganizationIdentity{ + Id: organizationIdentity.ID, + Name: organizationIdentity.Name, + } + grpcClient.GetOrganizationsWithAccessToLocationFunc = func(ctx context.Context, in *pb.GetOrganizationsWithAccessToLocationRequest, opts ...grpc.CallOption) (*pb.GetOrganizationsWithAccessToLocationResponse, error) { + test.That(t, in.LocationId, test.ShouldEqual, locationID) + return &pb.GetOrganizationsWithAccessToLocationResponse{ + OrganizationIdentities: []*pb.OrganizationIdentity{&pbOrganizationIdentity}, + }, nil + } + resp, _ := client.GetOrganizationsWithAccessToLocation(context.Background(), locationID) + test.That(t, len(resp), test.ShouldEqual, 1) + test.That(t, resp[0].ID, test.ShouldEqual, organizationIdentity.ID) + test.That(t, resp[0].Name, test.ShouldEqual, organizationIdentity.Name) + }) + + t.Run("ListOrganizationsByUser", func(t *testing.T) { + orgDetailsList := []OrgDetails{orgDetails} + pbOrgDetails := pb.OrgDetails{ + OrgId: orgDetails.OrgID, + OrgName: orgDetails.OrgName, + } + grpcClient.ListOrganizationsByUserFunc = func(ctx context.Context, in *pb.ListOrganizationsByUserRequest, opts ...grpc.CallOption) (*pb.ListOrganizationsByUserResponse, error) { + test.That(t, in.UserId, test.ShouldEqual, userID) + return &pb.ListOrganizationsByUserResponse{ + Orgs: []*pb.OrgDetails{&pbOrgDetails}, + }, nil + } + resp, _ := client.ListOrganizationsByUser(context.Background(), userID) + test.That(t, len(resp), test.ShouldEqual, len(orgDetailsList)) + test.That(t, resp[0].OrgID, test.ShouldEqual, orgDetailsList[0].OrgID) + test.That(t, resp[0].OrgName, test.ShouldEqual, orgDetailsList[0].OrgName) + }) + + t.Run("GetOrganization", func(t *testing.T) { + grpcClient.GetOrganizationFunc = func(ctx context.Context, in *pb.GetOrganizationRequest, opts ...grpc.CallOption) (*pb.GetOrganizationResponse, error) { + test.That(t, in.OrganizationId, test.ShouldEqual, organizationID) + return &pb.GetOrganizationResponse{ + Organization: &pbOrganization, + }, nil + } + resp, _ := client.GetOrganization(context.Background(), organizationID) + test.That(t, resp.ID, test.ShouldEqual, organization.ID) + test.That(t, resp.Name, test.ShouldEqual, organization.Name) + test.That(t, resp.PublicNamespace, test.ShouldEqual, organization.PublicNamespace) + test.That(t, resp.DefaultRegion, test.ShouldEqual, organization.DefaultRegion) + test.That(t, resp.Cid, test.ShouldEqual, organization.Cid) + }) + + t.Run("GetOrganizationNamespaceAvailability", func(t *testing.T) { + grpcClient.GetOrganizationNamespaceAvailabilityFunc = func(ctx context.Context, in *pb.GetOrganizationNamespaceAvailabilityRequest, opts ...grpc.CallOption) (*pb.GetOrganizationNamespaceAvailabilityResponse, error) { + test.That(t, in.PublicNamespace, test.ShouldEqual, namespace) + return &pb.GetOrganizationNamespaceAvailabilityResponse{ + Available: available, + }, nil + } + resp, _ := client.GetOrganizationNamespaceAvailability(context.Background(), namespace) + test.That(t, resp, test.ShouldEqual, available) + }) + + t.Run("UpdateOrganization", func(t *testing.T) { + grpcClient.UpdateOrganizationFunc = func(ctx context.Context, in *pb.UpdateOrganizationRequest, opts ...grpc.CallOption) (*pb.UpdateOrganizationResponse, error) { + test.That(t, in.PublicNamespace, test.ShouldEqual, &namespace) + return &pb.UpdateOrganizationResponse{ + Organization: &pbOrganization, + }, nil + } + resp, _ := client.UpdateOrganization(context.Background(), organizationID, &name, &namespace, ®ion, &cid) + test.That(t, resp.ID, test.ShouldEqual, organization.ID) + test.That(t, resp.Name, test.ShouldEqual, organization.Name) + test.That(t, resp.PublicNamespace, test.ShouldEqual, organization.PublicNamespace) + test.That(t, resp.DefaultRegion, test.ShouldEqual, organization.DefaultRegion) + test.That(t, resp.Cid, test.ShouldEqual, organization.Cid) + }) + + t.Run("DeleteOrganization", func(t *testing.T) { + grpcClient.DeleteOrganizationFunc = func(ctx context.Context, in *pb.DeleteOrganizationRequest, opts ...grpc.CallOption) (*pb.DeleteOrganizationResponse, error) { + test.That(t, in.OrganizationId, test.ShouldEqual, organizationID) + return &pb.DeleteOrganizationResponse{}, nil + } + client.DeleteOrganization(context.Background(), organizationID) + }) + + t.Run("ListOrganizationMembers", func(t *testing.T) { + expectedMembers := []OrganizationMember{member} + pbMember := pb.OrganizationMember{ + UserId: member.UserID, + Emails: member.Emails, + DateAdded: member.DateAdded, + LastLogin: member.LastLogin, + } + expectedInvites := []OrganizationInvite{invite} + grpcClient.ListOrganizationMembersFunc = func(ctx context.Context, in *pb.ListOrganizationMembersRequest, opts ...grpc.CallOption) (*pb.ListOrganizationMembersResponse, error) { + test.That(t, in.OrganizationId, test.ShouldEqual, organizationID) + return &pb.ListOrganizationMembersResponse{ + Members: []*pb.OrganizationMember{&pbMember}, + Invites: []*pb.OrganizationInvite{&pbInvite}, + }, nil + } + members, invites, _ := client.ListOrganizationMembers(context.Background(), organizationID) + test.That(t, len(members), test.ShouldEqual, len(expectedMembers)) + test.That(t, members[0].UserID, test.ShouldEqual, expectedMembers[0].UserID) + test.That(t, members[0].Emails, test.ShouldResemble, expectedMembers[0].Emails) + test.That(t, members[0].DateAdded, test.ShouldEqual, expectedMembers[0].DateAdded) + test.That(t, members[0].LastLogin, test.ShouldEqual, expectedMembers[0].LastLogin) + test.That(t, len(invites), test.ShouldEqual, len(expectedInvites)) + test.That(t, invites[0].OrganizationID, test.ShouldEqual, expectedInvites[0].OrganizationID) + test.That(t, invites[0].Email, test.ShouldResemble, expectedInvites[0].Email) + test.That(t, invites[0].CreatedOn, test.ShouldEqual, expectedInvites[0].CreatedOn) + test.That(t, len(invites[0].Authorizations), test.ShouldEqual, len(expectedInvites[0].Authorizations)) + test.That(t, invites[0].Authorizations[0], test.ShouldResemble, expectedInvites[0].Authorizations[0]) + }) + + t.Run("CreateOrganizationInvite", func(t *testing.T) { + grpcClient.CreateOrganizationInviteFunc = func(ctx context.Context, in *pb.CreateOrganizationInviteRequest, opts ...grpc.CallOption) (*pb.CreateOrganizationInviteResponse, error) { + test.That(t, in.OrganizationId, test.ShouldEqual, organizationID) + test.That(t, in.Email, test.ShouldEqual, email) + test.That(t, in.Authorizations, test.ShouldResemble, pbAuthorizations) + test.That(t, in.SendEmailInvite, test.ShouldEqual, &sendEmailInvite) + return &pb.CreateOrganizationInviteResponse{ + Invite: &pbInvite, + }, nil + } + resp, _ := client.CreateOrganizationInvite(context.Background(), organizationID, email, authorizations, &sendEmailInvite) + test.That(t, resp.OrganizationID, test.ShouldEqual, invite.OrganizationID) + test.That(t, resp.Email, test.ShouldResemble, invite.Email) + test.That(t, resp.CreatedOn, test.ShouldEqual, invite.CreatedOn) + test.That(t, len(resp.Authorizations), test.ShouldEqual, len(invite.Authorizations)) + test.That(t, resp.Authorizations[0], test.ShouldResemble, invite.Authorizations[0]) + }) + + t.Run("UpdateOrganizationInviteAuthorizations", func(t *testing.T) { + grpcClient.UpdateOrganizationInviteAuthorizationsFunc = func(ctx context.Context, in *pb.UpdateOrganizationInviteAuthorizationsRequest, opts ...grpc.CallOption) (*pb.UpdateOrganizationInviteAuthorizationsResponse, error) { + test.That(t, in.OrganizationId, test.ShouldEqual, organizationID) + return &pb.UpdateOrganizationInviteAuthorizationsResponse{ + Invite: &pbInvite, + }, nil + } + resp, _ := client.UpdateOrganizationInviteAuthorizations(context.Background(), organizationID, email, authorizations, authorizations) + test.That(t, resp.OrganizationID, test.ShouldEqual, invite.OrganizationID) + test.That(t, resp.Email, test.ShouldResemble, invite.Email) + test.That(t, resp.CreatedOn, test.ShouldEqual, invite.CreatedOn) + test.That(t, len(resp.Authorizations), test.ShouldResemble, len(invite.Authorizations)) + test.That(t, resp.Authorizations[0], test.ShouldResemble, invite.Authorizations[0]) + }) + + t.Run("DeleteOrganizationMember", func(t *testing.T) { + grpcClient.DeleteOrganizationMemberFunc = func(ctx context.Context, in *pb.DeleteOrganizationMemberRequest, opts ...grpc.CallOption) (*pb.DeleteOrganizationMemberResponse, error) { + test.That(t, in.OrganizationId, test.ShouldEqual, organizationID) + test.That(t, in.UserId, test.ShouldEqual, userID) + return &pb.DeleteOrganizationMemberResponse{}, nil + } + client.DeleteOrganizationMember(context.Background(), organizationID, userID) + }) + + t.Run("DeleteOrganizationInvite", func(t *testing.T) { + grpcClient.DeleteOrganizationInviteFunc = func(ctx context.Context, in *pb.DeleteOrganizationInviteRequest, opts ...grpc.CallOption) (*pb.DeleteOrganizationInviteResponse, error) { + test.That(t, in.OrganizationId, test.ShouldEqual, organizationID) + test.That(t, in.Email, test.ShouldEqual, email) + return &pb.DeleteOrganizationInviteResponse{}, nil + } + client.DeleteOrganizationInvite(context.Background(), organizationID, email) + }) + + t.Run("ResendOrganizationInvite", func(t *testing.T) { + grpcClient.ResendOrganizationInviteFunc = func(ctx context.Context, in *pb.ResendOrganizationInviteRequest, opts ...grpc.CallOption) (*pb.ResendOrganizationInviteResponse, error) { + test.That(t, in.OrganizationId, test.ShouldEqual, organizationID) + test.That(t, in.Email, test.ShouldEqual, email) + return &pb.ResendOrganizationInviteResponse{ + Invite: &pbInvite, + }, nil + } + resp, _ := client.ResendOrganizationInvite(context.Background(), organizationID, email) + test.That(t, resp.OrganizationID, test.ShouldEqual, invite.OrganizationID) + test.That(t, resp.Email, test.ShouldResemble, invite.Email) + test.That(t, resp.CreatedOn, test.ShouldEqual, invite.CreatedOn) + test.That(t, len(resp.Authorizations), test.ShouldEqual, len(invite.Authorizations)) + test.That(t, resp.Authorizations[0], test.ShouldResemble, invite.Authorizations[0]) + }) + + t.Run("EnableBillingService", func(t *testing.T) { + grpcClient.EnableBillingServiceFunc = func(ctx context.Context, in *pb.EnableBillingServiceRequest, opts ...grpc.CallOption) (*pb.EnableBillingServiceResponse, error) { + test.That(t, in.OrgId, test.ShouldEqual, organizationID) + test.That(t, in.BillingAddress, test.ShouldResemble, &pbAddress) + return &pb.EnableBillingServiceResponse{}, nil + } + client.EnableBillingService(context.Background(), organizationID, &address) + }) + + t.Run("DisableBillingService", func(t *testing.T) { + grpcClient.DisableBillingServiceFunc = func(ctx context.Context, in *pb.DisableBillingServiceRequest, opts ...grpc.CallOption) (*pb.DisableBillingServiceResponse, error) { + test.That(t, in.OrgId, test.ShouldEqual, organizationID) + return &pb.DisableBillingServiceResponse{}, nil + } + client.DisableBillingService(context.Background(), organizationID) + }) + + t.Run("UpdateBillingService", func(t *testing.T) { + grpcClient.UpdateBillingServiceFunc = func(ctx context.Context, in *pb.UpdateBillingServiceRequest, opts ...grpc.CallOption) (*pb.UpdateBillingServiceResponse, error) { + test.That(t, in.OrgId, test.ShouldEqual, organizationID) + test.That(t, in.BillingAddress, test.ShouldResemble, &pbAddress) + test.That(t, in.BillingSupportEmail, test.ShouldResemble, email) + return &pb.UpdateBillingServiceResponse{}, nil + } + client.UpdateBillingService(context.Background(), organizationID, &address, email) + }) + + t.Run("OrganizationSetSupportEmail", func(t *testing.T) { + grpcClient.OrganizationSetSupportEmailFunc = func(ctx context.Context, in *pb.OrganizationSetSupportEmailRequest, opts ...grpc.CallOption) (*pb.OrganizationSetSupportEmailResponse, error) { + test.That(t, in.OrgId, test.ShouldEqual, organizationID) + test.That(t, in.Email, test.ShouldResemble, email) + return &pb.OrganizationSetSupportEmailResponse{}, nil + } + client.OrganizationSetSupportEmail(context.Background(), organizationID, email) + }) + + t.Run("OrganizationGetSupportEmail", func(t *testing.T) { + grpcClient.OrganizationGetSupportEmailFunc = func(ctx context.Context, in *pb.OrganizationGetSupportEmailRequest, opts ...grpc.CallOption) (*pb.OrganizationGetSupportEmailResponse, error) { + test.That(t, in.OrgId, test.ShouldEqual, organizationID) + return &pb.OrganizationGetSupportEmailResponse{ + Email: email, + }, nil + } + resp, _ := client.OrganizationGetSupportEmail(context.Background(), organizationID) + test.That(t, resp, test.ShouldEqual, email) + }) + }) +} From a97914e8e5980d4c12b134f457b4556f32b6f9ca Mon Sep 17 00:00:00 2001 From: purplenicole730 Date: Thu, 14 Nov 2024 14:41:14 -0500 Subject: [PATCH 34/75] add location tests --- app/app_client_test.go | 205 +++++++++++++++++++++++++++++++++++++++++ app/authorization.go | 12 +-- 2 files changed, 211 insertions(+), 6 deletions(-) diff --git a/app/app_client_test.go b/app/app_client_test.go index 96dcf320cac..1a0bdef9626 100644 --- a/app/app_client_test.go +++ b/app/app_client_test.go @@ -2,6 +2,7 @@ package app import ( "context" + "fmt" "testing" pb "go.viam.com/api/app/v1" @@ -23,6 +24,9 @@ const ( resourceID = "resource_id" identityID = "identity_id" identityType = "identity_type" + secretID = "secret_ids" + primary = true + robotCount = 1 ) var ( @@ -109,8 +113,74 @@ var ( City: address.City, State: address.State, } + parentLocationID = "parent_location_id" + secret = SharedSecret{ + ID: secretID, + CreatedOn: &createdOn, + State: SharedSecretStateEnabled, + } + pbSharedSecretState, _ = sharedSecretStateToProto(secret.State) + pbSecret = pb.SharedSecret{ + Id: secret.ID, + CreatedOn: secret.CreatedOn, + State: pbSharedSecretState, + } + locationAuth = LocationAuth{ + LocationID: locationID, + Secrets: []*SharedSecret{&secret}, + } + pbLocationAuth = pb.LocationAuth{ + LocationId: locationAuth.LocationID, + Secrets: []*pb.SharedSecret{&pbSecret}, + } + locationOrg = LocationOrganization{ + OrganizationID: organizationID, + Primary: primary, + } + pbLocationOrg = pb.LocationOrganization{ + OrganizationId: locationOrg.OrganizationID, + Primary: locationOrg.Primary, + } + storageConfig = StorageConfig{ + Region: region, + } + pbStorageConfig = pb.StorageConfig{ + Region: storageConfig.Region, + } + location = Location{ + ID: locationID, + Name: name, + ParentLocationID: parentLocationID, + Auth: &locationAuth, + Organizations: []*LocationOrganization{&locationOrg}, + CreatedOn: &createdOn, + RobotCount: robotCount, + Config: &storageConfig, + } + pbLocation = pb.Location{ + Id: location.ID, + Name: location.Name, + ParentLocationId: location.ParentLocationID, + Auth: &pbLocationAuth, + Organizations: []*pb.LocationOrganization{&pbLocationOrg}, + CreatedOn: location.CreatedOn, + RobotCount: location.RobotCount, + Config: &pbStorageConfig, + } ) +func sharedSecretStateToProto(state SharedSecretState) (pb.SharedSecret_State, error) { + switch state { + case SharedSecretStateUnspecified: + return pb.SharedSecret_STATE_UNSPECIFIED, nil + case SharedSecretStateEnabled: + return pb.SharedSecret_STATE_ENABLED, nil + case SharedSecretStateDisabled: + return pb.SharedSecret_STATE_DISABLED, nil + default: + return 0, fmt.Errorf("uknown secret state: %v", state) + } +} func createGrpcClient() *inject.AppServiceClient { return &inject.AppServiceClient{} @@ -389,5 +459,140 @@ func TestAppClient(t *testing.T) { resp, _ := client.OrganizationGetSupportEmail(context.Background(), organizationID) test.That(t, resp, test.ShouldEqual, email) }) + + t.Run("CreateLocation", func(t *testing.T) { + grpcClient.CreateLocationFunc = func(ctx context.Context, in *pb.CreateLocationRequest, opts ...grpc.CallOption) (*pb.CreateLocationResponse, error) { + test.That(t, in.OrganizationId, test.ShouldEqual, organizationID) + test.That(t, in.Name, test.ShouldEqual, name) + test.That(t, in.ParentLocationId, test.ShouldEqual, &parentLocationID) + return &pb.CreateLocationResponse{ + Location: &pbLocation, + }, nil + } + resp, _ := client.CreateLocation(context.Background(), organizationID, name, &parentLocationID) + test.That(t, resp.ID, test.ShouldEqual, location.ID) + test.That(t, resp.Name, test.ShouldEqual, location.Name) + test.That(t, resp.ParentLocationID, test.ShouldEqual, location.ParentLocationID) + test.That(t, resp.Auth, test.ShouldResemble, location.Auth) + test.That(t, resp.Organizations, test.ShouldResemble, location.Organizations) + test.That(t, resp.CreatedOn, test.ShouldEqual, location.CreatedOn) + test.That(t, resp.RobotCount, test.ShouldEqual, location.RobotCount) + test.That(t, resp.Config, test.ShouldResemble, location.Config) + }) + + t.Run("GetLocation", func(t *testing.T) { + grpcClient.GetLocationFunc = func(ctx context.Context, in *pb.GetLocationRequest, opts ...grpc.CallOption) (*pb.GetLocationResponse, error) { + test.That(t, in.LocationId, test.ShouldEqual, locationID) + return &pb.GetLocationResponse{ + Location: &pbLocation, + }, nil + } + resp, _ := client.GetLocation(context.Background(), locationID) + test.That(t, resp.ID, test.ShouldEqual, location.ID) + test.That(t, resp.Name, test.ShouldEqual, location.Name) + test.That(t, resp.ParentLocationID, test.ShouldEqual, location.ParentLocationID) + test.That(t, resp.Auth, test.ShouldResemble, location.Auth) + test.That(t, resp.Organizations, test.ShouldResemble, location.Organizations) + test.That(t, resp.CreatedOn, test.ShouldEqual, location.CreatedOn) + test.That(t, resp.RobotCount, test.ShouldEqual, location.RobotCount) + test.That(t, resp.Config, test.ShouldResemble, location.Config) + }) + + t.Run("UpdateLocation", func(t *testing.T) { + grpcClient.UpdateLocationFunc = func(ctx context.Context, in *pb.UpdateLocationRequest, opts ...grpc.CallOption) (*pb.UpdateLocationResponse, error) { + test.That(t, in.LocationId, test.ShouldEqual, locationID) + test.That(t, in.Name, test.ShouldEqual, &name) + test.That(t, in.ParentLocationId, test.ShouldEqual, &parentLocationID) + test.That(t, in.Region, test.ShouldEqual, ®ion) + return &pb.UpdateLocationResponse{ + Location: &pbLocation, + }, nil + } + resp, _ := client.UpdateLocation(context.Background(), locationID, &name, &parentLocationID, ®ion) + test.That(t, resp.ID, test.ShouldEqual, location.ID) + test.That(t, resp.Name, test.ShouldEqual, location.Name) + test.That(t, resp.ParentLocationID, test.ShouldEqual, location.ParentLocationID) + test.That(t, resp.Auth, test.ShouldResemble, location.Auth) + test.That(t, resp.Organizations, test.ShouldResemble, location.Organizations) + test.That(t, resp.CreatedOn, test.ShouldEqual, location.CreatedOn) + test.That(t, resp.RobotCount, test.ShouldEqual, location.RobotCount) + test.That(t, resp.Config, test.ShouldResemble, location.Config) + }) + + t.Run("DeleteLocation", func(t *testing.T) { + grpcClient.DeleteLocationFunc = func(ctx context.Context, in *pb.DeleteLocationRequest, opts ...grpc.CallOption) (*pb.DeleteLocationResponse, error) { + test.That(t, in.LocationId, test.ShouldEqual, locationID) + return &pb.DeleteLocationResponse{}, nil + } + client.DeleteLocation(context.Background(), locationID) + }) + + t.Run("ListLocations", func(t *testing.T) { + expectedLocations := []Location{location} + grpcClient.ListLocationsFunc = func(ctx context.Context, in *pb.ListLocationsRequest, opts ...grpc.CallOption) (*pb.ListLocationsResponse, error) { + test.That(t, in.OrganizationId, test.ShouldEqual, organizationID) + return &pb.ListLocationsResponse{ + Locations: []*pb.Location{&pbLocation}, + }, nil + } + resp, _ := client.ListLocations(context.Background(), organizationID) + test.That(t, len(resp), test.ShouldEqual, len(expectedLocations)) + test.That(t, resp[0].ID, test.ShouldEqual, expectedLocations[0].ID) + test.That(t, resp[0].Name, test.ShouldEqual, expectedLocations[0].Name) + test.That(t, resp[0].ParentLocationID, test.ShouldEqual, expectedLocations[0].ParentLocationID) + test.That(t, resp[0].Auth, test.ShouldResemble, expectedLocations[0].Auth) + test.That(t, resp[0].Organizations, test.ShouldResemble, expectedLocations[0].Organizations) + test.That(t, resp[0].CreatedOn, test.ShouldEqual, expectedLocations[0].CreatedOn) + test.That(t, resp[0].RobotCount, test.ShouldEqual, expectedLocations[0].RobotCount) + test.That(t, resp[0].Config, test.ShouldResemble, expectedLocations[0].Config) + }) + + t.Run("ShareLocation", func(t *testing.T) { + grpcClient.ShareLocationFunc = func(ctx context.Context, in *pb.ShareLocationRequest, opts ...grpc.CallOption) (*pb.ShareLocationResponse, error) { + test.That(t, in.LocationId, test.ShouldEqual, locationID) + test.That(t, in.OrganizationId, test.ShouldEqual, organizationID) + return &pb.ShareLocationResponse{}, nil + } + client.ShareLocation(context.Background(), locationID, organizationID) + }) + + t.Run("UnshareLocation", func(t *testing.T) { + grpcClient.UnshareLocationFunc = func(ctx context.Context, in *pb.UnshareLocationRequest, opts ...grpc.CallOption) (*pb.UnshareLocationResponse, error) { + test.That(t, in.LocationId, test.ShouldEqual, locationID) + test.That(t, in.OrganizationId, test.ShouldEqual, organizationID) + return &pb.UnshareLocationResponse{}, nil + } + client.UnshareLocation(context.Background(), locationID, organizationID) + }) + + t.Run("LocationAuth", func(t *testing.T) { + grpcClient.LocationAuthFunc = func(ctx context.Context, in *pb.LocationAuthRequest, opts ...grpc.CallOption) (*pb.LocationAuthResponse, error) { + test.That(t, in.LocationId, test.ShouldEqual, locationID) + return &pb.LocationAuthResponse{ + Auth: &pbLocationAuth, + }, nil + } + resp, _ := client.LocationAuth(context.Background(), locationID) + test.That(t, resp, test.ShouldResemble, &locationAuth) + }) + + t.Run("CreateLocationSecret", func(t *testing.T) { + grpcClient.CreateLocationSecretFunc = func(ctx context.Context, in *pb.CreateLocationSecretRequest, opts ...grpc.CallOption) (*pb.CreateLocationSecretResponse, error) { + test.That(t, in.LocationId, test.ShouldEqual, locationID) + return &pb.CreateLocationSecretResponse{ + Auth: &pbLocationAuth, + }, nil + } + resp, _ := client.CreateLocationSecret(context.Background(), locationID) + test.That(t, resp, test.ShouldResemble, &locationAuth) + }) + + t.Run("DeleteLocationSecret", func(t *testing.T) { + grpcClient.DeleteLocationSecretFunc = func(ctx context.Context, in *pb.DeleteLocationSecretRequest, opts ...grpc.CallOption) (*pb.DeleteLocationSecretResponse, error) { + test.That(t, in.LocationId, test.ShouldEqual, locationID) + test.That(t, in.SecretId, test.ShouldEqual, secretID) + return &pb.DeleteLocationSecretResponse{}, nil + } + client.DeleteLocationSecret(context.Background(), locationID, secretID) }) } diff --git a/app/authorization.go b/app/authorization.go index 5041b2e5833..9eb2aad9c7f 100644 --- a/app/authorization.go +++ b/app/authorization.go @@ -118,21 +118,21 @@ type SharedSecretState int32 const ( // SharedSecretUnspecified represents an unspecified shared secret state. - SharedSecretUnspecified SharedSecretState = 0 + SharedSecretStateUnspecified SharedSecretState = 0 // SharedSecretEnabled represents an enabled secret that can be used in authentication. - SharedSecretEnabled SharedSecretState = 1 + SharedSecretStateEnabled SharedSecretState = 1 // SharedSecretDisabled represents a disabled secret that must not be used to authenticate to rpc. - SharedSecretDisabled SharedSecretState = 2 + SharedSecretStateDisabled SharedSecretState = 2 ) func sharedSecretStateFromProto(state pb.SharedSecret_State) (SharedSecretState, error) { switch state { case pb.SharedSecret_STATE_UNSPECIFIED: - return SharedSecretUnspecified, nil + return SharedSecretStateUnspecified, nil case pb.SharedSecret_STATE_ENABLED: - return SharedSecretEnabled, nil + return SharedSecretStateEnabled, nil case pb.SharedSecret_STATE_DISABLED: - return SharedSecretDisabled, nil + return SharedSecretStateDisabled, nil default: return 0, fmt.Errorf("uknown secret state: %v", state) } From 59ff6bacd097e3844ed6580067c72b2d3113be7f Mon Sep 17 00:00:00 2001 From: purplenicole730 Date: Fri, 15 Nov 2024 18:25:06 -0500 Subject: [PATCH 35/75] add robot tests --- app/app_client.go | 116 ++-------- app/app_client_test.go | 487 +++++++++++++++++++++++++++++++++++++++-- app/authorization.go | 44 ++-- app/fragment.go | 52 ++--- app/location.go | 20 +- app/robot.go | 36 +-- 6 files changed, 545 insertions(+), 210 deletions(-) diff --git a/app/app_client.go b/app/app_client.go index b9c36d4a1e1..0f6bd153238 100644 --- a/app/app_client.go +++ b/app/app_client.go @@ -314,11 +314,7 @@ func (c *Client) CreateLocation(ctx context.Context, orgID, name string, parentL if err != nil { return nil, err } - location, err := locationFromProto(resp.Location) - if err != nil { - return nil, err - } - return location, nil + return locationFromProto(resp.Location), nil } // GetLocation gets a location. @@ -329,11 +325,7 @@ func (c *Client) GetLocation(ctx context.Context, locationID string) (*Location, if err != nil { return nil, err } - location, err := locationFromProto(resp.Location) - if err != nil { - return nil, err - } - return location, nil + return locationFromProto(resp.Location), nil } // UpdateLocation updates a location. @@ -347,11 +339,7 @@ func (c *Client) UpdateLocation(ctx context.Context, locationID string, name, pa if err != nil { return nil, err } - location, err := locationFromProto(resp.Location) - if err != nil { - return nil, err - } - return location, nil + return locationFromProto(resp.Location), nil } // DeleteLocation deletes a location. @@ -376,11 +364,7 @@ func (c *Client) ListLocations(ctx context.Context, orgID string) ([]*Location, var locations []*Location for _, location := range resp.Locations { - l, err := locationFromProto(location) - if err != nil { - return nil, err - } - locations = append(locations, l) + locations = append(locations, locationFromProto(location)) } return locations, nil } @@ -417,11 +401,7 @@ func (c *Client) LocationAuth(ctx context.Context, locationID string) (*Location if err != nil { return nil, err } - auth, err := locationAuthFromProto(resp.Auth) - if err != nil { - return nil, err - } - return auth, nil + return locationAuthFromProto(resp.Auth), nil } // CreateLocationSecret creates a new generated secret in the location. Succeeds if there are no more than 2 active secrets after creation. @@ -432,11 +412,7 @@ func (c *Client) CreateLocationSecret(ctx context.Context, locationID string) (* if err != nil { return nil, err } - auth, err := locationAuthFromProto(resp.Auth) - if err != nil { - return nil, err - } - return auth, nil + return locationAuthFromProto(resp.Auth), nil } // DeleteLocationSecret deletes a secret from the location. @@ -487,11 +463,7 @@ func (c *Client) GetRobotParts(ctx context.Context, robotID string) ([]*RobotPar } var parts []*RobotPart for _, part := range resp.Parts { - p, err := robotPartFromProto(part) - if err != nil { - return nil, err - } - parts = append(parts, p) + parts = append(parts, robotPartFromProto(part)) } return parts, nil } @@ -504,11 +476,7 @@ func (c *Client) GetRobotPart(ctx context.Context, id string) (*RobotPart, strin if err != nil { return nil, "", err } - part, err := robotPartFromProto(resp.Part) - if err != nil { - return nil, "", err - } - return part, resp.ConfigJson, nil + return robotPartFromProto(resp.Part), resp.ConfigJson, nil } // GetRobotPartLogs gets the logs associated with a robot part from a page, defaulting to the most recent page if pageToken is empty. @@ -568,11 +536,7 @@ func (c *Client) GetRobotPartHistory(ctx context.Context, id string) ([]*RobotPa } var history []*RobotPartHistoryEntry for _, entry := range resp.History { - e, err := robotPartHistoryEntryFromProto(entry) - if err != nil { - return nil, err - } - history = append(history, e) + history = append(history, robotPartHistoryEntryFromProto(entry)) } return history, nil } @@ -591,11 +555,7 @@ func (c *Client) UpdateRobotPart(ctx context.Context, id, name string, robotConf if err != nil { return nil, err } - part, err := robotPartFromProto(resp.Part) - if err != nil { - return nil, err - } - return part, nil + return robotPartFromProto(resp.Part), nil } // NewRobotPart creates a new robot part. @@ -669,11 +629,7 @@ func (c *Client) CreateRobotPartSecret(ctx context.Context, partID string) (*Rob if err != nil { return nil, err } - part, err := robotPartFromProto(resp.Part) - if err != nil { - return nil, err - } - return part, nil + return robotPartFromProto(resp.Part), nil } // DeleteRobotPartSecret deletes a secret from the robot part. @@ -745,11 +701,8 @@ func (c *Client) ListFragments( ) ([]*Fragment, error) { var visibilities []pb.FragmentVisibility for _, visibility := range fragmentVisibility { - v, err := fragmentVisibilityToProto(visibility) - if err != nil { - return nil, err - } - visibilities = append(visibilities, v) + pbFragmentVisibility := fragmentVisibilityToProto(visibility) + visibilities = append(visibilities, pbFragmentVisibility) } resp, err := c.client.ListFragments(ctx, &pb.ListFragmentsRequest{ OrganizationId: orgID, @@ -761,11 +714,7 @@ func (c *Client) ListFragments( } var fragments []*Fragment for _, fragment := range resp.Fragments { - f, err := fragmentFromProto(fragment) - if err != nil { - return nil, err - } - fragments = append(fragments, f) + fragments = append(fragments, fragmentFromProto(fragment)) } return fragments, nil } @@ -778,11 +727,7 @@ func (c *Client) GetFragment(ctx context.Context, id string) (*Fragment, error) if err != nil { return nil, err } - fragment, err := fragmentFromProto(resp.Fragment) - if err != nil { - return nil, err - } - return fragment, nil + return fragmentFromProto(resp.Fragment), nil } // CreateFragment creates a fragment. @@ -793,24 +738,17 @@ func (c *Client) CreateFragment( if err != nil { return nil, err } - v, err := fragmentVisibilityToProto(*visibility) - if err != nil { - return nil, err - } + pbFragmentVisibility := fragmentVisibilityToProto(*visibility) resp, err := c.client.CreateFragment(ctx, &pb.CreateFragmentRequest{ Name: name, Config: cfg, OrganizationId: orgID, - Visibility: &v, + Visibility: &pbFragmentVisibility, }) if err != nil { return nil, err } - fragment, err := fragmentFromProto(resp.Fragment) - if err != nil { - return nil, err - } - return fragment, nil + return fragmentFromProto(resp.Fragment), nil } // UpdateFragment updates a fragment. @@ -831,11 +769,7 @@ func (c *Client) UpdateFragment( if err != nil { return nil, err } - fragment, err := fragmentFromProto(resp.Fragment) - if err != nil { - return nil, err - } - return fragment, nil + return fragmentFromProto(resp.Fragment), nil } // DeleteFragment deletes a fragment. @@ -861,11 +795,7 @@ func (c *Client) ListMachineFragments(ctx context.Context, machineID string, add } var fragments []*Fragment for _, fragment := range resp.Fragments { - f, err := fragmentFromProto(fragment) - if err != nil { - return nil, err - } - fragments = append(fragments, f) + fragments = append(fragments, fragmentFromProto(fragment)) } return fragments, nil } @@ -884,11 +814,7 @@ func (c *Client) GetFragmentHistory( } var history []*FragmentHistoryEntry for _, entry := range resp.History { - e, err := fragmentHistoryEntryFromProto(entry) - if err != nil { - return nil, "", err - } - history = append(history, e) + history = append(history, fragmentHistoryEntryFromProto(entry)) } return history, resp.NextPageToken, nil } diff --git a/app/app_client_test.go b/app/app_client_test.go index 1a0bdef9626..06bb8c62cce 100644 --- a/app/app_client_test.go +++ b/app/app_client_test.go @@ -2,13 +2,15 @@ package app import ( "context" - "fmt" "testing" pb "go.viam.com/api/app/v1" + common "go.viam.com/api/common/v1" "go.viam.com/rdk/testutils/inject" "go.viam.com/test" + "go.viam.com/utils/protoutils" "google.golang.org/grpc" + "google.golang.org/protobuf/types/known/structpb" "google.golang.org/protobuf/types/known/timestamppb" ) @@ -27,6 +29,24 @@ const ( secretID = "secret_ids" primary = true robotCount = 1 + robotID = "robot_id" + robotLocation = "robot_location" + partID = "part_id" + dnsName = "dns_name" + secret = "secret" + mainPart = false + fqdn = "fqdn" + localFQDN = "local_fqdn" + configJSON = "configJson" + host = "host" + level = "level" + loggerName = "logger_name" + message = "message" + stack = "stack" + value = "value" + isDeactivated = false + keyID = "key_id" + key = "key" ) var ( @@ -114,24 +134,25 @@ var ( State: address.State, } parentLocationID = "parent_location_id" - secret = SharedSecret{ + sharedSecret = SharedSecret{ ID: secretID, CreatedOn: &createdOn, State: SharedSecretStateEnabled, } - pbSharedSecretState, _ = sharedSecretStateToProto(secret.State) + sharedSecrets = []*SharedSecret{&sharedSecret} pbSecret = pb.SharedSecret{ - Id: secret.ID, - CreatedOn: secret.CreatedOn, - State: pbSharedSecretState, + Id: sharedSecret.ID, + CreatedOn: sharedSecret.CreatedOn, + State: sharedSecretStateToProto(sharedSecret.State), } + pbSecrets = []*pb.SharedSecret{&pbSecret} locationAuth = LocationAuth{ LocationID: locationID, - Secrets: []*SharedSecret{&secret}, + Secrets: sharedSecrets, } pbLocationAuth = pb.LocationAuth{ LocationId: locationAuth.LocationID, - Secrets: []*pb.SharedSecret{&pbSecret}, + Secrets: pbSecrets, } locationOrg = LocationOrganization{ OrganizationID: organizationID, @@ -167,18 +188,169 @@ var ( RobotCount: location.RobotCount, Config: &pbStorageConfig, } + lastAccess = timestamppb.Timestamp{Seconds: 0, Nanos: 110} + robot = Robot{ + ID: robotID, + Name: name, + Location: robotLocation, + LastAccess: &lastAccess, + CreatedOn: &createdOn, + } + pbRobot = pb.Robot{ + Id: robot.ID, + Name: robot.Name, + Location: robot.Location, + LastAccess: robot.LastAccess, + CreatedOn: robot.CreatedOn, + } + roverRentalRobot = RoverRentalRobot{ + RobotID: robotID, + LocationID: locationID, + RobotName: name, + RobotMainPartID: partID, + } + lastUpdated = timestamppb.Timestamp{Seconds: 0, Nanos: 130} + robotConfig = map[string]interface{}{"name": name, "ID": robotID} + pbRobotConfig, _ = protoutils.StructToStructPb(*robotPart.RobotConfig) + pbUserSuppliedInfo, _ = protoutils.StructToStructPb(*robotPart.UserSuppliedInfo) + userSuppliedInfo = map[string]interface{}{"userID": userID} + robotPart = RobotPart{ + ID: partID, + Name: name, + DNSName: dnsName, + Secret: secret, + Robot: robotID, + LocationID: locationID, + RobotConfig: &robotConfig, + LastAccess: &lastAccess, + UserSuppliedInfo: &userSuppliedInfo, + MainPart: mainPart, + FQDN: fqdn, + LocalFQDN: localFQDN, + CreatedOn: &createdOn, + Secrets: sharedSecrets, + LastUpdated: &lastUpdated, + } + pbRobotPart = pb.RobotPart{ + Id: robotPart.ID, + Name: robotPart.Name, + DnsName: robotPart.DNSName, + Secret: robotPart.Secret, + Robot: robotPart.Robot, + LocationId: robotPart.LocationID, + RobotConfig: pbRobotConfig, + LastAccess: robotPart.LastAccess, + UserSuppliedInfo: pbUserSuppliedInfo, + MainPart: robotPart.MainPart, + Fqdn: robotPart.FQDN, + LocalFqdn: robotPart.LocalFQDN, + CreatedOn: robotPart.CreatedOn, + Secrets: pbSecrets, + LastUpdated: robotPart.LastUpdated, + } + pageToken = "page_token" + levels = []string{level} + start = timestamppb.Timestamp{Seconds: 92, Nanos: 0} + end = timestamppb.Timestamp{Seconds: 99, Nanos: 999} + limit int64 = 2 + source = "source" + filter = "filter" + time = timestamppb.Timestamp{Seconds: 11, Nanos: 15} + caller = map[string]interface{}{"name": name} + pbCaller, _ = protoutils.StructToStructPb(*logEntry.Caller) + field = map[string]interface{}{"key": "value"} + pbField, _ = protoutils.StructToStructPb(field) + logEntry = LogEntry{ + Host: host, + Level: level, + Time: &time, + LoggerName: loggerName, + Message: message, + Caller: &caller, + Stack: stack, + Fields: []*map[string]interface{}{&field}, + } + pbLogEntry = common.LogEntry{ + Host: logEntry.Host, + Level: logEntry.Level, + Time: logEntry.Time, + LoggerName: logEntry.LoggerName, + Message: logEntry.Message, + Caller: pbCaller, + Stack: logEntry.Stack, + Fields: []*structpb.Struct{pbField}, + } + authenticatorInfo = AuthenticatorInfo{ + Type: AuthenticationTypeAPIKey, + Value: value, + IsDeactivated: isDeactivated, + } + robotPartHistoryEntry = RobotPartHistoryEntry{ + Part: partID, + Robot: robotID, + When: &time, + Old: &robotPart, + EditedBy: &authenticatorInfo, + } + apiKey = APIKey{ + ID: keyID, + Key: key, + Name: name, + CreatedOn: &createdOn, + } + authorizationDetails = AuthorizationDetails{ + AuthorizationType: authorizationType, + AuthorizationID: authorizationID, + ResourceType: resourceType, + ResourceID: resourceID, + OrgID: organizationID, + } + apiKeyWithAuthorizations = APIKeyWithAuthorizations{ + APIKey: &apiKey, + Authorizations: []*AuthorizationDetails{&authorizationDetails}, + } + pbAPIKeyWithAuthorizations = pb.APIKeyWithAuthorizations{ + ApiKey: &pb.APIKey{ + Id: apiKey.ID, + Key: apiKey.Key, + Name: apiKey.Name, + CreatedOn: apiKey.CreatedOn, + }, + Authorizations: []*pb.AuthorizationDetails{ + &pb.AuthorizationDetails{ + AuthorizationType: authorizationDetails.AuthorizationType, + AuthorizationId: authorizationDetails.AuthorizationID, + ResourceType: authorizationDetails.ResourceType, + ResourceId: authorizationDetails.ResourceID, + OrgId: authorizationDetails.OrgID, + }, + }, + } ) -func sharedSecretStateToProto(state SharedSecretState) (pb.SharedSecret_State, error) { +func sharedSecretStateToProto(state SharedSecretState) pb.SharedSecret_State { switch state { - case SharedSecretStateUnspecified: - return pb.SharedSecret_STATE_UNSPECIFIED, nil case SharedSecretStateEnabled: - return pb.SharedSecret_STATE_ENABLED, nil + return pb.SharedSecret_STATE_ENABLED case SharedSecretStateDisabled: - return pb.SharedSecret_STATE_DISABLED, nil + return pb.SharedSecret_STATE_DISABLED default: - return 0, fmt.Errorf("uknown secret state: %v", state) + return pb.SharedSecret_STATE_UNSPECIFIED + } +} + +func authenticationTypeToProto(authType AuthenticationType) pb.AuthenticationType { + switch authType { + case AuthenticationTypeWebOAuth: + return pb.AuthenticationType_AUTHENTICATION_TYPE_WEB_OAUTH + case AuthenticationTypeAPIKey: + return pb.AuthenticationType_AUTHENTICATION_TYPE_API_KEY + case AuthenticationTypeRobotPartSecret: + return pb.AuthenticationType_AUTHENTICATION_TYPE_ROBOT_PART_SECRET + case AuthenticationTypeLocationSecret: + return pb.AuthenticationType_AUTHENTICATION_TYPE_LOCATION_SECRET + default: + return pb.AuthenticationType_AUTHENTICATION_TYPE_UNSPECIFIED } } @@ -595,4 +767,291 @@ func TestAppClient(t *testing.T) { } client.DeleteLocationSecret(context.Background(), locationID, secretID) }) + + t.Run("GetRobot", func(t *testing.T) { + grpcClient.GetRobotFunc = func(ctx context.Context, in *pb.GetRobotRequest, opts ...grpc.CallOption) (*pb.GetRobotResponse, error) { + test.That(t, in.Id, test.ShouldEqual, robotID) + return &pb.GetRobotResponse{ + Robot: &pbRobot, + }, nil + } + resp, _ := client.GetRobot(context.Background(), robotID) + test.That(t, resp, test.ShouldResemble, &robot) + }) + + t.Run("GetRoverRentalRobots", func(t *testing.T) { + expectedRobots := []RoverRentalRobot{roverRentalRobot} + pbRobot := pb.RoverRentalRobot{ + RobotId: roverRentalRobot.RobotID, + LocationId: roverRentalRobot.LocationID, + RobotName: roverRentalRobot.RobotName, + RobotMainPartId: partID, + } + grpcClient.GetRoverRentalRobotsFunc = func(ctx context.Context, in *pb.GetRoverRentalRobotsRequest, opts ...grpc.CallOption) (*pb.GetRoverRentalRobotsResponse, error) { + test.That(t, in.OrgId, test.ShouldEqual, organizationID) + return &pb.GetRoverRentalRobotsResponse{ + Robots: []*pb.RoverRentalRobot{&pbRobot}, + }, nil + } + resp, _ := client.GetRoverRentalRobots(context.Background(), organizationID) + test.That(t, len(resp), test.ShouldEqual, len(expectedRobots)) + test.That(t, resp[0], test.ShouldResemble, &expectedRobots[0]) + }) + + t.Run("GetRobotParts", func(t *testing.T) { + expectedRobotParts := []RobotPart{robotPart} + grpcClient.GetRobotPartsFunc = func(ctx context.Context, in *pb.GetRobotPartsRequest, opts ...grpc.CallOption) (*pb.GetRobotPartsResponse, error) { + test.That(t, in.RobotId, test.ShouldEqual, robotID) + return &pb.GetRobotPartsResponse{ + Parts: []*pb.RobotPart{&pbRobotPart}, + }, nil + } + resp, _ := client.GetRobotParts(context.Background(), robotID) + test.That(t, len(resp), test.ShouldEqual, len(expectedRobotParts)) + test.That(t, resp[0].ID, test.ShouldEqual, expectedRobotParts[0].ID) + test.That(t, resp[0].Name, test.ShouldEqual, expectedRobotParts[0].Name) + test.That(t, resp[0].DNSName, test.ShouldEqual, expectedRobotParts[0].DNSName) + test.That(t, resp[0].Secret, test.ShouldEqual, expectedRobotParts[0].Secret) + test.That(t, resp[0].Robot, test.ShouldEqual, expectedRobotParts[0].Robot) + test.That(t, resp[0].LocationID, test.ShouldEqual, expectedRobotParts[0].LocationID) + test.That(t, resp[0].RobotConfig, test.ShouldResemble, expectedRobotParts[0].RobotConfig) + test.That(t, resp[0].LastAccess, test.ShouldEqual, expectedRobotParts[0].LastAccess) + test.That(t, resp[0].UserSuppliedInfo, test.ShouldResemble, expectedRobotParts[0].UserSuppliedInfo) + test.That(t, resp[0].MainPart, test.ShouldEqual, expectedRobotParts[0].MainPart) + test.That(t, resp[0].FQDN, test.ShouldEqual, expectedRobotParts[0].FQDN) + test.That(t, resp[0].LocalFQDN, test.ShouldEqual, expectedRobotParts[0].LocalFQDN) + }) + + t.Run("GetRobotPart", func(t *testing.T) { + grpcClient.GetRobotPartFunc = func(ctx context.Context, in *pb.GetRobotPartRequest, opts ...grpc.CallOption) (*pb.GetRobotPartResponse, error) { + test.That(t, in.Id, test.ShouldEqual, partID) + return &pb.GetRobotPartResponse{ + Part: &pbRobotPart, + ConfigJson: configJSON, + }, nil + } + part, json, _ := client.GetRobotPart(context.Background(), partID) + test.That(t, json, test.ShouldEqual, configJSON) + test.That(t, part.Name, test.ShouldEqual, robotPart.Name) + test.That(t, part.DNSName, test.ShouldEqual, robotPart.DNSName) + test.That(t, part.Secret, test.ShouldEqual, robotPart.Secret) + test.That(t, part.Robot, test.ShouldEqual, robotPart.Robot) + test.That(t, part.LocationID, test.ShouldEqual, robotPart.LocationID) + test.That(t, part.RobotConfig, test.ShouldResemble, robotPart.RobotConfig) + test.That(t, part.LastAccess, test.ShouldEqual, robotPart.LastAccess) + test.That(t, part.UserSuppliedInfo, test.ShouldResemble, robotPart.UserSuppliedInfo) + test.That(t, part.MainPart, test.ShouldEqual, robotPart.MainPart) + test.That(t, part.FQDN, test.ShouldEqual, robotPart.FQDN) + test.That(t, part.LocalFQDN, test.ShouldEqual, robotPart.LocalFQDN) + }) + + t.Run("GetRobotPartLogs", func(t *testing.T) { + expectedLogs := []*LogEntry{&logEntry} + grpcClient.GetRobotPartLogsFunc = func(ctx context.Context, in *pb.GetRobotPartLogsRequest, opts ...grpc.CallOption) (*pb.GetRobotPartLogsResponse, error) { + test.That(t, in.Id, test.ShouldEqual, partID) + test.That(t, in.Filter, test.ShouldEqual, &filter) + test.That(t, in.PageToken, test.ShouldEqual, &pageToken) + test.That(t, in.Levels, test.ShouldResemble, levels) + test.That(t, in.Start, test.ShouldEqual, &start) + test.That(t, in.End, test.ShouldEqual, &end) + test.That(t, in.Limit, test.ShouldEqual, &limit) + test.That(t, in.Source, test.ShouldEqual, &source) + return &pb.GetRobotPartLogsResponse{ + Logs: []*common.LogEntry{&pbLogEntry}, + NextPageToken: pageToken, + }, nil + } + logs, token, _ := client.GetRobotPartLogs(context.Background(), partID, &filter, &pageToken, levels, &start, &end, &limit, &source) + test.That(t, token, test.ShouldEqual, pageToken) + test.That(t, len(logs), test.ShouldEqual, len(expectedLogs)) + test.That(t, logs[0].Host, test.ShouldEqual, expectedLogs[0].Host) + test.That(t, logs[0].Level, test.ShouldEqual, expectedLogs[0].Level) + test.That(t, logs[0].Time, test.ShouldEqual, expectedLogs[0].Time) + test.That(t, logs[0].LoggerName, test.ShouldEqual, expectedLogs[0].LoggerName) + test.That(t, logs[0].Message, test.ShouldEqual, expectedLogs[0].Message) + test.That(t, logs[0].Caller, test.ShouldResemble, expectedLogs[0].Caller) + test.That(t, logs[0].Stack, test.ShouldEqual, expectedLogs[0].Stack) + test.That(t, len(logs[0].Fields), test.ShouldEqual, len(expectedLogs[0].Fields)) + test.That(t, logs[0].Fields[0], test.ShouldResemble, expectedLogs[0].Fields[0]) + }) + + t.Run("GetRobotPartHistory", func(t *testing.T) { + expectedEntries := []*RobotPartHistoryEntry{&robotPartHistoryEntry} + pbAuthenticatorInfo := pb.AuthenticatorInfo{ + Type: authenticationTypeToProto(authenticatorInfo.Type), + Value: authenticatorInfo.Value, + IsDeactivated: authenticatorInfo.IsDeactivated, + } + pbRobotPartHistoryEntry := pb.RobotPartHistoryEntry{ + Part: robotPartHistoryEntry.Part, + Robot: robotPartHistoryEntry.Robot, + When: robotPartHistoryEntry.When, + Old: &pbRobotPart, + EditedBy: &pbAuthenticatorInfo, + } + grpcClient.GetRobotPartHistoryFunc = func(ctx context.Context, in *pb.GetRobotPartHistoryRequest, opts ...grpc.CallOption) (*pb.GetRobotPartHistoryResponse, error) { + test.That(t, in.Id, test.ShouldEqual, partID) + return &pb.GetRobotPartHistoryResponse{ + History: []*pb.RobotPartHistoryEntry{&pbRobotPartHistoryEntry}, + }, nil + } + resp, _ := client.GetRobotPartHistory(context.Background(), partID) + test.That(t, resp[0].Part, test.ShouldEqual, expectedEntries[0].Part) + test.That(t, resp[0].Robot, test.ShouldEqual, expectedEntries[0].Robot) + test.That(t, resp[0].When , test.ShouldEqual, expectedEntries[0].When) + test.That(t, resp[0].Old.Name, test.ShouldEqual, expectedEntries[0].Old.Name) + test.That(t, resp[0].Old.DNSName, test.ShouldEqual, expectedEntries[0].Old.DNSName) + test.That(t, resp[0].Old.Secret, test.ShouldEqual, expectedEntries[0].Old.Secret) + test.That(t, resp[0].Old.Robot, test.ShouldEqual, expectedEntries[0].Old.Robot) + test.That(t, resp[0].Old.LocationID, test.ShouldEqual, expectedEntries[0].Old.LocationID) + test.That(t, resp[0].Old.RobotConfig, test.ShouldResemble, expectedEntries[0].Old.RobotConfig) + test.That(t, resp[0].Old.LastAccess, test.ShouldEqual, expectedEntries[0].Old.LastAccess) + test.That(t, resp[0].Old.UserSuppliedInfo, test.ShouldResemble, expectedEntries[0].Old.UserSuppliedInfo) + test.That(t, resp[0].Old.MainPart, test.ShouldEqual, expectedEntries[0].Old.MainPart) + test.That(t, resp[0].Old.FQDN, test.ShouldEqual, expectedEntries[0].Old.FQDN) + test.That(t, resp[0].Old.LocalFQDN, test.ShouldEqual, expectedEntries[0].Old.LocalFQDN) + test.That(t, resp[0].Old.Name, test.ShouldEqual, expectedEntries[0].Old.Name) + test.That(t, resp[0].Old.Name, test.ShouldEqual, expectedEntries[0].Old.Name) + test.That(t, resp[0].Old.Name, test.ShouldEqual, expectedEntries[0].Old.Name) + test.That(t, resp[0].EditedBy, test.ShouldResemble, expectedEntries[0].EditedBy) + }) + + t.Run("UpdateRobotPart", func(t *testing.T) { + grpcClient.UpdateRobotPartFunc = func(ctx context.Context, in *pb.UpdateRobotPartRequest, opts ...grpc.CallOption) (*pb.UpdateRobotPartResponse, error) { + test.That(t, in.Id, test.ShouldEqual, partID) + test.That(t, in.Name, test.ShouldEqual, name) + test.That(t, in.RobotConfig, test.ShouldResemble, pbRobotConfig) + return &pb.UpdateRobotPartResponse{ + Part: &pbRobotPart, + }, nil + } + part, _ := client.UpdateRobotPart(context.Background(), partID, name, robotConfig) + test.That(t, part.Name, test.ShouldEqual, robotPart.Name) + test.That(t, part.DNSName, test.ShouldEqual, robotPart.DNSName) + test.That(t, part.Secret, test.ShouldEqual, robotPart.Secret) + test.That(t, part.Robot, test.ShouldEqual, robotPart.Robot) + test.That(t, part.LocationID, test.ShouldEqual, robotPart.LocationID) + test.That(t, part.RobotConfig, test.ShouldResemble, robotPart.RobotConfig) + test.That(t, part.LastAccess, test.ShouldEqual, robotPart.LastAccess) + test.That(t, part.UserSuppliedInfo, test.ShouldResemble, robotPart.UserSuppliedInfo) + test.That(t, part.MainPart, test.ShouldEqual, robotPart.MainPart) + test.That(t, part.FQDN, test.ShouldEqual, robotPart.FQDN) + test.That(t, part.LocalFQDN, test.ShouldEqual, robotPart.LocalFQDN) + }) + + t.Run("NewRobotPart", func(t *testing.T) { + grpcClient.NewRobotPartFunc = func(ctx context.Context, in *pb.NewRobotPartRequest, opts ...grpc.CallOption) (*pb.NewRobotPartResponse, error) { + test.That(t, in.RobotId, test.ShouldEqual, robotID) + test.That(t, in.PartName, test.ShouldEqual, name) + return &pb.NewRobotPartResponse{}, nil + } + client.NewRobotPart(context.Background(), robotID, name) + }) + + t.Run("DeleteRobotPart", func(t *testing.T) { + grpcClient.DeleteRobotPartFunc = func(ctx context.Context, in *pb.DeleteRobotPartRequest, opts ...grpc.CallOption) (*pb.DeleteRobotPartResponse, error) { + test.That(t, in.PartId, test.ShouldEqual, partID) + return &pb.DeleteRobotPartResponse{}, nil + } + client.DeleteRobotPart(context.Background(), partID) + }) + + t.Run("GetRobotAPIKeys", func(t *testing.T) { + expectedAPIKeyWithAuthorizations := []APIKeyWithAuthorizations{apiKeyWithAuthorizations} + grpcClient.GetRobotAPIKeysFunc = func(ctx context.Context, in *pb.GetRobotAPIKeysRequest, opts ...grpc.CallOption) (*pb.GetRobotAPIKeysResponse, error) { + test.That(t, in.RobotId, test.ShouldEqual, robotID) + return &pb.GetRobotAPIKeysResponse{ + ApiKeys: []*pb.APIKeyWithAuthorizations{&pbAPIKeyWithAuthorizations}, + }, nil + } + resp, _ := client.GetRobotAPIKeys(context.Background(), robotID) + test.That(t, len(resp), test.ShouldEqual, len(expectedAPIKeyWithAuthorizations)) + test.That(t, resp[0].APIKey, test.ShouldResemble, expectedAPIKeyWithAuthorizations[0].APIKey) + test.That(t, resp[0].Authorizations, test.ShouldResemble, expectedAPIKeyWithAuthorizations[0].Authorizations) + }) + + t.Run("MarkPartForRestart", func(t *testing.T) { + grpcClient.MarkPartForRestartFunc = func(ctx context.Context, in *pb.MarkPartForRestartRequest, opts ...grpc.CallOption) (*pb.MarkPartForRestartResponse, error) { + test.That(t, in.PartId, test.ShouldEqual, partID) + return &pb.MarkPartForRestartResponse{}, nil + } + client.MarkPartForRestart(context.Background(), partID) + }) + + t.Run("CreateRobotPartSecret", func(t *testing.T) { + grpcClient.CreateRobotPartSecretFunc = func(ctx context.Context, in *pb.CreateRobotPartSecretRequest, opts ...grpc.CallOption) (*pb.CreateRobotPartSecretResponse, error) { + test.That(t, in.PartId, test.ShouldEqual, partID) + return &pb.CreateRobotPartSecretResponse{ + Part: &pbRobotPart, + }, nil + } + part, _ := client.CreateRobotPartSecret(context.Background(), partID) + test.That(t, part.Name, test.ShouldEqual, robotPart.Name) + test.That(t, part.DNSName, test.ShouldEqual, robotPart.DNSName) + test.That(t, part.Secret, test.ShouldEqual, robotPart.Secret) + test.That(t, part.Robot, test.ShouldEqual, robotPart.Robot) + test.That(t, part.LocationID, test.ShouldEqual, robotPart.LocationID) + test.That(t, part.RobotConfig, test.ShouldResemble, robotPart.RobotConfig) + test.That(t, part.LastAccess, test.ShouldEqual, robotPart.LastAccess) + test.That(t, part.UserSuppliedInfo, test.ShouldResemble, robotPart.UserSuppliedInfo) + test.That(t, part.MainPart, test.ShouldEqual, robotPart.MainPart) + test.That(t, part.FQDN, test.ShouldEqual, robotPart.FQDN) + test.That(t, part.LocalFQDN, test.ShouldEqual, robotPart.LocalFQDN) + }) + + t.Run("DeleteRobotPartSecret", func(t *testing.T) { + grpcClient.DeleteRobotPartSecretFunc = func(ctx context.Context, in *pb.DeleteRobotPartSecretRequest, opts ...grpc.CallOption) (*pb.DeleteRobotPartSecretResponse, error) { + test.That(t, in.PartId, test.ShouldEqual, partID) + test.That(t, in.SecretId, test.ShouldEqual, secretID) + return &pb.DeleteRobotPartSecretResponse{}, nil + } + client.DeleteRobotPartSecret(context.Background(), partID, secretID) + }) + + t.Run("ListRobots", func(t *testing.T) { + expectedRobots := []*Robot{&robot} + grpcClient.ListRobotsFunc = func(ctx context.Context, in *pb.ListRobotsRequest, opts ...grpc.CallOption) (*pb.ListRobotsResponse, error) { + test.That(t, in.LocationId, test.ShouldEqual, locationID) + return &pb.ListRobotsResponse{ + Robots: []*pb.Robot{&pbRobot}, + }, nil + } + resp, _ := client.ListRobots(context.Background(), locationID) + test.That(t, len(resp), test.ShouldEqual, len(expectedRobots)) + test.That(t, resp[0], test.ShouldResemble, expectedRobots[0]) + }) + + t.Run("NewRobot", func(t *testing.T) { + grpcClient.NewRobotFunc = func(ctx context.Context, in *pb.NewRobotRequest, opts ...grpc.CallOption) (*pb.NewRobotResponse, error) { + test.That(t, in.Name, test.ShouldEqual, name) + test.That(t, in.Location, test.ShouldEqual, locationID) + return &pb.NewRobotResponse{ + Id: robotID, + }, nil + } + resp, _ := client.NewRobot(context.Background(), name, locationID) + test.That(t, resp, test.ShouldResemble, robotID) + }) + + + t.Run("UpdateRobot", func(t *testing.T) { + grpcClient.UpdateRobotFunc = func(ctx context.Context, in *pb.UpdateRobotRequest, opts ...grpc.CallOption) (*pb.UpdateRobotResponse, error) { + test.That(t, in.Id, test.ShouldEqual, robotID) + test.That(t, in.Name, test.ShouldEqual, name) + test.That(t, in.Location, test.ShouldEqual, locationID) + return &pb.UpdateRobotResponse{ + Robot: &pbRobot, + }, nil + } + resp, _ := client.UpdateRobot(context.Background(), robotID, name, locationID) + test.That(t, resp, test.ShouldResemble, &robot) + }) + + t.Run("DeleteRobot", func(t *testing.T) { + grpcClient.DeleteRobotFunc = func(ctx context.Context, in *pb.DeleteRobotRequest, opts ...grpc.CallOption) (*pb.DeleteRobotResponse, error) { + test.That(t, in.Id, test.ShouldEqual, robotID) + return &pb.DeleteRobotResponse{}, nil + } + client.DeleteRobot(context.Background(), robotID) + }) } diff --git a/app/authorization.go b/app/authorization.go index 9eb2aad9c7f..b7c2242f00a 100644 --- a/app/authorization.go +++ b/app/authorization.go @@ -101,16 +101,12 @@ type SharedSecret struct { State SharedSecretState } -func sharedSecretFromProto(sharedSecret *pb.SharedSecret) (*SharedSecret, error) { - state, err := sharedSecretStateFromProto(sharedSecret.State) - if err != nil { - return nil, err - } +func sharedSecretFromProto(sharedSecret *pb.SharedSecret) *SharedSecret { return &SharedSecret{ ID: sharedSecret.Id, CreatedOn: sharedSecret.CreatedOn, - State: state, - }, nil + State: sharedSecretStateFromProto(sharedSecret.State), + } } // SharedSecretState specifies if the secret is enabled, disabled, or unspecified. @@ -125,16 +121,14 @@ const ( SharedSecretStateDisabled SharedSecretState = 2 ) -func sharedSecretStateFromProto(state pb.SharedSecret_State) (SharedSecretState, error) { +func sharedSecretStateFromProto(state pb.SharedSecret_State) SharedSecretState { switch state { - case pb.SharedSecret_STATE_UNSPECIFIED: - return SharedSecretStateUnspecified, nil case pb.SharedSecret_STATE_ENABLED: - return SharedSecretStateEnabled, nil + return SharedSecretStateEnabled case pb.SharedSecret_STATE_DISABLED: - return SharedSecretStateDisabled, nil + return SharedSecretStateDisabled default: - return 0, fmt.Errorf("uknown secret state: %v", state) + return SharedSecretStateUnspecified } } @@ -145,16 +139,12 @@ type AuthenticatorInfo struct { IsDeactivated bool } -func authenticatorInfoFromProto(info *pb.AuthenticatorInfo) (*AuthenticatorInfo, error) { - authenticationType, err := authenticationTypeFromProto(info.Type) - if err != nil { - return nil, err - } +func authenticatorInfoFromProto(info *pb.AuthenticatorInfo) *AuthenticatorInfo { return &AuthenticatorInfo{ - Type: authenticationType, + Type: authenticationTypeFromProto(info.Type), Value: info.Value, IsDeactivated: info.IsDeactivated, - }, nil + } } // AuthenticationType specifies the type of authentication. @@ -173,20 +163,18 @@ const ( AuthenticationTypeLocationSecret AuthenticationType = 4 ) -func authenticationTypeFromProto(authenticationType pb.AuthenticationType) (AuthenticationType, error) { +func authenticationTypeFromProto(authenticationType pb.AuthenticationType) AuthenticationType { switch authenticationType { - case pb.AuthenticationType_AUTHENTICATION_TYPE_UNSPECIFIED: - return AuthenticationTypeUnspecified, nil case pb.AuthenticationType_AUTHENTICATION_TYPE_WEB_OAUTH: - return AuthenticationTypeWebOAuth, nil + return AuthenticationTypeWebOAuth case pb.AuthenticationType_AUTHENTICATION_TYPE_API_KEY: - return AuthenticationTypeAPIKey, nil + return AuthenticationTypeAPIKey case pb.AuthenticationType_AUTHENTICATION_TYPE_ROBOT_PART_SECRET: - return AuthenticationTypeRobotPartSecret, nil + return AuthenticationTypeRobotPartSecret case pb.AuthenticationType_AUTHENTICATION_TYPE_LOCATION_SECRET: - return AuthenticationTypeLocationSecret, nil + return AuthenticationTypeLocationSecret default: - return 0, fmt.Errorf("uknown authentication type: %v", authenticationType) + return AuthenticationTypeUnspecified } } diff --git a/app/fragment.go b/app/fragment.go index 6c10c4ffa3f..9fa63c182a7 100644 --- a/app/fragment.go +++ b/app/fragment.go @@ -1,8 +1,6 @@ package app import ( - "fmt" - pb "go.viam.com/api/app/v1" "google.golang.org/protobuf/types/known/timestamppb" ) @@ -23,12 +21,8 @@ type Fragment struct { LastUpdated *timestamppb.Timestamp } -func fragmentFromProto(fragment *pb.Fragment) (*Fragment, error) { +func fragmentFromProto(fragment *pb.Fragment) (*Fragment) { f := fragment.Fragment.AsMap() - visibility, err := fragmentVisibilityFromProto(fragment.Visibility) - if err != nil { - return nil, err - } return &Fragment{ ID: fragment.Id, Name: fragment.Name, @@ -40,9 +34,9 @@ func fragmentFromProto(fragment *pb.Fragment) (*Fragment, error) { RobotPartCount: fragment.RobotPartCount, OrganizationCount: fragment.OrganizationCount, OnlyUsedByOwner: fragment.OnlyUsedByOwner, - Visibility: visibility, + Visibility: fragmentVisibilityFromProto(fragment.Visibility), LastUpdated: fragment.LastUpdated, - }, nil + } } // FragmentVisibility specifies the kind of visibility a fragment has. @@ -59,33 +53,29 @@ const ( FragmentVisibilityPublicUnlisted FragmentVisibility = 3 ) -func fragmentVisibilityFromProto(visibility pb.FragmentVisibility) (FragmentVisibility, error) { +func fragmentVisibilityFromProto(visibility pb.FragmentVisibility) FragmentVisibility { switch visibility { - case pb.FragmentVisibility_FRAGMENT_VISIBILITY_UNSPECIFIED: - return FragmentVisibilityUnspecified, nil case pb.FragmentVisibility_FRAGMENT_VISIBILITY_PRIVATE: - return FragmentVisibilityPrivate, nil + return FragmentVisibilityPrivate case pb.FragmentVisibility_FRAGMENT_VISIBILITY_PUBLIC: - return FragmentVisibilityPublic, nil + return FragmentVisibilityPublic case pb.FragmentVisibility_FRAGMENT_VISIBILITY_PUBLIC_UNLISTED: - return FragmentVisibilityPublicUnlisted, nil + return FragmentVisibilityPublicUnlisted default: - return 0, fmt.Errorf("uknown fragment visibililty: %v", visibility) + return FragmentVisibilityUnspecified } } -func fragmentVisibilityToProto(visibility FragmentVisibility) (pb.FragmentVisibility, error) { +func fragmentVisibilityToProto(visibility FragmentVisibility) (pb.FragmentVisibility) { switch visibility { - case FragmentVisibilityUnspecified: - return pb.FragmentVisibility_FRAGMENT_VISIBILITY_UNSPECIFIED, nil case FragmentVisibilityPrivate: - return pb.FragmentVisibility_FRAGMENT_VISIBILITY_PRIVATE, nil + return pb.FragmentVisibility_FRAGMENT_VISIBILITY_PRIVATE case FragmentVisibilityPublic: - return pb.FragmentVisibility_FRAGMENT_VISIBILITY_PUBLIC, nil + return pb.FragmentVisibility_FRAGMENT_VISIBILITY_PUBLIC case FragmentVisibilityPublicUnlisted: - return pb.FragmentVisibility_FRAGMENT_VISIBILITY_PUBLIC_UNLISTED, nil + return pb.FragmentVisibility_FRAGMENT_VISIBILITY_PUBLIC_UNLISTED default: - return 0, fmt.Errorf("unknown fragment visibility: %v", visibility) + return pb.FragmentVisibility_FRAGMENT_VISIBILITY_UNSPECIFIED } } @@ -97,19 +87,11 @@ type FragmentHistoryEntry struct { EditedBy *AuthenticatorInfo } -func fragmentHistoryEntryFromProto(entry *pb.FragmentHistoryEntry) (*FragmentHistoryEntry, error) { - old, err := fragmentFromProto(entry.Old) - if err != nil { - return nil, err - } - editedBy, err := authenticatorInfoFromProto(entry.EditedBy) - if err != nil { - return nil, err - } +func fragmentHistoryEntryFromProto(entry *pb.FragmentHistoryEntry) (*FragmentHistoryEntry) { return &FragmentHistoryEntry{ Fragment: entry.Fragment, EditedOn: entry.EditedOn, - Old: old, - EditedBy: editedBy, - }, nil + Old: fragmentFromProto(entry.Old), + EditedBy: authenticatorInfoFromProto(entry.EditedBy), + } } diff --git a/app/location.go b/app/location.go index f750389b700..3dfd89f56e3 100644 --- a/app/location.go +++ b/app/location.go @@ -17,25 +17,21 @@ type Location struct { Config *StorageConfig } -func locationFromProto(location *pb.Location) (*Location, error) { +func locationFromProto(location *pb.Location) *Location { var organizations []*LocationOrganization for _, organization := range location.Organizations { organizations = append(organizations, locationOrganizationFromProto(organization)) } - auth, err := locationAuthFromProto(location.Auth) - if err != nil { - return nil, err - } return &Location{ ID: location.Id, Name: location.Name, ParentLocationID: location.ParentLocationId, - Auth: auth, + Auth: locationAuthFromProto(location.Auth), Organizations: organizations, CreatedOn: location.CreatedOn, RobotCount: location.RobotCount, Config: storageConfigFromProto(location.Config), - }, nil + } } // LocationOrganization holds information of an organization the location is shared with. @@ -66,17 +62,13 @@ type LocationAuth struct { Secrets []*SharedSecret } -func locationAuthFromProto(locationAuth *pb.LocationAuth) (*LocationAuth, error) { +func locationAuthFromProto(locationAuth *pb.LocationAuth) *LocationAuth { var secrets []*SharedSecret for _, secret := range locationAuth.Secrets { - s, err := sharedSecretFromProto(secret) - if err != nil { - return nil, err - } - secrets = append(secrets, s) + secrets = append(secrets, sharedSecretFromProto(secret)) } return &LocationAuth{ LocationID: locationAuth.LocationId, Secrets: secrets, - }, nil + } } diff --git a/app/robot.go b/app/robot.go index e657498c564..b2a1f728528 100644 --- a/app/robot.go +++ b/app/robot.go @@ -53,21 +53,17 @@ type RobotPart struct { LastAccess *timestamppb.Timestamp UserSuppliedInfo *map[string]interface{} MainPart bool - Fqdn string - LocalFqdn string + FQDN string + LocalFQDN string CreatedOn *timestamppb.Timestamp Secrets []*SharedSecret LastUpdated *timestamppb.Timestamp } -func robotPartFromProto(robotPart *pb.RobotPart) (*RobotPart, error) { +func robotPartFromProto(robotPart *pb.RobotPart) *RobotPart { var secrets []*SharedSecret for _, secret := range robotPart.Secrets { - s, err := sharedSecretFromProto(secret) - if err != nil { - return nil, err - } - secrets = append(secrets, s) + secrets = append(secrets, sharedSecretFromProto(secret)) } cfg := robotPart.RobotConfig.AsMap() info := robotPart.UserSuppliedInfo.AsMap() @@ -76,18 +72,18 @@ func robotPartFromProto(robotPart *pb.RobotPart) (*RobotPart, error) { Name: robotPart.Name, DNSName: robotPart.DnsName, Secret: robotPart.Secret, - Robot: robotPart.DnsName, + Robot: robotPart.Robot, LocationID: robotPart.LocationId, RobotConfig: &cfg, LastAccess: robotPart.LastAccess, UserSuppliedInfo: &info, MainPart: robotPart.MainPart, - Fqdn: robotPart.Fqdn, - LocalFqdn: robotPart.LocalFqdn, + FQDN: robotPart.Fqdn, + LocalFQDN: robotPart.LocalFqdn, CreatedOn: robotPart.CreatedOn, Secrets: secrets, LastUpdated: robotPart.LastUpdated, - }, nil + } } // RobotPartHistoryEntry is a history entry of a robot part. @@ -99,20 +95,12 @@ type RobotPartHistoryEntry struct { EditedBy *AuthenticatorInfo } -func robotPartHistoryEntryFromProto(entry *pb.RobotPartHistoryEntry) (*RobotPartHistoryEntry, error) { - old, err := robotPartFromProto(entry.Old) - if err != nil { - return nil, err - } - info, err := authenticatorInfoFromProto(entry.EditedBy) - if err != nil { - return nil, err - } +func robotPartHistoryEntryFromProto(entry *pb.RobotPartHistoryEntry) *RobotPartHistoryEntry { return &RobotPartHistoryEntry{ Part: entry.Part, Robot: entry.Robot, When: entry.When, - Old: old, - EditedBy: info, - }, nil + Old: robotPartFromProto(entry.Old), + EditedBy: authenticatorInfoFromProto(entry.EditedBy), + } } From df384520c41e6b4058884781c3effff804c16daf Mon Sep 17 00:00:00 2001 From: purplenicole730 Date: Fri, 15 Nov 2024 19:23:49 -0500 Subject: [PATCH 36/75] make lint --- app/app_client.go | 8 +- app/app_client_test.go | 650 ++++++++++++++----------- app/authorization.go | 10 +- app/fragment.go | 10 +- app/organization.go | 16 +- testutils/inject/app_service_client.go | 313 ++++++------ 6 files changed, 550 insertions(+), 457 deletions(-) diff --git a/app/app_client.go b/app/app_client.go index 0f6bd153238..586b4faa087 100644 --- a/app/app_client.go +++ b/app/app_client.go @@ -248,7 +248,7 @@ func (c *Client) ResendOrganizationInvite(ctx context.Context, orgID, email stri // EnableBillingService enables a billing service to an address in an organization. func (c *Client) EnableBillingService(ctx context.Context, orgID string, billingAddress *BillingAddress) error { _, err := c.client.EnableBillingService(ctx, &pb.EnableBillingServiceRequest{ - OrgId: orgID, + OrgId: orgID, BillingAddress: billingAddressToProto(billingAddress), }) if err != nil { @@ -271,8 +271,8 @@ func (c *Client) DisableBillingService(ctx context.Context, orgID string) error // UpdateBillingService updates the billing service of an organization. func (c *Client) UpdateBillingService(ctx context.Context, orgID string, billingAddress *BillingAddress, billingSupportEmail string) error { _, err := c.client.UpdateBillingService(ctx, &pb.UpdateBillingServiceRequest{ - OrgId: orgID, - BillingAddress: billingAddressToProto(billingAddress), + OrgId: orgID, + BillingAddress: billingAddressToProto(billingAddress), BillingSupportEmail: billingSupportEmail, }) if err != nil { @@ -302,7 +302,7 @@ func (c *Client) OrganizationGetSupportEmail(ctx context.Context, orgID string) return "", err } return resp.Email, nil -} +} // CreateLocation creates a location. func (c *Client) CreateLocation(ctx context.Context, orgID, name string, parentLocationID *string) (*Location, error) { diff --git a/app/app_client_test.go b/app/app_client_test.go index 06bb8c62cce..c59390d2e43 100644 --- a/app/app_client_test.go +++ b/app/app_client_test.go @@ -6,62 +6,63 @@ import ( pb "go.viam.com/api/app/v1" common "go.viam.com/api/common/v1" - "go.viam.com/rdk/testutils/inject" "go.viam.com/test" "go.viam.com/utils/protoutils" "google.golang.org/grpc" "google.golang.org/protobuf/types/known/structpb" "google.golang.org/protobuf/types/known/timestamppb" + + "go.viam.com/rdk/testutils/inject" ) const ( - organizationID = "organization_id" - email = "email" - userID = "user_id" - locationID = "location_id" - available = true + organizationID = "organization_id" + email = "email" + userID = "user_id" + locationID = "location_id" + available = true authorizationType = "authorization_type" - authorizationID = "authorization_id" - resourceType = "resource_type" - resourceID = "resource_id" - identityID = "identity_id" - identityType = "identity_type" - secretID = "secret_ids" - primary = true - robotCount = 1 - robotID = "robot_id" - robotLocation = "robot_location" - partID = "part_id" - dnsName = "dns_name" - secret = "secret" - mainPart = false - fqdn = "fqdn" - localFQDN = "local_fqdn" - configJSON = "configJson" - host = "host" - level = "level" - loggerName = "logger_name" - message = "message" - stack = "stack" - value = "value" - isDeactivated = false - keyID = "key_id" - key = "key" + authorizationID = "authorization_id" + resourceType = "resource_type" + resourceID = "resource_id" + identityID = "identity_id" + identityType = "identity_type" + secretID = "secret_ids" + primary = true + robotCount = 1 + robotID = "robot_id" + robotLocation = "robot_location" + partID = "part_id" + dnsName = "dns_name" + secret = "secret" + mainPart = false + fqdn = "fqdn" + localFQDN = "local_fqdn" + configJSON = "configJson" + host = "host" + level = "level" + loggerName = "logger_name" + message = "message" + stack = "stack" + value = "value" + isDeactivated = false + keyID = "key_id" + key = "key" ) var ( - name = "name" - region = "region" - namespace = "public_namespace" - cid = "cid" - dateAdded = timestamppb.Timestamp{Seconds: 0, Nanos: 50} + name = "name" + region = "region" + namespace = "public_namespace" + cid = "cid" + dateAdded = timestamppb.Timestamp{Seconds: 0, Nanos: 50} organization = Organization{ - ID: organizationID, - Name: name, - CreatedOn: &dateAdded, + ID: organizationID, + Name: name, + CreatedOn: &dateAdded, PublicNamespace: namespace, - DefaultRegion: region, - Cid: &cid, + DefaultRegion: region, + Cid: &cid, } pbOrganization = pb.Organization{ Id: organization.ID, @@ -72,95 +73,95 @@ var ( Cid: organization.Cid, } organizationIdentity = OrganizationIdentity{ - ID: organizationID, + ID: organizationID, Name: name, } orgDetails = OrgDetails{ - OrgID: organizationID, + OrgID: organizationID, OrgName: name, } - lastLogin = timestamppb.Timestamp{Seconds: 0, Nanos: 100} - createdOn = timestamppb.Timestamp{Seconds: 0, Nanos: 0} + lastLogin = timestamppb.Timestamp{Seconds: 0, Nanos: 100} + createdOn = timestamppb.Timestamp{Seconds: 0, Nanos: 0} authorization = Authorization{ AuthorizationType: authorizationType, - AuthorizationID: authorizationID, - ResourceType: resourceType, - ResourceID: resourceID, - IdentityID: identityID, - OrganizationID: organizationID, - IdentityType: identityType, + AuthorizationID: authorizationID, + ResourceType: resourceType, + ResourceID: resourceID, + IdentityID: identityID, + OrganizationID: organizationID, + IdentityType: identityType, } pbAuthorization = pb.Authorization{ AuthorizationType: authorization.AuthorizationType, - AuthorizationId: authorization.AuthorizationID, - ResourceType: authorization.ResourceType, - ResourceId: authorization.ResourceID, - IdentityId: authorization.IdentityID, - OrganizationId: authorization.OrganizationID, - IdentityType: authorization.IdentityType, + AuthorizationId: authorization.AuthorizationID, + ResourceType: authorization.ResourceType, + ResourceId: authorization.ResourceID, + IdentityId: authorization.IdentityID, + OrganizationId: authorization.OrganizationID, + IdentityType: authorization.IdentityType, } - authorizations = []*Authorization{&authorization} + authorizations = []*Authorization{&authorization} pbAuthorizations = []*pb.Authorization{&pbAuthorization} - member = OrganizationMember{ - UserID: userID, - Emails: []string{email}, + member = OrganizationMember{ + UserID: userID, + Emails: []string{email}, DateAdded: &dateAdded, LastLogin: &lastLogin, } invite = OrganizationInvite{ OrganizationID: organizationID, - Email: email, - CreatedOn: &createdOn, + Email: email, + CreatedOn: &createdOn, Authorizations: authorizations, } pbInvite = pb.OrganizationInvite{ OrganizationId: invite.OrganizationID, - Email: invite.Email, - CreatedOn: invite.CreatedOn, + Email: invite.Email, + CreatedOn: invite.CreatedOn, Authorizations: pbAuthorizations, } sendEmailInvite = true - addressLine2 = "address_line_2" - address = BillingAddress{ - AddressLine_1: "address_line_1", - AddressLine_2: &addressLine2, - City: "city", - State: "state", + addressLine2 = "address_line_2" + address = BillingAddress{ + AddressLine1: "address_line_1", + AddressLine2: &addressLine2, + City: "city", + State: "state", } pbAddress = pb.BillingAddress{ - AddressLine_1: address.AddressLine_1, - AddressLine_2: address.AddressLine_2, - City: address.City, - State: address.State, + AddressLine_1: address.AddressLine1, + AddressLine_2: address.AddressLine2, + City: address.City, + State: address.State, } parentLocationID = "parent_location_id" - sharedSecret = SharedSecret{ - ID: secretID, + sharedSecret = SharedSecret{ + ID: secretID, CreatedOn: &createdOn, - State: SharedSecretStateEnabled, + State: SharedSecretStateEnabled, } sharedSecrets = []*SharedSecret{&sharedSecret} - pbSecret = pb.SharedSecret{ - Id: sharedSecret.ID, + pbSecret = pb.SharedSecret{ + Id: sharedSecret.ID, CreatedOn: sharedSecret.CreatedOn, - State: sharedSecretStateToProto(sharedSecret.State), + State: sharedSecretStateToProto(sharedSecret.State), } - pbSecrets = []*pb.SharedSecret{&pbSecret} + pbSecrets = []*pb.SharedSecret{&pbSecret} locationAuth = LocationAuth{ LocationID: locationID, - Secrets: sharedSecrets, + Secrets: sharedSecrets, } pbLocationAuth = pb.LocationAuth{ LocationId: locationAuth.LocationID, - Secrets: pbSecrets, + Secrets: pbSecrets, } locationOrg = LocationOrganization{ OrganizationID: organizationID, - Primary: primary, + Primary: primary, } pbLocationOrg = pb.LocationOrganization{ OrganizationId: locationOrg.OrganizationID, - Primary: locationOrg.Primary, + Primary: locationOrg.Primary, } storageConfig = StorageConfig{ Region: region, @@ -169,160 +170,160 @@ var ( Region: storageConfig.Region, } location = Location{ - ID: locationID, - Name: name, + ID: locationID, + Name: name, ParentLocationID: parentLocationID, - Auth: &locationAuth, - Organizations: []*LocationOrganization{&locationOrg}, - CreatedOn: &createdOn, - RobotCount: robotCount, - Config: &storageConfig, + Auth: &locationAuth, + Organizations: []*LocationOrganization{&locationOrg}, + CreatedOn: &createdOn, + RobotCount: robotCount, + Config: &storageConfig, } pbLocation = pb.Location{ - Id: location.ID, - Name: location.Name, + Id: location.ID, + Name: location.Name, ParentLocationId: location.ParentLocationID, - Auth: &pbLocationAuth, - Organizations: []*pb.LocationOrganization{&pbLocationOrg}, - CreatedOn: location.CreatedOn, - RobotCount: location.RobotCount, - Config: &pbStorageConfig, + Auth: &pbLocationAuth, + Organizations: []*pb.LocationOrganization{&pbLocationOrg}, + CreatedOn: location.CreatedOn, + RobotCount: location.RobotCount, + Config: &pbStorageConfig, } lastAccess = timestamppb.Timestamp{Seconds: 0, Nanos: 110} - robot = Robot{ - ID: robotID, - Name: name, - Location: robotLocation, + robot = Robot{ + ID: robotID, + Name: name, + Location: robotLocation, LastAccess: &lastAccess, - CreatedOn: &createdOn, + CreatedOn: &createdOn, } pbRobot = pb.Robot{ - Id: robot.ID, - Name: robot.Name, - Location: robot.Location, + Id: robot.ID, + Name: robot.Name, + Location: robot.Location, LastAccess: robot.LastAccess, - CreatedOn: robot.CreatedOn, + CreatedOn: robot.CreatedOn, } roverRentalRobot = RoverRentalRobot{ - RobotID: robotID, - LocationID: locationID, - RobotName: name, + RobotID: robotID, + LocationID: locationID, + RobotName: name, RobotMainPartID: partID, } - lastUpdated = timestamppb.Timestamp{Seconds: 0, Nanos: 130} - robotConfig = map[string]interface{}{"name": name, "ID": robotID} - pbRobotConfig, _ = protoutils.StructToStructPb(*robotPart.RobotConfig) + lastUpdated = timestamppb.Timestamp{Seconds: 0, Nanos: 130} + robotConfig = map[string]interface{}{"name": name, "ID": robotID} + pbRobotConfig, _ = protoutils.StructToStructPb(*robotPart.RobotConfig) pbUserSuppliedInfo, _ = protoutils.StructToStructPb(*robotPart.UserSuppliedInfo) - userSuppliedInfo = map[string]interface{}{"userID": userID} - robotPart = RobotPart{ - ID: partID, - Name: name, - DNSName: dnsName, - Secret: secret, - Robot: robotID, - LocationID: locationID, - RobotConfig: &robotConfig, - LastAccess: &lastAccess, + userSuppliedInfo = map[string]interface{}{"userID": userID} + robotPart = RobotPart{ + ID: partID, + Name: name, + DNSName: dnsName, + Secret: secret, + Robot: robotID, + LocationID: locationID, + RobotConfig: &robotConfig, + LastAccess: &lastAccess, UserSuppliedInfo: &userSuppliedInfo, - MainPart: mainPart, - FQDN: fqdn, - LocalFQDN: localFQDN, - CreatedOn: &createdOn, - Secrets: sharedSecrets, - LastUpdated: &lastUpdated, + MainPart: mainPart, + FQDN: fqdn, + LocalFQDN: localFQDN, + CreatedOn: &createdOn, + Secrets: sharedSecrets, + LastUpdated: &lastUpdated, } pbRobotPart = pb.RobotPart{ - Id: robotPart.ID, - Name: robotPart.Name, - DnsName: robotPart.DNSName, - Secret: robotPart.Secret, - Robot: robotPart.Robot, - LocationId: robotPart.LocationID, - RobotConfig: pbRobotConfig, - LastAccess: robotPart.LastAccess, + Id: robotPart.ID, + Name: robotPart.Name, + DnsName: robotPart.DNSName, + Secret: robotPart.Secret, + Robot: robotPart.Robot, + LocationId: robotPart.LocationID, + RobotConfig: pbRobotConfig, + LastAccess: robotPart.LastAccess, UserSuppliedInfo: pbUserSuppliedInfo, - MainPart: robotPart.MainPart, - Fqdn: robotPart.FQDN, - LocalFqdn: robotPart.LocalFQDN, - CreatedOn: robotPart.CreatedOn, - Secrets: pbSecrets, - LastUpdated: robotPart.LastUpdated, + MainPart: robotPart.MainPart, + Fqdn: robotPart.FQDN, + LocalFqdn: robotPart.LocalFQDN, + CreatedOn: robotPart.CreatedOn, + Secrets: pbSecrets, + LastUpdated: robotPart.LastUpdated, } - pageToken = "page_token" - levels = []string{level} - start = timestamppb.Timestamp{Seconds: 92, Nanos: 0} - end = timestamppb.Timestamp{Seconds: 99, Nanos: 999} - limit int64 = 2 - source = "source" - filter = "filter" - time = timestamppb.Timestamp{Seconds: 11, Nanos: 15} - caller = map[string]interface{}{"name": name} - pbCaller, _ = protoutils.StructToStructPb(*logEntry.Caller) - field = map[string]interface{}{"key": "value"} - pbField, _ = protoutils.StructToStructPb(field) - logEntry = LogEntry{ - Host: host, - Level: level, - Time: &time, + pageToken = "page_token" + levels = []string{level} + start = timestamppb.Timestamp{Seconds: 92, Nanos: 0} + end = timestamppb.Timestamp{Seconds: 99, Nanos: 999} + limit int64 = 2 + source = "source" + filter = "filter" + time = timestamppb.Timestamp{Seconds: 11, Nanos: 15} + caller = map[string]interface{}{"name": name} + pbCaller, _ = protoutils.StructToStructPb(*logEntry.Caller) + field = map[string]interface{}{"key": "value"} + pbField, _ = protoutils.StructToStructPb(field) + logEntry = LogEntry{ + Host: host, + Level: level, + Time: &time, LoggerName: loggerName, - Message: message, - Caller: &caller, - Stack: stack, - Fields: []*map[string]interface{}{&field}, + Message: message, + Caller: &caller, + Stack: stack, + Fields: []*map[string]interface{}{&field}, } pbLogEntry = common.LogEntry{ - Host: logEntry.Host, - Level: logEntry.Level, - Time: logEntry.Time, + Host: logEntry.Host, + Level: logEntry.Level, + Time: logEntry.Time, LoggerName: logEntry.LoggerName, - Message: logEntry.Message, - Caller: pbCaller, - Stack: logEntry.Stack, - Fields: []*structpb.Struct{pbField}, + Message: logEntry.Message, + Caller: pbCaller, + Stack: logEntry.Stack, + Fields: []*structpb.Struct{pbField}, } authenticatorInfo = AuthenticatorInfo{ - Type: AuthenticationTypeAPIKey, - Value: value, + Type: AuthenticationTypeAPIKey, + Value: value, IsDeactivated: isDeactivated, } robotPartHistoryEntry = RobotPartHistoryEntry{ - Part: partID, - Robot: robotID, - When: &time, - Old: &robotPart, + Part: partID, + Robot: robotID, + When: &time, + Old: &robotPart, EditedBy: &authenticatorInfo, } apiKey = APIKey{ - ID: keyID, - Key: key, - Name: name, + ID: keyID, + Key: key, + Name: name, CreatedOn: &createdOn, } authorizationDetails = AuthorizationDetails{ AuthorizationType: authorizationType, - AuthorizationID: authorizationID, - ResourceType: resourceType, - ResourceID: resourceID, - OrgID: organizationID, + AuthorizationID: authorizationID, + ResourceType: resourceType, + ResourceID: resourceID, + OrgID: organizationID, } apiKeyWithAuthorizations = APIKeyWithAuthorizations{ - APIKey: &apiKey, + APIKey: &apiKey, Authorizations: []*AuthorizationDetails{&authorizationDetails}, } pbAPIKeyWithAuthorizations = pb.APIKeyWithAuthorizations{ ApiKey: &pb.APIKey{ - Id: apiKey.ID, - Key: apiKey.Key, - Name: apiKey.Name, + Id: apiKey.ID, + Key: apiKey.Key, + Name: apiKey.Name, CreatedOn: apiKey.CreatedOn, }, Authorizations: []*pb.AuthorizationDetails{ - &pb.AuthorizationDetails{ + { AuthorizationType: authorizationDetails.AuthorizationType, - AuthorizationId: authorizationDetails.AuthorizationID, - ResourceType: authorizationDetails.ResourceType, - ResourceId: authorizationDetails.ResourceID, - OrgId: authorizationDetails.OrgID, + AuthorizationId: authorizationDetails.AuthorizationID, + ResourceType: authorizationDetails.ResourceType, + ResourceId: authorizationDetails.ResourceID, + OrgId: authorizationDetails.OrgID, }, }, } @@ -354,6 +355,14 @@ func authenticationTypeToProto(authType AuthenticationType) pb.AuthenticationTyp } } +func testOrganizationResponse(t *testing.T, actualOrg, expectedOrg *Organization) { + test.That(t, actualOrg.ID, test.ShouldEqual, expectedOrg.ID) + test.That(t, actualOrg.Name, test.ShouldEqual, expectedOrg.Name) + test.That(t, actualOrg.PublicNamespace, test.ShouldEqual, expectedOrg.PublicNamespace) + test.That(t, actualOrg.DefaultRegion, test.ShouldEqual, expectedOrg.DefaultRegion) + test.That(t, actualOrg.Cid, test.ShouldEqual, expectedOrg.Cid) +} + func createGrpcClient() *inject.AppServiceClient { return &inject.AppServiceClient{} } @@ -363,7 +372,9 @@ func TestAppClient(t *testing.T) { client := Client{client: grpcClient} t.Run("GetUserIDByEmail", func(t *testing.T) { - grpcClient.GetUserIDByEmailFunc = func(ctx context.Context, in *pb.GetUserIDByEmailRequest, opts ...grpc.CallOption) (*pb.GetUserIDByEmailResponse, error) { + grpcClient.GetUserIDByEmailFunc = func( + ctx context.Context, in *pb.GetUserIDByEmailRequest, opts ...grpc.CallOption, + ) (*pb.GetUserIDByEmailResponse, error) { test.That(t, in.Email, test.ShouldEqual, email) return &pb.GetUserIDByEmailResponse{ UserId: userID, @@ -374,42 +385,40 @@ func TestAppClient(t *testing.T) { }) t.Run("CreateOrganization", func(t *testing.T) { - grpcClient.CreateOrganizationFunc = func(ctx context.Context, in *pb.CreateOrganizationRequest, opts ...grpc.CallOption) (*pb.CreateOrganizationResponse, error) { + grpcClient.CreateOrganizationFunc = func( + ctx context.Context, in *pb.CreateOrganizationRequest, opts ...grpc.CallOption, + ) (*pb.CreateOrganizationResponse, error) { test.That(t, in.Name, test.ShouldEqual, name) return &pb.CreateOrganizationResponse{ Organization: &pbOrganization, }, nil } resp, _ := client.CreateOrganization(context.Background(), name) - test.That(t, resp.ID, test.ShouldEqual, organization.ID) - test.That(t, resp.Name, test.ShouldEqual, organization.Name) - test.That(t, resp.PublicNamespace, test.ShouldEqual, organization.PublicNamespace) - test.That(t, resp.DefaultRegion, test.ShouldEqual, organization.DefaultRegion) - test.That(t, resp.Cid, test.ShouldEqual, organization.Cid) + testOrganizationResponse(t, resp, &organization) }) t.Run("ListOrganizations", func(t *testing.T) { - organizations := []Organization{organization} - grpcClient.ListOrganizationsFunc = func(ctx context.Context, in *pb.ListOrganizationsRequest, opts ...grpc.CallOption) (*pb.ListOrganizationsResponse, error) { + expectedOrganizations := []Organization{organization} + grpcClient.ListOrganizationsFunc = func( + ctx context.Context, in *pb.ListOrganizationsRequest, opts ...grpc.CallOption, + ) (*pb.ListOrganizationsResponse, error) { return &pb.ListOrganizationsResponse{ Organizations: []*pb.Organization{&pbOrganization}, }, nil } resp, _ := client.ListOrganizations(context.Background()) - test.That(t, len(resp), test.ShouldEqual, 1) - test.That(t, resp[0].ID, test.ShouldEqual, organizations[0].ID) - test.That(t, resp[0].Name, test.ShouldEqual, organizations[0].Name) - test.That(t, resp[0].PublicNamespace, test.ShouldEqual, organizations[0].PublicNamespace) - test.That(t, resp[0].DefaultRegion, test.ShouldEqual, organizations[0].DefaultRegion) - test.That(t, resp[0].Cid, test.ShouldEqual, organizations[0].Cid) + test.That(t, len(resp), test.ShouldEqual, len(expectedOrganizations)) + testOrganizationResponse(t, resp[0], &expectedOrganizations[0]) }) t.Run("GetOrganizationsWithAccessToLocation", func(t *testing.T) { pbOrganizationIdentity := pb.OrganizationIdentity{ - Id: organizationIdentity.ID, + Id: organizationIdentity.ID, Name: organizationIdentity.Name, } - grpcClient.GetOrganizationsWithAccessToLocationFunc = func(ctx context.Context, in *pb.GetOrganizationsWithAccessToLocationRequest, opts ...grpc.CallOption) (*pb.GetOrganizationsWithAccessToLocationResponse, error) { + grpcClient.GetOrganizationsWithAccessToLocationFunc = func( + ctx context.Context, in *pb.GetOrganizationsWithAccessToLocationRequest, opts ...grpc.CallOption, + ) (*pb.GetOrganizationsWithAccessToLocationResponse, error) { test.That(t, in.LocationId, test.ShouldEqual, locationID) return &pb.GetOrganizationsWithAccessToLocationResponse{ OrganizationIdentities: []*pb.OrganizationIdentity{&pbOrganizationIdentity}, @@ -424,10 +433,12 @@ func TestAppClient(t *testing.T) { t.Run("ListOrganizationsByUser", func(t *testing.T) { orgDetailsList := []OrgDetails{orgDetails} pbOrgDetails := pb.OrgDetails{ - OrgId: orgDetails.OrgID, + OrgId: orgDetails.OrgID, OrgName: orgDetails.OrgName, } - grpcClient.ListOrganizationsByUserFunc = func(ctx context.Context, in *pb.ListOrganizationsByUserRequest, opts ...grpc.CallOption) (*pb.ListOrganizationsByUserResponse, error) { + grpcClient.ListOrganizationsByUserFunc = func( + ctx context.Context, in *pb.ListOrganizationsByUserRequest, opts ...grpc.CallOption, + ) (*pb.ListOrganizationsByUserResponse, error) { test.That(t, in.UserId, test.ShouldEqual, userID) return &pb.ListOrganizationsByUserResponse{ Orgs: []*pb.OrgDetails{&pbOrgDetails}, @@ -440,22 +451,22 @@ func TestAppClient(t *testing.T) { }) t.Run("GetOrganization", func(t *testing.T) { - grpcClient.GetOrganizationFunc = func(ctx context.Context, in *pb.GetOrganizationRequest, opts ...grpc.CallOption) (*pb.GetOrganizationResponse, error) { + grpcClient.GetOrganizationFunc = func( + ctx context.Context, in *pb.GetOrganizationRequest, opts ...grpc.CallOption, + ) (*pb.GetOrganizationResponse, error) { test.That(t, in.OrganizationId, test.ShouldEqual, organizationID) return &pb.GetOrganizationResponse{ Organization: &pbOrganization, }, nil } resp, _ := client.GetOrganization(context.Background(), organizationID) - test.That(t, resp.ID, test.ShouldEqual, organization.ID) - test.That(t, resp.Name, test.ShouldEqual, organization.Name) - test.That(t, resp.PublicNamespace, test.ShouldEqual, organization.PublicNamespace) - test.That(t, resp.DefaultRegion, test.ShouldEqual, organization.DefaultRegion) - test.That(t, resp.Cid, test.ShouldEqual, organization.Cid) + testOrganizationResponse(t, resp, &organization) }) t.Run("GetOrganizationNamespaceAvailability", func(t *testing.T) { - grpcClient.GetOrganizationNamespaceAvailabilityFunc = func(ctx context.Context, in *pb.GetOrganizationNamespaceAvailabilityRequest, opts ...grpc.CallOption) (*pb.GetOrganizationNamespaceAvailabilityResponse, error) { + grpcClient.GetOrganizationNamespaceAvailabilityFunc = func( + ctx context.Context, in *pb.GetOrganizationNamespaceAvailabilityRequest, opts ...grpc.CallOption, + ) (*pb.GetOrganizationNamespaceAvailabilityResponse, error) { test.That(t, in.PublicNamespace, test.ShouldEqual, namespace) return &pb.GetOrganizationNamespaceAvailabilityResponse{ Available: available, @@ -466,22 +477,22 @@ func TestAppClient(t *testing.T) { }) t.Run("UpdateOrganization", func(t *testing.T) { - grpcClient.UpdateOrganizationFunc = func(ctx context.Context, in *pb.UpdateOrganizationRequest, opts ...grpc.CallOption) (*pb.UpdateOrganizationResponse, error) { + grpcClient.UpdateOrganizationFunc = func( + ctx context.Context, in *pb.UpdateOrganizationRequest, opts ...grpc.CallOption, + ) (*pb.UpdateOrganizationResponse, error) { test.That(t, in.PublicNamespace, test.ShouldEqual, &namespace) return &pb.UpdateOrganizationResponse{ Organization: &pbOrganization, }, nil } resp, _ := client.UpdateOrganization(context.Background(), organizationID, &name, &namespace, ®ion, &cid) - test.That(t, resp.ID, test.ShouldEqual, organization.ID) - test.That(t, resp.Name, test.ShouldEqual, organization.Name) - test.That(t, resp.PublicNamespace, test.ShouldEqual, organization.PublicNamespace) - test.That(t, resp.DefaultRegion, test.ShouldEqual, organization.DefaultRegion) - test.That(t, resp.Cid, test.ShouldEqual, organization.Cid) + testOrganizationResponse(t, resp, &organization) }) t.Run("DeleteOrganization", func(t *testing.T) { - grpcClient.DeleteOrganizationFunc = func(ctx context.Context, in *pb.DeleteOrganizationRequest, opts ...grpc.CallOption) (*pb.DeleteOrganizationResponse, error) { + grpcClient.DeleteOrganizationFunc = func( + ctx context.Context, in *pb.DeleteOrganizationRequest, opts ...grpc.CallOption, + ) (*pb.DeleteOrganizationResponse, error) { test.That(t, in.OrganizationId, test.ShouldEqual, organizationID) return &pb.DeleteOrganizationResponse{}, nil } @@ -491,13 +502,15 @@ func TestAppClient(t *testing.T) { t.Run("ListOrganizationMembers", func(t *testing.T) { expectedMembers := []OrganizationMember{member} pbMember := pb.OrganizationMember{ - UserId: member.UserID, - Emails: member.Emails, + UserId: member.UserID, + Emails: member.Emails, DateAdded: member.DateAdded, LastLogin: member.LastLogin, } expectedInvites := []OrganizationInvite{invite} - grpcClient.ListOrganizationMembersFunc = func(ctx context.Context, in *pb.ListOrganizationMembersRequest, opts ...grpc.CallOption) (*pb.ListOrganizationMembersResponse, error) { + grpcClient.ListOrganizationMembersFunc = func( + ctx context.Context, in *pb.ListOrganizationMembersRequest, opts ...grpc.CallOption, + ) (*pb.ListOrganizationMembersResponse, error) { test.That(t, in.OrganizationId, test.ShouldEqual, organizationID) return &pb.ListOrganizationMembersResponse{ Members: []*pb.OrganizationMember{&pbMember}, @@ -519,7 +532,9 @@ func TestAppClient(t *testing.T) { }) t.Run("CreateOrganizationInvite", func(t *testing.T) { - grpcClient.CreateOrganizationInviteFunc = func(ctx context.Context, in *pb.CreateOrganizationInviteRequest, opts ...grpc.CallOption) (*pb.CreateOrganizationInviteResponse, error) { + grpcClient.CreateOrganizationInviteFunc = func( + ctx context.Context, in *pb.CreateOrganizationInviteRequest, opts ...grpc.CallOption, + ) (*pb.CreateOrganizationInviteResponse, error) { test.That(t, in.OrganizationId, test.ShouldEqual, organizationID) test.That(t, in.Email, test.ShouldEqual, email) test.That(t, in.Authorizations, test.ShouldResemble, pbAuthorizations) @@ -537,7 +552,9 @@ func TestAppClient(t *testing.T) { }) t.Run("UpdateOrganizationInviteAuthorizations", func(t *testing.T) { - grpcClient.UpdateOrganizationInviteAuthorizationsFunc = func(ctx context.Context, in *pb.UpdateOrganizationInviteAuthorizationsRequest, opts ...grpc.CallOption) (*pb.UpdateOrganizationInviteAuthorizationsResponse, error) { + grpcClient.UpdateOrganizationInviteAuthorizationsFunc = func( + ctx context.Context, in *pb.UpdateOrganizationInviteAuthorizationsRequest, opts ...grpc.CallOption, + ) (*pb.UpdateOrganizationInviteAuthorizationsResponse, error) { test.That(t, in.OrganizationId, test.ShouldEqual, organizationID) return &pb.UpdateOrganizationInviteAuthorizationsResponse{ Invite: &pbInvite, @@ -552,7 +569,9 @@ func TestAppClient(t *testing.T) { }) t.Run("DeleteOrganizationMember", func(t *testing.T) { - grpcClient.DeleteOrganizationMemberFunc = func(ctx context.Context, in *pb.DeleteOrganizationMemberRequest, opts ...grpc.CallOption) (*pb.DeleteOrganizationMemberResponse, error) { + grpcClient.DeleteOrganizationMemberFunc = func( + ctx context.Context, in *pb.DeleteOrganizationMemberRequest, opts ...grpc.CallOption, + ) (*pb.DeleteOrganizationMemberResponse, error) { test.That(t, in.OrganizationId, test.ShouldEqual, organizationID) test.That(t, in.UserId, test.ShouldEqual, userID) return &pb.DeleteOrganizationMemberResponse{}, nil @@ -561,7 +580,9 @@ func TestAppClient(t *testing.T) { }) t.Run("DeleteOrganizationInvite", func(t *testing.T) { - grpcClient.DeleteOrganizationInviteFunc = func(ctx context.Context, in *pb.DeleteOrganizationInviteRequest, opts ...grpc.CallOption) (*pb.DeleteOrganizationInviteResponse, error) { + grpcClient.DeleteOrganizationInviteFunc = func( + ctx context.Context, in *pb.DeleteOrganizationInviteRequest, opts ...grpc.CallOption, + ) (*pb.DeleteOrganizationInviteResponse, error) { test.That(t, in.OrganizationId, test.ShouldEqual, organizationID) test.That(t, in.Email, test.ShouldEqual, email) return &pb.DeleteOrganizationInviteResponse{}, nil @@ -570,7 +591,9 @@ func TestAppClient(t *testing.T) { }) t.Run("ResendOrganizationInvite", func(t *testing.T) { - grpcClient.ResendOrganizationInviteFunc = func(ctx context.Context, in *pb.ResendOrganizationInviteRequest, opts ...grpc.CallOption) (*pb.ResendOrganizationInviteResponse, error) { + grpcClient.ResendOrganizationInviteFunc = func( + ctx context.Context, in *pb.ResendOrganizationInviteRequest, opts ...grpc.CallOption, + ) (*pb.ResendOrganizationInviteResponse, error) { test.That(t, in.OrganizationId, test.ShouldEqual, organizationID) test.That(t, in.Email, test.ShouldEqual, email) return &pb.ResendOrganizationInviteResponse{ @@ -586,7 +609,9 @@ func TestAppClient(t *testing.T) { }) t.Run("EnableBillingService", func(t *testing.T) { - grpcClient.EnableBillingServiceFunc = func(ctx context.Context, in *pb.EnableBillingServiceRequest, opts ...grpc.CallOption) (*pb.EnableBillingServiceResponse, error) { + grpcClient.EnableBillingServiceFunc = func( + ctx context.Context, in *pb.EnableBillingServiceRequest, opts ...grpc.CallOption, + ) (*pb.EnableBillingServiceResponse, error) { test.That(t, in.OrgId, test.ShouldEqual, organizationID) test.That(t, in.BillingAddress, test.ShouldResemble, &pbAddress) return &pb.EnableBillingServiceResponse{}, nil @@ -595,7 +620,9 @@ func TestAppClient(t *testing.T) { }) t.Run("DisableBillingService", func(t *testing.T) { - grpcClient.DisableBillingServiceFunc = func(ctx context.Context, in *pb.DisableBillingServiceRequest, opts ...grpc.CallOption) (*pb.DisableBillingServiceResponse, error) { + grpcClient.DisableBillingServiceFunc = func( + ctx context.Context, in *pb.DisableBillingServiceRequest, opts ...grpc.CallOption, + ) (*pb.DisableBillingServiceResponse, error) { test.That(t, in.OrgId, test.ShouldEqual, organizationID) return &pb.DisableBillingServiceResponse{}, nil } @@ -603,7 +630,9 @@ func TestAppClient(t *testing.T) { }) t.Run("UpdateBillingService", func(t *testing.T) { - grpcClient.UpdateBillingServiceFunc = func(ctx context.Context, in *pb.UpdateBillingServiceRequest, opts ...grpc.CallOption) (*pb.UpdateBillingServiceResponse, error) { + grpcClient.UpdateBillingServiceFunc = func( + ctx context.Context, in *pb.UpdateBillingServiceRequest, opts ...grpc.CallOption, + ) (*pb.UpdateBillingServiceResponse, error) { test.That(t, in.OrgId, test.ShouldEqual, organizationID) test.That(t, in.BillingAddress, test.ShouldResemble, &pbAddress) test.That(t, in.BillingSupportEmail, test.ShouldResemble, email) @@ -613,7 +642,9 @@ func TestAppClient(t *testing.T) { }) t.Run("OrganizationSetSupportEmail", func(t *testing.T) { - grpcClient.OrganizationSetSupportEmailFunc = func(ctx context.Context, in *pb.OrganizationSetSupportEmailRequest, opts ...grpc.CallOption) (*pb.OrganizationSetSupportEmailResponse, error) { + grpcClient.OrganizationSetSupportEmailFunc = func( + ctx context.Context, in *pb.OrganizationSetSupportEmailRequest, opts ...grpc.CallOption, + ) (*pb.OrganizationSetSupportEmailResponse, error) { test.That(t, in.OrgId, test.ShouldEqual, organizationID) test.That(t, in.Email, test.ShouldResemble, email) return &pb.OrganizationSetSupportEmailResponse{}, nil @@ -622,7 +653,9 @@ func TestAppClient(t *testing.T) { }) t.Run("OrganizationGetSupportEmail", func(t *testing.T) { - grpcClient.OrganizationGetSupportEmailFunc = func(ctx context.Context, in *pb.OrganizationGetSupportEmailRequest, opts ...grpc.CallOption) (*pb.OrganizationGetSupportEmailResponse, error) { + grpcClient.OrganizationGetSupportEmailFunc = func( + ctx context.Context, in *pb.OrganizationGetSupportEmailRequest, opts ...grpc.CallOption, + ) (*pb.OrganizationGetSupportEmailResponse, error) { test.That(t, in.OrgId, test.ShouldEqual, organizationID) return &pb.OrganizationGetSupportEmailResponse{ Email: email, @@ -633,7 +666,9 @@ func TestAppClient(t *testing.T) { }) t.Run("CreateLocation", func(t *testing.T) { - grpcClient.CreateLocationFunc = func(ctx context.Context, in *pb.CreateLocationRequest, opts ...grpc.CallOption) (*pb.CreateLocationResponse, error) { + grpcClient.CreateLocationFunc = func( + ctx context.Context, in *pb.CreateLocationRequest, opts ...grpc.CallOption, + ) (*pb.CreateLocationResponse, error) { test.That(t, in.OrganizationId, test.ShouldEqual, organizationID) test.That(t, in.Name, test.ShouldEqual, name) test.That(t, in.ParentLocationId, test.ShouldEqual, &parentLocationID) @@ -653,7 +688,9 @@ func TestAppClient(t *testing.T) { }) t.Run("GetLocation", func(t *testing.T) { - grpcClient.GetLocationFunc = func(ctx context.Context, in *pb.GetLocationRequest, opts ...grpc.CallOption) (*pb.GetLocationResponse, error) { + grpcClient.GetLocationFunc = func( + ctx context.Context, in *pb.GetLocationRequest, opts ...grpc.CallOption, + ) (*pb.GetLocationResponse, error) { test.That(t, in.LocationId, test.ShouldEqual, locationID) return &pb.GetLocationResponse{ Location: &pbLocation, @@ -671,7 +708,9 @@ func TestAppClient(t *testing.T) { }) t.Run("UpdateLocation", func(t *testing.T) { - grpcClient.UpdateLocationFunc = func(ctx context.Context, in *pb.UpdateLocationRequest, opts ...grpc.CallOption) (*pb.UpdateLocationResponse, error) { + grpcClient.UpdateLocationFunc = func( + ctx context.Context, in *pb.UpdateLocationRequest, opts ...grpc.CallOption, + ) (*pb.UpdateLocationResponse, error) { test.That(t, in.LocationId, test.ShouldEqual, locationID) test.That(t, in.Name, test.ShouldEqual, &name) test.That(t, in.ParentLocationId, test.ShouldEqual, &parentLocationID) @@ -692,7 +731,9 @@ func TestAppClient(t *testing.T) { }) t.Run("DeleteLocation", func(t *testing.T) { - grpcClient.DeleteLocationFunc = func(ctx context.Context, in *pb.DeleteLocationRequest, opts ...grpc.CallOption) (*pb.DeleteLocationResponse, error) { + grpcClient.DeleteLocationFunc = func( + ctx context.Context, in *pb.DeleteLocationRequest, opts ...grpc.CallOption, + ) (*pb.DeleteLocationResponse, error) { test.That(t, in.LocationId, test.ShouldEqual, locationID) return &pb.DeleteLocationResponse{}, nil } @@ -701,7 +742,9 @@ func TestAppClient(t *testing.T) { t.Run("ListLocations", func(t *testing.T) { expectedLocations := []Location{location} - grpcClient.ListLocationsFunc = func(ctx context.Context, in *pb.ListLocationsRequest, opts ...grpc.CallOption) (*pb.ListLocationsResponse, error) { + grpcClient.ListLocationsFunc = func( + ctx context.Context, in *pb.ListLocationsRequest, opts ...grpc.CallOption, + ) (*pb.ListLocationsResponse, error) { test.That(t, in.OrganizationId, test.ShouldEqual, organizationID) return &pb.ListLocationsResponse{ Locations: []*pb.Location{&pbLocation}, @@ -720,7 +763,9 @@ func TestAppClient(t *testing.T) { }) t.Run("ShareLocation", func(t *testing.T) { - grpcClient.ShareLocationFunc = func(ctx context.Context, in *pb.ShareLocationRequest, opts ...grpc.CallOption) (*pb.ShareLocationResponse, error) { + grpcClient.ShareLocationFunc = func( + ctx context.Context, in *pb.ShareLocationRequest, opts ...grpc.CallOption, + ) (*pb.ShareLocationResponse, error) { test.That(t, in.LocationId, test.ShouldEqual, locationID) test.That(t, in.OrganizationId, test.ShouldEqual, organizationID) return &pb.ShareLocationResponse{}, nil @@ -729,7 +774,9 @@ func TestAppClient(t *testing.T) { }) t.Run("UnshareLocation", func(t *testing.T) { - grpcClient.UnshareLocationFunc = func(ctx context.Context, in *pb.UnshareLocationRequest, opts ...grpc.CallOption) (*pb.UnshareLocationResponse, error) { + grpcClient.UnshareLocationFunc = func( + ctx context.Context, in *pb.UnshareLocationRequest, opts ...grpc.CallOption, + ) (*pb.UnshareLocationResponse, error) { test.That(t, in.LocationId, test.ShouldEqual, locationID) test.That(t, in.OrganizationId, test.ShouldEqual, organizationID) return &pb.UnshareLocationResponse{}, nil @@ -738,7 +785,9 @@ func TestAppClient(t *testing.T) { }) t.Run("LocationAuth", func(t *testing.T) { - grpcClient.LocationAuthFunc = func(ctx context.Context, in *pb.LocationAuthRequest, opts ...grpc.CallOption) (*pb.LocationAuthResponse, error) { + grpcClient.LocationAuthFunc = func( + ctx context.Context, in *pb.LocationAuthRequest, opts ...grpc.CallOption, + ) (*pb.LocationAuthResponse, error) { test.That(t, in.LocationId, test.ShouldEqual, locationID) return &pb.LocationAuthResponse{ Auth: &pbLocationAuth, @@ -749,7 +798,9 @@ func TestAppClient(t *testing.T) { }) t.Run("CreateLocationSecret", func(t *testing.T) { - grpcClient.CreateLocationSecretFunc = func(ctx context.Context, in *pb.CreateLocationSecretRequest, opts ...grpc.CallOption) (*pb.CreateLocationSecretResponse, error) { + grpcClient.CreateLocationSecretFunc = func( + ctx context.Context, in *pb.CreateLocationSecretRequest, opts ...grpc.CallOption, + ) (*pb.CreateLocationSecretResponse, error) { test.That(t, in.LocationId, test.ShouldEqual, locationID) return &pb.CreateLocationSecretResponse{ Auth: &pbLocationAuth, @@ -760,7 +811,9 @@ func TestAppClient(t *testing.T) { }) t.Run("DeleteLocationSecret", func(t *testing.T) { - grpcClient.DeleteLocationSecretFunc = func(ctx context.Context, in *pb.DeleteLocationSecretRequest, opts ...grpc.CallOption) (*pb.DeleteLocationSecretResponse, error) { + grpcClient.DeleteLocationSecretFunc = func( + ctx context.Context, in *pb.DeleteLocationSecretRequest, opts ...grpc.CallOption, + ) (*pb.DeleteLocationSecretResponse, error) { test.That(t, in.LocationId, test.ShouldEqual, locationID) test.That(t, in.SecretId, test.ShouldEqual, secretID) return &pb.DeleteLocationSecretResponse{}, nil @@ -769,7 +822,9 @@ func TestAppClient(t *testing.T) { }) t.Run("GetRobot", func(t *testing.T) { - grpcClient.GetRobotFunc = func(ctx context.Context, in *pb.GetRobotRequest, opts ...grpc.CallOption) (*pb.GetRobotResponse, error) { + grpcClient.GetRobotFunc = func( + ctx context.Context, in *pb.GetRobotRequest, opts ...grpc.CallOption, + ) (*pb.GetRobotResponse, error) { test.That(t, in.Id, test.ShouldEqual, robotID) return &pb.GetRobotResponse{ Robot: &pbRobot, @@ -782,12 +837,14 @@ func TestAppClient(t *testing.T) { t.Run("GetRoverRentalRobots", func(t *testing.T) { expectedRobots := []RoverRentalRobot{roverRentalRobot} pbRobot := pb.RoverRentalRobot{ - RobotId: roverRentalRobot.RobotID, - LocationId: roverRentalRobot.LocationID, - RobotName: roverRentalRobot.RobotName, + RobotId: roverRentalRobot.RobotID, + LocationId: roverRentalRobot.LocationID, + RobotName: roverRentalRobot.RobotName, RobotMainPartId: partID, } - grpcClient.GetRoverRentalRobotsFunc = func(ctx context.Context, in *pb.GetRoverRentalRobotsRequest, opts ...grpc.CallOption) (*pb.GetRoverRentalRobotsResponse, error) { + grpcClient.GetRoverRentalRobotsFunc = func( + ctx context.Context, in *pb.GetRoverRentalRobotsRequest, opts ...grpc.CallOption, + ) (*pb.GetRoverRentalRobotsResponse, error) { test.That(t, in.OrgId, test.ShouldEqual, organizationID) return &pb.GetRoverRentalRobotsResponse{ Robots: []*pb.RoverRentalRobot{&pbRobot}, @@ -800,7 +857,9 @@ func TestAppClient(t *testing.T) { t.Run("GetRobotParts", func(t *testing.T) { expectedRobotParts := []RobotPart{robotPart} - grpcClient.GetRobotPartsFunc = func(ctx context.Context, in *pb.GetRobotPartsRequest, opts ...grpc.CallOption) (*pb.GetRobotPartsResponse, error) { + grpcClient.GetRobotPartsFunc = func( + ctx context.Context, in *pb.GetRobotPartsRequest, opts ...grpc.CallOption, + ) (*pb.GetRobotPartsResponse, error) { test.That(t, in.RobotId, test.ShouldEqual, robotID) return &pb.GetRobotPartsResponse{ Parts: []*pb.RobotPart{&pbRobotPart}, @@ -823,10 +882,12 @@ func TestAppClient(t *testing.T) { }) t.Run("GetRobotPart", func(t *testing.T) { - grpcClient.GetRobotPartFunc = func(ctx context.Context, in *pb.GetRobotPartRequest, opts ...grpc.CallOption) (*pb.GetRobotPartResponse, error) { + grpcClient.GetRobotPartFunc = func( + ctx context.Context, in *pb.GetRobotPartRequest, opts ...grpc.CallOption, + ) (*pb.GetRobotPartResponse, error) { test.That(t, in.Id, test.ShouldEqual, partID) return &pb.GetRobotPartResponse{ - Part: &pbRobotPart, + Part: &pbRobotPart, ConfigJson: configJSON, }, nil } @@ -844,10 +905,12 @@ func TestAppClient(t *testing.T) { test.That(t, part.FQDN, test.ShouldEqual, robotPart.FQDN) test.That(t, part.LocalFQDN, test.ShouldEqual, robotPart.LocalFQDN) }) - + t.Run("GetRobotPartLogs", func(t *testing.T) { expectedLogs := []*LogEntry{&logEntry} - grpcClient.GetRobotPartLogsFunc = func(ctx context.Context, in *pb.GetRobotPartLogsRequest, opts ...grpc.CallOption) (*pb.GetRobotPartLogsResponse, error) { + grpcClient.GetRobotPartLogsFunc = func( + ctx context.Context, in *pb.GetRobotPartLogsRequest, opts ...grpc.CallOption, + ) (*pb.GetRobotPartLogsResponse, error) { test.That(t, in.Id, test.ShouldEqual, partID) test.That(t, in.Filter, test.ShouldEqual, &filter) test.That(t, in.PageToken, test.ShouldEqual, &pageToken) @@ -857,7 +920,7 @@ func TestAppClient(t *testing.T) { test.That(t, in.Limit, test.ShouldEqual, &limit) test.That(t, in.Source, test.ShouldEqual, &source) return &pb.GetRobotPartLogsResponse{ - Logs: []*common.LogEntry{&pbLogEntry}, + Logs: []*common.LogEntry{&pbLogEntry}, NextPageToken: pageToken, }, nil } @@ -878,18 +941,20 @@ func TestAppClient(t *testing.T) { t.Run("GetRobotPartHistory", func(t *testing.T) { expectedEntries := []*RobotPartHistoryEntry{&robotPartHistoryEntry} pbAuthenticatorInfo := pb.AuthenticatorInfo{ - Type: authenticationTypeToProto(authenticatorInfo.Type), - Value: authenticatorInfo.Value, + Type: authenticationTypeToProto(authenticatorInfo.Type), + Value: authenticatorInfo.Value, IsDeactivated: authenticatorInfo.IsDeactivated, } pbRobotPartHistoryEntry := pb.RobotPartHistoryEntry{ - Part: robotPartHistoryEntry.Part, - Robot: robotPartHistoryEntry.Robot, - When: robotPartHistoryEntry.When, - Old: &pbRobotPart, + Part: robotPartHistoryEntry.Part, + Robot: robotPartHistoryEntry.Robot, + When: robotPartHistoryEntry.When, + Old: &pbRobotPart, EditedBy: &pbAuthenticatorInfo, } - grpcClient.GetRobotPartHistoryFunc = func(ctx context.Context, in *pb.GetRobotPartHistoryRequest, opts ...grpc.CallOption) (*pb.GetRobotPartHistoryResponse, error) { + grpcClient.GetRobotPartHistoryFunc = func( + ctx context.Context, in *pb.GetRobotPartHistoryRequest, opts ...grpc.CallOption, + ) (*pb.GetRobotPartHistoryResponse, error) { test.That(t, in.Id, test.ShouldEqual, partID) return &pb.GetRobotPartHistoryResponse{ History: []*pb.RobotPartHistoryEntry{&pbRobotPartHistoryEntry}, @@ -898,7 +963,7 @@ func TestAppClient(t *testing.T) { resp, _ := client.GetRobotPartHistory(context.Background(), partID) test.That(t, resp[0].Part, test.ShouldEqual, expectedEntries[0].Part) test.That(t, resp[0].Robot, test.ShouldEqual, expectedEntries[0].Robot) - test.That(t, resp[0].When , test.ShouldEqual, expectedEntries[0].When) + test.That(t, resp[0].When, test.ShouldEqual, expectedEntries[0].When) test.That(t, resp[0].Old.Name, test.ShouldEqual, expectedEntries[0].Old.Name) test.That(t, resp[0].Old.DNSName, test.ShouldEqual, expectedEntries[0].Old.DNSName) test.That(t, resp[0].Old.Secret, test.ShouldEqual, expectedEntries[0].Old.Secret) @@ -917,7 +982,9 @@ func TestAppClient(t *testing.T) { }) t.Run("UpdateRobotPart", func(t *testing.T) { - grpcClient.UpdateRobotPartFunc = func(ctx context.Context, in *pb.UpdateRobotPartRequest, opts ...grpc.CallOption) (*pb.UpdateRobotPartResponse, error) { + grpcClient.UpdateRobotPartFunc = func( + ctx context.Context, in *pb.UpdateRobotPartRequest, opts ...grpc.CallOption, + ) (*pb.UpdateRobotPartResponse, error) { test.That(t, in.Id, test.ShouldEqual, partID) test.That(t, in.Name, test.ShouldEqual, name) test.That(t, in.RobotConfig, test.ShouldResemble, pbRobotConfig) @@ -940,7 +1007,9 @@ func TestAppClient(t *testing.T) { }) t.Run("NewRobotPart", func(t *testing.T) { - grpcClient.NewRobotPartFunc = func(ctx context.Context, in *pb.NewRobotPartRequest, opts ...grpc.CallOption) (*pb.NewRobotPartResponse, error) { + grpcClient.NewRobotPartFunc = func( + ctx context.Context, in *pb.NewRobotPartRequest, opts ...grpc.CallOption, + ) (*pb.NewRobotPartResponse, error) { test.That(t, in.RobotId, test.ShouldEqual, robotID) test.That(t, in.PartName, test.ShouldEqual, name) return &pb.NewRobotPartResponse{}, nil @@ -949,7 +1018,9 @@ func TestAppClient(t *testing.T) { }) t.Run("DeleteRobotPart", func(t *testing.T) { - grpcClient.DeleteRobotPartFunc = func(ctx context.Context, in *pb.DeleteRobotPartRequest, opts ...grpc.CallOption) (*pb.DeleteRobotPartResponse, error) { + grpcClient.DeleteRobotPartFunc = func( + ctx context.Context, in *pb.DeleteRobotPartRequest, opts ...grpc.CallOption, + ) (*pb.DeleteRobotPartResponse, error) { test.That(t, in.PartId, test.ShouldEqual, partID) return &pb.DeleteRobotPartResponse{}, nil } @@ -958,7 +1029,9 @@ func TestAppClient(t *testing.T) { t.Run("GetRobotAPIKeys", func(t *testing.T) { expectedAPIKeyWithAuthorizations := []APIKeyWithAuthorizations{apiKeyWithAuthorizations} - grpcClient.GetRobotAPIKeysFunc = func(ctx context.Context, in *pb.GetRobotAPIKeysRequest, opts ...grpc.CallOption) (*pb.GetRobotAPIKeysResponse, error) { + grpcClient.GetRobotAPIKeysFunc = func( + ctx context.Context, in *pb.GetRobotAPIKeysRequest, opts ...grpc.CallOption, + ) (*pb.GetRobotAPIKeysResponse, error) { test.That(t, in.RobotId, test.ShouldEqual, robotID) return &pb.GetRobotAPIKeysResponse{ ApiKeys: []*pb.APIKeyWithAuthorizations{&pbAPIKeyWithAuthorizations}, @@ -971,7 +1044,9 @@ func TestAppClient(t *testing.T) { }) t.Run("MarkPartForRestart", func(t *testing.T) { - grpcClient.MarkPartForRestartFunc = func(ctx context.Context, in *pb.MarkPartForRestartRequest, opts ...grpc.CallOption) (*pb.MarkPartForRestartResponse, error) { + grpcClient.MarkPartForRestartFunc = func( + ctx context.Context, in *pb.MarkPartForRestartRequest, opts ...grpc.CallOption, + ) (*pb.MarkPartForRestartResponse, error) { test.That(t, in.PartId, test.ShouldEqual, partID) return &pb.MarkPartForRestartResponse{}, nil } @@ -979,7 +1054,9 @@ func TestAppClient(t *testing.T) { }) t.Run("CreateRobotPartSecret", func(t *testing.T) { - grpcClient.CreateRobotPartSecretFunc = func(ctx context.Context, in *pb.CreateRobotPartSecretRequest, opts ...grpc.CallOption) (*pb.CreateRobotPartSecretResponse, error) { + grpcClient.CreateRobotPartSecretFunc = func( + ctx context.Context, in *pb.CreateRobotPartSecretRequest, opts ...grpc.CallOption, + ) (*pb.CreateRobotPartSecretResponse, error) { test.That(t, in.PartId, test.ShouldEqual, partID) return &pb.CreateRobotPartSecretResponse{ Part: &pbRobotPart, @@ -1000,7 +1077,9 @@ func TestAppClient(t *testing.T) { }) t.Run("DeleteRobotPartSecret", func(t *testing.T) { - grpcClient.DeleteRobotPartSecretFunc = func(ctx context.Context, in *pb.DeleteRobotPartSecretRequest, opts ...grpc.CallOption) (*pb.DeleteRobotPartSecretResponse, error) { + grpcClient.DeleteRobotPartSecretFunc = func( + ctx context.Context, in *pb.DeleteRobotPartSecretRequest, opts ...grpc.CallOption, + ) (*pb.DeleteRobotPartSecretResponse, error) { test.That(t, in.PartId, test.ShouldEqual, partID) test.That(t, in.SecretId, test.ShouldEqual, secretID) return &pb.DeleteRobotPartSecretResponse{}, nil @@ -1010,7 +1089,9 @@ func TestAppClient(t *testing.T) { t.Run("ListRobots", func(t *testing.T) { expectedRobots := []*Robot{&robot} - grpcClient.ListRobotsFunc = func(ctx context.Context, in *pb.ListRobotsRequest, opts ...grpc.CallOption) (*pb.ListRobotsResponse, error) { + grpcClient.ListRobotsFunc = func( + ctx context.Context, in *pb.ListRobotsRequest, opts ...grpc.CallOption, + ) (*pb.ListRobotsResponse, error) { test.That(t, in.LocationId, test.ShouldEqual, locationID) return &pb.ListRobotsResponse{ Robots: []*pb.Robot{&pbRobot}, @@ -1022,7 +1103,9 @@ func TestAppClient(t *testing.T) { }) t.Run("NewRobot", func(t *testing.T) { - grpcClient.NewRobotFunc = func(ctx context.Context, in *pb.NewRobotRequest, opts ...grpc.CallOption) (*pb.NewRobotResponse, error) { + grpcClient.NewRobotFunc = func( + ctx context.Context, in *pb.NewRobotRequest, opts ...grpc.CallOption, + ) (*pb.NewRobotResponse, error) { test.That(t, in.Name, test.ShouldEqual, name) test.That(t, in.Location, test.ShouldEqual, locationID) return &pb.NewRobotResponse{ @@ -1033,9 +1116,10 @@ func TestAppClient(t *testing.T) { test.That(t, resp, test.ShouldResemble, robotID) }) - t.Run("UpdateRobot", func(t *testing.T) { - grpcClient.UpdateRobotFunc = func(ctx context.Context, in *pb.UpdateRobotRequest, opts ...grpc.CallOption) (*pb.UpdateRobotResponse, error) { + grpcClient.UpdateRobotFunc = func( + ctx context.Context, in *pb.UpdateRobotRequest, opts ...grpc.CallOption, + ) (*pb.UpdateRobotResponse, error) { test.That(t, in.Id, test.ShouldEqual, robotID) test.That(t, in.Name, test.ShouldEqual, name) test.That(t, in.Location, test.ShouldEqual, locationID) @@ -1048,7 +1132,9 @@ func TestAppClient(t *testing.T) { }) t.Run("DeleteRobot", func(t *testing.T) { - grpcClient.DeleteRobotFunc = func(ctx context.Context, in *pb.DeleteRobotRequest, opts ...grpc.CallOption) (*pb.DeleteRobotResponse, error) { + grpcClient.DeleteRobotFunc = func( + ctx context.Context, in *pb.DeleteRobotRequest, opts ...grpc.CallOption, + ) (*pb.DeleteRobotResponse, error) { test.That(t, in.Id, test.ShouldEqual, robotID) return &pb.DeleteRobotResponse{}, nil } diff --git a/app/authorization.go b/app/authorization.go index b7c2242f00a..60ab908dca5 100644 --- a/app/authorization.go +++ b/app/authorization.go @@ -113,16 +113,18 @@ func sharedSecretFromProto(sharedSecret *pb.SharedSecret) *SharedSecret { type SharedSecretState int32 const ( - // SharedSecretUnspecified represents an unspecified shared secret state. + // SharedSecretStateUnspecified represents an unspecified shared secret state. SharedSecretStateUnspecified SharedSecretState = 0 - // SharedSecretEnabled represents an enabled secret that can be used in authentication. + // SharedSecretStateEnabled represents an enabled secret that can be used in authentication. SharedSecretStateEnabled SharedSecretState = 1 - // SharedSecretDisabled represents a disabled secret that must not be used to authenticate to rpc. + // SharedSecretStateDisabled represents a disabled secret that must not be used to authenticate to rpc. SharedSecretStateDisabled SharedSecretState = 2 ) func sharedSecretStateFromProto(state pb.SharedSecret_State) SharedSecretState { switch state { + case pb.SharedSecret_STATE_UNSPECIFIED: + return SharedSecretStateUnspecified case pb.SharedSecret_STATE_ENABLED: return SharedSecretStateEnabled case pb.SharedSecret_STATE_DISABLED: @@ -165,6 +167,8 @@ const ( func authenticationTypeFromProto(authenticationType pb.AuthenticationType) AuthenticationType { switch authenticationType { + case pb.AuthenticationType_AUTHENTICATION_TYPE_UNSPECIFIED: + return AuthenticationTypeUnspecified case pb.AuthenticationType_AUTHENTICATION_TYPE_WEB_OAUTH: return AuthenticationTypeWebOAuth case pb.AuthenticationType_AUTHENTICATION_TYPE_API_KEY: diff --git a/app/fragment.go b/app/fragment.go index 9fa63c182a7..08033875c2b 100644 --- a/app/fragment.go +++ b/app/fragment.go @@ -21,7 +21,7 @@ type Fragment struct { LastUpdated *timestamppb.Timestamp } -func fragmentFromProto(fragment *pb.Fragment) (*Fragment) { +func fragmentFromProto(fragment *pb.Fragment) *Fragment { f := fragment.Fragment.AsMap() return &Fragment{ ID: fragment.Id, @@ -55,6 +55,8 @@ const ( func fragmentVisibilityFromProto(visibility pb.FragmentVisibility) FragmentVisibility { switch visibility { + case pb.FragmentVisibility_FRAGMENT_VISIBILITY_UNSPECIFIED: + return FragmentVisibilityUnspecified case pb.FragmentVisibility_FRAGMENT_VISIBILITY_PRIVATE: return FragmentVisibilityPrivate case pb.FragmentVisibility_FRAGMENT_VISIBILITY_PUBLIC: @@ -66,8 +68,10 @@ func fragmentVisibilityFromProto(visibility pb.FragmentVisibility) FragmentVisib } } -func fragmentVisibilityToProto(visibility FragmentVisibility) (pb.FragmentVisibility) { +func fragmentVisibilityToProto(visibility FragmentVisibility) pb.FragmentVisibility { switch visibility { + case FragmentVisibilityUnspecified: + return pb.FragmentVisibility_FRAGMENT_VISIBILITY_UNSPECIFIED case FragmentVisibilityPrivate: return pb.FragmentVisibility_FRAGMENT_VISIBILITY_PRIVATE case FragmentVisibilityPublic: @@ -87,7 +91,7 @@ type FragmentHistoryEntry struct { EditedBy *AuthenticatorInfo } -func fragmentHistoryEntryFromProto(entry *pb.FragmentHistoryEntry) (*FragmentHistoryEntry) { +func fragmentHistoryEntryFromProto(entry *pb.FragmentHistoryEntry) *FragmentHistoryEntry { return &FragmentHistoryEntry{ Fragment: entry.Fragment, EditedOn: entry.EditedOn, diff --git a/app/organization.go b/app/organization.go index 3645790080a..a7e8aadd0dc 100644 --- a/app/organization.go +++ b/app/organization.go @@ -92,17 +92,17 @@ func organizationInviteFromProto(organizationInvite *pb.OrganizationInvite) *Org // BillingAddress contains billing address details. type BillingAddress struct { - AddressLine_1 string - AddressLine_2 *string - City string - State string + AddressLine1 string + AddressLine2 *string + City string + State string } func billingAddressToProto(addr *BillingAddress) *pb.BillingAddress { return &pb.BillingAddress{ - AddressLine_1: addr.AddressLine_1, - AddressLine_2: addr.AddressLine_2, - City: addr.City, - State: addr.State, + AddressLine_1: addr.AddressLine1, + AddressLine_2: addr.AddressLine2, + City: addr.City, + State: addr.State, } } diff --git a/testutils/inject/app_service_client.go b/testutils/inject/app_service_client.go index c52884b95ae..6ed3e5036ed 100644 --- a/testutils/inject/app_service_client.go +++ b/testutils/inject/app_service_client.go @@ -166,11 +166,11 @@ type AppServiceClient struct { opts ...grpc.CallOption) (*apppb.RotateKeyResponse, error) CreateKeyFromExistingKeyAuthorizationsFunc func(ctx context.Context, in *apppb.CreateKeyFromExistingKeyAuthorizationsRequest, opts ...grpc.CallOption) (*apppb.CreateKeyFromExistingKeyAuthorizationsResponse, error) - } +} // GetUserIDByEmail calls the injected GetUserIDByEmailFunc or the real version. -func (asc *AppServiceClient) GetUserIDByEmail(ctx context.Context, in *apppb.GetUserIDByEmailRequest, - opts ...grpc.CallOption, +func (asc *AppServiceClient) GetUserIDByEmail( + ctx context.Context, in *apppb.GetUserIDByEmailRequest, opts ...grpc.CallOption, ) (*apppb.GetUserIDByEmailResponse, error) { if asc.GetUserIDByEmailFunc == nil { return asc.AppServiceClient.GetUserIDByEmail(ctx, in, opts...) @@ -179,8 +179,8 @@ func (asc *AppServiceClient) GetUserIDByEmail(ctx context.Context, in *apppb.Get } // CreateOrganization calls the injected CreateOrganizationFunc or the real version. -func (asc *AppServiceClient) CreateOrganization(ctx context.Context, in *apppb.CreateOrganizationRequest, - opts ...grpc.CallOption, +func (asc *AppServiceClient) CreateOrganization( + ctx context.Context, in *apppb.CreateOrganizationRequest, opts ...grpc.CallOption, ) (*apppb.CreateOrganizationResponse, error) { if asc.CreateOrganizationFunc == nil { return asc.AppServiceClient.CreateOrganization(ctx, in, opts...) @@ -189,8 +189,8 @@ func (asc *AppServiceClient) CreateOrganization(ctx context.Context, in *apppb.C } // ListOrganizations calls the injected ListOrganizationsFunc or the real version. -func (asc *AppServiceClient) ListOrganizations(ctx context.Context, in *apppb.ListOrganizationsRequest, - opts ...grpc.CallOption, +func (asc *AppServiceClient) ListOrganizations( + ctx context.Context, in *apppb.ListOrganizationsRequest, opts ...grpc.CallOption, ) (*apppb.ListOrganizationsResponse, error) { if asc.ListOrganizationsFunc == nil { return asc.AppServiceClient.ListOrganizations(ctx, in, opts...) @@ -199,8 +199,8 @@ func (asc *AppServiceClient) ListOrganizations(ctx context.Context, in *apppb.Li } // GetOrganizationsWithAccessToLocation calls the injected GetOrganizationsWithAccessToLocationFunc or the real version. -func (asc *AppServiceClient) GetOrganizationsWithAccessToLocation(ctx context.Context, in *apppb.GetOrganizationsWithAccessToLocationRequest, - opts ...grpc.CallOption, +func (asc *AppServiceClient) GetOrganizationsWithAccessToLocation( + ctx context.Context, in *apppb.GetOrganizationsWithAccessToLocationRequest, opts ...grpc.CallOption, ) (*apppb.GetOrganizationsWithAccessToLocationResponse, error) { if asc.GetOrganizationsWithAccessToLocationFunc == nil { return asc.AppServiceClient.GetOrganizationsWithAccessToLocation(ctx, in, opts...) @@ -209,8 +209,8 @@ func (asc *AppServiceClient) GetOrganizationsWithAccessToLocation(ctx context.Co } // ListOrganizationsByUser calls the injected ListOrganizationsByUserFunc or the real version. -func (asc *AppServiceClient) ListOrganizationsByUser(ctx context.Context, in *apppb.ListOrganizationsByUserRequest, - opts ...grpc.CallOption, +func (asc *AppServiceClient) ListOrganizationsByUser( + ctx context.Context, in *apppb.ListOrganizationsByUserRequest, opts ...grpc.CallOption, ) (*apppb.ListOrganizationsByUserResponse, error) { if asc.ListOrganizationsByUserFunc == nil { return asc.AppServiceClient.ListOrganizationsByUser(ctx, in, opts...) @@ -219,8 +219,8 @@ func (asc *AppServiceClient) ListOrganizationsByUser(ctx context.Context, in *ap } // GetOrganization calls the injected GetOrganizationFunc or the real version. -func (asc *AppServiceClient) GetOrganization(ctx context.Context, in *apppb.GetOrganizationRequest, - opts ...grpc.CallOption, +func (asc *AppServiceClient) GetOrganization( + ctx context.Context, in *apppb.GetOrganizationRequest, opts ...grpc.CallOption, ) (*apppb.GetOrganizationResponse, error) { if asc.GetOrganizationFunc == nil { return asc.AppServiceClient.GetOrganization(ctx, in, opts...) @@ -229,8 +229,8 @@ func (asc *AppServiceClient) GetOrganization(ctx context.Context, in *apppb.GetO } // GetOrganizationNamespaceAvailability calls the injected GetOrganizationNamespaceAvailabilityFunc or the real version. -func (asc *AppServiceClient) GetOrganizationNamespaceAvailability(ctx context.Context, in *apppb.GetOrganizationNamespaceAvailabilityRequest, - opts ...grpc.CallOption, +func (asc *AppServiceClient) GetOrganizationNamespaceAvailability( + ctx context.Context, in *apppb.GetOrganizationNamespaceAvailabilityRequest, opts ...grpc.CallOption, ) (*apppb.GetOrganizationNamespaceAvailabilityResponse, error) { if asc.GetOrganizationNamespaceAvailabilityFunc == nil { return asc.AppServiceClient.GetOrganizationNamespaceAvailability(ctx, in, opts...) @@ -239,8 +239,8 @@ func (asc *AppServiceClient) GetOrganizationNamespaceAvailability(ctx context.Co } // UpdateOrganization calls the injected UpdateOrganizationFunc or the real version. -func (asc *AppServiceClient) UpdateOrganization(ctx context.Context, in *apppb.UpdateOrganizationRequest, - opts ...grpc.CallOption, +func (asc *AppServiceClient) UpdateOrganization( + ctx context.Context, in *apppb.UpdateOrganizationRequest, opts ...grpc.CallOption, ) (*apppb.UpdateOrganizationResponse, error) { if asc.UpdateOrganizationFunc == nil { return asc.AppServiceClient.UpdateOrganization(ctx, in, opts...) @@ -249,8 +249,8 @@ func (asc *AppServiceClient) UpdateOrganization(ctx context.Context, in *apppb.U } // DeleteOrganization calls the injected DeleteOrganizationFunc or the real version. -func (asc *AppServiceClient) DeleteOrganization(ctx context.Context, in *apppb.DeleteOrganizationRequest, - opts ...grpc.CallOption, +func (asc *AppServiceClient) DeleteOrganization( + ctx context.Context, in *apppb.DeleteOrganizationRequest, opts ...grpc.CallOption, ) (*apppb.DeleteOrganizationResponse, error) { if asc.DeleteOrganizationFunc == nil { return asc.AppServiceClient.DeleteOrganization(ctx, in, opts...) @@ -259,8 +259,8 @@ func (asc *AppServiceClient) DeleteOrganization(ctx context.Context, in *apppb.D } // ListOrganizationMembers calls the injected ListOrganizationMembersFunc or the real version. -func (asc *AppServiceClient) ListOrganizationMembers(ctx context.Context, in *apppb.ListOrganizationMembersRequest, - opts ...grpc.CallOption, +func (asc *AppServiceClient) ListOrganizationMembers( + ctx context.Context, in *apppb.ListOrganizationMembersRequest, opts ...grpc.CallOption, ) (*apppb.ListOrganizationMembersResponse, error) { if asc.ListOrganizationMembersFunc == nil { return asc.AppServiceClient.ListOrganizationMembers(ctx, in, opts...) @@ -269,8 +269,8 @@ func (asc *AppServiceClient) ListOrganizationMembers(ctx context.Context, in *ap } // CreateOrganizationInvite calls the injected CreateOrganizationInviteFunc or the real version. -func (asc *AppServiceClient) CreateOrganizationInvite(ctx context.Context, in *apppb.CreateOrganizationInviteRequest, - opts ...grpc.CallOption, +func (asc *AppServiceClient) CreateOrganizationInvite( + ctx context.Context, in *apppb.CreateOrganizationInviteRequest, opts ...grpc.CallOption, ) (*apppb.CreateOrganizationInviteResponse, error) { if asc.CreateOrganizationInviteFunc == nil { return asc.AppServiceClient.CreateOrganizationInvite(ctx, in, opts...) @@ -279,8 +279,8 @@ func (asc *AppServiceClient) CreateOrganizationInvite(ctx context.Context, in *a } // UpdateOrganizationInviteAuthorizations calls the injected UpdateOrganizationInviteAuthorizationsFunc or the real version. -func (asc *AppServiceClient) UpdateOrganizationInviteAuthorizations(ctx context.Context, in *apppb.UpdateOrganizationInviteAuthorizationsRequest, - opts ...grpc.CallOption, +func (asc *AppServiceClient) UpdateOrganizationInviteAuthorizations( + ctx context.Context, in *apppb.UpdateOrganizationInviteAuthorizationsRequest, opts ...grpc.CallOption, ) (*apppb.UpdateOrganizationInviteAuthorizationsResponse, error) { if asc.UpdateOrganizationInviteAuthorizationsFunc == nil { return asc.AppServiceClient.UpdateOrganizationInviteAuthorizations(ctx, in, opts...) @@ -289,8 +289,8 @@ func (asc *AppServiceClient) UpdateOrganizationInviteAuthorizations(ctx context. } // DeleteOrganizationMember calls the injected DeleteOrganizationMemberFunc or the real version. -func (asc *AppServiceClient) DeleteOrganizationMember(ctx context.Context, in *apppb.DeleteOrganizationMemberRequest, - opts ...grpc.CallOption, +func (asc *AppServiceClient) DeleteOrganizationMember( + ctx context.Context, in *apppb.DeleteOrganizationMemberRequest, opts ...grpc.CallOption, ) (*apppb.DeleteOrganizationMemberResponse, error) { if asc.DeleteOrganizationMemberFunc == nil { return asc.AppServiceClient.DeleteOrganizationMember(ctx, in, opts...) @@ -299,8 +299,8 @@ func (asc *AppServiceClient) DeleteOrganizationMember(ctx context.Context, in *a } // DeleteOrganizationInvite calls the injected DeleteOrganizationInviteFunc or the real version. -func (asc *AppServiceClient) DeleteOrganizationInvite(ctx context.Context, in *apppb.DeleteOrganizationInviteRequest, - opts ...grpc.CallOption, +func (asc *AppServiceClient) DeleteOrganizationInvite( + ctx context.Context, in *apppb.DeleteOrganizationInviteRequest, opts ...grpc.CallOption, ) (*apppb.DeleteOrganizationInviteResponse, error) { if asc.DeleteOrganizationInviteFunc == nil { return asc.AppServiceClient.DeleteOrganizationInvite(ctx, in, opts...) @@ -309,8 +309,8 @@ func (asc *AppServiceClient) DeleteOrganizationInvite(ctx context.Context, in *a } // ResendOrganizationInvite calls the injected ResendOrganizationInviteFunc or the real version. -func (asc *AppServiceClient) ResendOrganizationInvite(ctx context.Context, in *apppb.ResendOrganizationInviteRequest, - opts ...grpc.CallOption, +func (asc *AppServiceClient) ResendOrganizationInvite( + ctx context.Context, in *apppb.ResendOrganizationInviteRequest, opts ...grpc.CallOption, ) (*apppb.ResendOrganizationInviteResponse, error) { if asc.ResendOrganizationInviteFunc == nil { return asc.AppServiceClient.ResendOrganizationInvite(ctx, in, opts...) @@ -319,8 +319,8 @@ func (asc *AppServiceClient) ResendOrganizationInvite(ctx context.Context, in *a } // EnableBillingService calls the injected EnableBillingServiceFunc or the real version. -func (asc *AppServiceClient) EnableBillingService(ctx context.Context, in *apppb.EnableBillingServiceRequest, - opts ...grpc.CallOption, +func (asc *AppServiceClient) EnableBillingService( + ctx context.Context, in *apppb.EnableBillingServiceRequest, opts ...grpc.CallOption, ) (*apppb.EnableBillingServiceResponse, error) { if asc.EnableBillingServiceFunc == nil { return asc.AppServiceClient.EnableBillingService(ctx, in, opts...) @@ -329,8 +329,8 @@ func (asc *AppServiceClient) EnableBillingService(ctx context.Context, in *apppb } // DisableBillingService calls the injected DisableBillingServiceFunc or the real version. -func (asc *AppServiceClient) DisableBillingService(ctx context.Context, in *apppb.DisableBillingServiceRequest, - opts ...grpc.CallOption, +func (asc *AppServiceClient) DisableBillingService( + ctx context.Context, in *apppb.DisableBillingServiceRequest, opts ...grpc.CallOption, ) (*apppb.DisableBillingServiceResponse, error) { if asc.DisableBillingServiceFunc == nil { return asc.AppServiceClient.DisableBillingService(ctx, in, opts...) @@ -339,8 +339,8 @@ func (asc *AppServiceClient) DisableBillingService(ctx context.Context, in *appp } // UpdateBillingService calls the injected UpdateBillingServiceFunc or the real version. -func (asc *AppServiceClient) UpdateBillingService(ctx context.Context, in *apppb.UpdateBillingServiceRequest, - opts ...grpc.CallOption, +func (asc *AppServiceClient) UpdateBillingService( + ctx context.Context, in *apppb.UpdateBillingServiceRequest, opts ...grpc.CallOption, ) (*apppb.UpdateBillingServiceResponse, error) { if asc.UpdateBillingServiceFunc == nil { return asc.AppServiceClient.UpdateBillingService(ctx, in, opts...) @@ -349,8 +349,8 @@ func (asc *AppServiceClient) UpdateBillingService(ctx context.Context, in *apppb } // OrganizationSetSupportEmail calls the injected OrganizationSetSupportEmailFunc or the real version. -func (asc *AppServiceClient) OrganizationSetSupportEmail(ctx context.Context, in *apppb.OrganizationSetSupportEmailRequest, - opts ...grpc.CallOption, +func (asc *AppServiceClient) OrganizationSetSupportEmail( + ctx context.Context, in *apppb.OrganizationSetSupportEmailRequest, opts ...grpc.CallOption, ) (*apppb.OrganizationSetSupportEmailResponse, error) { if asc.OrganizationSetSupportEmailFunc == nil { return asc.AppServiceClient.OrganizationSetSupportEmail(ctx, in, opts...) @@ -359,8 +359,8 @@ func (asc *AppServiceClient) OrganizationSetSupportEmail(ctx context.Context, in } // OrganizationGetSupportEmail calls the injected OrganizationGetSupportEmailFunc or the real version. -func (asc *AppServiceClient) OrganizationGetSupportEmail(ctx context.Context, in *apppb.OrganizationGetSupportEmailRequest, - opts ...grpc.CallOption, +func (asc *AppServiceClient) OrganizationGetSupportEmail( + ctx context.Context, in *apppb.OrganizationGetSupportEmailRequest, opts ...grpc.CallOption, ) (*apppb.OrganizationGetSupportEmailResponse, error) { if asc.OrganizationGetSupportEmailFunc == nil { return asc.AppServiceClient.OrganizationGetSupportEmail(ctx, in, opts...) @@ -369,8 +369,8 @@ func (asc *AppServiceClient) OrganizationGetSupportEmail(ctx context.Context, in } // CreateLocation calls the injected CreateLocationFunc or the real version. -func (asc *AppServiceClient) CreateLocation(ctx context.Context, in *apppb.CreateLocationRequest, - opts ...grpc.CallOption, +func (asc *AppServiceClient) CreateLocation( + ctx context.Context, in *apppb.CreateLocationRequest, opts ...grpc.CallOption, ) (*apppb.CreateLocationResponse, error) { if asc.CreateLocationFunc == nil { return asc.AppServiceClient.CreateLocation(ctx, in, opts...) @@ -379,8 +379,8 @@ func (asc *AppServiceClient) CreateLocation(ctx context.Context, in *apppb.Creat } // GetLocation calls the injected GetLocationFunc or the real version. -func (asc *AppServiceClient) GetLocation(ctx context.Context, in *apppb.GetLocationRequest, - opts ...grpc.CallOption, +func (asc *AppServiceClient) GetLocation( + ctx context.Context, in *apppb.GetLocationRequest, opts ...grpc.CallOption, ) (*apppb.GetLocationResponse, error) { if asc.GetLocationFunc == nil { return asc.AppServiceClient.GetLocation(ctx, in, opts...) @@ -389,8 +389,8 @@ func (asc *AppServiceClient) GetLocation(ctx context.Context, in *apppb.GetLocat } // UpdateLocation calls the injected UpdateLocationFunc or the real version. -func (asc *AppServiceClient) UpdateLocation(ctx context.Context, in *apppb.UpdateLocationRequest, - opts ...grpc.CallOption, +func (asc *AppServiceClient) UpdateLocation( + ctx context.Context, in *apppb.UpdateLocationRequest, opts ...grpc.CallOption, ) (*apppb.UpdateLocationResponse, error) { if asc.UpdateLocationFunc == nil { return asc.AppServiceClient.UpdateLocation(ctx, in, opts...) @@ -399,8 +399,8 @@ func (asc *AppServiceClient) UpdateLocation(ctx context.Context, in *apppb.Updat } // DeleteLocation calls the injected DeleteLocationFunc or the real version. -func (asc *AppServiceClient) DeleteLocation(ctx context.Context, in *apppb.DeleteLocationRequest, - opts ...grpc.CallOption, +func (asc *AppServiceClient) DeleteLocation( + ctx context.Context, in *apppb.DeleteLocationRequest, opts ...grpc.CallOption, ) (*apppb.DeleteLocationResponse, error) { if asc.DeleteLocationFunc == nil { return asc.AppServiceClient.DeleteLocation(ctx, in, opts...) @@ -409,8 +409,8 @@ func (asc *AppServiceClient) DeleteLocation(ctx context.Context, in *apppb.Delet } // ListLocations calls the injected ListLocationsFunc or the real version. -func (asc *AppServiceClient) ListLocations(ctx context.Context, in *apppb.ListLocationsRequest, - opts ...grpc.CallOption, +func (asc *AppServiceClient) ListLocations( + ctx context.Context, in *apppb.ListLocationsRequest, opts ...grpc.CallOption, ) (*apppb.ListLocationsResponse, error) { if asc.ListLocationsFunc == nil { return asc.AppServiceClient.ListLocations(ctx, in, opts...) @@ -419,8 +419,8 @@ func (asc *AppServiceClient) ListLocations(ctx context.Context, in *apppb.ListLo } // ShareLocation calls the injected ShareLocationFunc or the real version. -func (asc *AppServiceClient) ShareLocation(ctx context.Context, in *apppb.ShareLocationRequest, - opts ...grpc.CallOption, +func (asc *AppServiceClient) ShareLocation( + ctx context.Context, in *apppb.ShareLocationRequest, opts ...grpc.CallOption, ) (*apppb.ShareLocationResponse, error) { if asc.ShareLocationFunc == nil { return asc.AppServiceClient.ShareLocation(ctx, in, opts...) @@ -429,8 +429,8 @@ func (asc *AppServiceClient) ShareLocation(ctx context.Context, in *apppb.ShareL } // UnshareLocation calls the injected UnshareLocationFunc or the real version. -func (asc *AppServiceClient) UnshareLocation(ctx context.Context, in *apppb.UnshareLocationRequest, - opts ...grpc.CallOption, +func (asc *AppServiceClient) UnshareLocation( + ctx context.Context, in *apppb.UnshareLocationRequest, opts ...grpc.CallOption, ) (*apppb.UnshareLocationResponse, error) { if asc.UnshareLocationFunc == nil { return asc.AppServiceClient.UnshareLocation(ctx, in, opts...) @@ -439,8 +439,8 @@ func (asc *AppServiceClient) UnshareLocation(ctx context.Context, in *apppb.Unsh } // LocationAuth calls the injected LocationAuthFunc or the real version. -func (asc *AppServiceClient) LocationAuth(ctx context.Context, in *apppb.LocationAuthRequest, - opts ...grpc.CallOption, +func (asc *AppServiceClient) LocationAuth( + ctx context.Context, in *apppb.LocationAuthRequest, opts ...grpc.CallOption, ) (*apppb.LocationAuthResponse, error) { if asc.LocationAuthFunc == nil { return asc.AppServiceClient.LocationAuth(ctx, in, opts...) @@ -449,8 +449,8 @@ func (asc *AppServiceClient) LocationAuth(ctx context.Context, in *apppb.Locatio } // CreateLocationSecret calls the injected CreateLocationSecretFunc or the real version. -func (asc *AppServiceClient) CreateLocationSecret(ctx context.Context, in *apppb.CreateLocationSecretRequest, - opts ...grpc.CallOption, +func (asc *AppServiceClient) CreateLocationSecret( + ctx context.Context, in *apppb.CreateLocationSecretRequest, opts ...grpc.CallOption, ) (*apppb.CreateLocationSecretResponse, error) { if asc.CreateLocationSecretFunc == nil { return asc.AppServiceClient.CreateLocationSecret(ctx, in, opts...) @@ -459,8 +459,8 @@ func (asc *AppServiceClient) CreateLocationSecret(ctx context.Context, in *apppb } // DeleteLocationSecret calls the injected DeleteLocationSecretFunc or the real version. -func (asc *AppServiceClient) DeleteLocationSecret(ctx context.Context, in *apppb.DeleteLocationSecretRequest, - opts ...grpc.CallOption, +func (asc *AppServiceClient) DeleteLocationSecret( + ctx context.Context, in *apppb.DeleteLocationSecretRequest, opts ...grpc.CallOption, ) (*apppb.DeleteLocationSecretResponse, error) { if asc.DeleteLocationSecretFunc == nil { return asc.AppServiceClient.DeleteLocationSecret(ctx, in, opts...) @@ -469,8 +469,8 @@ func (asc *AppServiceClient) DeleteLocationSecret(ctx context.Context, in *apppb } // GetRobot calls the injected GetRobotFunc or the real version. -func (asc *AppServiceClient) GetRobot(ctx context.Context, in *apppb.GetRobotRequest, - opts ...grpc.CallOption, +func (asc *AppServiceClient) GetRobot( + ctx context.Context, in *apppb.GetRobotRequest, opts ...grpc.CallOption, ) (*apppb.GetRobotResponse, error) { if asc.GetRobotFunc == nil { return asc.AppServiceClient.GetRobot(ctx, in, opts...) @@ -479,8 +479,8 @@ func (asc *AppServiceClient) GetRobot(ctx context.Context, in *apppb.GetRobotReq } // GetRoverRentalRobots calls the injected GetRoverRentalRobotsFunc or the real version. -func (asc *AppServiceClient) GetRoverRentalRobots(ctx context.Context, in *apppb.GetRoverRentalRobotsRequest, - opts ...grpc.CallOption, +func (asc *AppServiceClient) GetRoverRentalRobots( + ctx context.Context, in *apppb.GetRoverRentalRobotsRequest, opts ...grpc.CallOption, ) (*apppb.GetRoverRentalRobotsResponse, error) { if asc.GetRoverRentalRobotsFunc == nil { return asc.AppServiceClient.GetRoverRentalRobots(ctx, in, opts...) @@ -489,8 +489,8 @@ func (asc *AppServiceClient) GetRoverRentalRobots(ctx context.Context, in *apppb } // GetRobotParts calls the injected GetRobotPartsFunc or the real version. -func (asc *AppServiceClient) GetRobotParts(ctx context.Context, in *apppb.GetRobotPartsRequest, - opts ...grpc.CallOption, +func (asc *AppServiceClient) GetRobotParts( + ctx context.Context, in *apppb.GetRobotPartsRequest, opts ...grpc.CallOption, ) (*apppb.GetRobotPartsResponse, error) { if asc.GetRobotPartsFunc == nil { return asc.AppServiceClient.GetRobotParts(ctx, in, opts...) @@ -499,8 +499,8 @@ func (asc *AppServiceClient) GetRobotParts(ctx context.Context, in *apppb.GetRob } // GetRobotPart calls the injected GetRobotPartFunc or the real version. -func (asc *AppServiceClient) GetRobotPart(ctx context.Context, in *apppb.GetRobotPartRequest, - opts ...grpc.CallOption, +func (asc *AppServiceClient) GetRobotPart( + ctx context.Context, in *apppb.GetRobotPartRequest, opts ...grpc.CallOption, ) (*apppb.GetRobotPartResponse, error) { if asc.GetRobotPartFunc == nil { return asc.AppServiceClient.GetRobotPart(ctx, in, opts...) @@ -509,8 +509,8 @@ func (asc *AppServiceClient) GetRobotPart(ctx context.Context, in *apppb.GetRobo } // GetRobotPartLogs calls the injected GetRobotPartLogsFunc or the real version. -func (asc *AppServiceClient) GetRobotPartLogs(ctx context.Context, in *apppb.GetRobotPartLogsRequest, - opts ...grpc.CallOption, +func (asc *AppServiceClient) GetRobotPartLogs( + ctx context.Context, in *apppb.GetRobotPartLogsRequest, opts ...grpc.CallOption, ) (*apppb.GetRobotPartLogsResponse, error) { if asc.GetRobotPartLogsFunc == nil { return asc.AppServiceClient.GetRobotPartLogs(ctx, in, opts...) @@ -519,8 +519,7 @@ func (asc *AppServiceClient) GetRobotPartLogs(ctx context.Context, in *apppb.Get } // // TailRobotPartLogs calls the injected TailRobotPartLogsFunc or the real version. -// func (asc *AppServiceClient) TailRobotPartLogs(ctx context.Context, in *apppb.TailRobotPartLogsRequest, -// opts ...grpc.CallOption, +// func (asc *AppServiceClient) TailRobotPartLogs(ctx context.Context, in *apppb.TailRobotPartLogsRequest// opts ...grpc.CallOption, // ) (*apppb.TailRobotPartLogsResponse, error) { // if asc.TailRobotPartLogsFunc == nil { // return asc.AppServiceClient.TailRobotPartLogs(ctx, in, opts...) @@ -529,8 +528,8 @@ func (asc *AppServiceClient) GetRobotPartLogs(ctx context.Context, in *apppb.Get // } // GetRobotPartHistory calls the injected GetRobotPartHistoryFunc or the real version. -func (asc *AppServiceClient) GetRobotPartHistory(ctx context.Context, in *apppb.GetRobotPartHistoryRequest, - opts ...grpc.CallOption, +func (asc *AppServiceClient) GetRobotPartHistory( + ctx context.Context, in *apppb.GetRobotPartHistoryRequest, opts ...grpc.CallOption, ) (*apppb.GetRobotPartHistoryResponse, error) { if asc.GetRobotPartHistoryFunc == nil { return asc.AppServiceClient.GetRobotPartHistory(ctx, in, opts...) @@ -539,8 +538,8 @@ func (asc *AppServiceClient) GetRobotPartHistory(ctx context.Context, in *apppb. } // UpdateRobotPart calls the injected UpdateRobotPartFunc or the real version. -func (asc *AppServiceClient) UpdateRobotPart(ctx context.Context, in *apppb.UpdateRobotPartRequest, - opts ...grpc.CallOption, +func (asc *AppServiceClient) UpdateRobotPart( + ctx context.Context, in *apppb.UpdateRobotPartRequest, opts ...grpc.CallOption, ) (*apppb.UpdateRobotPartResponse, error) { if asc.UpdateRobotPartFunc == nil { return asc.AppServiceClient.UpdateRobotPart(ctx, in, opts...) @@ -549,8 +548,8 @@ func (asc *AppServiceClient) UpdateRobotPart(ctx context.Context, in *apppb.Upda } // NewRobotPart calls the injected NewRobotPartFunc or the real version. -func (asc *AppServiceClient) NewRobotPart(ctx context.Context, in *apppb.NewRobotPartRequest, - opts ...grpc.CallOption, +func (asc *AppServiceClient) NewRobotPart( + ctx context.Context, in *apppb.NewRobotPartRequest, opts ...grpc.CallOption, ) (*apppb.NewRobotPartResponse, error) { if asc.NewRobotPartFunc == nil { return asc.AppServiceClient.NewRobotPart(ctx, in, opts...) @@ -559,8 +558,8 @@ func (asc *AppServiceClient) NewRobotPart(ctx context.Context, in *apppb.NewRobo } // DeleteRobotPart calls the injected DeleteRobotPartFunc or the real version. -func (asc *AppServiceClient) DeleteRobotPart(ctx context.Context, in *apppb.DeleteRobotPartRequest, - opts ...grpc.CallOption, +func (asc *AppServiceClient) DeleteRobotPart( + ctx context.Context, in *apppb.DeleteRobotPartRequest, opts ...grpc.CallOption, ) (*apppb.DeleteRobotPartResponse, error) { if asc.DeleteRobotPartFunc == nil { return asc.AppServiceClient.DeleteRobotPart(ctx, in, opts...) @@ -569,8 +568,8 @@ func (asc *AppServiceClient) DeleteRobotPart(ctx context.Context, in *apppb.Dele } // GetRobotAPIKeys calls the injected GetRobotAPIKeysFunc or the real version. -func (asc *AppServiceClient) GetRobotAPIKeys(ctx context.Context, in *apppb.GetRobotAPIKeysRequest, - opts ...grpc.CallOption, +func (asc *AppServiceClient) GetRobotAPIKeys( + ctx context.Context, in *apppb.GetRobotAPIKeysRequest, opts ...grpc.CallOption, ) (*apppb.GetRobotAPIKeysResponse, error) { if asc.GetRobotAPIKeysFunc == nil { return asc.AppServiceClient.GetRobotAPIKeys(ctx, in, opts...) @@ -579,8 +578,8 @@ func (asc *AppServiceClient) GetRobotAPIKeys(ctx context.Context, in *apppb.GetR } // MarkPartAsMain calls the injected MarkPartAsMainFunc or the real version. -func (asc *AppServiceClient) MarkPartAsMain(ctx context.Context, in *apppb.MarkPartAsMainRequest, - opts ...grpc.CallOption, +func (asc *AppServiceClient) MarkPartAsMain( + ctx context.Context, in *apppb.MarkPartAsMainRequest, opts ...grpc.CallOption, ) (*apppb.MarkPartAsMainResponse, error) { if asc.MarkPartAsMainFunc == nil { return asc.AppServiceClient.MarkPartAsMain(ctx, in, opts...) @@ -589,8 +588,8 @@ func (asc *AppServiceClient) MarkPartAsMain(ctx context.Context, in *apppb.MarkP } // MarkPartForRestart calls the injected MarkPartForRestartFunc or the real version. -func (asc *AppServiceClient) MarkPartForRestart(ctx context.Context, in *apppb.MarkPartForRestartRequest, - opts ...grpc.CallOption, +func (asc *AppServiceClient) MarkPartForRestart( + ctx context.Context, in *apppb.MarkPartForRestartRequest, opts ...grpc.CallOption, ) (*apppb.MarkPartForRestartResponse, error) { if asc.MarkPartForRestartFunc == nil { return asc.AppServiceClient.MarkPartForRestart(ctx, in, opts...) @@ -599,8 +598,8 @@ func (asc *AppServiceClient) MarkPartForRestart(ctx context.Context, in *apppb.M } // CreateRobotPartSecret calls the injected CreateRobotPartSecretFunc or the real version. -func (asc *AppServiceClient) CreateRobotPartSecret(ctx context.Context, in *apppb.CreateRobotPartSecretRequest, - opts ...grpc.CallOption, +func (asc *AppServiceClient) CreateRobotPartSecret( + ctx context.Context, in *apppb.CreateRobotPartSecretRequest, opts ...grpc.CallOption, ) (*apppb.CreateRobotPartSecretResponse, error) { if asc.CreateRobotPartSecretFunc == nil { return asc.AppServiceClient.CreateRobotPartSecret(ctx, in, opts...) @@ -609,8 +608,8 @@ func (asc *AppServiceClient) CreateRobotPartSecret(ctx context.Context, in *appp } // DeleteRobotPartSecret calls the injected DeleteRobotPartSecretFunc or the real version. -func (asc *AppServiceClient) DeleteRobotPartSecret(ctx context.Context, in *apppb.DeleteRobotPartSecretRequest, - opts ...grpc.CallOption, +func (asc *AppServiceClient) DeleteRobotPartSecret( + ctx context.Context, in *apppb.DeleteRobotPartSecretRequest, opts ...grpc.CallOption, ) (*apppb.DeleteRobotPartSecretResponse, error) { if asc.DeleteRobotPartSecretFunc == nil { return asc.AppServiceClient.DeleteRobotPartSecret(ctx, in, opts...) @@ -619,8 +618,8 @@ func (asc *AppServiceClient) DeleteRobotPartSecret(ctx context.Context, in *appp } // ListRobots calls the injected ListRobotsFunc or the real version. -func (asc *AppServiceClient) ListRobots(ctx context.Context, in *apppb.ListRobotsRequest, - opts ...grpc.CallOption, +func (asc *AppServiceClient) ListRobots( + ctx context.Context, in *apppb.ListRobotsRequest, opts ...grpc.CallOption, ) (*apppb.ListRobotsResponse, error) { if asc.ListRobotsFunc == nil { return asc.AppServiceClient.ListRobots(ctx, in, opts...) @@ -629,8 +628,8 @@ func (asc *AppServiceClient) ListRobots(ctx context.Context, in *apppb.ListRobot } // NewRobot calls the injected NewRobotFunc or the real version. -func (asc *AppServiceClient) NewRobot(ctx context.Context, in *apppb.NewRobotRequest, - opts ...grpc.CallOption, +func (asc *AppServiceClient) NewRobot( + ctx context.Context, in *apppb.NewRobotRequest, opts ...grpc.CallOption, ) (*apppb.NewRobotResponse, error) { if asc.NewRobotFunc == nil { return asc.AppServiceClient.NewRobot(ctx, in, opts...) @@ -639,8 +638,8 @@ func (asc *AppServiceClient) NewRobot(ctx context.Context, in *apppb.NewRobotReq } // UpdateRobot calls the injected UpdateRobotFunc or the real version. -func (asc *AppServiceClient) UpdateRobot(ctx context.Context, in *apppb.UpdateRobotRequest, - opts ...grpc.CallOption, +func (asc *AppServiceClient) UpdateRobot( + ctx context.Context, in *apppb.UpdateRobotRequest, opts ...grpc.CallOption, ) (*apppb.UpdateRobotResponse, error) { if asc.UpdateRobotFunc == nil { return asc.AppServiceClient.UpdateRobot(ctx, in, opts...) @@ -649,8 +648,8 @@ func (asc *AppServiceClient) UpdateRobot(ctx context.Context, in *apppb.UpdateRo } // DeleteRobot calls the injected DeleteRobotFunc or the real version. -func (asc *AppServiceClient) DeleteRobot(ctx context.Context, in *apppb.DeleteRobotRequest, - opts ...grpc.CallOption, +func (asc *AppServiceClient) DeleteRobot( + ctx context.Context, in *apppb.DeleteRobotRequest, opts ...grpc.CallOption, ) (*apppb.DeleteRobotResponse, error) { if asc.DeleteRobotFunc == nil { return asc.AppServiceClient.DeleteRobot(ctx, in, opts...) @@ -659,8 +658,8 @@ func (asc *AppServiceClient) DeleteRobot(ctx context.Context, in *apppb.DeleteRo } // ListFragments calls the injected ListFragmentsFunc or the real version. -func (asc *AppServiceClient) ListFragments(ctx context.Context, in *apppb.ListFragmentsRequest, - opts ...grpc.CallOption, +func (asc *AppServiceClient) ListFragments( + ctx context.Context, in *apppb.ListFragmentsRequest, opts ...grpc.CallOption, ) (*apppb.ListFragmentsResponse, error) { if asc.ListFragmentsFunc == nil { return asc.AppServiceClient.ListFragments(ctx, in, opts...) @@ -669,8 +668,8 @@ func (asc *AppServiceClient) ListFragments(ctx context.Context, in *apppb.ListFr } // GetFragment calls the injected GetFragmentFunc or the real version. -func (asc *AppServiceClient) GetFragment(ctx context.Context, in *apppb.GetFragmentRequest, - opts ...grpc.CallOption, +func (asc *AppServiceClient) GetFragment( + ctx context.Context, in *apppb.GetFragmentRequest, opts ...grpc.CallOption, ) (*apppb.GetFragmentResponse, error) { if asc.GetFragmentFunc == nil { return asc.AppServiceClient.GetFragment(ctx, in, opts...) @@ -679,8 +678,8 @@ func (asc *AppServiceClient) GetFragment(ctx context.Context, in *apppb.GetFragm } // CreateFragment calls the injected CreateFragmentFunc or the real version. -func (asc *AppServiceClient) CreateFragment(ctx context.Context, in *apppb.CreateFragmentRequest, - opts ...grpc.CallOption, +func (asc *AppServiceClient) CreateFragment( + ctx context.Context, in *apppb.CreateFragmentRequest, opts ...grpc.CallOption, ) (*apppb.CreateFragmentResponse, error) { if asc.CreateFragmentFunc == nil { return asc.AppServiceClient.CreateFragment(ctx, in, opts...) @@ -689,8 +688,8 @@ func (asc *AppServiceClient) CreateFragment(ctx context.Context, in *apppb.Creat } // UpdateFragment calls the injected UpdateFragmentFunc or the real version. -func (asc *AppServiceClient) UpdateFragment(ctx context.Context, in *apppb.UpdateFragmentRequest, - opts ...grpc.CallOption, +func (asc *AppServiceClient) UpdateFragment( + ctx context.Context, in *apppb.UpdateFragmentRequest, opts ...grpc.CallOption, ) (*apppb.UpdateFragmentResponse, error) { if asc.UpdateFragmentFunc == nil { return asc.AppServiceClient.UpdateFragment(ctx, in, opts...) @@ -699,8 +698,8 @@ func (asc *AppServiceClient) UpdateFragment(ctx context.Context, in *apppb.Updat } // DeleteFragment calls the injected DeleteFragmentFunc or the real version. -func (asc *AppServiceClient) DeleteFragment(ctx context.Context, in *apppb.DeleteFragmentRequest, - opts ...grpc.CallOption, +func (asc *AppServiceClient) DeleteFragment( + ctx context.Context, in *apppb.DeleteFragmentRequest, opts ...grpc.CallOption, ) (*apppb.DeleteFragmentResponse, error) { if asc.DeleteFragmentFunc == nil { return asc.AppServiceClient.DeleteFragment(ctx, in, opts...) @@ -709,8 +708,8 @@ func (asc *AppServiceClient) DeleteFragment(ctx context.Context, in *apppb.Delet } // ListMachineFragments calls the injected ListMachineFragmentsFunc or the real version. -func (asc *AppServiceClient) ListMachineFragments(ctx context.Context, in *apppb.ListMachineFragmentsRequest, - opts ...grpc.CallOption, +func (asc *AppServiceClient) ListMachineFragments( + ctx context.Context, in *apppb.ListMachineFragmentsRequest, opts ...grpc.CallOption, ) (*apppb.ListMachineFragmentsResponse, error) { if asc.ListMachineFragmentsFunc == nil { return asc.AppServiceClient.ListMachineFragments(ctx, in, opts...) @@ -719,8 +718,8 @@ func (asc *AppServiceClient) ListMachineFragments(ctx context.Context, in *apppb } // GetFragmentHistory calls the injected GetFragmentHistoryFunc or the real version. -func (asc *AppServiceClient) GetFragmentHistory(ctx context.Context, in *apppb.GetFragmentHistoryRequest, - opts ...grpc.CallOption, +func (asc *AppServiceClient) GetFragmentHistory( + ctx context.Context, in *apppb.GetFragmentHistoryRequest, opts ...grpc.CallOption, ) (*apppb.GetFragmentHistoryResponse, error) { if asc.GetFragmentHistoryFunc == nil { return asc.AppServiceClient.GetFragmentHistory(ctx, in, opts...) @@ -729,8 +728,8 @@ func (asc *AppServiceClient) GetFragmentHistory(ctx context.Context, in *apppb.G } // AddRole calls the injected AddRoleFunc or the real version. -func (asc *AppServiceClient) AddRole(ctx context.Context, in *apppb.AddRoleRequest, - opts ...grpc.CallOption, +func (asc *AppServiceClient) AddRole( + ctx context.Context, in *apppb.AddRoleRequest, opts ...grpc.CallOption, ) (*apppb.AddRoleResponse, error) { if asc.AddRoleFunc == nil { return asc.AppServiceClient.AddRole(ctx, in, opts...) @@ -739,8 +738,8 @@ func (asc *AppServiceClient) AddRole(ctx context.Context, in *apppb.AddRoleReque } // RemoveRole calls the injected RemoveRoleFunc or the real version. -func (asc *AppServiceClient) RemoveRole(ctx context.Context, in *apppb.RemoveRoleRequest, - opts ...grpc.CallOption, +func (asc *AppServiceClient) RemoveRole( + ctx context.Context, in *apppb.RemoveRoleRequest, opts ...grpc.CallOption, ) (*apppb.RemoveRoleResponse, error) { if asc.RemoveRoleFunc == nil { return asc.AppServiceClient.RemoveRole(ctx, in, opts...) @@ -749,8 +748,8 @@ func (asc *AppServiceClient) RemoveRole(ctx context.Context, in *apppb.RemoveRol } // ChangeRole calls the injected ChangeRoleFunc or the real version. -func (asc *AppServiceClient) ChangeRole(ctx context.Context, in *apppb.ChangeRoleRequest, - opts ...grpc.CallOption, +func (asc *AppServiceClient) ChangeRole( + ctx context.Context, in *apppb.ChangeRoleRequest, opts ...grpc.CallOption, ) (*apppb.ChangeRoleResponse, error) { if asc.ChangeRoleFunc == nil { return asc.AppServiceClient.ChangeRole(ctx, in, opts...) @@ -759,8 +758,8 @@ func (asc *AppServiceClient) ChangeRole(ctx context.Context, in *apppb.ChangeRol } // ListAuthorizations calls the injected ListAuthorizationsFunc or the real version. -func (asc *AppServiceClient) ListAuthorizations(ctx context.Context, in *apppb.ListAuthorizationsRequest, - opts ...grpc.CallOption, +func (asc *AppServiceClient) ListAuthorizations( + ctx context.Context, in *apppb.ListAuthorizationsRequest, opts ...grpc.CallOption, ) (*apppb.ListAuthorizationsResponse, error) { if asc.ListAuthorizationsFunc == nil { return asc.AppServiceClient.ListAuthorizations(ctx, in, opts...) @@ -769,8 +768,8 @@ func (asc *AppServiceClient) ListAuthorizations(ctx context.Context, in *apppb.L } // CheckPermissions calls the injected CheckPermissionsFunc or the real version. -func (asc *AppServiceClient) CheckPermissions(ctx context.Context, in *apppb.CheckPermissionsRequest, - opts ...grpc.CallOption, +func (asc *AppServiceClient) CheckPermissions( + ctx context.Context, in *apppb.CheckPermissionsRequest, opts ...grpc.CallOption, ) (*apppb.CheckPermissionsResponse, error) { if asc.CheckPermissionsFunc == nil { return asc.AppServiceClient.CheckPermissions(ctx, in, opts...) @@ -779,8 +778,8 @@ func (asc *AppServiceClient) CheckPermissions(ctx context.Context, in *apppb.Che } // GetRegistryItem calls the injected GetRegistryItemFunc or the real version. -func (asc *AppServiceClient) GetRegistryItem(ctx context.Context, in *apppb.GetRegistryItemRequest, - opts ...grpc.CallOption, +func (asc *AppServiceClient) GetRegistryItem( + ctx context.Context, in *apppb.GetRegistryItemRequest, opts ...grpc.CallOption, ) (*apppb.GetRegistryItemResponse, error) { if asc.GetRegistryItemFunc == nil { return asc.AppServiceClient.GetRegistryItem(ctx, in, opts...) @@ -789,8 +788,8 @@ func (asc *AppServiceClient) GetRegistryItem(ctx context.Context, in *apppb.GetR } // CreateRegistryItem calls the injected CreateRegistryItemFunc or the real version. -func (asc *AppServiceClient) CreateRegistryItem(ctx context.Context, in *apppb.CreateRegistryItemRequest, - opts ...grpc.CallOption, +func (asc *AppServiceClient) CreateRegistryItem( + ctx context.Context, in *apppb.CreateRegistryItemRequest, opts ...grpc.CallOption, ) (*apppb.CreateRegistryItemResponse, error) { if asc.CreateRegistryItemFunc == nil { return asc.AppServiceClient.CreateRegistryItem(ctx, in, opts...) @@ -799,8 +798,8 @@ func (asc *AppServiceClient) CreateRegistryItem(ctx context.Context, in *apppb.C } // UpdateRegistryItem calls the injected UpdateRegistryItemFunc or the real version. -func (asc *AppServiceClient) UpdateRegistryItem(ctx context.Context, in *apppb.UpdateRegistryItemRequest, - opts ...grpc.CallOption, +func (asc *AppServiceClient) UpdateRegistryItem( + ctx context.Context, in *apppb.UpdateRegistryItemRequest, opts ...grpc.CallOption, ) (*apppb.UpdateRegistryItemResponse, error) { if asc.UpdateRegistryItemFunc == nil { return asc.AppServiceClient.UpdateRegistryItem(ctx, in, opts...) @@ -809,8 +808,8 @@ func (asc *AppServiceClient) UpdateRegistryItem(ctx context.Context, in *apppb.U } // ListRegistryItems calls the injected ListRegistryItemsFunc or the real version. -func (asc *AppServiceClient) ListRegistryItems(ctx context.Context, in *apppb.ListRegistryItemsRequest, - opts ...grpc.CallOption, +func (asc *AppServiceClient) ListRegistryItems( + ctx context.Context, in *apppb.ListRegistryItemsRequest, opts ...grpc.CallOption, ) (*apppb.ListRegistryItemsResponse, error) { if asc.ListRegistryItemsFunc == nil { return asc.AppServiceClient.ListRegistryItems(ctx, in, opts...) @@ -819,8 +818,8 @@ func (asc *AppServiceClient) ListRegistryItems(ctx context.Context, in *apppb.Li } // DeleteRegistryItem calls the injected DeleteRegistryItemFunc or the real version. -func (asc *AppServiceClient) DeleteRegistryItem(ctx context.Context, in *apppb.DeleteRegistryItemRequest, - opts ...grpc.CallOption, +func (asc *AppServiceClient) DeleteRegistryItem( + ctx context.Context, in *apppb.DeleteRegistryItemRequest, opts ...grpc.CallOption, ) (*apppb.DeleteRegistryItemResponse, error) { if asc.DeleteRegistryItemFunc == nil { return asc.AppServiceClient.DeleteRegistryItem(ctx, in, opts...) @@ -829,8 +828,8 @@ func (asc *AppServiceClient) DeleteRegistryItem(ctx context.Context, in *apppb.D } // TransferRegistryItem calls the injected TransferRegistryItemFunc or the real version. -func (asc *AppServiceClient) TransferRegistryItem(ctx context.Context, in *apppb.TransferRegistryItemRequest, - opts ...grpc.CallOption, +func (asc *AppServiceClient) TransferRegistryItem( + ctx context.Context, in *apppb.TransferRegistryItemRequest, opts ...grpc.CallOption, ) (*apppb.TransferRegistryItemResponse, error) { if asc.TransferRegistryItemFunc == nil { return asc.AppServiceClient.TransferRegistryItem(ctx, in, opts...) @@ -839,8 +838,8 @@ func (asc *AppServiceClient) TransferRegistryItem(ctx context.Context, in *apppb } // CreateModule calls the injected CreateModuleFunc or the real version. -func (asc *AppServiceClient) CreateModule(ctx context.Context, in *apppb.CreateModuleRequest, - opts ...grpc.CallOption, +func (asc *AppServiceClient) CreateModule( + ctx context.Context, in *apppb.CreateModuleRequest, opts ...grpc.CallOption, ) (*apppb.CreateModuleResponse, error) { if asc.CreateModuleFunc == nil { return asc.AppServiceClient.CreateModule(ctx, in, opts...) @@ -849,8 +848,8 @@ func (asc *AppServiceClient) CreateModule(ctx context.Context, in *apppb.CreateM } // UpdateModule calls the injected UpdateModuleFunc or the real version. -func (asc *AppServiceClient) UpdateModule(ctx context.Context, in *apppb.UpdateModuleRequest, - opts ...grpc.CallOption, +func (asc *AppServiceClient) UpdateModule( + ctx context.Context, in *apppb.UpdateModuleRequest, opts ...grpc.CallOption, ) (*apppb.UpdateModuleResponse, error) { if asc.UpdateModuleFunc == nil { return asc.AppServiceClient.UpdateModule(ctx, in, opts...) @@ -859,8 +858,8 @@ func (asc *AppServiceClient) UpdateModule(ctx context.Context, in *apppb.UpdateM } // // UploadModuleFile calls the injected UploadModuleFileFunc or the real version. -// func (asc *AppServiceClient) UploadModuleFile(ctx context.Context, in *apppb.UploadModuleFileRequest, -// opts ...grpc.CallOption, +// func (asc *AppServiceClient) UploadModuleFile( +// ctx context.Context, in *apppb.UploadModuleFileRequest, opts ...grpc.CallOption, // ) (*apppb.UploadModuleFileResponse, error) { // if asc.UploadModuleFileFunc == nil { // return asc.AppServiceClient.UploadModuleFile(ctx, in, opts...) @@ -869,8 +868,8 @@ func (asc *AppServiceClient) UpdateModule(ctx context.Context, in *apppb.UpdateM // } // GetModule calls the injected GetModuleFunc or the real version. -func (asc *AppServiceClient) GetModule(ctx context.Context, in *apppb.GetModuleRequest, - opts ...grpc.CallOption, +func (asc *AppServiceClient) GetModule( + ctx context.Context, in *apppb.GetModuleRequest, opts ...grpc.CallOption, ) (*apppb.GetModuleResponse, error) { if asc.GetModuleFunc == nil { return asc.AppServiceClient.GetModule(ctx, in, opts...) @@ -879,8 +878,8 @@ func (asc *AppServiceClient) GetModule(ctx context.Context, in *apppb.GetModuleR } // ListModules calls the injected ListModulesFunc or the real version. -func (asc *AppServiceClient) ListModules(ctx context.Context, in *apppb.ListModulesRequest, - opts ...grpc.CallOption, +func (asc *AppServiceClient) ListModules( + ctx context.Context, in *apppb.ListModulesRequest, opts ...grpc.CallOption, ) (*apppb.ListModulesResponse, error) { if asc.ListModulesFunc == nil { return asc.AppServiceClient.ListModules(ctx, in, opts...) @@ -889,8 +888,8 @@ func (asc *AppServiceClient) ListModules(ctx context.Context, in *apppb.ListModu } // CreateKey calls the injected CreateKeyFunc or the real version. -func (asc *AppServiceClient) CreateKey(ctx context.Context, in *apppb.CreateKeyRequest, - opts ...grpc.CallOption, +func (asc *AppServiceClient) CreateKey( + ctx context.Context, in *apppb.CreateKeyRequest, opts ...grpc.CallOption, ) (*apppb.CreateKeyResponse, error) { if asc.CreateKeyFunc == nil { return asc.AppServiceClient.CreateKey(ctx, in, opts...) @@ -899,8 +898,8 @@ func (asc *AppServiceClient) CreateKey(ctx context.Context, in *apppb.CreateKeyR } // DeleteKey calls the injected DeleteKeyFunc or the real version. -func (asc *AppServiceClient) DeleteKey(ctx context.Context, in *apppb.DeleteKeyRequest, - opts ...grpc.CallOption, +func (asc *AppServiceClient) DeleteKey( + ctx context.Context, in *apppb.DeleteKeyRequest, opts ...grpc.CallOption, ) (*apppb.DeleteKeyResponse, error) { if asc.DeleteKeyFunc == nil { return asc.AppServiceClient.DeleteKey(ctx, in, opts...) @@ -909,8 +908,8 @@ func (asc *AppServiceClient) DeleteKey(ctx context.Context, in *apppb.DeleteKeyR } // ListKeys calls the injected ListKeysFunc or the real version. -func (asc *AppServiceClient) ListKeys(ctx context.Context, in *apppb.ListKeysRequest, - opts ...grpc.CallOption, +func (asc *AppServiceClient) ListKeys( + ctx context.Context, in *apppb.ListKeysRequest, opts ...grpc.CallOption, ) (*apppb.ListKeysResponse, error) { if asc.ListKeysFunc == nil { return asc.AppServiceClient.ListKeys(ctx, in, opts...) @@ -919,8 +918,8 @@ func (asc *AppServiceClient) ListKeys(ctx context.Context, in *apppb.ListKeysReq } // RenameKey calls the injected RenameKeyFunc or the real version. -func (asc *AppServiceClient) RenameKey(ctx context.Context, in *apppb.RenameKeyRequest, - opts ...grpc.CallOption, +func (asc *AppServiceClient) RenameKey( + ctx context.Context, in *apppb.RenameKeyRequest, opts ...grpc.CallOption, ) (*apppb.RenameKeyResponse, error) { if asc.RenameKeyFunc == nil { return asc.AppServiceClient.RenameKey(ctx, in, opts...) @@ -929,8 +928,8 @@ func (asc *AppServiceClient) RenameKey(ctx context.Context, in *apppb.RenameKeyR } // RotateKey calls the injected RotateKeyFunc or the real version. -func (asc *AppServiceClient) RotateKey(ctx context.Context, in *apppb.RotateKeyRequest, - opts ...grpc.CallOption, +func (asc *AppServiceClient) RotateKey( + ctx context.Context, in *apppb.RotateKeyRequest, opts ...grpc.CallOption, ) (*apppb.RotateKeyResponse, error) { if asc.RotateKeyFunc == nil { return asc.AppServiceClient.RotateKey(ctx, in, opts...) @@ -939,8 +938,8 @@ func (asc *AppServiceClient) RotateKey(ctx context.Context, in *apppb.RotateKeyR } // CreateKeyFromExistingKeyAuthorizations calls the injected CreateKeyFromExistingKeyAuthorizationsFunc or the real version. -func (asc *AppServiceClient) CreateKeyFromExistingKeyAuthorizations(ctx context.Context, in *apppb.CreateKeyFromExistingKeyAuthorizationsRequest, - opts ...grpc.CallOption, +func (asc *AppServiceClient) CreateKeyFromExistingKeyAuthorizations( + ctx context.Context, in *apppb.CreateKeyFromExistingKeyAuthorizationsRequest, opts ...grpc.CallOption, ) (*apppb.CreateKeyFromExistingKeyAuthorizationsResponse, error) { if asc.CreateKeyFromExistingKeyAuthorizationsFunc == nil { return asc.AppServiceClient.CreateKeyFromExistingKeyAuthorizations(ctx, in, opts...) From 935b1b1288f23ea11aad60df5fdcd2c267afe8cc Mon Sep 17 00:00:00 2001 From: purplenicole730 Date: Fri, 15 Nov 2024 19:51:38 -0500 Subject: [PATCH 37/75] add test helper functions --- app/app_client_test.go | 246 ++++++++++++++++------------------------- 1 file changed, 97 insertions(+), 149 deletions(-) diff --git a/app/app_client_test.go b/app/app_client_test.go index c59390d2e43..a5ed7257c66 100644 --- a/app/app_client_test.go +++ b/app/app_client_test.go @@ -91,18 +91,19 @@ var ( OrganizationID: organizationID, IdentityType: identityType, } - pbAuthorization = pb.Authorization{ - AuthorizationType: authorization.AuthorizationType, - AuthorizationId: authorization.AuthorizationID, - ResourceType: authorization.ResourceType, - ResourceId: authorization.ResourceID, - IdentityId: authorization.IdentityID, - OrganizationId: authorization.OrganizationID, - IdentityType: authorization.IdentityType, - } authorizations = []*Authorization{&authorization} - pbAuthorizations = []*pb.Authorization{&pbAuthorization} - member = OrganizationMember{ + pbAuthorizations = []*pb.Authorization{ + { + AuthorizationType: authorization.AuthorizationType, + AuthorizationId: authorization.AuthorizationID, + ResourceType: authorization.ResourceType, + ResourceId: authorization.ResourceID, + IdentityId: authorization.IdentityID, + OrganizationId: authorization.OrganizationID, + IdentityType: authorization.IdentityType, + }, + } + member = OrganizationMember{ UserID: userID, Emails: []string{email}, DateAdded: &dateAdded, @@ -159,16 +160,9 @@ var ( OrganizationID: organizationID, Primary: primary, } - pbLocationOrg = pb.LocationOrganization{ - OrganizationId: locationOrg.OrganizationID, - Primary: locationOrg.Primary, - } storageConfig = StorageConfig{ Region: region, } - pbStorageConfig = pb.StorageConfig{ - Region: storageConfig.Region, - } location = Location{ ID: locationID, Name: name, @@ -184,10 +178,17 @@ var ( Name: location.Name, ParentLocationId: location.ParentLocationID, Auth: &pbLocationAuth, - Organizations: []*pb.LocationOrganization{&pbLocationOrg}, - CreatedOn: location.CreatedOn, - RobotCount: location.RobotCount, - Config: &pbStorageConfig, + Organizations: []*pb.LocationOrganization{ + { + OrganizationId: locationOrg.OrganizationID, + Primary: locationOrg.Primary, + }, + }, + CreatedOn: location.CreatedOn, + RobotCount: location.RobotCount, + Config: &pb.StorageConfig{ + Region: storageConfig.Region, + }, } lastAccess = timestamppb.Timestamp{Seconds: 0, Nanos: 110} robot = Robot{ @@ -249,19 +250,17 @@ var ( Secrets: pbSecrets, LastUpdated: robotPart.LastUpdated, } - pageToken = "page_token" - levels = []string{level} - start = timestamppb.Timestamp{Seconds: 92, Nanos: 0} - end = timestamppb.Timestamp{Seconds: 99, Nanos: 999} - limit int64 = 2 - source = "source" - filter = "filter" - time = timestamppb.Timestamp{Seconds: 11, Nanos: 15} - caller = map[string]interface{}{"name": name} - pbCaller, _ = protoutils.StructToStructPb(*logEntry.Caller) - field = map[string]interface{}{"key": "value"} - pbField, _ = protoutils.StructToStructPb(field) - logEntry = LogEntry{ + pageToken = "page_token" + levels = []string{level} + start = timestamppb.Timestamp{Seconds: 92, Nanos: 0} + end = timestamppb.Timestamp{Seconds: 99, Nanos: 999} + limit int64 = 2 + source = "source" + filter = "filter" + time = timestamppb.Timestamp{Seconds: 11, Nanos: 15} + caller = map[string]interface{}{"name": name} + field = map[string]interface{}{"key": "value"} + logEntry = LogEntry{ Host: host, Level: level, Time: &time, @@ -271,16 +270,6 @@ var ( Stack: stack, Fields: []*map[string]interface{}{&field}, } - pbLogEntry = common.LogEntry{ - Host: logEntry.Host, - Level: logEntry.Level, - Time: logEntry.Time, - LoggerName: logEntry.LoggerName, - Message: logEntry.Message, - Caller: pbCaller, - Stack: logEntry.Stack, - Fields: []*structpb.Struct{pbField}, - } authenticatorInfo = AuthenticatorInfo{ Type: AuthenticationTypeAPIKey, Value: value, @@ -293,12 +282,6 @@ var ( Old: &robotPart, EditedBy: &authenticatorInfo, } - apiKey = APIKey{ - ID: keyID, - Key: key, - Name: name, - CreatedOn: &createdOn, - } authorizationDetails = AuthorizationDetails{ AuthorizationType: authorizationType, AuthorizationID: authorizationID, @@ -307,15 +290,20 @@ var ( OrgID: organizationID, } apiKeyWithAuthorizations = APIKeyWithAuthorizations{ - APIKey: &apiKey, + APIKey: &APIKey{ + ID: keyID, + Key: key, + Name: name, + CreatedOn: &createdOn, + }, Authorizations: []*AuthorizationDetails{&authorizationDetails}, } pbAPIKeyWithAuthorizations = pb.APIKeyWithAuthorizations{ ApiKey: &pb.APIKey{ - Id: apiKey.ID, - Key: apiKey.Key, - Name: apiKey.Name, - CreatedOn: apiKey.CreatedOn, + Id: apiKeyWithAuthorizations.APIKey.ID, + Key: apiKeyWithAuthorizations.APIKey.Key, + Name: apiKeyWithAuthorizations.APIKey.Name, + CreatedOn: apiKeyWithAuthorizations.APIKey.CreatedOn, }, Authorizations: []*pb.AuthorizationDetails{ { @@ -363,6 +351,36 @@ func testOrganizationResponse(t *testing.T, actualOrg, expectedOrg *Organization test.That(t, actualOrg.Cid, test.ShouldEqual, expectedOrg.Cid) } +func testLocationResponse(t *testing.T, actualLocation, expectedLocation *Location) { + test.That(t, actualLocation.ID, test.ShouldEqual, expectedLocation.ID) + test.That(t, actualLocation.Name, test.ShouldEqual, expectedLocation.Name) + test.That(t, actualLocation.ParentLocationID, test.ShouldEqual, expectedLocation.ParentLocationID) + test.That(t, actualLocation.Auth, test.ShouldResemble, expectedLocation.Auth) + test.That(t, actualLocation.Organizations, test.ShouldResemble, expectedLocation.Organizations) + test.That(t, actualLocation.CreatedOn, test.ShouldEqual, expectedLocation.CreatedOn) + test.That(t, actualLocation.RobotCount, test.ShouldEqual, expectedLocation.RobotCount) + test.That(t, actualLocation.Config, test.ShouldResemble, expectedLocation.Config) +} + +func testRobotPartResponse(t *testing.T, actualRobotPart, expectedRobotPart *RobotPart) { + test.That(t, actualRobotPart.ID, test.ShouldEqual, expectedRobotPart.ID) + test.That(t, actualRobotPart.Name, test.ShouldEqual, expectedRobotPart.Name) + test.That(t, actualRobotPart.DNSName, test.ShouldEqual, expectedRobotPart.DNSName) + test.That(t, actualRobotPart.Secret, test.ShouldEqual, expectedRobotPart.Secret) + test.That(t, actualRobotPart.Robot, test.ShouldEqual, expectedRobotPart.Robot) + test.That(t, actualRobotPart.LocationID, test.ShouldEqual, expectedRobotPart.LocationID) + test.That(t, actualRobotPart.RobotConfig, test.ShouldResemble, expectedRobotPart.RobotConfig) + test.That(t, actualRobotPart.LastAccess, test.ShouldEqual, expectedRobotPart.LastAccess) + test.That(t, actualRobotPart.UserSuppliedInfo, test.ShouldResemble, expectedRobotPart.UserSuppliedInfo) + test.That(t, actualRobotPart.MainPart, test.ShouldEqual, expectedRobotPart.MainPart) + test.That(t, actualRobotPart.FQDN, test.ShouldEqual, expectedRobotPart.FQDN) + test.That(t, actualRobotPart.LocalFQDN, test.ShouldEqual, expectedRobotPart.LocalFQDN) + test.That(t, actualRobotPart.CreatedOn, test.ShouldEqual, expectedRobotPart.CreatedOn) + test.That(t, len(actualRobotPart.Secrets), test.ShouldEqual, len(expectedRobotPart.Secrets)) + test.That(t, actualRobotPart.Secrets[0], test.ShouldResemble, expectedRobotPart.Secrets[0]) + test.That(t, actualRobotPart.LastUpdated, test.ShouldEqual, expectedRobotPart.LastUpdated) +} + func createGrpcClient() *inject.AppServiceClient { return &inject.AppServiceClient{} } @@ -677,14 +695,7 @@ func TestAppClient(t *testing.T) { }, nil } resp, _ := client.CreateLocation(context.Background(), organizationID, name, &parentLocationID) - test.That(t, resp.ID, test.ShouldEqual, location.ID) - test.That(t, resp.Name, test.ShouldEqual, location.Name) - test.That(t, resp.ParentLocationID, test.ShouldEqual, location.ParentLocationID) - test.That(t, resp.Auth, test.ShouldResemble, location.Auth) - test.That(t, resp.Organizations, test.ShouldResemble, location.Organizations) - test.That(t, resp.CreatedOn, test.ShouldEqual, location.CreatedOn) - test.That(t, resp.RobotCount, test.ShouldEqual, location.RobotCount) - test.That(t, resp.Config, test.ShouldResemble, location.Config) + testLocationResponse(t, resp, &location) }) t.Run("GetLocation", func(t *testing.T) { @@ -697,14 +708,7 @@ func TestAppClient(t *testing.T) { }, nil } resp, _ := client.GetLocation(context.Background(), locationID) - test.That(t, resp.ID, test.ShouldEqual, location.ID) - test.That(t, resp.Name, test.ShouldEqual, location.Name) - test.That(t, resp.ParentLocationID, test.ShouldEqual, location.ParentLocationID) - test.That(t, resp.Auth, test.ShouldResemble, location.Auth) - test.That(t, resp.Organizations, test.ShouldResemble, location.Organizations) - test.That(t, resp.CreatedOn, test.ShouldEqual, location.CreatedOn) - test.That(t, resp.RobotCount, test.ShouldEqual, location.RobotCount) - test.That(t, resp.Config, test.ShouldResemble, location.Config) + testLocationResponse(t, resp, &location) }) t.Run("UpdateLocation", func(t *testing.T) { @@ -720,14 +724,7 @@ func TestAppClient(t *testing.T) { }, nil } resp, _ := client.UpdateLocation(context.Background(), locationID, &name, &parentLocationID, ®ion) - test.That(t, resp.ID, test.ShouldEqual, location.ID) - test.That(t, resp.Name, test.ShouldEqual, location.Name) - test.That(t, resp.ParentLocationID, test.ShouldEqual, location.ParentLocationID) - test.That(t, resp.Auth, test.ShouldResemble, location.Auth) - test.That(t, resp.Organizations, test.ShouldResemble, location.Organizations) - test.That(t, resp.CreatedOn, test.ShouldEqual, location.CreatedOn) - test.That(t, resp.RobotCount, test.ShouldEqual, location.RobotCount) - test.That(t, resp.Config, test.ShouldResemble, location.Config) + testLocationResponse(t, resp, &location) }) t.Run("DeleteLocation", func(t *testing.T) { @@ -752,14 +749,7 @@ func TestAppClient(t *testing.T) { } resp, _ := client.ListLocations(context.Background(), organizationID) test.That(t, len(resp), test.ShouldEqual, len(expectedLocations)) - test.That(t, resp[0].ID, test.ShouldEqual, expectedLocations[0].ID) - test.That(t, resp[0].Name, test.ShouldEqual, expectedLocations[0].Name) - test.That(t, resp[0].ParentLocationID, test.ShouldEqual, expectedLocations[0].ParentLocationID) - test.That(t, resp[0].Auth, test.ShouldResemble, expectedLocations[0].Auth) - test.That(t, resp[0].Organizations, test.ShouldResemble, expectedLocations[0].Organizations) - test.That(t, resp[0].CreatedOn, test.ShouldEqual, expectedLocations[0].CreatedOn) - test.That(t, resp[0].RobotCount, test.ShouldEqual, expectedLocations[0].RobotCount) - test.That(t, resp[0].Config, test.ShouldResemble, expectedLocations[0].Config) + testLocationResponse(t, resp[0], &expectedLocations[0]) }) t.Run("ShareLocation", func(t *testing.T) { @@ -867,18 +857,7 @@ func TestAppClient(t *testing.T) { } resp, _ := client.GetRobotParts(context.Background(), robotID) test.That(t, len(resp), test.ShouldEqual, len(expectedRobotParts)) - test.That(t, resp[0].ID, test.ShouldEqual, expectedRobotParts[0].ID) - test.That(t, resp[0].Name, test.ShouldEqual, expectedRobotParts[0].Name) - test.That(t, resp[0].DNSName, test.ShouldEqual, expectedRobotParts[0].DNSName) - test.That(t, resp[0].Secret, test.ShouldEqual, expectedRobotParts[0].Secret) - test.That(t, resp[0].Robot, test.ShouldEqual, expectedRobotParts[0].Robot) - test.That(t, resp[0].LocationID, test.ShouldEqual, expectedRobotParts[0].LocationID) - test.That(t, resp[0].RobotConfig, test.ShouldResemble, expectedRobotParts[0].RobotConfig) - test.That(t, resp[0].LastAccess, test.ShouldEqual, expectedRobotParts[0].LastAccess) - test.That(t, resp[0].UserSuppliedInfo, test.ShouldResemble, expectedRobotParts[0].UserSuppliedInfo) - test.That(t, resp[0].MainPart, test.ShouldEqual, expectedRobotParts[0].MainPart) - test.That(t, resp[0].FQDN, test.ShouldEqual, expectedRobotParts[0].FQDN) - test.That(t, resp[0].LocalFQDN, test.ShouldEqual, expectedRobotParts[0].LocalFQDN) + testRobotPartResponse(t, resp[0], &expectedRobotParts[0]) }) t.Run("GetRobotPart", func(t *testing.T) { @@ -893,21 +872,23 @@ func TestAppClient(t *testing.T) { } part, json, _ := client.GetRobotPart(context.Background(), partID) test.That(t, json, test.ShouldEqual, configJSON) - test.That(t, part.Name, test.ShouldEqual, robotPart.Name) - test.That(t, part.DNSName, test.ShouldEqual, robotPart.DNSName) - test.That(t, part.Secret, test.ShouldEqual, robotPart.Secret) - test.That(t, part.Robot, test.ShouldEqual, robotPart.Robot) - test.That(t, part.LocationID, test.ShouldEqual, robotPart.LocationID) - test.That(t, part.RobotConfig, test.ShouldResemble, robotPart.RobotConfig) - test.That(t, part.LastAccess, test.ShouldEqual, robotPart.LastAccess) - test.That(t, part.UserSuppliedInfo, test.ShouldResemble, robotPart.UserSuppliedInfo) - test.That(t, part.MainPart, test.ShouldEqual, robotPart.MainPart) - test.That(t, part.FQDN, test.ShouldEqual, robotPart.FQDN) - test.That(t, part.LocalFQDN, test.ShouldEqual, robotPart.LocalFQDN) + testRobotPartResponse(t, part, &robotPart) }) t.Run("GetRobotPartLogs", func(t *testing.T) { expectedLogs := []*LogEntry{&logEntry} + pbCaller, _ := protoutils.StructToStructPb(*logEntry.Caller) + pbField, _ := protoutils.StructToStructPb(field) + pbLogEntry := common.LogEntry{ + Host: logEntry.Host, + Level: logEntry.Level, + Time: logEntry.Time, + LoggerName: logEntry.LoggerName, + Message: logEntry.Message, + Caller: pbCaller, + Stack: logEntry.Stack, + Fields: []*structpb.Struct{pbField}, + } grpcClient.GetRobotPartLogsFunc = func( ctx context.Context, in *pb.GetRobotPartLogsRequest, opts ...grpc.CallOption, ) (*pb.GetRobotPartLogsResponse, error) { @@ -964,20 +945,7 @@ func TestAppClient(t *testing.T) { test.That(t, resp[0].Part, test.ShouldEqual, expectedEntries[0].Part) test.That(t, resp[0].Robot, test.ShouldEqual, expectedEntries[0].Robot) test.That(t, resp[0].When, test.ShouldEqual, expectedEntries[0].When) - test.That(t, resp[0].Old.Name, test.ShouldEqual, expectedEntries[0].Old.Name) - test.That(t, resp[0].Old.DNSName, test.ShouldEqual, expectedEntries[0].Old.DNSName) - test.That(t, resp[0].Old.Secret, test.ShouldEqual, expectedEntries[0].Old.Secret) - test.That(t, resp[0].Old.Robot, test.ShouldEqual, expectedEntries[0].Old.Robot) - test.That(t, resp[0].Old.LocationID, test.ShouldEqual, expectedEntries[0].Old.LocationID) - test.That(t, resp[0].Old.RobotConfig, test.ShouldResemble, expectedEntries[0].Old.RobotConfig) - test.That(t, resp[0].Old.LastAccess, test.ShouldEqual, expectedEntries[0].Old.LastAccess) - test.That(t, resp[0].Old.UserSuppliedInfo, test.ShouldResemble, expectedEntries[0].Old.UserSuppliedInfo) - test.That(t, resp[0].Old.MainPart, test.ShouldEqual, expectedEntries[0].Old.MainPart) - test.That(t, resp[0].Old.FQDN, test.ShouldEqual, expectedEntries[0].Old.FQDN) - test.That(t, resp[0].Old.LocalFQDN, test.ShouldEqual, expectedEntries[0].Old.LocalFQDN) - test.That(t, resp[0].Old.Name, test.ShouldEqual, expectedEntries[0].Old.Name) - test.That(t, resp[0].Old.Name, test.ShouldEqual, expectedEntries[0].Old.Name) - test.That(t, resp[0].Old.Name, test.ShouldEqual, expectedEntries[0].Old.Name) + testRobotPartResponse(t, resp[0].Old, expectedEntries[0].Old) test.That(t, resp[0].EditedBy, test.ShouldResemble, expectedEntries[0].EditedBy) }) @@ -992,18 +960,8 @@ func TestAppClient(t *testing.T) { Part: &pbRobotPart, }, nil } - part, _ := client.UpdateRobotPart(context.Background(), partID, name, robotConfig) - test.That(t, part.Name, test.ShouldEqual, robotPart.Name) - test.That(t, part.DNSName, test.ShouldEqual, robotPart.DNSName) - test.That(t, part.Secret, test.ShouldEqual, robotPart.Secret) - test.That(t, part.Robot, test.ShouldEqual, robotPart.Robot) - test.That(t, part.LocationID, test.ShouldEqual, robotPart.LocationID) - test.That(t, part.RobotConfig, test.ShouldResemble, robotPart.RobotConfig) - test.That(t, part.LastAccess, test.ShouldEqual, robotPart.LastAccess) - test.That(t, part.UserSuppliedInfo, test.ShouldResemble, robotPart.UserSuppliedInfo) - test.That(t, part.MainPart, test.ShouldEqual, robotPart.MainPart) - test.That(t, part.FQDN, test.ShouldEqual, robotPart.FQDN) - test.That(t, part.LocalFQDN, test.ShouldEqual, robotPart.LocalFQDN) + resp, _ := client.UpdateRobotPart(context.Background(), partID, name, robotConfig) + testRobotPartResponse(t, resp, &robotPart) }) t.Run("NewRobotPart", func(t *testing.T) { @@ -1062,18 +1020,8 @@ func TestAppClient(t *testing.T) { Part: &pbRobotPart, }, nil } - part, _ := client.CreateRobotPartSecret(context.Background(), partID) - test.That(t, part.Name, test.ShouldEqual, robotPart.Name) - test.That(t, part.DNSName, test.ShouldEqual, robotPart.DNSName) - test.That(t, part.Secret, test.ShouldEqual, robotPart.Secret) - test.That(t, part.Robot, test.ShouldEqual, robotPart.Robot) - test.That(t, part.LocationID, test.ShouldEqual, robotPart.LocationID) - test.That(t, part.RobotConfig, test.ShouldResemble, robotPart.RobotConfig) - test.That(t, part.LastAccess, test.ShouldEqual, robotPart.LastAccess) - test.That(t, part.UserSuppliedInfo, test.ShouldResemble, robotPart.UserSuppliedInfo) - test.That(t, part.MainPart, test.ShouldEqual, robotPart.MainPart) - test.That(t, part.FQDN, test.ShouldEqual, robotPart.FQDN) - test.That(t, part.LocalFQDN, test.ShouldEqual, robotPart.LocalFQDN) + resp, _ := client.CreateRobotPartSecret(context.Background(), partID) + testRobotPartResponse(t, resp, &robotPart) }) t.Run("DeleteRobotPartSecret", func(t *testing.T) { From f6144e89f9a1a35ca12c55c9cab818a33f6de402 Mon Sep 17 00:00:00 2001 From: purplenicole730 Date: Fri, 15 Nov 2024 21:40:17 -0500 Subject: [PATCH 38/75] add fragment tests --- app/app_client.go | 5 +- app/app_client_test.go | 139 +++++++++++++++++++++++++++++++++++++++-- 2 files changed, 137 insertions(+), 7 deletions(-) diff --git a/app/app_client.go b/app/app_client.go index 586b4faa087..d4af1f37ebb 100644 --- a/app/app_client.go +++ b/app/app_client.go @@ -753,18 +753,19 @@ func (c *Client) CreateFragment( // UpdateFragment updates a fragment. func (c *Client) UpdateFragment( - ctx context.Context, id, name string, config interface{}, public *bool, visibility *pb.FragmentVisibility, + ctx context.Context, id, name string, config map[string]interface{}, public *bool, visibility *FragmentVisibility, ) (*Fragment, error) { cfg, err := protoutils.StructToStructPb(config) if err != nil { return nil, err } + pbVisibility := fragmentVisibilityToProto(*visibility) resp, err := c.client.UpdateFragment(ctx, &pb.UpdateFragmentRequest{ Id: id, Name: name, Config: cfg, Public: public, - Visibility: visibility, + Visibility: &pbVisibility, }) if err != nil { return nil, err diff --git a/app/app_client_test.go b/app/app_client_test.go index a5ed7257c66..6acae27ad0c 100644 --- a/app/app_client_test.go +++ b/app/app_client_test.go @@ -48,6 +48,11 @@ const ( isDeactivated = false keyID = "key_id" key = "key" + fragmentID = "fragment_id" + organizationOwner = "organization_owner" + robotPartCount = 5 + onlyUsedByOwner = false + organizationCount = 2 ) var ( @@ -275,6 +280,11 @@ var ( Value: value, IsDeactivated: isDeactivated, } + pbAuthenticatorInfo = pb.AuthenticatorInfo{ + Type: authenticationTypeToProto(authenticatorInfo.Type), + Value: authenticatorInfo.Value, + IsDeactivated: authenticatorInfo.IsDeactivated, + } robotPartHistoryEntry = RobotPartHistoryEntry{ Part: partID, Robot: robotID, @@ -315,6 +325,46 @@ var ( }, }, } + public = true + fragmentVisibility = FragmentVisibilityPublic + f = map[string]interface{}{"name": name, "id": fragmentID} + pbF, _ = protoutils.StructToStructPb(f) + fragment = Fragment{ + ID: fragmentID, + Name: name, + Fragment: &f, + OrganizationOwner: organizationOwner, + Public: public, + CreatedOn: &createdOn, + OrganizationName: name, + RobotPartCount: robotPartCount, + OrganizationCount: organizationCount, + OnlyUsedByOwner: onlyUsedByOwner, + Visibility: fragmentVisibility, + LastUpdated: &lastUpdated, + } + pbFragment = pb.Fragment{ + Id: fragment.ID, + Name: fragment.Name, + Fragment: pbF, + OrganizationOwner: fragment.OrganizationOwner, + Public: fragment.Public, + CreatedOn: fragment.CreatedOn, + OrganizationName: fragment.OrganizationName, + RobotPartCount: fragment.RobotPartCount, + OrganizationCount: fragment.OrganizationCount, + OnlyUsedByOwner: fragment.OnlyUsedByOwner, + Visibility: fragmentVisibilityToProto(fragment.Visibility), + LastUpdated: fragment.LastUpdated, + } + fragmentConfig = map[string]interface{}{"organizationCount": 4} + editedOn = timestamppb.Timestamp{Seconds: 8, Nanos: 278} + fragmentHistoryEntry = FragmentHistoryEntry{ + Fragment: fragmentID, + EditedOn: &editedOn, + Old: &fragment, + EditedBy: &authenticatorInfo, + } ) func sharedSecretStateToProto(state SharedSecretState) pb.SharedSecret_State { @@ -921,11 +971,6 @@ func TestAppClient(t *testing.T) { t.Run("GetRobotPartHistory", func(t *testing.T) { expectedEntries := []*RobotPartHistoryEntry{&robotPartHistoryEntry} - pbAuthenticatorInfo := pb.AuthenticatorInfo{ - Type: authenticationTypeToProto(authenticatorInfo.Type), - Value: authenticatorInfo.Value, - IsDeactivated: authenticatorInfo.IsDeactivated, - } pbRobotPartHistoryEntry := pb.RobotPartHistoryEntry{ Part: robotPartHistoryEntry.Part, Robot: robotPartHistoryEntry.Robot, @@ -1088,4 +1133,88 @@ func TestAppClient(t *testing.T) { } client.DeleteRobot(context.Background(), robotID) }) + + t.Run("GetFragment", func(t *testing.T) { + grpcClient.GetFragmentFunc = func( + ctx context.Context, in *pb.GetFragmentRequest, opts ...grpc.CallOption, + ) (*pb.GetFragmentResponse, error) { + test.That(t, in.Id, test.ShouldEqual, fragmentID) + return &pb.GetFragmentResponse{ + Fragment: &pbFragment, + }, nil + } + resp, _ := client.GetFragment(context.Background(), fragmentID) + test.That(t, resp, test.ShouldResemble, &fragment) + }) + + t.Run("UpdateFragment", func(t *testing.T) { + pbFragmentConfig, _ := protoutils.StructToStructPb(fragmentConfig) + pbFragmentVisibility := fragmentVisibilityToProto(fragmentVisibility) + grpcClient.UpdateFragmentFunc = func( + ctx context.Context, in *pb.UpdateFragmentRequest, opts ...grpc.CallOption, + ) (*pb.UpdateFragmentResponse, error) { + test.That(t, in.Id, test.ShouldEqual, fragmentID) + test.That(t, in.Name, test.ShouldEqual, name) + test.That(t, in.Config, test.ShouldResemble, pbFragmentConfig) + test.That(t, in.Public, test.ShouldEqual, &public) + test.That(t, in.Visibility, test.ShouldResemble, &pbFragmentVisibility) + return &pb.UpdateFragmentResponse{ + Fragment: &pbFragment, + }, nil + } + resp, _ := client.UpdateFragment(context.Background(), fragmentID, name, fragmentConfig, &public, &fragmentVisibility) + test.That(t, resp, test.ShouldResemble, &fragment) + }) + + t.Run("DeleteFragment", func(t *testing.T) { + grpcClient.DeleteFragmentFunc = func( + ctx context.Context, in *pb.DeleteFragmentRequest, opts ...grpc.CallOption, + ) (*pb.DeleteFragmentResponse, error) { + test.That(t, in.Id, test.ShouldEqual, fragmentID) + return &pb.DeleteFragmentResponse{}, nil + } + client.DeleteFragment(context.Background(), fragmentID) + }) + + t.Run("ListMachineFragments", func(t *testing.T) { + expectedFragments := []Fragment{fragment} + additionalFragmentIDs := []string{fragmentID} + grpcClient.ListMachineFragmentsFunc = func( + ctx context.Context, in *pb.ListMachineFragmentsRequest, opts ...grpc.CallOption, + ) (*pb.ListMachineFragmentsResponse, error) { + test.That(t, in.MachineId, test.ShouldEqual, robotID) + test.That(t, in.AdditionalFragmentIds, test.ShouldResemble, additionalFragmentIDs) + return &pb.ListMachineFragmentsResponse{ + Fragments: []*pb.Fragment{&pbFragment}, + }, nil + } + resp, _ := client.ListMachineFragments(context.Background(), robotID, additionalFragmentIDs) + test.That(t, len(resp), test.ShouldEqual, len(expectedFragments)) + test.That(t, resp[0], test.ShouldResemble, &expectedFragments[0]) + }) + + t.Run("GetFragmentHistory", func(t *testing.T) { + expectedHistory := []FragmentHistoryEntry{fragmentHistoryEntry} + pbFragmentHistoryEntry := pb.FragmentHistoryEntry{ + Fragment: fragmentHistoryEntry.Fragment, + EditedOn: fragmentHistoryEntry.EditedOn, + Old: &pbFragment, + EditedBy: &pbAuthenticatorInfo, + } + grpcClient.GetFragmentHistoryFunc = func( + ctx context.Context, in *pb.GetFragmentHistoryRequest, opts ...grpc.CallOption, + ) (*pb.GetFragmentHistoryResponse, error) { + test.That(t, in.Id, test.ShouldEqual, fragmentID) + test.That(t, in.PageToken, test.ShouldResemble, &pageToken) + test.That(t, in.PageLimit, test.ShouldResemble, &limit) + return &pb.GetFragmentHistoryResponse{ + History: []*pb.FragmentHistoryEntry{&pbFragmentHistoryEntry}, + NextPageToken: pageToken, + }, nil + } + resp, token, _ := client.GetFragmentHistory(context.Background(), fragmentID, &pageToken, &limit) + test.That(t, token, test.ShouldEqual, pageToken) + test.That(t, len(resp), test.ShouldEqual, len(expectedHistory)) + test.That(t, resp[0], test.ShouldResemble, &expectedHistory[0]) + }) } From 4a3ca8d36161c640df7a5a4475366023c6b94b78 Mon Sep 17 00:00:00 2001 From: purplenicole730 Date: Mon, 18 Nov 2024 08:33:02 -0500 Subject: [PATCH 39/75] include appclient in viamclient --- app/viam_client.go | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/app/viam_client.go b/app/viam_client.go index e9d4a59f6b2..30ac252dfc7 100644 --- a/app/viam_client.go +++ b/app/viam_client.go @@ -15,6 +15,7 @@ import ( // ViamClient is a gRPC client for method calls to Viam app. type ViamClient struct { conn rpc.ClientConn + appClient Client } // Options has the options necessary to connect through gRPC. @@ -47,7 +48,10 @@ func CreateViamClientWithOptions(ctx context.Context, options Options, logger lo if err != nil { return nil, err } - return &ViamClient{conn: conn}, nil + return &ViamClient{ + conn: conn, + appClient: NewClientFromConn(conn, logger), + }, nil } // CreateViamClientWithAPIKey creates a ViamClient with an API key. From 2b60c34c79dbbec6f008b597df0d81d5b71ddc1d Mon Sep 17 00:00:00 2001 From: purplenicole730 Date: Mon, 18 Nov 2024 08:38:14 -0500 Subject: [PATCH 40/75] use iota --- app/authorization.go | 16 ++++++++-------- app/fragment.go | 8 ++++---- app/registry_item.go | 44 ++++++++++++++++++++++---------------------- 3 files changed, 34 insertions(+), 34 deletions(-) diff --git a/app/authorization.go b/app/authorization.go index 60ab908dca5..7fd98638ecc 100644 --- a/app/authorization.go +++ b/app/authorization.go @@ -114,11 +114,11 @@ type SharedSecretState int32 const ( // SharedSecretStateUnspecified represents an unspecified shared secret state. - SharedSecretStateUnspecified SharedSecretState = 0 + SharedSecretStateUnspecified SharedSecretState = iota // SharedSecretStateEnabled represents an enabled secret that can be used in authentication. - SharedSecretStateEnabled SharedSecretState = 1 + SharedSecretStateEnabled // SharedSecretStateDisabled represents a disabled secret that must not be used to authenticate to rpc. - SharedSecretStateDisabled SharedSecretState = 2 + SharedSecretStateDisabled ) func sharedSecretStateFromProto(state pb.SharedSecret_State) SharedSecretState { @@ -154,15 +154,15 @@ type AuthenticationType int32 const ( // AuthenticationTypeUnspecified represents an unspecified authentication. - AuthenticationTypeUnspecified AuthenticationType = 0 + AuthenticationTypeUnspecified AuthenticationType = iota // AuthenticationTypeWebOAuth represents authentication using Web OAuth. - AuthenticationTypeWebOAuth AuthenticationType = 1 + AuthenticationTypeWebOAuth // AuthenticationTypeAPIKey represents authentication using an API key. - AuthenticationTypeAPIKey AuthenticationType = 2 + AuthenticationTypeAPIKey // AuthenticationTypeRobotPartSecret represents authentication using a robot part secret. - AuthenticationTypeRobotPartSecret AuthenticationType = 3 + AuthenticationTypeRobotPartSecret // AuthenticationTypeLocationSecret represents authentication using a location secret. - AuthenticationTypeLocationSecret AuthenticationType = 4 + AuthenticationTypeLocationSecret ) func authenticationTypeFromProto(authenticationType pb.AuthenticationType) AuthenticationType { diff --git a/app/fragment.go b/app/fragment.go index 08033875c2b..62755a0eaa7 100644 --- a/app/fragment.go +++ b/app/fragment.go @@ -44,13 +44,13 @@ type FragmentVisibility int32 const ( // FragmentVisibilityUnspecified is an unspecified visibility. - FragmentVisibilityUnspecified FragmentVisibility = 0 + FragmentVisibilityUnspecified FragmentVisibility = iota // FragmentVisibilityPrivate restricts access to a fragment to its organization. - FragmentVisibilityPrivate FragmentVisibility = 1 + FragmentVisibilityPrivate // FragmentVisibilityPublic allows the fragment to be accessible to everyone. - FragmentVisibilityPublic FragmentVisibility = 2 + FragmentVisibilityPublic // FragmentVisibilityPublicUnlisted allows the fragment to be accessible to everyone but is hidden from public listings like it is private. - FragmentVisibilityPublicUnlisted FragmentVisibility = 3 + FragmentVisibilityPublicUnlisted ) func fragmentVisibilityFromProto(visibility pb.FragmentVisibility) FragmentVisibility { diff --git a/app/registry_item.go b/app/registry_item.go index 6029e002a9d..2d02275a426 100644 --- a/app/registry_item.go +++ b/app/registry_item.go @@ -83,11 +83,11 @@ type RegistryItemStatus int32 const ( // RegistryItemStatusUnspecified is an unspecified registry item status. - RegistryItemStatusUnspecified RegistryItemStatus = 0 + RegistryItemStatusUnspecified RegistryItemStatus = iota // RegistryItemStatusPublished represents a published registry item. - RegistryItemStatusPublished RegistryItemStatus = 1 + RegistryItemStatusPublished // RegistryItemStatusInDevelopment represents a registry item still in development. - RegistryItemStatusInDevelopment RegistryItemStatus = 2 + RegistryItemStatusInDevelopment ) func registryItemStatusToProto(status RegistryItemStatus) (pb.RegistryItemStatus, error) { @@ -108,17 +108,17 @@ type PackageType int32 const ( // PackageTypeUnspecified represents an unspecified package type. - PackageTypeUnspecified PackageType = 0 + PackageTypeUnspecified PackageType = iota // PackageTypeArchive represents an archive package type. - PackageTypeArchive PackageType = 1 + PackageTypeArchive // PackageTypeMLModel represents a ML model package type. - PackageTypeMLModel PackageType = 2 + PackageTypeMLModel // PackageTypeModule represents a module package type. - PackageTypeModule PackageType = 3 + PackageTypeModule // PackageTypeSLAMMap represents a SLAM map package type. - PackageTypeSLAMMap PackageType = 4 + PackageTypeSLAMMap // PackageTypeMLTraining represents a ML training package type. - PackageTypeMLTraining PackageType = 5 + PackageTypeMLTraining ) func packageTypeFromProto(packageType packages.PackageType) (PackageType, error) { @@ -164,13 +164,13 @@ type Visibility int32 const ( // VisibilityUnspecified represents an unspecified visibility. - VisibilityUnspecified Visibility = 0 + VisibilityUnspecified Visibility = iota // VisibilityPrivate are for registry items visible only within the owning org. - VisibilityPrivate Visibility = 1 + VisibilityPrivate // VisibilityPublic are for registry items that are visible to everyone. - VisibilityPublic Visibility = 2 + VisibilityPublic // VisibilityPublicUnlisted are for registry items usable in everyone's robot but are hidden from the registry page as if they are private. - VisibilityPublicUnlisted Visibility = 3 + VisibilityPublicUnlisted ) func visibilityFromProto(visibility pb.Visibility) (Visibility, error) { @@ -341,13 +341,13 @@ type ModelType int32 const ( // ModelTypeUnspecified represents an unspecified model. - ModelTypeUnspecified ModelType = 0 + ModelTypeUnspecified ModelType = iota // ModelTypeSingleLabelClassification represents a single-label classification model. - ModelTypeSingleLabelClassification ModelType = 1 + ModelTypeSingleLabelClassification // ModelTypeMultiLabelClassification represents a multi-label classification model. - ModelTypeMultiLabelClassification ModelType = 2 + ModelTypeMultiLabelClassification // ModelTypeObjectDetection represents an object detection model. - ModelTypeObjectDetection ModelType = 3 + ModelTypeObjectDetection ) func modelTypeFromProto(modelType mlTraining.ModelType) (ModelType, error) { @@ -370,15 +370,15 @@ type ModelFramework int32 const ( // ModelFrameworkUnspecified is an unspecified model framework. - ModelFrameworkUnspecified ModelFramework = 0 + ModelFrameworkUnspecified ModelFramework = iota // ModelFrameworkTFLite specifies a TFLite model framework. - ModelFrameworkTFLite ModelFramework = 1 + ModelFrameworkTFLite // ModelFrameworkTensorFlow specifies a TensorFlow model framework. - ModelFrameworkTensorFlow ModelFramework = 2 + ModelFrameworkTensorFlow // ModelFrameworkPyTorch specifies a PyTorch model framework. - ModelFrameworkPyTorch ModelFramework = 3 + ModelFrameworkPyTorch // ModelFrameworkONNX specifies a ONNX model framework. - ModelFrameworkONNX ModelFramework = 4 + ModelFrameworkONNX ) func modelFrameworkFromProto(framework mlTraining.ModelFramework) (ModelFramework, error) { From bdf569a2a2c882d80795c8962fac8f0edf3dc3a8 Mon Sep 17 00:00:00 2001 From: purplenicole730 Date: Mon, 18 Nov 2024 08:59:17 -0500 Subject: [PATCH 41/75] clean up code --- app/app_client.go | 171 ++++++++--------------------------------- app/app_client_test.go | 11 ++- app/authorization.go | 3 +- app/fragment.go | 6 +- app/registry_item.go | 165 +++++++++++++++------------------------ 5 files changed, 104 insertions(+), 252 deletions(-) diff --git a/app/app_client.go b/app/app_client.go index d4af1f37ebb..afa966c9269 100644 --- a/app/app_client.go +++ b/app/app_client.go @@ -139,10 +139,7 @@ func (c *Client) DeleteOrganization(ctx context.Context, orgID string) error { _, err := c.client.DeleteOrganization(ctx, &pb.DeleteOrganizationRequest{ OrganizationId: orgID, }) - if err != nil { - return err - } - return nil + return err } // ListOrganizationMembers lists all members of an organization and all invited members to the organization. @@ -215,10 +212,7 @@ func (c *Client) DeleteOrganizationMember(ctx context.Context, orgID, userID str OrganizationId: orgID, UserId: userID, }) - if err != nil { - return err - } - return nil + return err } // DeleteOrganizationInvite deletes an organization invite. @@ -227,10 +221,7 @@ func (c *Client) DeleteOrganizationInvite(ctx context.Context, orgID, email stri OrganizationId: orgID, Email: email, }) - if err != nil { - return err - } - return nil + return err } // ResendOrganizationInvite resends an organization invite. @@ -251,10 +242,7 @@ func (c *Client) EnableBillingService(ctx context.Context, orgID string, billing OrgId: orgID, BillingAddress: billingAddressToProto(billingAddress), }) - if err != nil { - return err - } - return nil + return err } // DisableBillingService disables the billing service for an organization. @@ -262,10 +250,7 @@ func (c *Client) DisableBillingService(ctx context.Context, orgID string) error _, err := c.client.DisableBillingService(ctx, &pb.DisableBillingServiceRequest{ OrgId: orgID, }) - if err != nil { - return err - } - return nil + return err } // UpdateBillingService updates the billing service of an organization. @@ -275,10 +260,7 @@ func (c *Client) UpdateBillingService(ctx context.Context, orgID string, billing BillingAddress: billingAddressToProto(billingAddress), BillingSupportEmail: billingSupportEmail, }) - if err != nil { - return err - } - return nil + return err } // OrganizationSetSupportEmail sets an organization's support email. @@ -287,10 +269,7 @@ func (c *Client) OrganizationSetSupportEmail(ctx context.Context, orgID, email s OrgId: orgID, Email: email, }) - if err != nil { - return err - } - return nil + return err } // OrganizationGetSupportEmail gets an organization's support email. @@ -347,10 +326,7 @@ func (c *Client) DeleteLocation(ctx context.Context, locationID string) error { _, err := c.client.DeleteLocation(ctx, &pb.DeleteLocationRequest{ LocationId: locationID, }) - if err != nil { - return err - } - return nil + return err } // ListLocations gets a list of locations under the specified organization. @@ -375,10 +351,7 @@ func (c *Client) ShareLocation(ctx context.Context, locationID, orgID string) er LocationId: locationID, OrganizationId: orgID, }) - if err != nil { - return err - } - return nil + return err } // UnshareLocation stops sharing a location with an organization. @@ -387,10 +360,7 @@ func (c *Client) UnshareLocation(ctx context.Context, locationID, orgID string) LocationId: locationID, OrganizationId: orgID, }) - if err != nil { - return err - } - return nil + return err } // LocationAuth gets a location's authorization secrets. @@ -421,10 +391,7 @@ func (c *Client) DeleteLocationSecret(ctx context.Context, locationID, secretID LocationId: locationID, SecretId: secretID, }) - if err != nil { - return err - } - return nil + return err } // GetRobot gets a specific robot by ID. @@ -575,10 +542,7 @@ func (c *Client) DeleteRobotPart(ctx context.Context, partID string) error { _, err := c.client.DeleteRobotPart(ctx, &pb.DeleteRobotPartRequest{ PartId: partID, }) - if err != nil { - return err - } - return nil + return err } // GetRobotAPIKeys gets the robot API keys for the robot. @@ -601,10 +565,7 @@ func (c *Client) MarkPartAsMain(ctx context.Context, partID string) error { _, err := c.client.MarkPartAsMain(ctx, &pb.MarkPartAsMainRequest{ PartId: partID, }) - if err != nil { - return err - } - return nil + return err } // MarkPartForRestart marks the given part for restart. @@ -614,10 +575,7 @@ func (c *Client) MarkPartForRestart(ctx context.Context, partID string) error { _, err := c.client.MarkPartForRestart(ctx, &pb.MarkPartForRestartRequest{ PartId: partID, }) - if err != nil { - return err - } - return nil + return err } // CreateRobotPartSecret creates a new generated secret in the robot part. @@ -638,10 +596,7 @@ func (c *Client) DeleteRobotPartSecret(ctx context.Context, partID, secretID str PartId: partID, SecretId: secretID, }) - if err != nil { - return err - } - return nil + return err } // ListRobots gets a list of robots under a location. @@ -689,10 +644,7 @@ func (c *Client) DeleteRobot(ctx context.Context, id string) error { _, err := c.client.DeleteRobot(ctx, &pb.DeleteRobotRequest{ Id: id, }) - if err != nil { - return err - } - return nil + return err } // ListFragments gets a list of fragments. @@ -778,10 +730,7 @@ func (c *Client) DeleteFragment(ctx context.Context, id string) error { _, err := c.client.DeleteFragment(ctx, &pb.DeleteFragmentRequest{ Id: id, }) - if err != nil { - return err - } - return nil + return err } // ListMachineFragments gets top level and nested fragments for a amchine, as well as any other fragments specified by IDs. Additional @@ -829,10 +778,7 @@ func (c *Client) AddRole(ctx context.Context, orgID, identityID, role, resourceT _, err = c.client.AddRole(ctx, &pb.AddRoleRequest{ Authorization: authorization, }) - if err != nil { - return err - } - return nil + return err } // RemoveRole deletes an identity authorization. @@ -844,10 +790,7 @@ func (c *Client) RemoveRole(ctx context.Context, orgID, identityID, role, resour _, err = c.client.RemoveRole(ctx, &pb.RemoveRoleRequest{ Authorization: authorization, }) - if err != nil { - return err - } - return nil + return err } // ChangeRole changes an identity authorization to a new identity authorization. @@ -876,10 +819,7 @@ func (c *Client) ChangeRole( OldAuthorization: oldAuthorization, NewAuthorization: newAuthorization, }) - if err != nil { - return err - } - return nil + return err } // ListAuthorizations returns all authorization roles for any given resources. @@ -937,44 +877,26 @@ func (c *Client) GetRegistryItem(ctx context.Context, itemID string) (*RegistryI // CreateRegistryItem creates a registry item. func (c *Client) CreateRegistryItem(ctx context.Context, orgID, name string, packageType PackageType) error { - pbPackageType, err := packageTypeToProto(packageType) - if err != nil { - return err - } - _, err = c.client.CreateRegistryItem(ctx, &pb.CreateRegistryItemRequest{ + _, err := c.client.CreateRegistryItem(ctx, &pb.CreateRegistryItemRequest{ OrganizationId: orgID, Name: name, - Type: pbPackageType, + Type: packageTypeToProto(packageType), }) - if err != nil { - return err - } - return nil + return err } // UpdateRegistryItem updates a registry item. func (c *Client) UpdateRegistryItem( ctx context.Context, itemID string, packageType PackageType, description string, visibility Visibility, url *string, ) error { - pbPackageType, err := packageTypeToProto(packageType) - if err != nil { - return err - } - pbVisibility, err := visibilityToProto(visibility) - if err != nil { - return err - } - _, err = c.client.UpdateRegistryItem(ctx, &pb.UpdateRegistryItemRequest{ + _, err := c.client.UpdateRegistryItem(ctx, &pb.UpdateRegistryItemRequest{ ItemId: itemID, - Type: pbPackageType, + Type: packageTypeToProto(packageType), Description: description, - Visibility: pbVisibility, + Visibility: visibilityToProto(visibility), Url: url, }) - if err != nil { - return err - } - return nil + return err } // ListRegistryItems lists the registry items in an organization. @@ -991,27 +913,15 @@ func (c *Client) ListRegistryItems( ) ([]*RegistryItem, error) { var pbTypes []packages.PackageType for _, packageType := range types { - t, err := packageTypeToProto(packageType) - if err != nil { - return nil, err - } - pbTypes = append(pbTypes, t) + pbTypes = append(pbTypes, packageTypeToProto(packageType)) } var pbVisibilities []pb.Visibility for _, visibility := range visibilities { - v, err := visibilityToProto(visibility) - if err != nil { - return nil, err - } - pbVisibilities = append(pbVisibilities, v) + pbVisibilities = append(pbVisibilities, visibilityToProto(visibility)) } var pbStatuses []pb.RegistryItemStatus for _, status := range statuses { - s, err := registryItemStatusToProto(status) - if err != nil { - return nil, err - } - pbStatuses = append(pbStatuses, s) + pbStatuses = append(pbStatuses, registryItemStatusToProto(status)) } resp, err := c.client.ListRegistryItems(ctx, &pb.ListRegistryItemsRequest{ OrganizationId: orgID, @@ -1043,10 +953,7 @@ func (c *Client) DeleteRegistryItem(ctx context.Context, itemID string) error { _, err := c.client.DeleteRegistryItem(ctx, &pb.DeleteRegistryItemRequest{ ItemId: itemID, }) - if err != nil { - return err - } - return nil + return err } // TransferRegistryItem transfers a registry item to a namespace. @@ -1055,10 +962,7 @@ func (c *Client) TransferRegistryItem(ctx context.Context, itemID, newPublicName ItemId: itemID, NewPublicNamespace: newPublicNamespace, }) - if err != nil { - return err - } - return nil + return err } // CreateModule creates a module. @@ -1078,17 +982,13 @@ func (c *Client) CreateModule(ctx context.Context, orgID, name string) (string, func (c *Client) UpdateModule( ctx context.Context, moduleID string, visibility Visibility, url, description string, models []*Model, entrypoint string, firstRun *string, ) (string, error) { - pbVisibility, err := visibilityToProto(visibility) - if err != nil { - return "", err - } var pbModels []*pb.Model for _, model := range models { pbModels = append(pbModels, modelToProto(model)) } resp, err := c.client.UpdateModule(ctx, &pb.UpdateModuleRequest{ ModuleId: moduleID, - Visibility: pbVisibility, + Visibility: visibilityToProto(visibility), Url: url, Description: description, Models: pbModels, @@ -1215,10 +1115,7 @@ func (c *Client) DeleteKey(ctx context.Context, id string) error { _, err := c.client.DeleteKey(ctx, &pb.DeleteKeyRequest{ Id: id, }) - if err != nil { - return err - } - return nil + return err } // ListKeys lists all the keys for the organization. diff --git a/app/app_client_test.go b/app/app_client_test.go index 6acae27ad0c..4c8ede2426d 100644 --- a/app/app_client_test.go +++ b/app/app_client_test.go @@ -369,17 +369,20 @@ var ( func sharedSecretStateToProto(state SharedSecretState) pb.SharedSecret_State { switch state { + case SharedSecretStateUnspecified: + return pb.SharedSecret_STATE_UNSPECIFIED case SharedSecretStateEnabled: return pb.SharedSecret_STATE_ENABLED case SharedSecretStateDisabled: return pb.SharedSecret_STATE_DISABLED - default: - return pb.SharedSecret_STATE_UNSPECIFIED } + return pb.SharedSecret_STATE_UNSPECIFIED } func authenticationTypeToProto(authType AuthenticationType) pb.AuthenticationType { switch authType { + case AuthenticationTypeUnspecified: + return pb.AuthenticationType_AUTHENTICATION_TYPE_UNSPECIFIED case AuthenticationTypeWebOAuth: return pb.AuthenticationType_AUTHENTICATION_TYPE_WEB_OAUTH case AuthenticationTypeAPIKey: @@ -388,9 +391,9 @@ func authenticationTypeToProto(authType AuthenticationType) pb.AuthenticationTyp return pb.AuthenticationType_AUTHENTICATION_TYPE_ROBOT_PART_SECRET case AuthenticationTypeLocationSecret: return pb.AuthenticationType_AUTHENTICATION_TYPE_LOCATION_SECRET - default: - return pb.AuthenticationType_AUTHENTICATION_TYPE_UNSPECIFIED } + return pb.AuthenticationType_AUTHENTICATION_TYPE_UNSPECIFIED + } func testOrganizationResponse(t *testing.T, actualOrg, expectedOrg *Organization) { diff --git a/app/authorization.go b/app/authorization.go index 7fd98638ecc..895ac0c53af 100644 --- a/app/authorization.go +++ b/app/authorization.go @@ -177,9 +177,8 @@ func authenticationTypeFromProto(authenticationType pb.AuthenticationType) Authe return AuthenticationTypeRobotPartSecret case pb.AuthenticationType_AUTHENTICATION_TYPE_LOCATION_SECRET: return AuthenticationTypeLocationSecret - default: - return AuthenticationTypeUnspecified } + return AuthenticationTypeUnspecified } // APIKeyWithAuthorizations is an API Key with its authorizations. diff --git a/app/fragment.go b/app/fragment.go index 62755a0eaa7..36ea107547c 100644 --- a/app/fragment.go +++ b/app/fragment.go @@ -63,9 +63,8 @@ func fragmentVisibilityFromProto(visibility pb.FragmentVisibility) FragmentVisib return FragmentVisibilityPublic case pb.FragmentVisibility_FRAGMENT_VISIBILITY_PUBLIC_UNLISTED: return FragmentVisibilityPublicUnlisted - default: - return FragmentVisibilityUnspecified } + return FragmentVisibilityUnspecified } func fragmentVisibilityToProto(visibility FragmentVisibility) pb.FragmentVisibility { @@ -78,9 +77,8 @@ func fragmentVisibilityToProto(visibility FragmentVisibility) pb.FragmentVisibil return pb.FragmentVisibility_FRAGMENT_VISIBILITY_PUBLIC case FragmentVisibilityPublicUnlisted: return pb.FragmentVisibility_FRAGMENT_VISIBILITY_PUBLIC_UNLISTED - default: - return pb.FragmentVisibility_FRAGMENT_VISIBILITY_UNSPECIFIED } + return pb.FragmentVisibility_FRAGMENT_VISIBILITY_UNSPECIFIED } // FragmentHistoryEntry is an entry of a fragment's history. diff --git a/app/registry_item.go b/app/registry_item.go index 2d02275a426..f5907af3249 100644 --- a/app/registry_item.go +++ b/app/registry_item.go @@ -29,32 +29,14 @@ type RegistryItem struct { } func registryItemFromProto(item *pb.RegistryItem) (*RegistryItem, error) { - packageType, err := packageTypeFromProto(item.Type) - if err != nil { - return nil, err - } - visibility, err := visibilityFromProto(item.Visibility) - if err != nil { - return nil, err - } - var metadata isRegistryItemMetadata switch pbMetadata := item.Metadata.(type) { case *pb.RegistryItem_ModuleMetadata: - md := moduleMetadataFromProto(pbMetadata.ModuleMetadata) - metadata = &RegistryItemModuleMetadata{ModuleMetadata: md} + metadata = &RegistryItemModuleMetadata{ModuleMetadata: moduleMetadataFromProto(pbMetadata.ModuleMetadata)} case *pb.RegistryItem_MlModelMetadata: - md, err := mlModelMetadataFromProto(pbMetadata.MlModelMetadata) - if err != nil { - return nil, err - } - metadata = &RegistryItemMLModelMetadata{MlModelMetadata: md} + metadata = &RegistryItemMLModelMetadata{MlModelMetadata: mlModelMetadataFromProto(pbMetadata.MlModelMetadata)} case *pb.RegistryItem_MlTrainingMetadata: - md, err := mlTrainingMetadataFromProto(pbMetadata.MlTrainingMetadata) - if err != nil { - return nil, err - } - metadata = &RegistryItemMLTrainingMetadata{MlTrainingMetadata: md} + metadata = &RegistryItemMLTrainingMetadata{MlTrainingMetadata: mlTrainingMetadataFromProto(pbMetadata.MlTrainingMetadata)} default: return nil, fmt.Errorf("unknown registry item metadata type: %T", item.Metadata) } @@ -64,8 +46,8 @@ func registryItemFromProto(item *pb.RegistryItem) (*RegistryItem, error) { OrganizationID: item.OrganizationId, PublicNamespace: item.PublicNamespace, Name: item.Name, - Type: packageType, - Visibility: visibility, + Type: packageTypeFromProto(item.Type), + Visibility: visibilityFromProto(item.Visibility), URL: item.Url, Description: item.Description, TotalRobotUsage: item.TotalRobotUsage, @@ -90,17 +72,16 @@ const ( RegistryItemStatusInDevelopment ) -func registryItemStatusToProto(status RegistryItemStatus) (pb.RegistryItemStatus, error) { +func registryItemStatusToProto(status RegistryItemStatus) (pb.RegistryItemStatus) { switch status { case RegistryItemStatusUnspecified: - return pb.RegistryItemStatus_REGISTRY_ITEM_STATUS_UNSPECIFIED, nil + return pb.RegistryItemStatus_REGISTRY_ITEM_STATUS_UNSPECIFIED case RegistryItemStatusPublished: - return pb.RegistryItemStatus_REGISTRY_ITEM_STATUS_PUBLISHED, nil + return pb.RegistryItemStatus_REGISTRY_ITEM_STATUS_PUBLISHED case RegistryItemStatusInDevelopment: - return pb.RegistryItemStatus_REGISTRY_ITEM_STATUS_IN_DEVELOPMENT, nil - default: - return 0, fmt.Errorf("unknown registry item status: %v", status) + return pb.RegistryItemStatus_REGISTRY_ITEM_STATUS_IN_DEVELOPMENT } + return pb.RegistryItemStatus_REGISTRY_ITEM_STATUS_UNSPECIFIED } // PackageType is the type of package being used. @@ -121,42 +102,40 @@ const ( PackageTypeMLTraining ) -func packageTypeFromProto(packageType packages.PackageType) (PackageType, error) { +func packageTypeFromProto(packageType packages.PackageType) (PackageType) { switch packageType { case packages.PackageType_PACKAGE_TYPE_UNSPECIFIED: - return PackageTypeUnspecified, nil + return PackageTypeUnspecified case packages.PackageType_PACKAGE_TYPE_ARCHIVE: - return PackageTypeArchive, nil + return PackageTypeArchive case packages.PackageType_PACKAGE_TYPE_ML_MODEL: - return PackageTypeMLModel, nil + return PackageTypeMLModel case packages.PackageType_PACKAGE_TYPE_MODULE: - return PackageTypeModule, nil + return PackageTypeModule case packages.PackageType_PACKAGE_TYPE_SLAM_MAP: - return PackageTypeSLAMMap, nil + return PackageTypeSLAMMap case packages.PackageType_PACKAGE_TYPE_ML_TRAINING: - return PackageTypeMLTraining, nil - default: - return 0, fmt.Errorf("unknown fragment visibility: %v", packageType) + return PackageTypeMLTraining } + return PackageTypeUnspecified } -func packageTypeToProto(packageType PackageType) (packages.PackageType, error) { +func packageTypeToProto(packageType PackageType) (packages.PackageType) { switch packageType { case PackageTypeUnspecified: - return packages.PackageType_PACKAGE_TYPE_UNSPECIFIED, nil + return packages.PackageType_PACKAGE_TYPE_UNSPECIFIED case PackageTypeArchive: - return packages.PackageType_PACKAGE_TYPE_ARCHIVE, nil + return packages.PackageType_PACKAGE_TYPE_ARCHIVE case PackageTypeMLModel: - return packages.PackageType_PACKAGE_TYPE_ML_MODEL, nil + return packages.PackageType_PACKAGE_TYPE_ML_MODEL case PackageTypeModule: - return packages.PackageType_PACKAGE_TYPE_MODULE, nil + return packages.PackageType_PACKAGE_TYPE_MODULE case PackageTypeSLAMMap: - return packages.PackageType_PACKAGE_TYPE_SLAM_MAP, nil + return packages.PackageType_PACKAGE_TYPE_SLAM_MAP case PackageTypeMLTraining: - return packages.PackageType_PACKAGE_TYPE_ML_TRAINING, nil - default: - return 0, fmt.Errorf("unknown fragment visibility: %v", packageType) + return packages.PackageType_PACKAGE_TYPE_ML_TRAINING } + return packages.PackageType_PACKAGE_TYPE_UNSPECIFIED } // Visibility specifies the type of visibility of a registry item. @@ -173,34 +152,32 @@ const ( VisibilityPublicUnlisted ) -func visibilityFromProto(visibility pb.Visibility) (Visibility, error) { +func visibilityFromProto(visibility pb.Visibility) Visibility { switch visibility { case pb.Visibility_VISIBILITY_UNSPECIFIED: - return VisibilityUnspecified, nil + return VisibilityUnspecified case pb.Visibility_VISIBILITY_PRIVATE: - return VisibilityPrivate, nil + return VisibilityPrivate case pb.Visibility_VISIBILITY_PUBLIC: - return VisibilityPublic, nil + return VisibilityPublic case pb.Visibility_VISIBILITY_PUBLIC_UNLISTED: - return VisibilityPublicUnlisted, nil - default: - return 0, fmt.Errorf("unknown fragment visibility: %v", visibility) + return VisibilityPublicUnlisted } + return VisibilityUnspecified } -func visibilityToProto(visibility Visibility) (pb.Visibility, error) { +func visibilityToProto(visibility Visibility) (pb.Visibility) { switch visibility { case VisibilityUnspecified: - return pb.Visibility_VISIBILITY_UNSPECIFIED, nil + return pb.Visibility_VISIBILITY_UNSPECIFIED case VisibilityPrivate: - return pb.Visibility_VISIBILITY_PRIVATE, nil + return pb.Visibility_VISIBILITY_PRIVATE case VisibilityPublic: - return pb.Visibility_VISIBILITY_PUBLIC, nil + return pb.Visibility_VISIBILITY_PUBLIC case VisibilityPublicUnlisted: - return pb.Visibility_VISIBILITY_PUBLIC_UNLISTED, nil - default: - return 0, fmt.Errorf("unknown fragment visibility: %v", visibility) + return pb.Visibility_VISIBILITY_PUBLIC_UNLISTED } + return pb.Visibility_VISIBILITY_UNSPECIFIED } type isRegistryItemMetadata interface { @@ -320,20 +297,12 @@ type MLModelMetadata struct { ModelFramework ModelFramework } -func mlModelMetadataFromProto(md *pb.MLModelMetadata) (*MLModelMetadata, error) { - modelType, err := modelTypeFromProto(md.ModelType) - if err != nil { - return nil, err - } - modelFramework, err := modelFrameworkFromProto(md.ModelFramework) - if err != nil { - return nil, err - } +func mlModelMetadataFromProto(md *pb.MLModelMetadata) (*MLModelMetadata) { return &MLModelMetadata{ Versions: md.Versions, - ModelType: modelType, - ModelFramework: modelFramework, - }, nil + ModelType: modelTypeFromProto(md.ModelType), + ModelFramework: modelFrameworkFromProto(md.ModelFramework), + } } // ModelType specifies the type of model used for classification or detection. @@ -350,19 +319,18 @@ const ( ModelTypeObjectDetection ) -func modelTypeFromProto(modelType mlTraining.ModelType) (ModelType, error) { +func modelTypeFromProto(modelType mlTraining.ModelType) (ModelType) { switch modelType { case mlTraining.ModelType_MODEL_TYPE_UNSPECIFIED: - return ModelTypeUnspecified, nil + return ModelTypeUnspecified case mlTraining.ModelType_MODEL_TYPE_SINGLE_LABEL_CLASSIFICATION: - return ModelTypeSingleLabelClassification, nil + return ModelTypeSingleLabelClassification case mlTraining.ModelType_MODEL_TYPE_MULTI_LABEL_CLASSIFICATION: - return ModelTypeMultiLabelClassification, nil + return ModelTypeMultiLabelClassification case mlTraining.ModelType_MODEL_TYPE_OBJECT_DETECTION: - return ModelTypeObjectDetection, nil - default: - return 0, fmt.Errorf("unknown model type: %v", modelType) + return ModelTypeObjectDetection } + return ModelTypeUnspecified } // ModelFramework is the framework type of a model. @@ -381,21 +349,20 @@ const ( ModelFrameworkONNX ) -func modelFrameworkFromProto(framework mlTraining.ModelFramework) (ModelFramework, error) { +func modelFrameworkFromProto(framework mlTraining.ModelFramework) (ModelFramework) { switch framework { case mlTraining.ModelFramework_MODEL_FRAMEWORK_UNSPECIFIED: - return ModelFrameworkUnspecified, nil + return ModelFrameworkUnspecified case mlTraining.ModelFramework_MODEL_FRAMEWORK_TFLITE: - return ModelFrameworkTFLite, nil + return ModelFrameworkTFLite case mlTraining.ModelFramework_MODEL_FRAMEWORK_TENSORFLOW: - return ModelFrameworkTensorFlow, nil + return ModelFrameworkTensorFlow case mlTraining.ModelFramework_MODEL_FRAMEWORK_PYTORCH: - return ModelFrameworkPyTorch, nil + return ModelFrameworkPyTorch case mlTraining.ModelFramework_MODEL_FRAMEWORK_ONNX: - return ModelFrameworkONNX, nil - default: - return 0, fmt.Errorf("unknown model framework: %v", framework) + return ModelFrameworkONNX } + return ModelFrameworkUnspecified } // MLTrainingMetadata is the metadata of an ML Training. @@ -406,25 +373,17 @@ type MLTrainingMetadata struct { Draft bool } -func mlTrainingMetadataFromProto(md *pb.MLTrainingMetadata) (*MLTrainingMetadata, error) { +func mlTrainingMetadataFromProto(md *pb.MLTrainingMetadata) (*MLTrainingMetadata) { var versions []*MLTrainingVersion for _, version := range md.Versions { versions = append(versions, mlTrainingVersionFromProto(version)) } - modelType, err := modelTypeFromProto(md.ModelType) - if err != nil { - return nil, err - } - modelFramework, err := modelFrameworkFromProto(md.ModelFramework) - if err != nil { - return nil, err - } return &MLTrainingMetadata{ Versions: versions, - ModelType: modelType, - ModelFramework: modelFramework, + ModelType: modelTypeFromProto(md.ModelType), + ModelFramework: modelFrameworkFromProto(md.ModelFramework), Draft: md.Draft, - }, nil + } } // MLTrainingVersion is the version of ML Training. @@ -458,10 +417,6 @@ type Module struct { } func moduleFromProto(module *pb.Module) (*Module, error) { - visibility, err := visibilityFromProto(module.Visibility) - if err != nil { - return nil, err - } var versions []*VersionHistory for _, version := range module.Versions { versions = append(versions, versionHistoryFromProto(version)) @@ -473,7 +428,7 @@ func moduleFromProto(module *pb.Module) (*Module, error) { return &Module{ ModuleID: module.ModuleId, Name: module.Name, - Visibility: visibility, + Visibility: visibilityFromProto(module.Visibility), Versions: versions, URL: module.Url, Description: module.Description, From 8a5dbb6e1d4063e60e1fc9e860dca983acb6cc3a Mon Sep 17 00:00:00 2001 From: purplenicole730 Date: Mon, 18 Nov 2024 09:02:57 -0500 Subject: [PATCH 42/75] make lint --- app/app_client.go | 12 ++---------- app/app_client_test.go | 1 - app/registry_item.go | 20 ++++++++++---------- app/viam_client.go | 4 ++-- 4 files changed, 14 insertions(+), 23 deletions(-) diff --git a/app/app_client.go b/app/app_client.go index afa966c9269..a819bf04b48 100644 --- a/app/app_client.go +++ b/app/app_client.go @@ -1060,11 +1060,7 @@ func (c *Client) GetModule(ctx context.Context, moduleID string) (*Module, error if err != nil { return nil, err } - module, err := moduleFromProto(resp.Module) - if err != nil { - return nil, err - } - return module, nil + return moduleFromProto(resp.Module), nil } // ListModules lists the modules in the organization. @@ -1077,11 +1073,7 @@ func (c *Client) ListModules(ctx context.Context, orgID *string) ([]*Module, err } var modules []*Module for _, module := range resp.Modules { - m, err := moduleFromProto(module) - if err != nil { - return nil, err - } - modules = append(modules, m) + modules = append(modules, moduleFromProto(module)) } return modules, nil } diff --git a/app/app_client_test.go b/app/app_client_test.go index 4c8ede2426d..acab6ef5873 100644 --- a/app/app_client_test.go +++ b/app/app_client_test.go @@ -393,7 +393,6 @@ func authenticationTypeToProto(authType AuthenticationType) pb.AuthenticationTyp return pb.AuthenticationType_AUTHENTICATION_TYPE_LOCATION_SECRET } return pb.AuthenticationType_AUTHENTICATION_TYPE_UNSPECIFIED - } func testOrganizationResponse(t *testing.T, actualOrg, expectedOrg *Organization) { diff --git a/app/registry_item.go b/app/registry_item.go index f5907af3249..54e0417d00c 100644 --- a/app/registry_item.go +++ b/app/registry_item.go @@ -72,7 +72,7 @@ const ( RegistryItemStatusInDevelopment ) -func registryItemStatusToProto(status RegistryItemStatus) (pb.RegistryItemStatus) { +func registryItemStatusToProto(status RegistryItemStatus) pb.RegistryItemStatus { switch status { case RegistryItemStatusUnspecified: return pb.RegistryItemStatus_REGISTRY_ITEM_STATUS_UNSPECIFIED @@ -102,7 +102,7 @@ const ( PackageTypeMLTraining ) -func packageTypeFromProto(packageType packages.PackageType) (PackageType) { +func packageTypeFromProto(packageType packages.PackageType) PackageType { switch packageType { case packages.PackageType_PACKAGE_TYPE_UNSPECIFIED: return PackageTypeUnspecified @@ -120,7 +120,7 @@ func packageTypeFromProto(packageType packages.PackageType) (PackageType) { return PackageTypeUnspecified } -func packageTypeToProto(packageType PackageType) (packages.PackageType) { +func packageTypeToProto(packageType PackageType) packages.PackageType { switch packageType { case PackageTypeUnspecified: return packages.PackageType_PACKAGE_TYPE_UNSPECIFIED @@ -166,7 +166,7 @@ func visibilityFromProto(visibility pb.Visibility) Visibility { return VisibilityUnspecified } -func visibilityToProto(visibility Visibility) (pb.Visibility) { +func visibilityToProto(visibility Visibility) pb.Visibility { switch visibility { case VisibilityUnspecified: return pb.Visibility_VISIBILITY_UNSPECIFIED @@ -297,7 +297,7 @@ type MLModelMetadata struct { ModelFramework ModelFramework } -func mlModelMetadataFromProto(md *pb.MLModelMetadata) (*MLModelMetadata) { +func mlModelMetadataFromProto(md *pb.MLModelMetadata) *MLModelMetadata { return &MLModelMetadata{ Versions: md.Versions, ModelType: modelTypeFromProto(md.ModelType), @@ -319,7 +319,7 @@ const ( ModelTypeObjectDetection ) -func modelTypeFromProto(modelType mlTraining.ModelType) (ModelType) { +func modelTypeFromProto(modelType mlTraining.ModelType) ModelType { switch modelType { case mlTraining.ModelType_MODEL_TYPE_UNSPECIFIED: return ModelTypeUnspecified @@ -349,7 +349,7 @@ const ( ModelFrameworkONNX ) -func modelFrameworkFromProto(framework mlTraining.ModelFramework) (ModelFramework) { +func modelFrameworkFromProto(framework mlTraining.ModelFramework) ModelFramework { switch framework { case mlTraining.ModelFramework_MODEL_FRAMEWORK_UNSPECIFIED: return ModelFrameworkUnspecified @@ -373,7 +373,7 @@ type MLTrainingMetadata struct { Draft bool } -func mlTrainingMetadataFromProto(md *pb.MLTrainingMetadata) (*MLTrainingMetadata) { +func mlTrainingMetadataFromProto(md *pb.MLTrainingMetadata) *MLTrainingMetadata { var versions []*MLTrainingVersion for _, version := range md.Versions { versions = append(versions, mlTrainingVersionFromProto(version)) @@ -416,7 +416,7 @@ type Module struct { FirstRun *string } -func moduleFromProto(module *pb.Module) (*Module, error) { +func moduleFromProto(module *pb.Module) *Module { var versions []*VersionHistory for _, version := range module.Versions { versions = append(versions, versionHistoryFromProto(version)) @@ -439,7 +439,7 @@ func moduleFromProto(module *pb.Module) (*Module, error) { Entrypoint: module.Entrypoint, PublicNamespace: module.PublicNamespace, FirstRun: module.FirstRun, - }, nil + } } // VersionHistory holds the history of a version. diff --git a/app/viam_client.go b/app/viam_client.go index 30ac252dfc7..94c4a15520e 100644 --- a/app/viam_client.go +++ b/app/viam_client.go @@ -14,7 +14,7 @@ import ( // ViamClient is a gRPC client for method calls to Viam app. type ViamClient struct { - conn rpc.ClientConn + conn rpc.ClientConn appClient Client } @@ -49,7 +49,7 @@ func CreateViamClientWithOptions(ctx context.Context, options Options, logger lo return nil, err } return &ViamClient{ - conn: conn, + conn: conn, appClient: NewClientFromConn(conn, logger), }, nil } From bf0ad6d57d9f8b0b6112eea9f6b2a673d6262e5d Mon Sep 17 00:00:00 2001 From: purplenicole730 Date: Mon, 18 Nov 2024 10:46:04 -0500 Subject: [PATCH 43/75] add authorization tests --- app/app_client_test.go | 364 +++++++++++++++++++++++++++++++---------- 1 file changed, 279 insertions(+), 85 deletions(-) diff --git a/app/app_client_test.go b/app/app_client_test.go index acab6ef5873..2b918074c46 100644 --- a/app/app_client_test.go +++ b/app/app_client_test.go @@ -2,6 +2,7 @@ package app import ( "context" + "fmt" "testing" pb "go.viam.com/api/app/v1" @@ -16,43 +17,50 @@ import ( ) const ( - organizationID = "organization_id" - email = "email" - userID = "user_id" - locationID = "location_id" - available = true - authorizationType = "authorization_type" - authorizationID = "authorization_id" - resourceType = "resource_type" - resourceID = "resource_id" - identityID = "identity_id" - identityType = "identity_type" - secretID = "secret_ids" - primary = true - robotCount = 1 - robotID = "robot_id" - robotLocation = "robot_location" - partID = "part_id" - dnsName = "dns_name" - secret = "secret" - mainPart = false - fqdn = "fqdn" - localFQDN = "local_fqdn" - configJSON = "configJson" - host = "host" - level = "level" - loggerName = "logger_name" - message = "message" - stack = "stack" - value = "value" - isDeactivated = false - keyID = "key_id" - key = "key" - fragmentID = "fragment_id" - organizationOwner = "organization_owner" - robotPartCount = 5 - onlyUsedByOwner = false - organizationCount = 2 + organizationID = "organization_id" + organizationID2 = "organization_id_2" + email = "email" + userID = "user_id" + locationID = "location_id" + available = true + authorizationType = "owner" + authorizationType2 = "operator" + badAuthorizationType = "authorization_type" + resourceType = "organization" + resourceType2 = "location" + badResourceType = "resource_type" + resourceID = "resource_id" + resourceID2 = "resource_id_2" + identityID = "identity_id" + identityID2 = "identity_id_2" + identityType = "" + secretID = "secret_ids" + primary = true + robotCount = 1 + robotID = "robot_id" + robotLocation = "robot_location" + partID = "part_id" + dnsName = "dns_name" + secret = "secret" + mainPart = false + fqdn = "fqdn" + localFQDN = "local_fqdn" + configJSON = "configJson" + host = "host" + level = "level" + loggerName = "logger_name" + message = "message" + stack = "stack" + value = "value" + isDeactivated = false + keyID = "key_id" + key = "key" + fragmentID = "fragment_id" + organizationOwner = "organization_owner" + robotPartCount = 5 + onlyUsedByOwner = false + organizationCount = 2 + permission = "permission" ) var ( @@ -96,19 +104,36 @@ var ( OrganizationID: organizationID, IdentityType: identityType, } - authorizations = []*Authorization{&authorization} - pbAuthorizations = []*pb.Authorization{ - { - AuthorizationType: authorization.AuthorizationType, - AuthorizationId: authorization.AuthorizationID, - ResourceType: authorization.ResourceType, - ResourceId: authorization.ResourceID, - IdentityId: authorization.IdentityID, - OrganizationId: authorization.OrganizationID, - IdentityType: authorization.IdentityType, - }, + pbAuthorization = pb.Authorization{ + AuthorizationType: authorization.AuthorizationType, + AuthorizationId: authorization.AuthorizationID, + ResourceType: authorization.ResourceType, + ResourceId: authorization.ResourceID, + IdentityId: authorization.IdentityID, + OrganizationId: authorization.OrganizationID, + IdentityType: authorization.IdentityType, + } + authorization2 = Authorization{ + AuthorizationType: authorizationType2, + AuthorizationID: authorizationID2, + ResourceType: resourceType2, + ResourceID: resourceID2, + IdentityID: identityID2, + OrganizationID: organizationID2, + IdentityType: identityType, } - member = OrganizationMember{ + pbAuthorization2 = pb.Authorization{ + AuthorizationType: authorization2.AuthorizationType, + AuthorizationId: authorization2.AuthorizationID, + ResourceType: authorization2.ResourceType, + ResourceId: authorization2.ResourceID, + IdentityId: authorization2.IdentityID, + OrganizationId: authorization2.OrganizationID, + IdentityType: authorization2.IdentityType, + } + authorizations = []*Authorization{&authorization, &authorization2} + pbAuthorizations = []*pb.Authorization{&pbAuthorization, &pbAuthorization2} + member = OrganizationMember{ UserID: userID, Emails: []string{email}, DateAdded: &dateAdded, @@ -292,6 +317,8 @@ var ( Old: &robotPart, EditedBy: &authenticatorInfo, } + authorizationID = fmt.Sprintf("%s_%s", resourceType, authorizationType) + authorizationID2 = fmt.Sprintf("%s_%s", resourceType2, authorizationType2) authorizationDetails = AuthorizationDetails{ AuthorizationType: authorizationType, AuthorizationID: authorizationID, @@ -365,6 +392,14 @@ var ( Old: &fragment, EditedBy: &authenticatorInfo, } + resourceIDs = []string{resourceID, resourceID2} + permissions = []*AuthorizedPermissions{ + { + ResourceType: resourceType, + ResourceID: resourceID, + Permissions: []string{permission}, + }, + } ) func sharedSecretStateToProto(state SharedSecretState) pb.SharedSecret_State { @@ -450,7 +485,8 @@ func TestAppClient(t *testing.T) { UserId: userID, }, nil } - resp, _ := client.GetUserIDByEmail(context.Background(), email) + resp, err := client.GetUserIDByEmail(context.Background(), email) + test.That(t, err, test.ShouldBeNil) test.That(t, resp, test.ShouldEqual, userID) }) @@ -463,7 +499,8 @@ func TestAppClient(t *testing.T) { Organization: &pbOrganization, }, nil } - resp, _ := client.CreateOrganization(context.Background(), name) + resp, err := client.CreateOrganization(context.Background(), name) + test.That(t, err, test.ShouldBeNil) testOrganizationResponse(t, resp, &organization) }) @@ -476,7 +513,8 @@ func TestAppClient(t *testing.T) { Organizations: []*pb.Organization{&pbOrganization}, }, nil } - resp, _ := client.ListOrganizations(context.Background()) + resp, err := client.ListOrganizations(context.Background()) + test.That(t, err, test.ShouldBeNil) test.That(t, len(resp), test.ShouldEqual, len(expectedOrganizations)) testOrganizationResponse(t, resp[0], &expectedOrganizations[0]) }) @@ -494,7 +532,8 @@ func TestAppClient(t *testing.T) { OrganizationIdentities: []*pb.OrganizationIdentity{&pbOrganizationIdentity}, }, nil } - resp, _ := client.GetOrganizationsWithAccessToLocation(context.Background(), locationID) + resp, err := client.GetOrganizationsWithAccessToLocation(context.Background(), locationID) + test.That(t, err, test.ShouldBeNil) test.That(t, len(resp), test.ShouldEqual, 1) test.That(t, resp[0].ID, test.ShouldEqual, organizationIdentity.ID) test.That(t, resp[0].Name, test.ShouldEqual, organizationIdentity.Name) @@ -514,7 +553,8 @@ func TestAppClient(t *testing.T) { Orgs: []*pb.OrgDetails{&pbOrgDetails}, }, nil } - resp, _ := client.ListOrganizationsByUser(context.Background(), userID) + resp, err := client.ListOrganizationsByUser(context.Background(), userID) + test.That(t, err, test.ShouldBeNil) test.That(t, len(resp), test.ShouldEqual, len(orgDetailsList)) test.That(t, resp[0].OrgID, test.ShouldEqual, orgDetailsList[0].OrgID) test.That(t, resp[0].OrgName, test.ShouldEqual, orgDetailsList[0].OrgName) @@ -529,7 +569,8 @@ func TestAppClient(t *testing.T) { Organization: &pbOrganization, }, nil } - resp, _ := client.GetOrganization(context.Background(), organizationID) + resp, err := client.GetOrganization(context.Background(), organizationID) + test.That(t, err, test.ShouldBeNil) testOrganizationResponse(t, resp, &organization) }) @@ -542,7 +583,8 @@ func TestAppClient(t *testing.T) { Available: available, }, nil } - resp, _ := client.GetOrganizationNamespaceAvailability(context.Background(), namespace) + resp, err := client.GetOrganizationNamespaceAvailability(context.Background(), namespace) + test.That(t, err, test.ShouldBeNil) test.That(t, resp, test.ShouldEqual, available) }) @@ -555,7 +597,8 @@ func TestAppClient(t *testing.T) { Organization: &pbOrganization, }, nil } - resp, _ := client.UpdateOrganization(context.Background(), organizationID, &name, &namespace, ®ion, &cid) + resp, err := client.UpdateOrganization(context.Background(), organizationID, &name, &namespace, ®ion, &cid) + test.That(t, err, test.ShouldBeNil) testOrganizationResponse(t, resp, &organization) }) @@ -587,7 +630,8 @@ func TestAppClient(t *testing.T) { Invites: []*pb.OrganizationInvite{&pbInvite}, }, nil } - members, invites, _ := client.ListOrganizationMembers(context.Background(), organizationID) + members, invites, err := client.ListOrganizationMembers(context.Background(), organizationID) + test.That(t, err, test.ShouldBeNil) test.That(t, len(members), test.ShouldEqual, len(expectedMembers)) test.That(t, members[0].UserID, test.ShouldEqual, expectedMembers[0].UserID) test.That(t, members[0].Emails, test.ShouldResemble, expectedMembers[0].Emails) @@ -597,7 +641,6 @@ func TestAppClient(t *testing.T) { test.That(t, invites[0].OrganizationID, test.ShouldEqual, expectedInvites[0].OrganizationID) test.That(t, invites[0].Email, test.ShouldResemble, expectedInvites[0].Email) test.That(t, invites[0].CreatedOn, test.ShouldEqual, expectedInvites[0].CreatedOn) - test.That(t, len(invites[0].Authorizations), test.ShouldEqual, len(expectedInvites[0].Authorizations)) test.That(t, invites[0].Authorizations[0], test.ShouldResemble, expectedInvites[0].Authorizations[0]) }) @@ -613,7 +656,8 @@ func TestAppClient(t *testing.T) { Invite: &pbInvite, }, nil } - resp, _ := client.CreateOrganizationInvite(context.Background(), organizationID, email, authorizations, &sendEmailInvite) + resp, err := client.CreateOrganizationInvite(context.Background(), organizationID, email, authorizations, &sendEmailInvite) + test.That(t, err, test.ShouldBeNil) test.That(t, resp.OrganizationID, test.ShouldEqual, invite.OrganizationID) test.That(t, resp.Email, test.ShouldResemble, invite.Email) test.That(t, resp.CreatedOn, test.ShouldEqual, invite.CreatedOn) @@ -630,7 +674,8 @@ func TestAppClient(t *testing.T) { Invite: &pbInvite, }, nil } - resp, _ := client.UpdateOrganizationInviteAuthorizations(context.Background(), organizationID, email, authorizations, authorizations) + resp, err := client.UpdateOrganizationInviteAuthorizations(context.Background(), organizationID, email, authorizations, authorizations) + test.That(t, err, test.ShouldBeNil) test.That(t, resp.OrganizationID, test.ShouldEqual, invite.OrganizationID) test.That(t, resp.Email, test.ShouldResemble, invite.Email) test.That(t, resp.CreatedOn, test.ShouldEqual, invite.CreatedOn) @@ -670,7 +715,8 @@ func TestAppClient(t *testing.T) { Invite: &pbInvite, }, nil } - resp, _ := client.ResendOrganizationInvite(context.Background(), organizationID, email) + resp, err := client.ResendOrganizationInvite(context.Background(), organizationID, email) + test.That(t, err, test.ShouldBeNil) test.That(t, resp.OrganizationID, test.ShouldEqual, invite.OrganizationID) test.That(t, resp.Email, test.ShouldResemble, invite.Email) test.That(t, resp.CreatedOn, test.ShouldEqual, invite.CreatedOn) @@ -731,7 +777,8 @@ func TestAppClient(t *testing.T) { Email: email, }, nil } - resp, _ := client.OrganizationGetSupportEmail(context.Background(), organizationID) + resp, err := client.OrganizationGetSupportEmail(context.Background(), organizationID) + test.That(t, err, test.ShouldBeNil) test.That(t, resp, test.ShouldEqual, email) }) @@ -746,7 +793,8 @@ func TestAppClient(t *testing.T) { Location: &pbLocation, }, nil } - resp, _ := client.CreateLocation(context.Background(), organizationID, name, &parentLocationID) + resp, err := client.CreateLocation(context.Background(), organizationID, name, &parentLocationID) + test.That(t, err, test.ShouldBeNil) testLocationResponse(t, resp, &location) }) @@ -759,7 +807,8 @@ func TestAppClient(t *testing.T) { Location: &pbLocation, }, nil } - resp, _ := client.GetLocation(context.Background(), locationID) + resp, err := client.GetLocation(context.Background(), locationID) + test.That(t, err, test.ShouldBeNil) testLocationResponse(t, resp, &location) }) @@ -775,7 +824,8 @@ func TestAppClient(t *testing.T) { Location: &pbLocation, }, nil } - resp, _ := client.UpdateLocation(context.Background(), locationID, &name, &parentLocationID, ®ion) + resp, err := client.UpdateLocation(context.Background(), locationID, &name, &parentLocationID, ®ion) + test.That(t, err, test.ShouldBeNil) testLocationResponse(t, resp, &location) }) @@ -799,7 +849,8 @@ func TestAppClient(t *testing.T) { Locations: []*pb.Location{&pbLocation}, }, nil } - resp, _ := client.ListLocations(context.Background(), organizationID) + resp, err := client.ListLocations(context.Background(), organizationID) + test.That(t, err, test.ShouldBeNil) test.That(t, len(resp), test.ShouldEqual, len(expectedLocations)) testLocationResponse(t, resp[0], &expectedLocations[0]) }) @@ -835,7 +886,8 @@ func TestAppClient(t *testing.T) { Auth: &pbLocationAuth, }, nil } - resp, _ := client.LocationAuth(context.Background(), locationID) + resp, err := client.LocationAuth(context.Background(), locationID) + test.That(t, err, test.ShouldBeNil) test.That(t, resp, test.ShouldResemble, &locationAuth) }) @@ -848,7 +900,8 @@ func TestAppClient(t *testing.T) { Auth: &pbLocationAuth, }, nil } - resp, _ := client.CreateLocationSecret(context.Background(), locationID) + resp, err := client.CreateLocationSecret(context.Background(), locationID) + test.That(t, err, test.ShouldBeNil) test.That(t, resp, test.ShouldResemble, &locationAuth) }) @@ -872,7 +925,8 @@ func TestAppClient(t *testing.T) { Robot: &pbRobot, }, nil } - resp, _ := client.GetRobot(context.Background(), robotID) + resp, err := client.GetRobot(context.Background(), robotID) + test.That(t, err, test.ShouldBeNil) test.That(t, resp, test.ShouldResemble, &robot) }) @@ -892,7 +946,8 @@ func TestAppClient(t *testing.T) { Robots: []*pb.RoverRentalRobot{&pbRobot}, }, nil } - resp, _ := client.GetRoverRentalRobots(context.Background(), organizationID) + resp, err := client.GetRoverRentalRobots(context.Background(), organizationID) + test.That(t, err, test.ShouldBeNil) test.That(t, len(resp), test.ShouldEqual, len(expectedRobots)) test.That(t, resp[0], test.ShouldResemble, &expectedRobots[0]) }) @@ -907,7 +962,8 @@ func TestAppClient(t *testing.T) { Parts: []*pb.RobotPart{&pbRobotPart}, }, nil } - resp, _ := client.GetRobotParts(context.Background(), robotID) + resp, err := client.GetRobotParts(context.Background(), robotID) + test.That(t, err, test.ShouldBeNil) test.That(t, len(resp), test.ShouldEqual, len(expectedRobotParts)) testRobotPartResponse(t, resp[0], &expectedRobotParts[0]) }) @@ -922,7 +978,8 @@ func TestAppClient(t *testing.T) { ConfigJson: configJSON, }, nil } - part, json, _ := client.GetRobotPart(context.Background(), partID) + part, json, err := client.GetRobotPart(context.Background(), partID) + test.That(t, err, test.ShouldBeNil) test.That(t, json, test.ShouldEqual, configJSON) testRobotPartResponse(t, part, &robotPart) }) @@ -957,7 +1014,8 @@ func TestAppClient(t *testing.T) { NextPageToken: pageToken, }, nil } - logs, token, _ := client.GetRobotPartLogs(context.Background(), partID, &filter, &pageToken, levels, &start, &end, &limit, &source) + logs, token, err := client.GetRobotPartLogs(context.Background(), partID, &filter, &pageToken, levels, &start, &end, &limit, &source) + test.That(t, err, test.ShouldBeNil) test.That(t, token, test.ShouldEqual, pageToken) test.That(t, len(logs), test.ShouldEqual, len(expectedLogs)) test.That(t, logs[0].Host, test.ShouldEqual, expectedLogs[0].Host) @@ -988,7 +1046,8 @@ func TestAppClient(t *testing.T) { History: []*pb.RobotPartHistoryEntry{&pbRobotPartHistoryEntry}, }, nil } - resp, _ := client.GetRobotPartHistory(context.Background(), partID) + resp, err := client.GetRobotPartHistory(context.Background(), partID) + test.That(t, err, test.ShouldBeNil) test.That(t, resp[0].Part, test.ShouldEqual, expectedEntries[0].Part) test.That(t, resp[0].Robot, test.ShouldEqual, expectedEntries[0].Robot) test.That(t, resp[0].When, test.ShouldEqual, expectedEntries[0].When) @@ -1007,7 +1066,8 @@ func TestAppClient(t *testing.T) { Part: &pbRobotPart, }, nil } - resp, _ := client.UpdateRobotPart(context.Background(), partID, name, robotConfig) + resp, err := client.UpdateRobotPart(context.Background(), partID, name, robotConfig) + test.That(t, err, test.ShouldBeNil) testRobotPartResponse(t, resp, &robotPart) }) @@ -1042,7 +1102,8 @@ func TestAppClient(t *testing.T) { ApiKeys: []*pb.APIKeyWithAuthorizations{&pbAPIKeyWithAuthorizations}, }, nil } - resp, _ := client.GetRobotAPIKeys(context.Background(), robotID) + resp, err := client.GetRobotAPIKeys(context.Background(), robotID) + test.That(t, err, test.ShouldBeNil) test.That(t, len(resp), test.ShouldEqual, len(expectedAPIKeyWithAuthorizations)) test.That(t, resp[0].APIKey, test.ShouldResemble, expectedAPIKeyWithAuthorizations[0].APIKey) test.That(t, resp[0].Authorizations, test.ShouldResemble, expectedAPIKeyWithAuthorizations[0].Authorizations) @@ -1067,7 +1128,8 @@ func TestAppClient(t *testing.T) { Part: &pbRobotPart, }, nil } - resp, _ := client.CreateRobotPartSecret(context.Background(), partID) + resp, err := client.CreateRobotPartSecret(context.Background(), partID) + test.That(t, err, test.ShouldBeNil) testRobotPartResponse(t, resp, &robotPart) }) @@ -1092,7 +1154,8 @@ func TestAppClient(t *testing.T) { Robots: []*pb.Robot{&pbRobot}, }, nil } - resp, _ := client.ListRobots(context.Background(), locationID) + resp, err := client.ListRobots(context.Background(), locationID) + test.That(t, err, test.ShouldBeNil) test.That(t, len(resp), test.ShouldEqual, len(expectedRobots)) test.That(t, resp[0], test.ShouldResemble, expectedRobots[0]) }) @@ -1107,7 +1170,8 @@ func TestAppClient(t *testing.T) { Id: robotID, }, nil } - resp, _ := client.NewRobot(context.Background(), name, locationID) + resp, err := client.NewRobot(context.Background(), name, locationID) + test.That(t, err, test.ShouldBeNil) test.That(t, resp, test.ShouldResemble, robotID) }) @@ -1122,7 +1186,8 @@ func TestAppClient(t *testing.T) { Robot: &pbRobot, }, nil } - resp, _ := client.UpdateRobot(context.Background(), robotID, name, locationID) + resp, err := client.UpdateRobot(context.Background(), robotID, name, locationID) + test.That(t, err, test.ShouldBeNil) test.That(t, resp, test.ShouldResemble, &robot) }) @@ -1145,7 +1210,8 @@ func TestAppClient(t *testing.T) { Fragment: &pbFragment, }, nil } - resp, _ := client.GetFragment(context.Background(), fragmentID) + resp, err := client.GetFragment(context.Background(), fragmentID) + test.That(t, err, test.ShouldBeNil) test.That(t, resp, test.ShouldResemble, &fragment) }) @@ -1164,7 +1230,8 @@ func TestAppClient(t *testing.T) { Fragment: &pbFragment, }, nil } - resp, _ := client.UpdateFragment(context.Background(), fragmentID, name, fragmentConfig, &public, &fragmentVisibility) + resp, err := client.UpdateFragment(context.Background(), fragmentID, name, fragmentConfig, &public, &fragmentVisibility) + test.That(t, err, test.ShouldBeNil) test.That(t, resp, test.ShouldResemble, &fragment) }) @@ -1190,7 +1257,8 @@ func TestAppClient(t *testing.T) { Fragments: []*pb.Fragment{&pbFragment}, }, nil } - resp, _ := client.ListMachineFragments(context.Background(), robotID, additionalFragmentIDs) + resp, err := client.ListMachineFragments(context.Background(), robotID, additionalFragmentIDs) + test.That(t, err, test.ShouldBeNil) test.That(t, len(resp), test.ShouldEqual, len(expectedFragments)) test.That(t, resp[0], test.ShouldResemble, &expectedFragments[0]) }) @@ -1214,9 +1282,135 @@ func TestAppClient(t *testing.T) { NextPageToken: pageToken, }, nil } - resp, token, _ := client.GetFragmentHistory(context.Background(), fragmentID, &pageToken, &limit) + resp, token, err := client.GetFragmentHistory(context.Background(), fragmentID, &pageToken, &limit) + test.That(t, err, test.ShouldBeNil) test.That(t, token, test.ShouldEqual, pageToken) test.That(t, len(resp), test.ShouldEqual, len(expectedHistory)) test.That(t, resp[0], test.ShouldResemble, &expectedHistory[0]) }) + + t.Run("createAuthorization", func(t *testing.T) { + resp, err := createAuthorization(authorization.OrganizationID, + authorization.IdentityID, + authorization.IdentityType, + authorization.AuthorizationType, + authorization.ResourceType, + authorization.ResourceID, + ) + test.That(t, resp, test.ShouldResemble, &pbAuthorization) + test.That(t, err, test.ShouldBeNil) + resp, err = createAuthorization( + authorization.OrganizationID, + authorization.IdentityID, + authorization.IdentityType, + badAuthorizationType, + authorization.ResourceType, + authorization.ResourceID, + ) + test.That(t, resp, test.ShouldBeNil) + test.That(t, err.Error(), test.ShouldEqual, "role string must be 'owner' or 'operator'") + resp, err = createAuthorization( + authorization.OrganizationID, + authorization.IdentityID, + authorization.IdentityType, + authorization.AuthorizationType, + badResourceType, + authorization.ResourceID, + ) + test.That(t, resp, test.ShouldBeNil) + test.That(t, err.Error(), test.ShouldEqual, "resourceType must be 'organization', 'location', or 'robot'") + }) + + t.Run("AddRole", func(t *testing.T) { + grpcClient.AddRoleFunc = func( + ctx context.Context, in *pb.AddRoleRequest, opts ...grpc.CallOption, + ) (*pb.AddRoleResponse, error) { + test.That(t, in.Authorization, test.ShouldResemble, &pbAuthorization) + return &pb.AddRoleResponse{}, nil + } + client.AddRole( + context.Background(), + authorization.OrganizationID, + authorization.IdentityID, + authorization.AuthorizationType, + authorization.ResourceType, + authorization.ResourceID, + ) + }) + + t.Run("RemoveRole", func(t *testing.T) { + grpcClient.RemoveRoleFunc = func( + ctx context.Context, in *pb.RemoveRoleRequest, opts ...grpc.CallOption, + ) (*pb.RemoveRoleResponse, error) { + test.That(t, in.Authorization, test.ShouldResemble, &pbAuthorization) + return &pb.RemoveRoleResponse{}, nil + } + client.RemoveRole( + context.Background(), + authorization.OrganizationID, + authorization.IdentityID, + authorization.AuthorizationType, + authorization.ResourceType, + authorization.ResourceID, + ) + }) + + t.Run("ChangeRole", func(t *testing.T) { + grpcClient.ChangeRoleFunc = func( + ctx context.Context, in *pb.ChangeRoleRequest, opts ...grpc.CallOption, + ) (*pb.ChangeRoleResponse, error) { + test.That(t, in.OldAuthorization, test.ShouldResemble, &pbAuthorization) + test.That(t, in.NewAuthorization, test.ShouldResemble, &pbAuthorization2) + return &pb.ChangeRoleResponse{}, nil + } + client.ChangeRole( + context.Background(), + authorization.OrganizationID, + authorization.IdentityID, + authorization.AuthorizationType, + authorization.ResourceType, + authorization.ResourceID, + authorization2.OrganizationID, + authorization2.IdentityID, + authorization2.AuthorizationType, + authorization2.ResourceType, + authorization2.ResourceID, + ) + }) + + t.Run("ListAuthorizations", func(t *testing.T) { + grpcClient.ListAuthorizationsFunc = func( + ctx context.Context, in *pb.ListAuthorizationsRequest, opts ...grpc.CallOption, + ) (*pb.ListAuthorizationsResponse, error) { + test.That(t, in.OrganizationId, test.ShouldResemble, organizationID) + test.That(t, in.ResourceIds, test.ShouldResemble, resourceIDs) + return &pb.ListAuthorizationsResponse{ + Authorizations: pbAuthorizations, + }, nil + } + resp, err := client.ListAuthorizations(context.Background(), organizationID, resourceIDs) + test.That(t, err, test.ShouldBeNil) + test.That(t, resp, test.ShouldResemble, authorizations) + }) + + t.Run("CheckPermissions", func(t *testing.T) { + pbPermissions := []*pb.AuthorizedPermissions{ + { + ResourceType: permissions[0].ResourceType, + ResourceId: permissions[0].ResourceID, + Permissions: permissions[0].Permissions, + }, + } + grpcClient.CheckPermissionsFunc = func( + ctx context.Context, in *pb.CheckPermissionsRequest, opts ...grpc.CallOption, + ) (*pb.CheckPermissionsResponse, error) { + test.That(t, in.Permissions, test.ShouldResemble, pbPermissions) + return &pb.CheckPermissionsResponse{ + AuthorizedPermissions: pbPermissions, + }, nil + } + resp, err := client.CheckPermissions(context.Background(), permissions) + test.That(t, err, test.ShouldBeNil) + test.That(t, resp, test.ShouldResemble, permissions) + }) } From cb4e04c4a5307f302ffea4886b1253ccce8b2c92 Mon Sep 17 00:00:00 2001 From: purplenicole730 Date: Mon, 18 Nov 2024 13:02:49 -0500 Subject: [PATCH 44/75] clean up tests --- app/app_client_test.go | 557 ++++++++++++++++++++++++----------------- 1 file changed, 332 insertions(+), 225 deletions(-) diff --git a/app/app_client_test.go b/app/app_client_test.go index 2b918074c46..7cd4e474a62 100644 --- a/app/app_client_test.go +++ b/app/app_client_test.go @@ -5,6 +5,8 @@ import ( "fmt" "testing" + mlTraining "go.viam.com/api/app/mltraining/v1" + packages "go.viam.com/api/app/packages/v1" pb "go.viam.com/api/app/v1" common "go.viam.com/api/common/v1" "go.viam.com/test" @@ -17,59 +19,73 @@ import ( ) const ( - organizationID = "organization_id" - organizationID2 = "organization_id_2" - email = "email" - userID = "user_id" - locationID = "location_id" - available = true - authorizationType = "owner" - authorizationType2 = "operator" - badAuthorizationType = "authorization_type" - resourceType = "organization" - resourceType2 = "location" - badResourceType = "resource_type" - resourceID = "resource_id" - resourceID2 = "resource_id_2" - identityID = "identity_id" - identityID2 = "identity_id_2" - identityType = "" - secretID = "secret_ids" - primary = true - robotCount = 1 - robotID = "robot_id" - robotLocation = "robot_location" - partID = "part_id" - dnsName = "dns_name" - secret = "secret" - mainPart = false - fqdn = "fqdn" - localFQDN = "local_fqdn" - configJSON = "configJson" - host = "host" - level = "level" - loggerName = "logger_name" - message = "message" - stack = "stack" - value = "value" - isDeactivated = false - keyID = "key_id" - key = "key" - fragmentID = "fragment_id" - organizationOwner = "organization_owner" - robotPartCount = 5 - onlyUsedByOwner = false - organizationCount = 2 - permission = "permission" + organizationID2 = "organization_id_2" + email = "email" + userID = "user_id" + locationID = "location_id" + available = true + authorizationType = "owner" + authorizationType2 = "operator" + badAuthorizationType = "authorization_type" + resourceType = "organization" + resourceType2 = "location" + badResourceType = "resource_type" + resourceID = "resource_id" + resourceID2 = "resource_id_2" + identityID = "identity_id" + identityID2 = "identity_id_2" + identityType = "" + secretID = "secret_ids" + primary = true + robotCount = 1 + robotID = "robot_id" + robotLocation = "robot_location" + partID = "part_id" + dnsName = "dns_name" + secret = "secret" + mainPart = false + fqdn = "fqdn" + localFQDN = "local_fqdn" + configJSON = "configJson" + host = "host" + level = "level" + loggerName = "logger_name" + message = "message" + stack = "stack" + value = "value" + isDeactivated = false + keyID = "key_id" + key = "key" + fragmentID = "fragment_id" + organizationOwner = "organization_owner" + robotPartCount = 5 + onlyUsedByOwner = false + organizationCount = 2 + permission = "permission" + itemID = "item_id" + description = "description" + packageType = PackageTypeMLTraining + visibility = VisibilityPublic + totalRobotUsage = 4 + totalExternalRobotUsage = 2 + totalOrganizationUsage = 40 + totalExternalOrganizationUsage = 52 + version = "version" + modelType = ModelTypeObjectDetection + modelFramework = ModelFrameworkPyTorch + draft = false + platform = "platform" + registryItemStatus = RegistryItemStatusPublished ) var ( - name = "name" - region = "region" - namespace = "public_namespace" - cid = "cid" - dateAdded = timestamppb.Timestamp{Seconds: 0, Nanos: 50} - organization = Organization{ + organizationID = "organization_id" + name = "name" + region = "region" + namespace = "public_namespace" + cid = "cid" + dateAdded = timestamppb.Timestamp{Seconds: 0, Nanos: 50} + organization = Organization{ ID: organizationID, Name: name, CreatedOn: &dateAdded, @@ -400,6 +416,39 @@ var ( Permissions: []string{permission}, }, } + siteURL = "url" + metadata = RegistryItemMLTrainingMetadata{ + MlTrainingMetadata: &MLTrainingMetadata{ + Versions: []*MLTrainingVersion{ + { + Version: version, + CreatedOn: &createdOn, + }, + }, + ModelType: modelType, + ModelFramework: modelFramework, + Draft: draft, + }, + } + registryItem = RegistryItem{ + ItemID: itemID, + OrganizationID: organizationID, + PublicNamespace: namespace, + Name: name, + Type: packageType, + Visibility: visibility, + URL: siteURL, + Description: description, + TotalRobotUsage: totalRobotUsage, + TotalExternalRobotUsage: totalExternalRobotUsage, + TotalOrganizationUsage: totalOrganizationUsage, + TotalExternalOrganizationUsage: totalExternalOrganizationUsage, + Metadata: &metadata, + CreatedAt: &createdOn, + UpdatedAt: &lastUpdated, + } + pbRegistryItem, _ = registryItemToProto(®istryItem) + searchTerm = "search_term" ) func sharedSecretStateToProto(state SharedSecretState) pb.SharedSecret_State { @@ -430,42 +479,116 @@ func authenticationTypeToProto(authType AuthenticationType) pb.AuthenticationTyp return pb.AuthenticationType_AUTHENTICATION_TYPE_UNSPECIFIED } -func testOrganizationResponse(t *testing.T, actualOrg, expectedOrg *Organization) { - test.That(t, actualOrg.ID, test.ShouldEqual, expectedOrg.ID) - test.That(t, actualOrg.Name, test.ShouldEqual, expectedOrg.Name) - test.That(t, actualOrg.PublicNamespace, test.ShouldEqual, expectedOrg.PublicNamespace) - test.That(t, actualOrg.DefaultRegion, test.ShouldEqual, expectedOrg.DefaultRegion) - test.That(t, actualOrg.Cid, test.ShouldEqual, expectedOrg.Cid) +func modelTypeToProto(modelType ModelType) mlTraining.ModelType { + switch modelType { + case ModelTypeUnspecified: + return mlTraining.ModelType_MODEL_TYPE_UNSPECIFIED + case ModelTypeSingleLabelClassification: + return mlTraining.ModelType_MODEL_TYPE_SINGLE_LABEL_CLASSIFICATION + case ModelTypeMultiLabelClassification: + return mlTraining.ModelType_MODEL_TYPE_MULTI_LABEL_CLASSIFICATION + case ModelTypeObjectDetection: + return mlTraining.ModelType_MODEL_TYPE_OBJECT_DETECTION + } + return mlTraining.ModelType_MODEL_TYPE_UNSPECIFIED } -func testLocationResponse(t *testing.T, actualLocation, expectedLocation *Location) { - test.That(t, actualLocation.ID, test.ShouldEqual, expectedLocation.ID) - test.That(t, actualLocation.Name, test.ShouldEqual, expectedLocation.Name) - test.That(t, actualLocation.ParentLocationID, test.ShouldEqual, expectedLocation.ParentLocationID) - test.That(t, actualLocation.Auth, test.ShouldResemble, expectedLocation.Auth) - test.That(t, actualLocation.Organizations, test.ShouldResemble, expectedLocation.Organizations) - test.That(t, actualLocation.CreatedOn, test.ShouldEqual, expectedLocation.CreatedOn) - test.That(t, actualLocation.RobotCount, test.ShouldEqual, expectedLocation.RobotCount) - test.That(t, actualLocation.Config, test.ShouldResemble, expectedLocation.Config) +func modelFrameworkToProto(framework ModelFramework) mlTraining.ModelFramework { + switch framework { + case ModelFrameworkUnspecified: + return mlTraining.ModelFramework_MODEL_FRAMEWORK_UNSPECIFIED + case ModelFrameworkTFLite: + return mlTraining.ModelFramework_MODEL_FRAMEWORK_TFLITE + case ModelFrameworkTensorFlow: + return mlTraining.ModelFramework_MODEL_FRAMEWORK_TENSORFLOW + case ModelFrameworkPyTorch: + return mlTraining.ModelFramework_MODEL_FRAMEWORK_PYTORCH + case ModelFrameworkONNX: + return mlTraining.ModelFramework_MODEL_FRAMEWORK_ONNX + } + return mlTraining.ModelFramework_MODEL_FRAMEWORK_UNSPECIFIED } -func testRobotPartResponse(t *testing.T, actualRobotPart, expectedRobotPart *RobotPart) { - test.That(t, actualRobotPart.ID, test.ShouldEqual, expectedRobotPart.ID) - test.That(t, actualRobotPart.Name, test.ShouldEqual, expectedRobotPart.Name) - test.That(t, actualRobotPart.DNSName, test.ShouldEqual, expectedRobotPart.DNSName) - test.That(t, actualRobotPart.Secret, test.ShouldEqual, expectedRobotPart.Secret) - test.That(t, actualRobotPart.Robot, test.ShouldEqual, expectedRobotPart.Robot) - test.That(t, actualRobotPart.LocationID, test.ShouldEqual, expectedRobotPart.LocationID) - test.That(t, actualRobotPart.RobotConfig, test.ShouldResemble, expectedRobotPart.RobotConfig) - test.That(t, actualRobotPart.LastAccess, test.ShouldEqual, expectedRobotPart.LastAccess) - test.That(t, actualRobotPart.UserSuppliedInfo, test.ShouldResemble, expectedRobotPart.UserSuppliedInfo) - test.That(t, actualRobotPart.MainPart, test.ShouldEqual, expectedRobotPart.MainPart) - test.That(t, actualRobotPart.FQDN, test.ShouldEqual, expectedRobotPart.FQDN) - test.That(t, actualRobotPart.LocalFQDN, test.ShouldEqual, expectedRobotPart.LocalFQDN) - test.That(t, actualRobotPart.CreatedOn, test.ShouldEqual, expectedRobotPart.CreatedOn) - test.That(t, len(actualRobotPart.Secrets), test.ShouldEqual, len(expectedRobotPart.Secrets)) - test.That(t, actualRobotPart.Secrets[0], test.ShouldResemble, expectedRobotPart.Secrets[0]) - test.That(t, actualRobotPart.LastUpdated, test.ShouldEqual, expectedRobotPart.LastUpdated) +func mlTrainingVersionToProto(version *MLTrainingVersion) *pb.MLTrainingVersion { + return &pb.MLTrainingVersion{ + Version: version.Version, + CreatedOn: version.CreatedOn, + } +} + +func mlTrainingMetadataToProto(md MLTrainingMetadata) *pb.MLTrainingMetadata { + var versions []*pb.MLTrainingVersion + for _, version := range md.Versions { + versions = append(versions, mlTrainingVersionToProto(version)) + } + return &pb.MLTrainingMetadata{ + Versions: versions, + ModelType: modelTypeToProto(md.ModelType), + ModelFramework: modelFrameworkToProto(md.ModelFramework), + Draft: md.Draft, + } +} + +func registryItemToProto(item *RegistryItem) (*pb.RegistryItem, error) { + switch metadata := item.Metadata.(type) { + case *RegistryItemModuleMetadata: + return &pb.RegistryItem{ + ItemId: item.ItemID, + OrganizationId: item.OrganizationID, + PublicNamespace: item.PublicNamespace, + Name: item.Name, + Type: packageTypeToProto(item.Type), + Visibility: visibilityToProto(item.Visibility), + Url: item.URL, + Description: item.Description, + TotalRobotUsage: item.TotalRobotUsage, + TotalExternalRobotUsage: item.TotalExternalRobotUsage, + TotalOrganizationUsage: item.TotalOrganizationUsage, + TotalExternalOrganizationUsage: item.TotalExternalOrganizationUsage, + Metadata: &pb.RegistryItem_ModuleMetadata{ModuleMetadata: &pb.ModuleMetadata{}}, + CreatedAt: item.CreatedAt, + UpdatedAt: item.UpdatedAt, + }, nil + case *RegistryItemMLModelMetadata: + return &pb.RegistryItem{ + ItemId: item.ItemID, + OrganizationId: item.OrganizationID, + PublicNamespace: item.PublicNamespace, + Name: item.Name, + Type: packageTypeToProto(item.Type), + Visibility: visibilityToProto(item.Visibility), + Url: item.URL, + Description: item.Description, + TotalRobotUsage: item.TotalRobotUsage, + TotalExternalRobotUsage: item.TotalExternalRobotUsage, + TotalOrganizationUsage: item.TotalOrganizationUsage, + TotalExternalOrganizationUsage: item.TotalExternalOrganizationUsage, + Metadata: &pb.RegistryItem_ModuleMetadata{ModuleMetadata: &pb.ModuleMetadata{}}, + CreatedAt: item.CreatedAt, + UpdatedAt: item.UpdatedAt, + }, nil + case *RegistryItemMLTrainingMetadata: + protoMetadata := mlTrainingMetadataToProto(*metadata.MlTrainingMetadata) + return &pb.RegistryItem{ + ItemId: item.ItemID, + OrganizationId: item.OrganizationID, + PublicNamespace: item.PublicNamespace, + Name: item.Name, + Type: packageTypeToProto(item.Type), + Visibility: visibilityToProto(item.Visibility), + Url: item.URL, + Description: item.Description, + TotalRobotUsage: item.TotalRobotUsage, + TotalExternalRobotUsage: item.TotalExternalRobotUsage, + TotalOrganizationUsage: item.TotalOrganizationUsage, + TotalExternalOrganizationUsage: item.TotalExternalOrganizationUsage, + Metadata: &pb.RegistryItem_MlTrainingMetadata{MlTrainingMetadata: protoMetadata}, + CreatedAt: item.CreatedAt, + UpdatedAt: item.UpdatedAt, + }, nil + default: + return nil, fmt.Errorf("unknown registry item metadata type: %T", item.Metadata) + } } func createGrpcClient() *inject.AppServiceClient { @@ -501,11 +624,11 @@ func TestAppClient(t *testing.T) { } resp, err := client.CreateOrganization(context.Background(), name) test.That(t, err, test.ShouldBeNil) - testOrganizationResponse(t, resp, &organization) + test.That(t, resp, test.ShouldResemble, &organization) }) t.Run("ListOrganizations", func(t *testing.T) { - expectedOrganizations := []Organization{organization} + expectedOrganizations := []*Organization{&organization} grpcClient.ListOrganizationsFunc = func( ctx context.Context, in *pb.ListOrganizationsRequest, opts ...grpc.CallOption, ) (*pb.ListOrganizationsResponse, error) { @@ -515,49 +638,47 @@ func TestAppClient(t *testing.T) { } resp, err := client.ListOrganizations(context.Background()) test.That(t, err, test.ShouldBeNil) - test.That(t, len(resp), test.ShouldEqual, len(expectedOrganizations)) - testOrganizationResponse(t, resp[0], &expectedOrganizations[0]) + test.That(t, resp, test.ShouldResemble, expectedOrganizations) }) t.Run("GetOrganizationsWithAccessToLocation", func(t *testing.T) { - pbOrganizationIdentity := pb.OrganizationIdentity{ - Id: organizationIdentity.ID, - Name: organizationIdentity.Name, - } + expectedOrganizationIdentities := []*OrganizationIdentity{&organizationIdentity} grpcClient.GetOrganizationsWithAccessToLocationFunc = func( ctx context.Context, in *pb.GetOrganizationsWithAccessToLocationRequest, opts ...grpc.CallOption, ) (*pb.GetOrganizationsWithAccessToLocationResponse, error) { test.That(t, in.LocationId, test.ShouldEqual, locationID) return &pb.GetOrganizationsWithAccessToLocationResponse{ - OrganizationIdentities: []*pb.OrganizationIdentity{&pbOrganizationIdentity}, + OrganizationIdentities: []*pb.OrganizationIdentity{ + { + Id: organizationIdentity.ID, + Name: organizationIdentity.Name, + }, + }, }, nil } resp, err := client.GetOrganizationsWithAccessToLocation(context.Background(), locationID) test.That(t, err, test.ShouldBeNil) - test.That(t, len(resp), test.ShouldEqual, 1) - test.That(t, resp[0].ID, test.ShouldEqual, organizationIdentity.ID) - test.That(t, resp[0].Name, test.ShouldEqual, organizationIdentity.Name) + test.That(t, resp, test.ShouldResemble, expectedOrganizationIdentities) }) t.Run("ListOrganizationsByUser", func(t *testing.T) { - orgDetailsList := []OrgDetails{orgDetails} - pbOrgDetails := pb.OrgDetails{ - OrgId: orgDetails.OrgID, - OrgName: orgDetails.OrgName, - } + expectedOrgDetailsList := []*OrgDetails{&orgDetails} grpcClient.ListOrganizationsByUserFunc = func( ctx context.Context, in *pb.ListOrganizationsByUserRequest, opts ...grpc.CallOption, ) (*pb.ListOrganizationsByUserResponse, error) { test.That(t, in.UserId, test.ShouldEqual, userID) return &pb.ListOrganizationsByUserResponse{ - Orgs: []*pb.OrgDetails{&pbOrgDetails}, + Orgs: []*pb.OrgDetails{ + { + OrgId: orgDetails.OrgID, + OrgName: orgDetails.OrgName, + }, + }, }, nil } resp, err := client.ListOrganizationsByUser(context.Background(), userID) test.That(t, err, test.ShouldBeNil) - test.That(t, len(resp), test.ShouldEqual, len(orgDetailsList)) - test.That(t, resp[0].OrgID, test.ShouldEqual, orgDetailsList[0].OrgID) - test.That(t, resp[0].OrgName, test.ShouldEqual, orgDetailsList[0].OrgName) + test.That(t, resp, test.ShouldResemble, expectedOrgDetailsList) }) t.Run("GetOrganization", func(t *testing.T) { @@ -571,7 +692,7 @@ func TestAppClient(t *testing.T) { } resp, err := client.GetOrganization(context.Background(), organizationID) test.That(t, err, test.ShouldBeNil) - testOrganizationResponse(t, resp, &organization) + test.That(t, resp, test.ShouldResemble, &organization) }) t.Run("GetOrganizationNamespaceAvailability", func(t *testing.T) { @@ -599,7 +720,7 @@ func TestAppClient(t *testing.T) { } resp, err := client.UpdateOrganization(context.Background(), organizationID, &name, &namespace, ®ion, &cid) test.That(t, err, test.ShouldBeNil) - testOrganizationResponse(t, resp, &organization) + test.That(t, resp, test.ShouldResemble, &organization) }) t.Run("DeleteOrganization", func(t *testing.T) { @@ -609,39 +730,33 @@ func TestAppClient(t *testing.T) { test.That(t, in.OrganizationId, test.ShouldEqual, organizationID) return &pb.DeleteOrganizationResponse{}, nil } - client.DeleteOrganization(context.Background(), organizationID) + err := client.DeleteOrganization(context.Background(), organizationID) + test.That(t, err, test.ShouldBeNil) }) t.Run("ListOrganizationMembers", func(t *testing.T) { - expectedMembers := []OrganizationMember{member} - pbMember := pb.OrganizationMember{ - UserId: member.UserID, - Emails: member.Emails, - DateAdded: member.DateAdded, - LastLogin: member.LastLogin, - } - expectedInvites := []OrganizationInvite{invite} + expectedMembers := []*OrganizationMember{&member} + expectedInvites := []*OrganizationInvite{&invite} grpcClient.ListOrganizationMembersFunc = func( ctx context.Context, in *pb.ListOrganizationMembersRequest, opts ...grpc.CallOption, ) (*pb.ListOrganizationMembersResponse, error) { test.That(t, in.OrganizationId, test.ShouldEqual, organizationID) return &pb.ListOrganizationMembersResponse{ - Members: []*pb.OrganizationMember{&pbMember}, + Members: []*pb.OrganizationMember{ + { + UserId: member.UserID, + Emails: member.Emails, + DateAdded: member.DateAdded, + LastLogin: member.LastLogin, + }, + }, Invites: []*pb.OrganizationInvite{&pbInvite}, }, nil } members, invites, err := client.ListOrganizationMembers(context.Background(), organizationID) test.That(t, err, test.ShouldBeNil) - test.That(t, len(members), test.ShouldEqual, len(expectedMembers)) - test.That(t, members[0].UserID, test.ShouldEqual, expectedMembers[0].UserID) - test.That(t, members[0].Emails, test.ShouldResemble, expectedMembers[0].Emails) - test.That(t, members[0].DateAdded, test.ShouldEqual, expectedMembers[0].DateAdded) - test.That(t, members[0].LastLogin, test.ShouldEqual, expectedMembers[0].LastLogin) - test.That(t, len(invites), test.ShouldEqual, len(expectedInvites)) - test.That(t, invites[0].OrganizationID, test.ShouldEqual, expectedInvites[0].OrganizationID) - test.That(t, invites[0].Email, test.ShouldResemble, expectedInvites[0].Email) - test.That(t, invites[0].CreatedOn, test.ShouldEqual, expectedInvites[0].CreatedOn) - test.That(t, invites[0].Authorizations[0], test.ShouldResemble, expectedInvites[0].Authorizations[0]) + test.That(t, members, test.ShouldResemble, expectedMembers) + test.That(t, invites, test.ShouldResemble, expectedInvites) }) t.Run("CreateOrganizationInvite", func(t *testing.T) { @@ -658,11 +773,7 @@ func TestAppClient(t *testing.T) { } resp, err := client.CreateOrganizationInvite(context.Background(), organizationID, email, authorizations, &sendEmailInvite) test.That(t, err, test.ShouldBeNil) - test.That(t, resp.OrganizationID, test.ShouldEqual, invite.OrganizationID) - test.That(t, resp.Email, test.ShouldResemble, invite.Email) - test.That(t, resp.CreatedOn, test.ShouldEqual, invite.CreatedOn) - test.That(t, len(resp.Authorizations), test.ShouldEqual, len(invite.Authorizations)) - test.That(t, resp.Authorizations[0], test.ShouldResemble, invite.Authorizations[0]) + test.That(t, resp, test.ShouldResemble, &invite) }) t.Run("UpdateOrganizationInviteAuthorizations", func(t *testing.T) { @@ -676,11 +787,7 @@ func TestAppClient(t *testing.T) { } resp, err := client.UpdateOrganizationInviteAuthorizations(context.Background(), organizationID, email, authorizations, authorizations) test.That(t, err, test.ShouldBeNil) - test.That(t, resp.OrganizationID, test.ShouldEqual, invite.OrganizationID) - test.That(t, resp.Email, test.ShouldResemble, invite.Email) - test.That(t, resp.CreatedOn, test.ShouldEqual, invite.CreatedOn) - test.That(t, len(resp.Authorizations), test.ShouldResemble, len(invite.Authorizations)) - test.That(t, resp.Authorizations[0], test.ShouldResemble, invite.Authorizations[0]) + test.That(t, resp, test.ShouldResemble, &invite) }) t.Run("DeleteOrganizationMember", func(t *testing.T) { @@ -691,7 +798,8 @@ func TestAppClient(t *testing.T) { test.That(t, in.UserId, test.ShouldEqual, userID) return &pb.DeleteOrganizationMemberResponse{}, nil } - client.DeleteOrganizationMember(context.Background(), organizationID, userID) + err := client.DeleteOrganizationMember(context.Background(), organizationID, userID) + test.That(t, err, test.ShouldBeNil) }) t.Run("DeleteOrganizationInvite", func(t *testing.T) { @@ -702,7 +810,8 @@ func TestAppClient(t *testing.T) { test.That(t, in.Email, test.ShouldEqual, email) return &pb.DeleteOrganizationInviteResponse{}, nil } - client.DeleteOrganizationInvite(context.Background(), organizationID, email) + err := client.DeleteOrganizationInvite(context.Background(), organizationID, email) + test.That(t, err, test.ShouldBeNil) }) t.Run("ResendOrganizationInvite", func(t *testing.T) { @@ -717,11 +826,7 @@ func TestAppClient(t *testing.T) { } resp, err := client.ResendOrganizationInvite(context.Background(), organizationID, email) test.That(t, err, test.ShouldBeNil) - test.That(t, resp.OrganizationID, test.ShouldEqual, invite.OrganizationID) - test.That(t, resp.Email, test.ShouldResemble, invite.Email) - test.That(t, resp.CreatedOn, test.ShouldEqual, invite.CreatedOn) - test.That(t, len(resp.Authorizations), test.ShouldEqual, len(invite.Authorizations)) - test.That(t, resp.Authorizations[0], test.ShouldResemble, invite.Authorizations[0]) + test.That(t, resp, test.ShouldResemble, &invite) }) t.Run("EnableBillingService", func(t *testing.T) { @@ -732,7 +837,8 @@ func TestAppClient(t *testing.T) { test.That(t, in.BillingAddress, test.ShouldResemble, &pbAddress) return &pb.EnableBillingServiceResponse{}, nil } - client.EnableBillingService(context.Background(), organizationID, &address) + err := client.EnableBillingService(context.Background(), organizationID, &address) + test.That(t, err, test.ShouldBeNil) }) t.Run("DisableBillingService", func(t *testing.T) { @@ -742,7 +848,8 @@ func TestAppClient(t *testing.T) { test.That(t, in.OrgId, test.ShouldEqual, organizationID) return &pb.DisableBillingServiceResponse{}, nil } - client.DisableBillingService(context.Background(), organizationID) + err := client.DisableBillingService(context.Background(), organizationID) + test.That(t, err, test.ShouldBeNil) }) t.Run("UpdateBillingService", func(t *testing.T) { @@ -754,7 +861,8 @@ func TestAppClient(t *testing.T) { test.That(t, in.BillingSupportEmail, test.ShouldResemble, email) return &pb.UpdateBillingServiceResponse{}, nil } - client.UpdateBillingService(context.Background(), organizationID, &address, email) + err := client.UpdateBillingService(context.Background(), organizationID, &address, email) + test.That(t, err, test.ShouldBeNil) }) t.Run("OrganizationSetSupportEmail", func(t *testing.T) { @@ -765,7 +873,8 @@ func TestAppClient(t *testing.T) { test.That(t, in.Email, test.ShouldResemble, email) return &pb.OrganizationSetSupportEmailResponse{}, nil } - client.OrganizationSetSupportEmail(context.Background(), organizationID, email) + err := client.OrganizationSetSupportEmail(context.Background(), organizationID, email) + test.That(t, err, test.ShouldBeNil) }) t.Run("OrganizationGetSupportEmail", func(t *testing.T) { @@ -795,7 +904,7 @@ func TestAppClient(t *testing.T) { } resp, err := client.CreateLocation(context.Background(), organizationID, name, &parentLocationID) test.That(t, err, test.ShouldBeNil) - testLocationResponse(t, resp, &location) + test.That(t, resp, test.ShouldResemble, &location) }) t.Run("GetLocation", func(t *testing.T) { @@ -809,7 +918,7 @@ func TestAppClient(t *testing.T) { } resp, err := client.GetLocation(context.Background(), locationID) test.That(t, err, test.ShouldBeNil) - testLocationResponse(t, resp, &location) + test.That(t, resp, test.ShouldResemble, &location) }) t.Run("UpdateLocation", func(t *testing.T) { @@ -826,7 +935,7 @@ func TestAppClient(t *testing.T) { } resp, err := client.UpdateLocation(context.Background(), locationID, &name, &parentLocationID, ®ion) test.That(t, err, test.ShouldBeNil) - testLocationResponse(t, resp, &location) + test.That(t, resp, test.ShouldResemble, &location) }) t.Run("DeleteLocation", func(t *testing.T) { @@ -836,11 +945,12 @@ func TestAppClient(t *testing.T) { test.That(t, in.LocationId, test.ShouldEqual, locationID) return &pb.DeleteLocationResponse{}, nil } - client.DeleteLocation(context.Background(), locationID) + err := client.DeleteLocation(context.Background(), locationID) + test.That(t, err, test.ShouldBeNil) }) t.Run("ListLocations", func(t *testing.T) { - expectedLocations := []Location{location} + expectedLocations := []*Location{&location} grpcClient.ListLocationsFunc = func( ctx context.Context, in *pb.ListLocationsRequest, opts ...grpc.CallOption, ) (*pb.ListLocationsResponse, error) { @@ -851,8 +961,7 @@ func TestAppClient(t *testing.T) { } resp, err := client.ListLocations(context.Background(), organizationID) test.That(t, err, test.ShouldBeNil) - test.That(t, len(resp), test.ShouldEqual, len(expectedLocations)) - testLocationResponse(t, resp[0], &expectedLocations[0]) + test.That(t, resp, test.ShouldResemble, expectedLocations) }) t.Run("ShareLocation", func(t *testing.T) { @@ -863,7 +972,8 @@ func TestAppClient(t *testing.T) { test.That(t, in.OrganizationId, test.ShouldEqual, organizationID) return &pb.ShareLocationResponse{}, nil } - client.ShareLocation(context.Background(), locationID, organizationID) + err := client.ShareLocation(context.Background(), locationID, organizationID) + test.That(t, err, test.ShouldBeNil) }) t.Run("UnshareLocation", func(t *testing.T) { @@ -874,7 +984,8 @@ func TestAppClient(t *testing.T) { test.That(t, in.OrganizationId, test.ShouldEqual, organizationID) return &pb.UnshareLocationResponse{}, nil } - client.UnshareLocation(context.Background(), locationID, organizationID) + err := client.UnshareLocation(context.Background(), locationID, organizationID) + test.That(t, err, test.ShouldBeNil) }) t.Run("LocationAuth", func(t *testing.T) { @@ -913,7 +1024,8 @@ func TestAppClient(t *testing.T) { test.That(t, in.SecretId, test.ShouldEqual, secretID) return &pb.DeleteLocationSecretResponse{}, nil } - client.DeleteLocationSecret(context.Background(), locationID, secretID) + err := client.DeleteLocationSecret(context.Background(), locationID, secretID) + test.That(t, err, test.ShouldBeNil) }) t.Run("GetRobot", func(t *testing.T) { @@ -931,29 +1043,29 @@ func TestAppClient(t *testing.T) { }) t.Run("GetRoverRentalRobots", func(t *testing.T) { - expectedRobots := []RoverRentalRobot{roverRentalRobot} - pbRobot := pb.RoverRentalRobot{ - RobotId: roverRentalRobot.RobotID, - LocationId: roverRentalRobot.LocationID, - RobotName: roverRentalRobot.RobotName, - RobotMainPartId: partID, - } + expectedRobots := []*RoverRentalRobot{&roverRentalRobot} grpcClient.GetRoverRentalRobotsFunc = func( ctx context.Context, in *pb.GetRoverRentalRobotsRequest, opts ...grpc.CallOption, ) (*pb.GetRoverRentalRobotsResponse, error) { test.That(t, in.OrgId, test.ShouldEqual, organizationID) return &pb.GetRoverRentalRobotsResponse{ - Robots: []*pb.RoverRentalRobot{&pbRobot}, + Robots: []*pb.RoverRentalRobot{ + { + RobotId: roverRentalRobot.RobotID, + LocationId: roverRentalRobot.LocationID, + RobotName: roverRentalRobot.RobotName, + RobotMainPartId: partID, + }, + }, }, nil } resp, err := client.GetRoverRentalRobots(context.Background(), organizationID) test.That(t, err, test.ShouldBeNil) - test.That(t, len(resp), test.ShouldEqual, len(expectedRobots)) - test.That(t, resp[0], test.ShouldResemble, &expectedRobots[0]) + test.That(t, resp, test.ShouldResemble, expectedRobots) }) t.Run("GetRobotParts", func(t *testing.T) { - expectedRobotParts := []RobotPart{robotPart} + expectedRobotParts := []*RobotPart{&robotPart} grpcClient.GetRobotPartsFunc = func( ctx context.Context, in *pb.GetRobotPartsRequest, opts ...grpc.CallOption, ) (*pb.GetRobotPartsResponse, error) { @@ -964,8 +1076,7 @@ func TestAppClient(t *testing.T) { } resp, err := client.GetRobotParts(context.Background(), robotID) test.That(t, err, test.ShouldBeNil) - test.That(t, len(resp), test.ShouldEqual, len(expectedRobotParts)) - testRobotPartResponse(t, resp[0], &expectedRobotParts[0]) + test.That(t, resp, test.ShouldResemble, expectedRobotParts) }) t.Run("GetRobotPart", func(t *testing.T) { @@ -981,7 +1092,7 @@ func TestAppClient(t *testing.T) { part, json, err := client.GetRobotPart(context.Background(), partID) test.That(t, err, test.ShouldBeNil) test.That(t, json, test.ShouldEqual, configJSON) - testRobotPartResponse(t, part, &robotPart) + test.That(t, part, test.ShouldResemble, &robotPart) }) t.Run("GetRobotPartLogs", func(t *testing.T) { @@ -1017,42 +1128,30 @@ func TestAppClient(t *testing.T) { logs, token, err := client.GetRobotPartLogs(context.Background(), partID, &filter, &pageToken, levels, &start, &end, &limit, &source) test.That(t, err, test.ShouldBeNil) test.That(t, token, test.ShouldEqual, pageToken) - test.That(t, len(logs), test.ShouldEqual, len(expectedLogs)) - test.That(t, logs[0].Host, test.ShouldEqual, expectedLogs[0].Host) - test.That(t, logs[0].Level, test.ShouldEqual, expectedLogs[0].Level) - test.That(t, logs[0].Time, test.ShouldEqual, expectedLogs[0].Time) - test.That(t, logs[0].LoggerName, test.ShouldEqual, expectedLogs[0].LoggerName) - test.That(t, logs[0].Message, test.ShouldEqual, expectedLogs[0].Message) - test.That(t, logs[0].Caller, test.ShouldResemble, expectedLogs[0].Caller) - test.That(t, logs[0].Stack, test.ShouldEqual, expectedLogs[0].Stack) - test.That(t, len(logs[0].Fields), test.ShouldEqual, len(expectedLogs[0].Fields)) - test.That(t, logs[0].Fields[0], test.ShouldResemble, expectedLogs[0].Fields[0]) + test.That(t, logs, test.ShouldResemble, expectedLogs) }) t.Run("GetRobotPartHistory", func(t *testing.T) { expectedEntries := []*RobotPartHistoryEntry{&robotPartHistoryEntry} - pbRobotPartHistoryEntry := pb.RobotPartHistoryEntry{ - Part: robotPartHistoryEntry.Part, - Robot: robotPartHistoryEntry.Robot, - When: robotPartHistoryEntry.When, - Old: &pbRobotPart, - EditedBy: &pbAuthenticatorInfo, - } grpcClient.GetRobotPartHistoryFunc = func( ctx context.Context, in *pb.GetRobotPartHistoryRequest, opts ...grpc.CallOption, ) (*pb.GetRobotPartHistoryResponse, error) { test.That(t, in.Id, test.ShouldEqual, partID) return &pb.GetRobotPartHistoryResponse{ - History: []*pb.RobotPartHistoryEntry{&pbRobotPartHistoryEntry}, + History: []*pb.RobotPartHistoryEntry{ + { + Part: robotPartHistoryEntry.Part, + Robot: robotPartHistoryEntry.Robot, + When: robotPartHistoryEntry.When, + Old: &pbRobotPart, + EditedBy: &pbAuthenticatorInfo, + }, + }, }, nil } resp, err := client.GetRobotPartHistory(context.Background(), partID) test.That(t, err, test.ShouldBeNil) - test.That(t, resp[0].Part, test.ShouldEqual, expectedEntries[0].Part) - test.That(t, resp[0].Robot, test.ShouldEqual, expectedEntries[0].Robot) - test.That(t, resp[0].When, test.ShouldEqual, expectedEntries[0].When) - testRobotPartResponse(t, resp[0].Old, expectedEntries[0].Old) - test.That(t, resp[0].EditedBy, test.ShouldResemble, expectedEntries[0].EditedBy) + test.That(t, resp, test.ShouldResemble, expectedEntries) }) t.Run("UpdateRobotPart", func(t *testing.T) { @@ -1068,7 +1167,7 @@ func TestAppClient(t *testing.T) { } resp, err := client.UpdateRobotPart(context.Background(), partID, name, robotConfig) test.That(t, err, test.ShouldBeNil) - testRobotPartResponse(t, resp, &robotPart) + test.That(t, resp, test.ShouldResemble, &robotPart) }) t.Run("NewRobotPart", func(t *testing.T) { @@ -1077,9 +1176,13 @@ func TestAppClient(t *testing.T) { ) (*pb.NewRobotPartResponse, error) { test.That(t, in.RobotId, test.ShouldEqual, robotID) test.That(t, in.PartName, test.ShouldEqual, name) - return &pb.NewRobotPartResponse{}, nil + return &pb.NewRobotPartResponse{ + PartId: partID, + }, nil } - client.NewRobotPart(context.Background(), robotID, name) + resp, err := client.NewRobotPart(context.Background(), robotID, name) + test.That(t, err, test.ShouldBeNil) + test.That(t, resp, test.ShouldEqual, partID) }) t.Run("DeleteRobotPart", func(t *testing.T) { @@ -1089,11 +1192,12 @@ func TestAppClient(t *testing.T) { test.That(t, in.PartId, test.ShouldEqual, partID) return &pb.DeleteRobotPartResponse{}, nil } - client.DeleteRobotPart(context.Background(), partID) + err := client.DeleteRobotPart(context.Background(), partID) + test.That(t, err, test.ShouldBeNil) }) t.Run("GetRobotAPIKeys", func(t *testing.T) { - expectedAPIKeyWithAuthorizations := []APIKeyWithAuthorizations{apiKeyWithAuthorizations} + expectedAPIKeyWithAuthorizations := []*APIKeyWithAuthorizations{&apiKeyWithAuthorizations} grpcClient.GetRobotAPIKeysFunc = func( ctx context.Context, in *pb.GetRobotAPIKeysRequest, opts ...grpc.CallOption, ) (*pb.GetRobotAPIKeysResponse, error) { @@ -1104,9 +1208,7 @@ func TestAppClient(t *testing.T) { } resp, err := client.GetRobotAPIKeys(context.Background(), robotID) test.That(t, err, test.ShouldBeNil) - test.That(t, len(resp), test.ShouldEqual, len(expectedAPIKeyWithAuthorizations)) - test.That(t, resp[0].APIKey, test.ShouldResemble, expectedAPIKeyWithAuthorizations[0].APIKey) - test.That(t, resp[0].Authorizations, test.ShouldResemble, expectedAPIKeyWithAuthorizations[0].Authorizations) + test.That(t, resp, test.ShouldResemble, expectedAPIKeyWithAuthorizations) }) t.Run("MarkPartForRestart", func(t *testing.T) { @@ -1116,7 +1218,8 @@ func TestAppClient(t *testing.T) { test.That(t, in.PartId, test.ShouldEqual, partID) return &pb.MarkPartForRestartResponse{}, nil } - client.MarkPartForRestart(context.Background(), partID) + err := client.MarkPartForRestart(context.Background(), partID) + test.That(t, err, test.ShouldBeNil) }) t.Run("CreateRobotPartSecret", func(t *testing.T) { @@ -1130,7 +1233,7 @@ func TestAppClient(t *testing.T) { } resp, err := client.CreateRobotPartSecret(context.Background(), partID) test.That(t, err, test.ShouldBeNil) - testRobotPartResponse(t, resp, &robotPart) + test.That(t, resp, test.ShouldResemble, &robotPart) }) t.Run("DeleteRobotPartSecret", func(t *testing.T) { @@ -1141,7 +1244,8 @@ func TestAppClient(t *testing.T) { test.That(t, in.SecretId, test.ShouldEqual, secretID) return &pb.DeleteRobotPartSecretResponse{}, nil } - client.DeleteRobotPartSecret(context.Background(), partID, secretID) + err := client.DeleteRobotPartSecret(context.Background(), partID, secretID) + test.That(t, err, test.ShouldBeNil) }) t.Run("ListRobots", func(t *testing.T) { @@ -1156,8 +1260,7 @@ func TestAppClient(t *testing.T) { } resp, err := client.ListRobots(context.Background(), locationID) test.That(t, err, test.ShouldBeNil) - test.That(t, len(resp), test.ShouldEqual, len(expectedRobots)) - test.That(t, resp[0], test.ShouldResemble, expectedRobots[0]) + test.That(t, resp, test.ShouldResemble, expectedRobots) }) t.Run("NewRobot", func(t *testing.T) { @@ -1172,7 +1275,7 @@ func TestAppClient(t *testing.T) { } resp, err := client.NewRobot(context.Background(), name, locationID) test.That(t, err, test.ShouldBeNil) - test.That(t, resp, test.ShouldResemble, robotID) + test.That(t, resp, test.ShouldEqual, robotID) }) t.Run("UpdateRobot", func(t *testing.T) { @@ -1198,7 +1301,8 @@ func TestAppClient(t *testing.T) { test.That(t, in.Id, test.ShouldEqual, robotID) return &pb.DeleteRobotResponse{}, nil } - client.DeleteRobot(context.Background(), robotID) + err := client.DeleteRobot(context.Background(), robotID) + test.That(t, err, test.ShouldBeNil) }) t.Run("GetFragment", func(t *testing.T) { @@ -1242,11 +1346,12 @@ func TestAppClient(t *testing.T) { test.That(t, in.Id, test.ShouldEqual, fragmentID) return &pb.DeleteFragmentResponse{}, nil } - client.DeleteFragment(context.Background(), fragmentID) + err := client.DeleteFragment(context.Background(), fragmentID) + test.That(t, err, test.ShouldBeNil) }) t.Run("ListMachineFragments", func(t *testing.T) { - expectedFragments := []Fragment{fragment} + expectedFragments := []*Fragment{&fragment} additionalFragmentIDs := []string{fragmentID} grpcClient.ListMachineFragmentsFunc = func( ctx context.Context, in *pb.ListMachineFragmentsRequest, opts ...grpc.CallOption, @@ -1259,18 +1364,11 @@ func TestAppClient(t *testing.T) { } resp, err := client.ListMachineFragments(context.Background(), robotID, additionalFragmentIDs) test.That(t, err, test.ShouldBeNil) - test.That(t, len(resp), test.ShouldEqual, len(expectedFragments)) - test.That(t, resp[0], test.ShouldResemble, &expectedFragments[0]) + test.That(t, resp, test.ShouldResemble, expectedFragments) }) t.Run("GetFragmentHistory", func(t *testing.T) { - expectedHistory := []FragmentHistoryEntry{fragmentHistoryEntry} - pbFragmentHistoryEntry := pb.FragmentHistoryEntry{ - Fragment: fragmentHistoryEntry.Fragment, - EditedOn: fragmentHistoryEntry.EditedOn, - Old: &pbFragment, - EditedBy: &pbAuthenticatorInfo, - } + expectedHistory := []*FragmentHistoryEntry{&fragmentHistoryEntry} grpcClient.GetFragmentHistoryFunc = func( ctx context.Context, in *pb.GetFragmentHistoryRequest, opts ...grpc.CallOption, ) (*pb.GetFragmentHistoryResponse, error) { @@ -1278,15 +1376,21 @@ func TestAppClient(t *testing.T) { test.That(t, in.PageToken, test.ShouldResemble, &pageToken) test.That(t, in.PageLimit, test.ShouldResemble, &limit) return &pb.GetFragmentHistoryResponse{ - History: []*pb.FragmentHistoryEntry{&pbFragmentHistoryEntry}, + History: []*pb.FragmentHistoryEntry{ + { + Fragment: fragmentHistoryEntry.Fragment, + EditedOn: fragmentHistoryEntry.EditedOn, + Old: &pbFragment, + EditedBy: &pbAuthenticatorInfo, + }, + }, NextPageToken: pageToken, }, nil } resp, token, err := client.GetFragmentHistory(context.Background(), fragmentID, &pageToken, &limit) test.That(t, err, test.ShouldBeNil) test.That(t, token, test.ShouldEqual, pageToken) - test.That(t, len(resp), test.ShouldEqual, len(expectedHistory)) - test.That(t, resp[0], test.ShouldResemble, &expectedHistory[0]) + test.That(t, resp, test.ShouldResemble, expectedHistory) }) t.Run("createAuthorization", func(t *testing.T) { @@ -1328,7 +1432,7 @@ func TestAppClient(t *testing.T) { test.That(t, in.Authorization, test.ShouldResemble, &pbAuthorization) return &pb.AddRoleResponse{}, nil } - client.AddRole( + err := client.AddRole( context.Background(), authorization.OrganizationID, authorization.IdentityID, @@ -1336,6 +1440,7 @@ func TestAppClient(t *testing.T) { authorization.ResourceType, authorization.ResourceID, ) + test.That(t, err, test.ShouldBeNil) }) t.Run("RemoveRole", func(t *testing.T) { @@ -1345,7 +1450,7 @@ func TestAppClient(t *testing.T) { test.That(t, in.Authorization, test.ShouldResemble, &pbAuthorization) return &pb.RemoveRoleResponse{}, nil } - client.RemoveRole( + err := client.RemoveRole( context.Background(), authorization.OrganizationID, authorization.IdentityID, @@ -1353,6 +1458,7 @@ func TestAppClient(t *testing.T) { authorization.ResourceType, authorization.ResourceID, ) + test.That(t, err, test.ShouldBeNil) }) t.Run("ChangeRole", func(t *testing.T) { @@ -1363,7 +1469,7 @@ func TestAppClient(t *testing.T) { test.That(t, in.NewAuthorization, test.ShouldResemble, &pbAuthorization2) return &pb.ChangeRoleResponse{}, nil } - client.ChangeRole( + err := client.ChangeRole( context.Background(), authorization.OrganizationID, authorization.IdentityID, @@ -1376,6 +1482,7 @@ func TestAppClient(t *testing.T) { authorization2.ResourceType, authorization2.ResourceID, ) + test.That(t, err, test.ShouldBeNil) }) t.Run("ListAuthorizations", func(t *testing.T) { From ed15c5a7d692dd8e67ecfcfc6a3ea169e90463f1 Mon Sep 17 00:00:00 2001 From: purplenicole730 Date: Mon, 18 Nov 2024 13:02:56 -0500 Subject: [PATCH 45/75] registry item tests --- app/app_client_test.go | 99 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 99 insertions(+) diff --git a/app/app_client_test.go b/app/app_client_test.go index 7cd4e474a62..e657c4cba15 100644 --- a/app/app_client_test.go +++ b/app/app_client_test.go @@ -1520,4 +1520,103 @@ func TestAppClient(t *testing.T) { test.That(t, err, test.ShouldBeNil) test.That(t, resp, test.ShouldResemble, permissions) }) + + t.Run("GetRegistryItem", func(t *testing.T) { + grpcClient.GetRegistryItemFunc = func( + ctx context.Context, in *pb.GetRegistryItemRequest, opts ...grpc.CallOption, + ) (*pb.GetRegistryItemResponse, error) { + test.That(t, in.ItemId, test.ShouldResemble, itemID) + return &pb.GetRegistryItemResponse{ + Item: pbRegistryItem, + }, nil + } + resp, err := client.GetRegistryItem(context.Background(), itemID) + test.That(t, err, test.ShouldBeNil) + test.That(t, resp, test.ShouldResemble, ®istryItem) + }) + + t.Run("CreateRegistryItem", func(t *testing.T) { + grpcClient.CreateRegistryItemFunc = func( + ctx context.Context, in *pb.CreateRegistryItemRequest, opts ...grpc.CallOption, + ) (*pb.CreateRegistryItemResponse, error) { + test.That(t, in.OrganizationId, test.ShouldResemble, registryItem.OrganizationID) + test.That(t, in.Name, test.ShouldResemble, registryItem.Name) + test.That(t, in.Type, test.ShouldResemble, pbRegistryItem.Type) + return &pb.CreateRegistryItemResponse{}, nil + } + err := client.CreateRegistryItem(context.Background(), registryItem.OrganizationID, registryItem.Name, registryItem.Type) + test.That(t, err, test.ShouldBeNil) + }) + + t.Run("UpdateRegistryItem", func(t *testing.T) { + grpcClient.UpdateRegistryItemFunc = func( + ctx context.Context, in *pb.UpdateRegistryItemRequest, opts ...grpc.CallOption, + ) (*pb.UpdateRegistryItemResponse, error) { + test.That(t, in.ItemId, test.ShouldResemble, itemID) + test.That(t, in.Type, test.ShouldResemble, packageTypeToProto(packageType)) + test.That(t, in.Description, test.ShouldResemble, description) + test.That(t, in.Visibility, test.ShouldResemble, visibilityToProto(visibility)) + test.That(t, in.Url, test.ShouldResemble, &siteURL) + return &pb.UpdateRegistryItemResponse{}, nil + } + err := client.UpdateRegistryItem(context.Background(), registryItem.ItemID, packageType, description, visibility, &siteURL) + test.That(t, err, test.ShouldBeNil) + }) + + t.Run("ListRegistryItems", func(t *testing.T) { + platforms := []string{platform} + namespaces := []string{namespace} + expectedRegistryItems := []*RegistryItem{®istryItem} + grpcClient.ListRegistryItemsFunc = func( + ctx context.Context, in *pb.ListRegistryItemsRequest, opts ...grpc.CallOption, + ) (*pb.ListRegistryItemsResponse, error) { + test.That(t, in.OrganizationId, test.ShouldResemble, &organizationID) + test.That(t, in.Types, test.ShouldResemble, []packages.PackageType{packageTypeToProto(packageType)}) + test.That(t, in.Visibilities, test.ShouldResemble, []pb.Visibility{visibilityToProto(visibility)}) + test.That(t, in.Platforms, test.ShouldResemble, platforms) + test.That(t, in.Statuses, test.ShouldResemble, []pb.RegistryItemStatus{pb.RegistryItemStatus(registryItemStatus)}) + test.That(t, in.SearchTerm, test.ShouldResemble, &searchTerm) + test.That(t, in.PageToken, test.ShouldResemble, &pageToken) + test.That(t, in.PublicNamespaces, test.ShouldResemble, namespaces) + return &pb.ListRegistryItemsResponse{ + Items: []*pb.RegistryItem{pbRegistryItem}, + }, nil + } + resp, err := client.ListRegistryItems( + context.Background(), + &organizationID, + []PackageType{packageType}, + []Visibility{visibility}, + platforms, + []RegistryItemStatus{registryItemStatus}, + &searchTerm, + &pageToken, + namespaces, + ) + test.That(t, err, test.ShouldBeNil) + test.That(t, resp, test.ShouldResemble, expectedRegistryItems) + }) + + t.Run("DeleteRegistryItem", func(t *testing.T) { + grpcClient.DeleteRegistryItemFunc = func( + ctx context.Context, in *pb.DeleteRegistryItemRequest, opts ...grpc.CallOption, + ) (*pb.DeleteRegistryItemResponse, error) { + test.That(t, in.ItemId, test.ShouldResemble, itemID) + return &pb.DeleteRegistryItemResponse{}, nil + } + err := client.DeleteRegistryItem(context.Background(), registryItem.ItemID) + test.That(t, err, test.ShouldBeNil) + }) + + t.Run("TransferRegistryItem", func(t *testing.T) { + grpcClient.TransferRegistryItemFunc = func( + ctx context.Context, in *pb.TransferRegistryItemRequest, opts ...grpc.CallOption, + ) (*pb.TransferRegistryItemResponse, error) { + test.That(t, in.ItemId, test.ShouldResemble, itemID) + test.That(t, in.NewPublicNamespace, test.ShouldResemble, namespace) + return &pb.TransferRegistryItemResponse{}, nil + } + err := client.TransferRegistryItem(context.Background(), registryItem.ItemID, namespace) + test.That(t, err, test.ShouldBeNil) + }) } From 552ce01b5401b32700d81390a4ac9c98e6f3d8e7 Mon Sep 17 00:00:00 2001 From: purplenicole730 Date: Mon, 18 Nov 2024 13:36:47 -0500 Subject: [PATCH 46/75] module tests --- app/app_client_test.go | 125 ++++++++++++++++++++++++++++++++++++++++- 1 file changed, 123 insertions(+), 2 deletions(-) diff --git a/app/app_client_test.go b/app/app_client_test.go index e657c4cba15..38679af4d72 100644 --- a/app/app_client_test.go +++ b/app/app_client_test.go @@ -76,6 +76,10 @@ const ( draft = false platform = "platform" registryItemStatus = RegistryItemStatusPublished + moduleID = "module_id" + api = "api" + modelString = "model_string" + entryPoint = "entry_point" ) var ( @@ -447,8 +451,76 @@ var ( CreatedAt: &createdOn, UpdatedAt: &lastUpdated, } + pbVisibility = visibilityToProto(visibility) pbRegistryItem, _ = registryItemToProto(®istryItem) searchTerm = "search_term" + model = Model{ + API: api, + Model: modelString, + } + models = []*Model{&model} + pbModels = []*pb.Model{ + { + Api: model.API, + Model: modelString, + }, + } + firstRun = "first_run" + uploadedAt = timestamppb.Timestamp{Seconds: 3, Nanos: 211} + uploads = Uploads{ + Platform: platform, + UploadedAt: &uploadedAt, + } + pbUploads = pb.Uploads{ + Platform: uploads.Platform, + UploadedAt: uploads.UploadedAt, + } + versionHistory = VersionHistory{ + Version: version, + Files: []*Uploads{&uploads}, + Models: models, + Entrypoint: entryPoint, + FirstRun: &firstRun, + } + pbVersionHistory = pb.VersionHistory{ + Version: versionHistory.Version, + Files: []*pb.Uploads{&pbUploads}, + Models: pbModels, + Entrypoint: versionHistory.Entrypoint, + FirstRun: versionHistory.FirstRun, + } + versionHistories = []*VersionHistory{&versionHistory} + pbVersionHistories = []*pb.VersionHistory{&pbVersionHistory} + module = Module{ + ModuleID: moduleID, + Name: name, + Visibility: visibility, + Versions: versionHistories, + URL: siteURL, + Description: description, + Models: models, + TotalRobotUsage: totalRobotUsage, + TotalOrganizationUsage: totalOrganizationUsage, + OrganizationID: organizationID, + Entrypoint: entryPoint, + PublicNamespace: namespace, + FirstRun: &firstRun, + } + pbModule = pb.Module{ + ModuleId: module.ModuleID, + Name: module.Name, + Visibility: pbVisibility, + Versions: pbVersionHistories, + Url: module.URL, + Description: module.Description, + Models: pbModels, + TotalRobotUsage: module.TotalRobotUsage, + TotalOrganizationUsage: module.TotalOrganizationUsage, + OrganizationId: module.OrganizationID, + Entrypoint: module.Entrypoint, + PublicNamespace: module.PublicNamespace, + FirstRun: module.FirstRun, + } ) func sharedSecretStateToProto(state SharedSecretState) pb.SharedSecret_State { @@ -1555,7 +1627,7 @@ func TestAppClient(t *testing.T) { test.That(t, in.ItemId, test.ShouldResemble, itemID) test.That(t, in.Type, test.ShouldResemble, packageTypeToProto(packageType)) test.That(t, in.Description, test.ShouldResemble, description) - test.That(t, in.Visibility, test.ShouldResemble, visibilityToProto(visibility)) + test.That(t, in.Visibility, test.ShouldResemble, pbVisibility) test.That(t, in.Url, test.ShouldResemble, &siteURL) return &pb.UpdateRegistryItemResponse{}, nil } @@ -1572,7 +1644,7 @@ func TestAppClient(t *testing.T) { ) (*pb.ListRegistryItemsResponse, error) { test.That(t, in.OrganizationId, test.ShouldResemble, &organizationID) test.That(t, in.Types, test.ShouldResemble, []packages.PackageType{packageTypeToProto(packageType)}) - test.That(t, in.Visibilities, test.ShouldResemble, []pb.Visibility{visibilityToProto(visibility)}) + test.That(t, in.Visibilities, test.ShouldResemble, []pb.Visibility{pbVisibility}) test.That(t, in.Platforms, test.ShouldResemble, platforms) test.That(t, in.Statuses, test.ShouldResemble, []pb.RegistryItemStatus{pb.RegistryItemStatus(registryItemStatus)}) test.That(t, in.SearchTerm, test.ShouldResemble, &searchTerm) @@ -1619,4 +1691,53 @@ func TestAppClient(t *testing.T) { err := client.TransferRegistryItem(context.Background(), registryItem.ItemID, namespace) test.That(t, err, test.ShouldBeNil) }) + + t.Run("UpdateModule", func(t *testing.T) { + grpcClient.UpdateModuleFunc = func( + ctx context.Context, in *pb.UpdateModuleRequest, opts ...grpc.CallOption, + ) (*pb.UpdateModuleResponse, error) { + test.That(t, in.ModuleId, test.ShouldResemble, moduleID) + test.That(t, in.Visibility, test.ShouldResemble, pbVisibility) + test.That(t, in.Url, test.ShouldResemble, siteURL) + test.That(t, in.Description, test.ShouldResemble, description) + test.That(t, in.Models, test.ShouldResemble, pbModels) + test.That(t, in.Entrypoint, test.ShouldResemble, entryPoint) + test.That(t, in.FirstRun, test.ShouldResemble, &firstRun) + return &pb.UpdateModuleResponse{ + Url: siteURL, + }, nil + } + resp, err := client.UpdateModule(context.Background(), moduleID, visibility, siteURL, description, models, entryPoint, &firstRun) + test.That(t, err, test.ShouldBeNil) + test.That(t, resp, test.ShouldEqual, siteURL) + }) + + t.Run("GetModule", func(t *testing.T) { + grpcClient.GetModuleFunc = func( + ctx context.Context, in *pb.GetModuleRequest, opts ...grpc.CallOption, + ) (*pb.GetModuleResponse, error) { + test.That(t, in.ModuleId, test.ShouldResemble, moduleID) + return &pb.GetModuleResponse{ + Module: &pbModule, + }, nil + } + resp, err := client.GetModule(context.Background(), moduleID) + test.That(t, err, test.ShouldBeNil) + test.That(t, resp, test.ShouldResemble, &module) + }) + + t.Run("ListModules", func(t *testing.T) { + expectedModules := []*Module{&module} + grpcClient.ListModulesFunc = func( + ctx context.Context, in *pb.ListModulesRequest, opts ...grpc.CallOption, + ) (*pb.ListModulesResponse, error) { + test.That(t, in.OrganizationId, test.ShouldResemble, &organizationID) + return &pb.ListModulesResponse{ + Modules: []*pb.Module{&pbModule}, + }, nil + } + resp, err := client.ListModules(context.Background(), &organizationID) + test.That(t, err, test.ShouldBeNil) + test.That(t, resp, test.ShouldResemble, expectedModules) + }) } From b52d3013ff5197f08cf78bf60ebf5f5d0739ea9e Mon Sep 17 00:00:00 2001 From: purplenicole730 Date: Mon, 18 Nov 2024 14:00:28 -0500 Subject: [PATCH 47/75] add key tests --- app/app_client.go | 6 +- app/app_client_test.go | 220 ++++++++++++++++++++++++++++++----------- 2 files changed, 168 insertions(+), 58 deletions(-) diff --git a/app/app_client.go b/app/app_client.go index a819bf04b48..b730bfb15ed 100644 --- a/app/app_client.go +++ b/app/app_client.go @@ -1111,16 +1111,16 @@ func (c *Client) DeleteKey(ctx context.Context, id string) error { } // ListKeys lists all the keys for the organization. -func (c *Client) ListKeys(ctx context.Context, orgID string) ([]APIKeyWithAuthorizations, error) { +func (c *Client) ListKeys(ctx context.Context, orgID string) ([]*APIKeyWithAuthorizations, error) { resp, err := c.client.ListKeys(ctx, &pb.ListKeysRequest{ OrgId: orgID, }) if err != nil { return nil, err } - var apiKeys []APIKeyWithAuthorizations + var apiKeys []*APIKeyWithAuthorizations for _, key := range resp.ApiKeys { - apiKeys = append(apiKeys, *apiKeyWithAuthorizationsFromProto(key)) + apiKeys = append(apiKeys, apiKeyWithAuthorizationsFromProto(key)) } return apiKeys, nil } diff --git a/app/app_client_test.go b/app/app_client_test.go index 38679af4d72..2e4a70ba7d9 100644 --- a/app/app_client_test.go +++ b/app/app_client_test.go @@ -76,10 +76,10 @@ const ( draft = false platform = "platform" registryItemStatus = RegistryItemStatusPublished - moduleID = "module_id" - api = "api" - modelString = "model_string" - entryPoint = "entry_point" + moduleID = "module_id" + api = "api" + modelString = "model_string" + entryPoint = "entry_point" ) var ( @@ -372,11 +372,12 @@ var ( }, }, } - public = true - fragmentVisibility = FragmentVisibilityPublic - f = map[string]interface{}{"name": name, "id": fragmentID} - pbF, _ = protoutils.StructToStructPb(f) - fragment = Fragment{ + pbAPIKeysWithAuthorizations = []*pb.APIKeyWithAuthorizations{&pbAPIKeyWithAuthorizations} + public = true + fragmentVisibility = FragmentVisibilityPublic + f = map[string]interface{}{"name": name, "id": fragmentID} + pbF, _ = protoutils.StructToStructPb(f) + fragment = Fragment{ ID: fragmentID, Name: name, Fragment: &f, @@ -451,76 +452,82 @@ var ( CreatedAt: &createdOn, UpdatedAt: &lastUpdated, } - pbVisibility = visibilityToProto(visibility) + pbVisibility = visibilityToProto(visibility) pbRegistryItem, _ = registryItemToProto(®istryItem) searchTerm = "search_term" - model = Model{ - API: api, + model = Model{ + API: api, Model: modelString, } - models = []*Model{&model} + models = []*Model{&model} pbModels = []*pb.Model{ { - Api: model.API, + Api: model.API, Model: modelString, }, } - firstRun = "first_run" + firstRun = "first_run" uploadedAt = timestamppb.Timestamp{Seconds: 3, Nanos: 211} - uploads = Uploads{ - Platform: platform, + uploads = Uploads{ + Platform: platform, UploadedAt: &uploadedAt, } pbUploads = pb.Uploads{ - Platform: uploads.Platform, + Platform: uploads.Platform, UploadedAt: uploads.UploadedAt, } versionHistory = VersionHistory{ - Version: version, - Files: []*Uploads{&uploads}, - Models: models, - Entrypoint: entryPoint, - FirstRun: &firstRun, - } + Version: version, + Files: []*Uploads{&uploads}, + Models: models, + Entrypoint: entryPoint, + FirstRun: &firstRun, + } pbVersionHistory = pb.VersionHistory{ - Version: versionHistory.Version, - Files: []*pb.Uploads{&pbUploads}, - Models: pbModels, + Version: versionHistory.Version, + Files: []*pb.Uploads{&pbUploads}, + Models: pbModels, Entrypoint: versionHistory.Entrypoint, - FirstRun: versionHistory.FirstRun, + FirstRun: versionHistory.FirstRun, } - versionHistories = []*VersionHistory{&versionHistory} + versionHistories = []*VersionHistory{&versionHistory} pbVersionHistories = []*pb.VersionHistory{&pbVersionHistory} - module = Module{ - ModuleID: moduleID, - Name: name, - Visibility: visibility, - Versions: versionHistories, - URL: siteURL, - Description: description, - Models: models, - TotalRobotUsage: totalRobotUsage, + module = Module{ + ModuleID: moduleID, + Name: name, + Visibility: visibility, + Versions: versionHistories, + URL: siteURL, + Description: description, + Models: models, + TotalRobotUsage: totalRobotUsage, TotalOrganizationUsage: totalOrganizationUsage, - OrganizationID: organizationID, - Entrypoint: entryPoint, - PublicNamespace: namespace, - FirstRun: &firstRun, + OrganizationID: organizationID, + Entrypoint: entryPoint, + PublicNamespace: namespace, + FirstRun: &firstRun, } pbModule = pb.Module{ - ModuleId: module.ModuleID, - Name: module.Name, - Visibility: pbVisibility, - Versions: pbVersionHistories, - Url: module.URL, - Description: module.Description, - Models: pbModels, - TotalRobotUsage: module.TotalRobotUsage, + ModuleId: module.ModuleID, + Name: module.Name, + Visibility: pbVisibility, + Versions: pbVersionHistories, + Url: module.URL, + Description: module.Description, + Models: pbModels, + TotalRobotUsage: module.TotalRobotUsage, TotalOrganizationUsage: module.TotalOrganizationUsage, - OrganizationId: module.OrganizationID, - Entrypoint: module.Entrypoint, - PublicNamespace: module.PublicNamespace, - FirstRun: module.FirstRun, + OrganizationId: module.OrganizationID, + Entrypoint: module.Entrypoint, + PublicNamespace: module.PublicNamespace, + FirstRun: module.FirstRun, + } + apiKeyAuthorization = APIKeyAuthorization{ + role: authorizationType, + resourceType: resourceType, + resourceID: resourceID, } + apiKeyAuthorizations = []APIKeyAuthorization{apiKeyAuthorization} ) func sharedSecretStateToProto(state SharedSecretState) pb.SharedSecret_State { @@ -1275,7 +1282,7 @@ func TestAppClient(t *testing.T) { ) (*pb.GetRobotAPIKeysResponse, error) { test.That(t, in.RobotId, test.ShouldEqual, robotID) return &pb.GetRobotAPIKeysResponse{ - ApiKeys: []*pb.APIKeyWithAuthorizations{&pbAPIKeyWithAuthorizations}, + ApiKeys: pbAPIKeysWithAuthorizations, }, nil } resp, err := client.GetRobotAPIKeys(context.Background(), robotID) @@ -1740,4 +1747,107 @@ func TestAppClient(t *testing.T) { test.That(t, err, test.ShouldBeNil) test.That(t, resp, test.ShouldResemble, expectedModules) }) + + t.Run("CreateKey", func(t *testing.T) { + pbAPIKeyAuthorizations := []*pb.Authorization{ + { + AuthorizationType: apiKeyAuthorization.role, + AuthorizationId: fmt.Sprintf("%s_%s", apiKeyAuthorization.resourceType, apiKeyAuthorization.role), + ResourceType: apiKeyAuthorization.resourceType, + ResourceId: apiKeyAuthorization.resourceID, + IdentityId: "", + OrganizationId: organizationID, + IdentityType: "api-key", + }, + } + grpcClient.CreateKeyFunc = func( + ctx context.Context, in *pb.CreateKeyRequest, opts ...grpc.CallOption, + ) (*pb.CreateKeyResponse, error) { + test.That(t, in.Authorizations, test.ShouldResemble, pbAPIKeyAuthorizations) + test.That(t, in.Name, test.ShouldResemble, name) + return &pb.CreateKeyResponse{ + Key: key, + Id: keyID, + }, nil + } + key, id, err := client.CreateKey(context.Background(), organizationID, apiKeyAuthorizations, name) + test.That(t, err, test.ShouldBeNil) + test.That(t, key, test.ShouldResemble, key) + test.That(t, id, test.ShouldResemble, keyID) + }) + + t.Run("DeleteKey", func(t *testing.T) { + grpcClient.DeleteKeyFunc = func( + ctx context.Context, in *pb.DeleteKeyRequest, opts ...grpc.CallOption, + ) (*pb.DeleteKeyResponse, error) { + test.That(t, in.Id, test.ShouldResemble, keyID) + return &pb.DeleteKeyResponse{}, nil + } + err := client.DeleteKey(context.Background(), keyID) + test.That(t, err, test.ShouldBeNil) + }) + + t.Run("ListKeys", func(t *testing.T) { + expectedAPIKeyWithAuthorizations := []*APIKeyWithAuthorizations{&apiKeyWithAuthorizations} + grpcClient.ListKeysFunc = func( + ctx context.Context, in *pb.ListKeysRequest, opts ...grpc.CallOption, + ) (*pb.ListKeysResponse, error) { + test.That(t, in.OrgId, test.ShouldResemble, organizationID) + return &pb.ListKeysResponse{ + ApiKeys: pbAPIKeysWithAuthorizations, + }, nil + } + resp, err := client.ListKeys(context.Background(), organizationID) + test.That(t, err, test.ShouldBeNil) + test.That(t, resp, test.ShouldResemble, expectedAPIKeyWithAuthorizations) + }) + + t.Run("RenameKey", func(t *testing.T) { + grpcClient.RenameKeyFunc = func( + ctx context.Context, in *pb.RenameKeyRequest, opts ...grpc.CallOption, + ) (*pb.RenameKeyResponse, error) { + test.That(t, in.Id, test.ShouldResemble, keyID) + test.That(t, in.Name, test.ShouldResemble, name) + return &pb.RenameKeyResponse{ + Id: keyID, + Name: name, + }, nil + } + id, name, err := client.RenameKey(context.Background(), keyID, name) + test.That(t, err, test.ShouldBeNil) + test.That(t, id, test.ShouldResemble, keyID) + test.That(t, name, test.ShouldEqual, name) + }) + + t.Run("RotateKey", func(t *testing.T) { + grpcClient.RotateKeyFunc = func( + ctx context.Context, in *pb.RotateKeyRequest, opts ...grpc.CallOption, + ) (*pb.RotateKeyResponse, error) { + test.That(t, in.Id, test.ShouldResemble, keyID) + return &pb.RotateKeyResponse{ + Id: keyID, + Key: key, + }, nil + } + id, key, err := client.RotateKey(context.Background(), keyID) + test.That(t, err, test.ShouldBeNil) + test.That(t, id, test.ShouldResemble, keyID) + test.That(t, key, test.ShouldEqual, key) + }) + + t.Run("CreateKeyFromExistingKeyAuthorizations", func(t *testing.T) { + grpcClient.CreateKeyFromExistingKeyAuthorizationsFunc = func( + ctx context.Context, in *pb.CreateKeyFromExistingKeyAuthorizationsRequest, opts ...grpc.CallOption, + ) (*pb.CreateKeyFromExistingKeyAuthorizationsResponse, error) { + test.That(t, in.Id, test.ShouldResemble, keyID) + return &pb.CreateKeyFromExistingKeyAuthorizationsResponse{ + Id: keyID, + Key: key, + }, nil + } + id, key, err := client.CreateKeyFromExistingKeyAuthorizations(context.Background(), keyID) + test.That(t, err, test.ShouldBeNil) + test.That(t, id, test.ShouldResemble, keyID) + test.That(t, key, test.ShouldEqual, key) + }) } From 4d1efe22572843d9d902b537011ee77434d88452 Mon Sep 17 00:00:00 2001 From: purplenicole730 Date: Mon, 18 Nov 2024 14:15:48 -0500 Subject: [PATCH 48/75] consolidate files --- app/common.go | 37 ------- app/fragment.go | 99 ----------------- app/location.go | 74 ------------- app/{registry_item.go => registry.go} | 0 app/{organization.go => resource_type.go} | 69 ++++++++++++ app/robot.go | 125 ++++++++++++++++++++++ 6 files changed, 194 insertions(+), 210 deletions(-) delete mode 100644 app/common.go delete mode 100644 app/fragment.go delete mode 100644 app/location.go rename app/{registry_item.go => registry.go} (100%) rename app/{organization.go => resource_type.go} (59%) diff --git a/app/common.go b/app/common.go deleted file mode 100644 index e0f31711f8b..00000000000 --- a/app/common.go +++ /dev/null @@ -1,37 +0,0 @@ -package app - -import ( - common "go.viam.com/api/common/v1" - "google.golang.org/protobuf/types/known/timestamppb" -) - -// LogEntry holds the information of a single log entry. -type LogEntry struct { - Host string - Level string - Time *timestamppb.Timestamp - LoggerName string - Message string - Caller *map[string]interface{} - Stack string - Fields []*map[string]interface{} -} - -func logEntryFromProto(logEntry *common.LogEntry) *LogEntry { - var fields []*map[string]interface{} - for _, field := range logEntry.Fields { - f := field.AsMap() - fields = append(fields, &f) - } - caller := logEntry.Caller.AsMap() - return &LogEntry{ - Host: logEntry.Host, - Level: logEntry.Level, - Time: logEntry.Time, - LoggerName: logEntry.LoggerName, - Message: logEntry.Message, - Caller: &caller, - Stack: logEntry.Stack, - Fields: fields, - } -} diff --git a/app/fragment.go b/app/fragment.go deleted file mode 100644 index 36ea107547c..00000000000 --- a/app/fragment.go +++ /dev/null @@ -1,99 +0,0 @@ -package app - -import ( - pb "go.viam.com/api/app/v1" - "google.golang.org/protobuf/types/known/timestamppb" -) - -// Fragment stores the information of a fragment. -type Fragment struct { - ID string - Name string - Fragment *map[string]interface{} - OrganizationOwner string - Public bool - CreatedOn *timestamppb.Timestamp - OrganizationName string - RobotPartCount int32 - OrganizationCount int32 - OnlyUsedByOwner bool - Visibility FragmentVisibility - LastUpdated *timestamppb.Timestamp -} - -func fragmentFromProto(fragment *pb.Fragment) *Fragment { - f := fragment.Fragment.AsMap() - return &Fragment{ - ID: fragment.Id, - Name: fragment.Name, - Fragment: &f, - OrganizationOwner: fragment.OrganizationOwner, - Public: fragment.Public, - CreatedOn: fragment.CreatedOn, - OrganizationName: fragment.OrganizationName, - RobotPartCount: fragment.RobotPartCount, - OrganizationCount: fragment.OrganizationCount, - OnlyUsedByOwner: fragment.OnlyUsedByOwner, - Visibility: fragmentVisibilityFromProto(fragment.Visibility), - LastUpdated: fragment.LastUpdated, - } -} - -// FragmentVisibility specifies the kind of visibility a fragment has. -type FragmentVisibility int32 - -const ( - // FragmentVisibilityUnspecified is an unspecified visibility. - FragmentVisibilityUnspecified FragmentVisibility = iota - // FragmentVisibilityPrivate restricts access to a fragment to its organization. - FragmentVisibilityPrivate - // FragmentVisibilityPublic allows the fragment to be accessible to everyone. - FragmentVisibilityPublic - // FragmentVisibilityPublicUnlisted allows the fragment to be accessible to everyone but is hidden from public listings like it is private. - FragmentVisibilityPublicUnlisted -) - -func fragmentVisibilityFromProto(visibility pb.FragmentVisibility) FragmentVisibility { - switch visibility { - case pb.FragmentVisibility_FRAGMENT_VISIBILITY_UNSPECIFIED: - return FragmentVisibilityUnspecified - case pb.FragmentVisibility_FRAGMENT_VISIBILITY_PRIVATE: - return FragmentVisibilityPrivate - case pb.FragmentVisibility_FRAGMENT_VISIBILITY_PUBLIC: - return FragmentVisibilityPublic - case pb.FragmentVisibility_FRAGMENT_VISIBILITY_PUBLIC_UNLISTED: - return FragmentVisibilityPublicUnlisted - } - return FragmentVisibilityUnspecified -} - -func fragmentVisibilityToProto(visibility FragmentVisibility) pb.FragmentVisibility { - switch visibility { - case FragmentVisibilityUnspecified: - return pb.FragmentVisibility_FRAGMENT_VISIBILITY_UNSPECIFIED - case FragmentVisibilityPrivate: - return pb.FragmentVisibility_FRAGMENT_VISIBILITY_PRIVATE - case FragmentVisibilityPublic: - return pb.FragmentVisibility_FRAGMENT_VISIBILITY_PUBLIC - case FragmentVisibilityPublicUnlisted: - return pb.FragmentVisibility_FRAGMENT_VISIBILITY_PUBLIC_UNLISTED - } - return pb.FragmentVisibility_FRAGMENT_VISIBILITY_UNSPECIFIED -} - -// FragmentHistoryEntry is an entry of a fragment's history. -type FragmentHistoryEntry struct { - Fragment string - EditedOn *timestamppb.Timestamp - Old *Fragment - EditedBy *AuthenticatorInfo -} - -func fragmentHistoryEntryFromProto(entry *pb.FragmentHistoryEntry) *FragmentHistoryEntry { - return &FragmentHistoryEntry{ - Fragment: entry.Fragment, - EditedOn: entry.EditedOn, - Old: fragmentFromProto(entry.Old), - EditedBy: authenticatorInfoFromProto(entry.EditedBy), - } -} diff --git a/app/location.go b/app/location.go deleted file mode 100644 index 3dfd89f56e3..00000000000 --- a/app/location.go +++ /dev/null @@ -1,74 +0,0 @@ -package app - -import ( - pb "go.viam.com/api/app/v1" - "google.golang.org/protobuf/types/known/timestamppb" -) - -// Location holds the information of a specific location. -type Location struct { - ID string - Name string - ParentLocationID string - Auth *LocationAuth - Organizations []*LocationOrganization - CreatedOn *timestamppb.Timestamp - RobotCount int32 - Config *StorageConfig -} - -func locationFromProto(location *pb.Location) *Location { - var organizations []*LocationOrganization - for _, organization := range location.Organizations { - organizations = append(organizations, locationOrganizationFromProto(organization)) - } - return &Location{ - ID: location.Id, - Name: location.Name, - ParentLocationID: location.ParentLocationId, - Auth: locationAuthFromProto(location.Auth), - Organizations: organizations, - CreatedOn: location.CreatedOn, - RobotCount: location.RobotCount, - Config: storageConfigFromProto(location.Config), - } -} - -// LocationOrganization holds information of an organization the location is shared with. -type LocationOrganization struct { - OrganizationID string - Primary bool -} - -func locationOrganizationFromProto(locationOrganization *pb.LocationOrganization) *LocationOrganization { - return &LocationOrganization{ - OrganizationID: locationOrganization.OrganizationId, - Primary: locationOrganization.Primary, - } -} - -// StorageConfig holds the GCS region that data is stored in. -type StorageConfig struct { - Region string -} - -func storageConfigFromProto(config *pb.StorageConfig) *StorageConfig { - return &StorageConfig{Region: config.Region} -} - -// LocationAuth holds the secrets used to authenticate to a location. -type LocationAuth struct { - LocationID string - Secrets []*SharedSecret -} - -func locationAuthFromProto(locationAuth *pb.LocationAuth) *LocationAuth { - var secrets []*SharedSecret - for _, secret := range locationAuth.Secrets { - secrets = append(secrets, sharedSecretFromProto(secret)) - } - return &LocationAuth{ - LocationID: locationAuth.LocationId, - Secrets: secrets, - } -} diff --git a/app/registry_item.go b/app/registry.go similarity index 100% rename from app/registry_item.go rename to app/registry.go diff --git a/app/organization.go b/app/resource_type.go similarity index 59% rename from app/organization.go rename to app/resource_type.go index a7e8aadd0dc..0611508da06 100644 --- a/app/organization.go +++ b/app/resource_type.go @@ -106,3 +106,72 @@ func billingAddressToProto(addr *BillingAddress) *pb.BillingAddress { State: addr.State, } } + + +// Location holds the information of a specific location. +type Location struct { + ID string + Name string + ParentLocationID string + Auth *LocationAuth + Organizations []*LocationOrganization + CreatedOn *timestamppb.Timestamp + RobotCount int32 + Config *StorageConfig +} + +func locationFromProto(location *pb.Location) *Location { + var organizations []*LocationOrganization + for _, organization := range location.Organizations { + organizations = append(organizations, locationOrganizationFromProto(organization)) + } + return &Location{ + ID: location.Id, + Name: location.Name, + ParentLocationID: location.ParentLocationId, + Auth: locationAuthFromProto(location.Auth), + Organizations: organizations, + CreatedOn: location.CreatedOn, + RobotCount: location.RobotCount, + Config: storageConfigFromProto(location.Config), + } +} + +// LocationOrganization holds information of an organization the location is shared with. +type LocationOrganization struct { + OrganizationID string + Primary bool +} + +func locationOrganizationFromProto(locationOrganization *pb.LocationOrganization) *LocationOrganization { + return &LocationOrganization{ + OrganizationID: locationOrganization.OrganizationId, + Primary: locationOrganization.Primary, + } +} + +// StorageConfig holds the GCS region that data is stored in. +type StorageConfig struct { + Region string +} + +func storageConfigFromProto(config *pb.StorageConfig) *StorageConfig { + return &StorageConfig{Region: config.Region} +} + +// LocationAuth holds the secrets used to authenticate to a location. +type LocationAuth struct { + LocationID string + Secrets []*SharedSecret +} + +func locationAuthFromProto(locationAuth *pb.LocationAuth) *LocationAuth { + var secrets []*SharedSecret + for _, secret := range locationAuth.Secrets { + secrets = append(secrets, sharedSecretFromProto(secret)) + } + return &LocationAuth{ + LocationID: locationAuth.LocationId, + Secrets: secrets, + } +} diff --git a/app/robot.go b/app/robot.go index b2a1f728528..77ecf07f725 100644 --- a/app/robot.go +++ b/app/robot.go @@ -2,6 +2,7 @@ package app import ( pb "go.viam.com/api/app/v1" + common "go.viam.com/api/common/v1" "google.golang.org/protobuf/types/known/timestamppb" ) @@ -104,3 +105,127 @@ func robotPartHistoryEntryFromProto(entry *pb.RobotPartHistoryEntry) *RobotPartH EditedBy: authenticatorInfoFromProto(entry.EditedBy), } } + +// LogEntry holds the information of a single log entry. +type LogEntry struct { + Host string + Level string + Time *timestamppb.Timestamp + LoggerName string + Message string + Caller *map[string]interface{} + Stack string + Fields []*map[string]interface{} +} + +func logEntryFromProto(logEntry *common.LogEntry) *LogEntry { + var fields []*map[string]interface{} + for _, field := range logEntry.Fields { + f := field.AsMap() + fields = append(fields, &f) + } + caller := logEntry.Caller.AsMap() + return &LogEntry{ + Host: logEntry.Host, + Level: logEntry.Level, + Time: logEntry.Time, + LoggerName: logEntry.LoggerName, + Message: logEntry.Message, + Caller: &caller, + Stack: logEntry.Stack, + Fields: fields, + } +} + +// Fragment stores the information of a fragment. +type Fragment struct { + ID string + Name string + Fragment *map[string]interface{} + OrganizationOwner string + Public bool + CreatedOn *timestamppb.Timestamp + OrganizationName string + RobotPartCount int32 + OrganizationCount int32 + OnlyUsedByOwner bool + Visibility FragmentVisibility + LastUpdated *timestamppb.Timestamp +} + +func fragmentFromProto(fragment *pb.Fragment) *Fragment { + f := fragment.Fragment.AsMap() + return &Fragment{ + ID: fragment.Id, + Name: fragment.Name, + Fragment: &f, + OrganizationOwner: fragment.OrganizationOwner, + Public: fragment.Public, + CreatedOn: fragment.CreatedOn, + OrganizationName: fragment.OrganizationName, + RobotPartCount: fragment.RobotPartCount, + OrganizationCount: fragment.OrganizationCount, + OnlyUsedByOwner: fragment.OnlyUsedByOwner, + Visibility: fragmentVisibilityFromProto(fragment.Visibility), + LastUpdated: fragment.LastUpdated, + } +} + +// FragmentVisibility specifies the kind of visibility a fragment has. +type FragmentVisibility int32 + +const ( + // FragmentVisibilityUnspecified is an unspecified visibility. + FragmentVisibilityUnspecified FragmentVisibility = iota + // FragmentVisibilityPrivate restricts access to a fragment to its organization. + FragmentVisibilityPrivate + // FragmentVisibilityPublic allows the fragment to be accessible to everyone. + FragmentVisibilityPublic + // FragmentVisibilityPublicUnlisted allows the fragment to be accessible to everyone but is hidden from public listings like it is private. + FragmentVisibilityPublicUnlisted +) + +func fragmentVisibilityFromProto(visibility pb.FragmentVisibility) FragmentVisibility { + switch visibility { + case pb.FragmentVisibility_FRAGMENT_VISIBILITY_UNSPECIFIED: + return FragmentVisibilityUnspecified + case pb.FragmentVisibility_FRAGMENT_VISIBILITY_PRIVATE: + return FragmentVisibilityPrivate + case pb.FragmentVisibility_FRAGMENT_VISIBILITY_PUBLIC: + return FragmentVisibilityPublic + case pb.FragmentVisibility_FRAGMENT_VISIBILITY_PUBLIC_UNLISTED: + return FragmentVisibilityPublicUnlisted + } + return FragmentVisibilityUnspecified +} + +func fragmentVisibilityToProto(visibility FragmentVisibility) pb.FragmentVisibility { + switch visibility { + case FragmentVisibilityUnspecified: + return pb.FragmentVisibility_FRAGMENT_VISIBILITY_UNSPECIFIED + case FragmentVisibilityPrivate: + return pb.FragmentVisibility_FRAGMENT_VISIBILITY_PRIVATE + case FragmentVisibilityPublic: + return pb.FragmentVisibility_FRAGMENT_VISIBILITY_PUBLIC + case FragmentVisibilityPublicUnlisted: + return pb.FragmentVisibility_FRAGMENT_VISIBILITY_PUBLIC_UNLISTED + } + return pb.FragmentVisibility_FRAGMENT_VISIBILITY_UNSPECIFIED +} + +// FragmentHistoryEntry is an entry of a fragment's history. +type FragmentHistoryEntry struct { + Fragment string + EditedOn *timestamppb.Timestamp + Old *Fragment + EditedBy *AuthenticatorInfo +} + +func fragmentHistoryEntryFromProto(entry *pb.FragmentHistoryEntry) *FragmentHistoryEntry { + return &FragmentHistoryEntry{ + Fragment: entry.Fragment, + EditedOn: entry.EditedOn, + Old: fragmentFromProto(entry.Old), + EditedBy: authenticatorInfoFromProto(entry.EditedBy), + } +} From d8ece72967c1e661e429af9c2f990c8dd472a7d8 Mon Sep 17 00:00:00 2001 From: purplenicole730 Date: Mon, 18 Nov 2024 14:18:59 -0500 Subject: [PATCH 49/75] consolidate even further --- app/resource_type.go | 225 +++++++++++++++++++++++++++++++++++++++++ app/robot.go | 231 ------------------------------------------- 2 files changed, 225 insertions(+), 231 deletions(-) delete mode 100644 app/robot.go diff --git a/app/resource_type.go b/app/resource_type.go index 0611508da06..4c4063701fe 100644 --- a/app/resource_type.go +++ b/app/resource_type.go @@ -2,6 +2,7 @@ package app import ( pb "go.viam.com/api/app/v1" + common "go.viam.com/api/common/v1" "google.golang.org/protobuf/types/known/timestamppb" ) @@ -175,3 +176,227 @@ func locationAuthFromProto(locationAuth *pb.LocationAuth) *LocationAuth { Secrets: secrets, } } + +// Robot holds the information of a machine. +type Robot struct { + ID string + Name string + Location string + LastAccess *timestamppb.Timestamp + CreatedOn *timestamppb.Timestamp +} + +func robotFromProto(robot *pb.Robot) *Robot { + return &Robot{ + ID: robot.Id, + Name: robot.Name, + Location: robot.Location, + LastAccess: robot.LastAccess, + CreatedOn: robot.CreatedOn, + } +} + +// RoverRentalRobot holds the information of a rover rental robot. +type RoverRentalRobot struct { + RobotID string + LocationID string + RobotName string + RobotMainPartID string +} + +func roverRentalRobotFromProto(rrRobot *pb.RoverRentalRobot) *RoverRentalRobot { + return &RoverRentalRobot{ + RobotID: rrRobot.RobotId, + LocationID: rrRobot.LocationId, + RobotName: rrRobot.RobotName, + RobotMainPartID: rrRobot.RobotMainPartId, + } +} + +// RobotPart is a specific machine part. +type RobotPart struct { + ID string + Name string + DNSName string + Secret string + Robot string + LocationID string + RobotConfig *map[string]interface{} + LastAccess *timestamppb.Timestamp + UserSuppliedInfo *map[string]interface{} + MainPart bool + FQDN string + LocalFQDN string + CreatedOn *timestamppb.Timestamp + Secrets []*SharedSecret + LastUpdated *timestamppb.Timestamp +} + +func robotPartFromProto(robotPart *pb.RobotPart) *RobotPart { + var secrets []*SharedSecret + for _, secret := range robotPart.Secrets { + secrets = append(secrets, sharedSecretFromProto(secret)) + } + cfg := robotPart.RobotConfig.AsMap() + info := robotPart.UserSuppliedInfo.AsMap() + return &RobotPart{ + ID: robotPart.Id, + Name: robotPart.Name, + DNSName: robotPart.DnsName, + Secret: robotPart.Secret, + Robot: robotPart.Robot, + LocationID: robotPart.LocationId, + RobotConfig: &cfg, + LastAccess: robotPart.LastAccess, + UserSuppliedInfo: &info, + MainPart: robotPart.MainPart, + FQDN: robotPart.Fqdn, + LocalFQDN: robotPart.LocalFqdn, + CreatedOn: robotPart.CreatedOn, + Secrets: secrets, + LastUpdated: robotPart.LastUpdated, + } +} + +// RobotPartHistoryEntry is a history entry of a robot part. +type RobotPartHistoryEntry struct { + Part string + Robot string + When *timestamppb.Timestamp + Old *RobotPart + EditedBy *AuthenticatorInfo +} + +func robotPartHistoryEntryFromProto(entry *pb.RobotPartHistoryEntry) *RobotPartHistoryEntry { + return &RobotPartHistoryEntry{ + Part: entry.Part, + Robot: entry.Robot, + When: entry.When, + Old: robotPartFromProto(entry.Old), + EditedBy: authenticatorInfoFromProto(entry.EditedBy), + } +} + +// LogEntry holds the information of a single log entry. +type LogEntry struct { + Host string + Level string + Time *timestamppb.Timestamp + LoggerName string + Message string + Caller *map[string]interface{} + Stack string + Fields []*map[string]interface{} +} + +func logEntryFromProto(logEntry *common.LogEntry) *LogEntry { + var fields []*map[string]interface{} + for _, field := range logEntry.Fields { + f := field.AsMap() + fields = append(fields, &f) + } + caller := logEntry.Caller.AsMap() + return &LogEntry{ + Host: logEntry.Host, + Level: logEntry.Level, + Time: logEntry.Time, + LoggerName: logEntry.LoggerName, + Message: logEntry.Message, + Caller: &caller, + Stack: logEntry.Stack, + Fields: fields, + } +} + +// Fragment stores the information of a fragment. +type Fragment struct { + ID string + Name string + Fragment *map[string]interface{} + OrganizationOwner string + Public bool + CreatedOn *timestamppb.Timestamp + OrganizationName string + RobotPartCount int32 + OrganizationCount int32 + OnlyUsedByOwner bool + Visibility FragmentVisibility + LastUpdated *timestamppb.Timestamp +} + +func fragmentFromProto(fragment *pb.Fragment) *Fragment { + f := fragment.Fragment.AsMap() + return &Fragment{ + ID: fragment.Id, + Name: fragment.Name, + Fragment: &f, + OrganizationOwner: fragment.OrganizationOwner, + Public: fragment.Public, + CreatedOn: fragment.CreatedOn, + OrganizationName: fragment.OrganizationName, + RobotPartCount: fragment.RobotPartCount, + OrganizationCount: fragment.OrganizationCount, + OnlyUsedByOwner: fragment.OnlyUsedByOwner, + Visibility: fragmentVisibilityFromProto(fragment.Visibility), + LastUpdated: fragment.LastUpdated, + } +} + +// FragmentVisibility specifies the kind of visibility a fragment has. +type FragmentVisibility int32 + +const ( + // FragmentVisibilityUnspecified is an unspecified visibility. + FragmentVisibilityUnspecified FragmentVisibility = iota + // FragmentVisibilityPrivate restricts access to a fragment to its organization. + FragmentVisibilityPrivate + // FragmentVisibilityPublic allows the fragment to be accessible to everyone. + FragmentVisibilityPublic + // FragmentVisibilityPublicUnlisted allows the fragment to be accessible to everyone but is hidden from public listings like it is private. + FragmentVisibilityPublicUnlisted +) + +func fragmentVisibilityFromProto(visibility pb.FragmentVisibility) FragmentVisibility { + switch visibility { + case pb.FragmentVisibility_FRAGMENT_VISIBILITY_UNSPECIFIED: + return FragmentVisibilityUnspecified + case pb.FragmentVisibility_FRAGMENT_VISIBILITY_PRIVATE: + return FragmentVisibilityPrivate + case pb.FragmentVisibility_FRAGMENT_VISIBILITY_PUBLIC: + return FragmentVisibilityPublic + case pb.FragmentVisibility_FRAGMENT_VISIBILITY_PUBLIC_UNLISTED: + return FragmentVisibilityPublicUnlisted + } + return FragmentVisibilityUnspecified +} + +func fragmentVisibilityToProto(visibility FragmentVisibility) pb.FragmentVisibility { + switch visibility { + case FragmentVisibilityUnspecified: + return pb.FragmentVisibility_FRAGMENT_VISIBILITY_UNSPECIFIED + case FragmentVisibilityPrivate: + return pb.FragmentVisibility_FRAGMENT_VISIBILITY_PRIVATE + case FragmentVisibilityPublic: + return pb.FragmentVisibility_FRAGMENT_VISIBILITY_PUBLIC + case FragmentVisibilityPublicUnlisted: + return pb.FragmentVisibility_FRAGMENT_VISIBILITY_PUBLIC_UNLISTED + } + return pb.FragmentVisibility_FRAGMENT_VISIBILITY_UNSPECIFIED +} + +// FragmentHistoryEntry is an entry of a fragment's history. +type FragmentHistoryEntry struct { + Fragment string + EditedOn *timestamppb.Timestamp + Old *Fragment + EditedBy *AuthenticatorInfo +} + +func fragmentHistoryEntryFromProto(entry *pb.FragmentHistoryEntry) *FragmentHistoryEntry { + return &FragmentHistoryEntry{ + Fragment: entry.Fragment, + EditedOn: entry.EditedOn, + Old: fragmentFromProto(entry.Old), + EditedBy: authenticatorInfoFromProto(entry.EditedBy), + } +} diff --git a/app/robot.go b/app/robot.go deleted file mode 100644 index 77ecf07f725..00000000000 --- a/app/robot.go +++ /dev/null @@ -1,231 +0,0 @@ -package app - -import ( - pb "go.viam.com/api/app/v1" - common "go.viam.com/api/common/v1" - "google.golang.org/protobuf/types/known/timestamppb" -) - -// Robot holds the information of a machine. -type Robot struct { - ID string - Name string - Location string - LastAccess *timestamppb.Timestamp - CreatedOn *timestamppb.Timestamp -} - -func robotFromProto(robot *pb.Robot) *Robot { - return &Robot{ - ID: robot.Id, - Name: robot.Name, - Location: robot.Location, - LastAccess: robot.LastAccess, - CreatedOn: robot.CreatedOn, - } -} - -// RoverRentalRobot holds the information of a rover rental robot. -type RoverRentalRobot struct { - RobotID string - LocationID string - RobotName string - RobotMainPartID string -} - -func roverRentalRobotFromProto(rrRobot *pb.RoverRentalRobot) *RoverRentalRobot { - return &RoverRentalRobot{ - RobotID: rrRobot.RobotId, - LocationID: rrRobot.LocationId, - RobotName: rrRobot.RobotName, - RobotMainPartID: rrRobot.RobotMainPartId, - } -} - -// RobotPart is a specific machine part. -type RobotPart struct { - ID string - Name string - DNSName string - Secret string - Robot string - LocationID string - RobotConfig *map[string]interface{} - LastAccess *timestamppb.Timestamp - UserSuppliedInfo *map[string]interface{} - MainPart bool - FQDN string - LocalFQDN string - CreatedOn *timestamppb.Timestamp - Secrets []*SharedSecret - LastUpdated *timestamppb.Timestamp -} - -func robotPartFromProto(robotPart *pb.RobotPart) *RobotPart { - var secrets []*SharedSecret - for _, secret := range robotPart.Secrets { - secrets = append(secrets, sharedSecretFromProto(secret)) - } - cfg := robotPart.RobotConfig.AsMap() - info := robotPart.UserSuppliedInfo.AsMap() - return &RobotPart{ - ID: robotPart.Id, - Name: robotPart.Name, - DNSName: robotPart.DnsName, - Secret: robotPart.Secret, - Robot: robotPart.Robot, - LocationID: robotPart.LocationId, - RobotConfig: &cfg, - LastAccess: robotPart.LastAccess, - UserSuppliedInfo: &info, - MainPart: robotPart.MainPart, - FQDN: robotPart.Fqdn, - LocalFQDN: robotPart.LocalFqdn, - CreatedOn: robotPart.CreatedOn, - Secrets: secrets, - LastUpdated: robotPart.LastUpdated, - } -} - -// RobotPartHistoryEntry is a history entry of a robot part. -type RobotPartHistoryEntry struct { - Part string - Robot string - When *timestamppb.Timestamp - Old *RobotPart - EditedBy *AuthenticatorInfo -} - -func robotPartHistoryEntryFromProto(entry *pb.RobotPartHistoryEntry) *RobotPartHistoryEntry { - return &RobotPartHistoryEntry{ - Part: entry.Part, - Robot: entry.Robot, - When: entry.When, - Old: robotPartFromProto(entry.Old), - EditedBy: authenticatorInfoFromProto(entry.EditedBy), - } -} - -// LogEntry holds the information of a single log entry. -type LogEntry struct { - Host string - Level string - Time *timestamppb.Timestamp - LoggerName string - Message string - Caller *map[string]interface{} - Stack string - Fields []*map[string]interface{} -} - -func logEntryFromProto(logEntry *common.LogEntry) *LogEntry { - var fields []*map[string]interface{} - for _, field := range logEntry.Fields { - f := field.AsMap() - fields = append(fields, &f) - } - caller := logEntry.Caller.AsMap() - return &LogEntry{ - Host: logEntry.Host, - Level: logEntry.Level, - Time: logEntry.Time, - LoggerName: logEntry.LoggerName, - Message: logEntry.Message, - Caller: &caller, - Stack: logEntry.Stack, - Fields: fields, - } -} - -// Fragment stores the information of a fragment. -type Fragment struct { - ID string - Name string - Fragment *map[string]interface{} - OrganizationOwner string - Public bool - CreatedOn *timestamppb.Timestamp - OrganizationName string - RobotPartCount int32 - OrganizationCount int32 - OnlyUsedByOwner bool - Visibility FragmentVisibility - LastUpdated *timestamppb.Timestamp -} - -func fragmentFromProto(fragment *pb.Fragment) *Fragment { - f := fragment.Fragment.AsMap() - return &Fragment{ - ID: fragment.Id, - Name: fragment.Name, - Fragment: &f, - OrganizationOwner: fragment.OrganizationOwner, - Public: fragment.Public, - CreatedOn: fragment.CreatedOn, - OrganizationName: fragment.OrganizationName, - RobotPartCount: fragment.RobotPartCount, - OrganizationCount: fragment.OrganizationCount, - OnlyUsedByOwner: fragment.OnlyUsedByOwner, - Visibility: fragmentVisibilityFromProto(fragment.Visibility), - LastUpdated: fragment.LastUpdated, - } -} - -// FragmentVisibility specifies the kind of visibility a fragment has. -type FragmentVisibility int32 - -const ( - // FragmentVisibilityUnspecified is an unspecified visibility. - FragmentVisibilityUnspecified FragmentVisibility = iota - // FragmentVisibilityPrivate restricts access to a fragment to its organization. - FragmentVisibilityPrivate - // FragmentVisibilityPublic allows the fragment to be accessible to everyone. - FragmentVisibilityPublic - // FragmentVisibilityPublicUnlisted allows the fragment to be accessible to everyone but is hidden from public listings like it is private. - FragmentVisibilityPublicUnlisted -) - -func fragmentVisibilityFromProto(visibility pb.FragmentVisibility) FragmentVisibility { - switch visibility { - case pb.FragmentVisibility_FRAGMENT_VISIBILITY_UNSPECIFIED: - return FragmentVisibilityUnspecified - case pb.FragmentVisibility_FRAGMENT_VISIBILITY_PRIVATE: - return FragmentVisibilityPrivate - case pb.FragmentVisibility_FRAGMENT_VISIBILITY_PUBLIC: - return FragmentVisibilityPublic - case pb.FragmentVisibility_FRAGMENT_VISIBILITY_PUBLIC_UNLISTED: - return FragmentVisibilityPublicUnlisted - } - return FragmentVisibilityUnspecified -} - -func fragmentVisibilityToProto(visibility FragmentVisibility) pb.FragmentVisibility { - switch visibility { - case FragmentVisibilityUnspecified: - return pb.FragmentVisibility_FRAGMENT_VISIBILITY_UNSPECIFIED - case FragmentVisibilityPrivate: - return pb.FragmentVisibility_FRAGMENT_VISIBILITY_PRIVATE - case FragmentVisibilityPublic: - return pb.FragmentVisibility_FRAGMENT_VISIBILITY_PUBLIC - case FragmentVisibilityPublicUnlisted: - return pb.FragmentVisibility_FRAGMENT_VISIBILITY_PUBLIC_UNLISTED - } - return pb.FragmentVisibility_FRAGMENT_VISIBILITY_UNSPECIFIED -} - -// FragmentHistoryEntry is an entry of a fragment's history. -type FragmentHistoryEntry struct { - Fragment string - EditedOn *timestamppb.Timestamp - Old *Fragment - EditedBy *AuthenticatorInfo -} - -func fragmentHistoryEntryFromProto(entry *pb.FragmentHistoryEntry) *FragmentHistoryEntry { - return &FragmentHistoryEntry{ - Fragment: entry.Fragment, - EditedOn: entry.EditedOn, - Old: fragmentFromProto(entry.Old), - EditedBy: authenticatorInfoFromProto(entry.EditedBy), - } -} From 167aeeca276c4529815902308e520362c97213d1 Mon Sep 17 00:00:00 2001 From: purplenicole730 Date: Mon, 18 Nov 2024 14:20:05 -0500 Subject: [PATCH 50/75] consolidate everything related to resource --- app/authorization.go | 235 -------------------------- app/{resource_type.go => resource.go} | 230 +++++++++++++++++++++++++ 2 files changed, 230 insertions(+), 235 deletions(-) delete mode 100644 app/authorization.go rename app/{resource_type.go => resource.go} (61%) diff --git a/app/authorization.go b/app/authorization.go deleted file mode 100644 index 895ac0c53af..00000000000 --- a/app/authorization.go +++ /dev/null @@ -1,235 +0,0 @@ -package app - -import ( - "errors" - "fmt" - - pb "go.viam.com/api/app/v1" - "google.golang.org/protobuf/types/known/timestamppb" -) - -// Authorization has the information about a specific authorization. -type Authorization struct { - AuthorizationType string - AuthorizationID string - ResourceType string - ResourceID string - IdentityID string - OrganizationID string - IdentityType string -} - -func authorizationFromProto(authorization *pb.Authorization) *Authorization { - return &Authorization{ - AuthorizationType: authorization.AuthorizationType, - AuthorizationID: authorization.AuthorizationId, - ResourceType: authorization.ResourceType, - ResourceID: authorization.ResourceId, - IdentityID: authorization.IdentityId, - OrganizationID: authorization.OrganizationId, - IdentityType: authorization.IdentityType, - } -} - -func authorizationToProto(authorization *Authorization) *pb.Authorization { - return &pb.Authorization{ - AuthorizationType: authorization.AuthorizationType, - AuthorizationId: authorization.AuthorizationID, - ResourceType: authorization.ResourceType, - ResourceId: authorization.ResourceID, - IdentityId: authorization.IdentityID, - OrganizationId: authorization.OrganizationID, - IdentityType: authorization.IdentityType, - } -} - -// AuthorizedPermissions is authorized permissions. -type AuthorizedPermissions struct { - ResourceType string - ResourceID string - Permissions []string -} - -func authorizedPermissionsFromProto(permissions *pb.AuthorizedPermissions) *AuthorizedPermissions { - return &AuthorizedPermissions{ - ResourceType: permissions.ResourceType, - ResourceID: permissions.ResourceId, - Permissions: permissions.Permissions, - } -} - -func authorizedPermissionsToProto(permissions *AuthorizedPermissions) *pb.AuthorizedPermissions { - return &pb.AuthorizedPermissions{ - ResourceType: permissions.ResourceType, - ResourceId: permissions.ResourceID, - Permissions: permissions.Permissions, - } -} - -// APIKeyAuthorization is a struct with the necessary authorization data to create an API key. -type APIKeyAuthorization struct { - // `role`` must be "owner" or "operator" - role string - // `resourceType` must be "organization", "location", or "robot" - resourceType string - resourceID string -} - -func createAuthorization(orgID, identityID, identityType, role, resourceType, resourceID string) (*pb.Authorization, error) { - if role != "owner" && role != "operator" { - return nil, errors.New("role string must be 'owner' or 'operator'") - } - if resourceType != "organization" && resourceType != "location" && resourceType != "robot" { - return nil, errors.New("resourceType must be 'organization', 'location', or 'robot'") - } - - return &pb.Authorization{ - AuthorizationType: role, - AuthorizationId: fmt.Sprintf("%s_%s", resourceType, role), - ResourceType: resourceType, - ResourceId: resourceID, - IdentityId: identityID, - OrganizationId: orgID, - IdentityType: identityType, - }, nil -} - -// SharedSecret is a secret used for LocationAuth and RobotParts. -type SharedSecret struct { - ID string - CreatedOn *timestamppb.Timestamp - State SharedSecretState -} - -func sharedSecretFromProto(sharedSecret *pb.SharedSecret) *SharedSecret { - return &SharedSecret{ - ID: sharedSecret.Id, - CreatedOn: sharedSecret.CreatedOn, - State: sharedSecretStateFromProto(sharedSecret.State), - } -} - -// SharedSecretState specifies if the secret is enabled, disabled, or unspecified. -type SharedSecretState int32 - -const ( - // SharedSecretStateUnspecified represents an unspecified shared secret state. - SharedSecretStateUnspecified SharedSecretState = iota - // SharedSecretStateEnabled represents an enabled secret that can be used in authentication. - SharedSecretStateEnabled - // SharedSecretStateDisabled represents a disabled secret that must not be used to authenticate to rpc. - SharedSecretStateDisabled -) - -func sharedSecretStateFromProto(state pb.SharedSecret_State) SharedSecretState { - switch state { - case pb.SharedSecret_STATE_UNSPECIFIED: - return SharedSecretStateUnspecified - case pb.SharedSecret_STATE_ENABLED: - return SharedSecretStateEnabled - case pb.SharedSecret_STATE_DISABLED: - return SharedSecretStateDisabled - default: - return SharedSecretStateUnspecified - } -} - -// AuthenticatorInfo holds the information of an authenticator. -type AuthenticatorInfo struct { - Type AuthenticationType - Value string - IsDeactivated bool -} - -func authenticatorInfoFromProto(info *pb.AuthenticatorInfo) *AuthenticatorInfo { - return &AuthenticatorInfo{ - Type: authenticationTypeFromProto(info.Type), - Value: info.Value, - IsDeactivated: info.IsDeactivated, - } -} - -// AuthenticationType specifies the type of authentication. -type AuthenticationType int32 - -const ( - // AuthenticationTypeUnspecified represents an unspecified authentication. - AuthenticationTypeUnspecified AuthenticationType = iota - // AuthenticationTypeWebOAuth represents authentication using Web OAuth. - AuthenticationTypeWebOAuth - // AuthenticationTypeAPIKey represents authentication using an API key. - AuthenticationTypeAPIKey - // AuthenticationTypeRobotPartSecret represents authentication using a robot part secret. - AuthenticationTypeRobotPartSecret - // AuthenticationTypeLocationSecret represents authentication using a location secret. - AuthenticationTypeLocationSecret -) - -func authenticationTypeFromProto(authenticationType pb.AuthenticationType) AuthenticationType { - switch authenticationType { - case pb.AuthenticationType_AUTHENTICATION_TYPE_UNSPECIFIED: - return AuthenticationTypeUnspecified - case pb.AuthenticationType_AUTHENTICATION_TYPE_WEB_OAUTH: - return AuthenticationTypeWebOAuth - case pb.AuthenticationType_AUTHENTICATION_TYPE_API_KEY: - return AuthenticationTypeAPIKey - case pb.AuthenticationType_AUTHENTICATION_TYPE_ROBOT_PART_SECRET: - return AuthenticationTypeRobotPartSecret - case pb.AuthenticationType_AUTHENTICATION_TYPE_LOCATION_SECRET: - return AuthenticationTypeLocationSecret - } - return AuthenticationTypeUnspecified -} - -// APIKeyWithAuthorizations is an API Key with its authorizations. -type APIKeyWithAuthorizations struct { - APIKey *APIKey - Authorizations []*AuthorizationDetails -} - -func apiKeyWithAuthorizationsFromProto(key *pb.APIKeyWithAuthorizations) *APIKeyWithAuthorizations { - var details []*AuthorizationDetails - for _, detail := range key.Authorizations { - details = append(details, authorizationDetailsFromProto(detail)) - } - return &APIKeyWithAuthorizations{ - APIKey: apiKeyFromProto(key.ApiKey), - Authorizations: details, - } -} - -// APIKey is a API key to make a request to an API. -type APIKey struct { - ID string - Key string - Name string - CreatedOn *timestamppb.Timestamp -} - -func apiKeyFromProto(key *pb.APIKey) *APIKey { - return &APIKey{ - ID: key.Id, - Key: key.Key, - Name: key.Name, - CreatedOn: key.CreatedOn, - } -} - -// AuthorizationDetails has the details for an authorization. -type AuthorizationDetails struct { - AuthorizationType string - AuthorizationID string - ResourceType string - ResourceID string - OrgID string -} - -func authorizationDetailsFromProto(details *pb.AuthorizationDetails) *AuthorizationDetails { - return &AuthorizationDetails{ - AuthorizationType: details.AuthorizationType, - AuthorizationID: details.AuthorizationId, - ResourceType: details.ResourceType, - ResourceID: details.ResourceId, - OrgID: details.OrgId, - } -} diff --git a/app/resource_type.go b/app/resource.go similarity index 61% rename from app/resource_type.go rename to app/resource.go index 4c4063701fe..e8b67ba8a6e 100644 --- a/app/resource_type.go +++ b/app/resource.go @@ -1,6 +1,9 @@ package app import ( + "errors" + "fmt" + pb "go.viam.com/api/app/v1" common "go.viam.com/api/common/v1" "google.golang.org/protobuf/types/known/timestamppb" @@ -400,3 +403,230 @@ func fragmentHistoryEntryFromProto(entry *pb.FragmentHistoryEntry) *FragmentHist EditedBy: authenticatorInfoFromProto(entry.EditedBy), } } + + +// Authorization has the information about a specific authorization. +type Authorization struct { + AuthorizationType string + AuthorizationID string + ResourceType string + ResourceID string + IdentityID string + OrganizationID string + IdentityType string +} + +func authorizationFromProto(authorization *pb.Authorization) *Authorization { + return &Authorization{ + AuthorizationType: authorization.AuthorizationType, + AuthorizationID: authorization.AuthorizationId, + ResourceType: authorization.ResourceType, + ResourceID: authorization.ResourceId, + IdentityID: authorization.IdentityId, + OrganizationID: authorization.OrganizationId, + IdentityType: authorization.IdentityType, + } +} + +func authorizationToProto(authorization *Authorization) *pb.Authorization { + return &pb.Authorization{ + AuthorizationType: authorization.AuthorizationType, + AuthorizationId: authorization.AuthorizationID, + ResourceType: authorization.ResourceType, + ResourceId: authorization.ResourceID, + IdentityId: authorization.IdentityID, + OrganizationId: authorization.OrganizationID, + IdentityType: authorization.IdentityType, + } +} + +// AuthorizedPermissions is authorized permissions. +type AuthorizedPermissions struct { + ResourceType string + ResourceID string + Permissions []string +} + +func authorizedPermissionsFromProto(permissions *pb.AuthorizedPermissions) *AuthorizedPermissions { + return &AuthorizedPermissions{ + ResourceType: permissions.ResourceType, + ResourceID: permissions.ResourceId, + Permissions: permissions.Permissions, + } +} + +func authorizedPermissionsToProto(permissions *AuthorizedPermissions) *pb.AuthorizedPermissions { + return &pb.AuthorizedPermissions{ + ResourceType: permissions.ResourceType, + ResourceId: permissions.ResourceID, + Permissions: permissions.Permissions, + } +} + +// APIKeyAuthorization is a struct with the necessary authorization data to create an API key. +type APIKeyAuthorization struct { + // `role`` must be "owner" or "operator" + role string + // `resourceType` must be "organization", "location", or "robot" + resourceType string + resourceID string +} + +func createAuthorization(orgID, identityID, identityType, role, resourceType, resourceID string) (*pb.Authorization, error) { + if role != "owner" && role != "operator" { + return nil, errors.New("role string must be 'owner' or 'operator'") + } + if resourceType != "organization" && resourceType != "location" && resourceType != "robot" { + return nil, errors.New("resourceType must be 'organization', 'location', or 'robot'") + } + + return &pb.Authorization{ + AuthorizationType: role, + AuthorizationId: fmt.Sprintf("%s_%s", resourceType, role), + ResourceType: resourceType, + ResourceId: resourceID, + IdentityId: identityID, + OrganizationId: orgID, + IdentityType: identityType, + }, nil +} + +// SharedSecret is a secret used for LocationAuth and RobotParts. +type SharedSecret struct { + ID string + CreatedOn *timestamppb.Timestamp + State SharedSecretState +} + +func sharedSecretFromProto(sharedSecret *pb.SharedSecret) *SharedSecret { + return &SharedSecret{ + ID: sharedSecret.Id, + CreatedOn: sharedSecret.CreatedOn, + State: sharedSecretStateFromProto(sharedSecret.State), + } +} + +// SharedSecretState specifies if the secret is enabled, disabled, or unspecified. +type SharedSecretState int32 + +const ( + // SharedSecretStateUnspecified represents an unspecified shared secret state. + SharedSecretStateUnspecified SharedSecretState = iota + // SharedSecretStateEnabled represents an enabled secret that can be used in authentication. + SharedSecretStateEnabled + // SharedSecretStateDisabled represents a disabled secret that must not be used to authenticate to rpc. + SharedSecretStateDisabled +) + +func sharedSecretStateFromProto(state pb.SharedSecret_State) SharedSecretState { + switch state { + case pb.SharedSecret_STATE_UNSPECIFIED: + return SharedSecretStateUnspecified + case pb.SharedSecret_STATE_ENABLED: + return SharedSecretStateEnabled + case pb.SharedSecret_STATE_DISABLED: + return SharedSecretStateDisabled + default: + return SharedSecretStateUnspecified + } +} + +// AuthenticatorInfo holds the information of an authenticator. +type AuthenticatorInfo struct { + Type AuthenticationType + Value string + IsDeactivated bool +} + +func authenticatorInfoFromProto(info *pb.AuthenticatorInfo) *AuthenticatorInfo { + return &AuthenticatorInfo{ + Type: authenticationTypeFromProto(info.Type), + Value: info.Value, + IsDeactivated: info.IsDeactivated, + } +} + +// AuthenticationType specifies the type of authentication. +type AuthenticationType int32 + +const ( + // AuthenticationTypeUnspecified represents an unspecified authentication. + AuthenticationTypeUnspecified AuthenticationType = iota + // AuthenticationTypeWebOAuth represents authentication using Web OAuth. + AuthenticationTypeWebOAuth + // AuthenticationTypeAPIKey represents authentication using an API key. + AuthenticationTypeAPIKey + // AuthenticationTypeRobotPartSecret represents authentication using a robot part secret. + AuthenticationTypeRobotPartSecret + // AuthenticationTypeLocationSecret represents authentication using a location secret. + AuthenticationTypeLocationSecret +) + +func authenticationTypeFromProto(authenticationType pb.AuthenticationType) AuthenticationType { + switch authenticationType { + case pb.AuthenticationType_AUTHENTICATION_TYPE_UNSPECIFIED: + return AuthenticationTypeUnspecified + case pb.AuthenticationType_AUTHENTICATION_TYPE_WEB_OAUTH: + return AuthenticationTypeWebOAuth + case pb.AuthenticationType_AUTHENTICATION_TYPE_API_KEY: + return AuthenticationTypeAPIKey + case pb.AuthenticationType_AUTHENTICATION_TYPE_ROBOT_PART_SECRET: + return AuthenticationTypeRobotPartSecret + case pb.AuthenticationType_AUTHENTICATION_TYPE_LOCATION_SECRET: + return AuthenticationTypeLocationSecret + } + return AuthenticationTypeUnspecified +} + +// APIKeyWithAuthorizations is an API Key with its authorizations. +type APIKeyWithAuthorizations struct { + APIKey *APIKey + Authorizations []*AuthorizationDetails +} + +func apiKeyWithAuthorizationsFromProto(key *pb.APIKeyWithAuthorizations) *APIKeyWithAuthorizations { + var details []*AuthorizationDetails + for _, detail := range key.Authorizations { + details = append(details, authorizationDetailsFromProto(detail)) + } + return &APIKeyWithAuthorizations{ + APIKey: apiKeyFromProto(key.ApiKey), + Authorizations: details, + } +} + +// APIKey is a API key to make a request to an API. +type APIKey struct { + ID string + Key string + Name string + CreatedOn *timestamppb.Timestamp +} + +func apiKeyFromProto(key *pb.APIKey) *APIKey { + return &APIKey{ + ID: key.Id, + Key: key.Key, + Name: key.Name, + CreatedOn: key.CreatedOn, + } +} + +// AuthorizationDetails has the details for an authorization. +type AuthorizationDetails struct { + AuthorizationType string + AuthorizationID string + ResourceType string + ResourceID string + OrgID string +} + +func authorizationDetailsFromProto(details *pb.AuthorizationDetails) *AuthorizationDetails { + return &AuthorizationDetails{ + AuthorizationType: details.AuthorizationType, + AuthorizationID: details.AuthorizationId, + ResourceType: details.ResourceType, + ResourceID: details.ResourceId, + OrgID: details.OrgId, + } +} From 0c046dfe426485acc9dc54de266c82ccad7fba14 Mon Sep 17 00:00:00 2001 From: purplenicole730 Date: Mon, 18 Nov 2024 14:22:42 -0500 Subject: [PATCH 51/75] rename to resource_types --- app/{resource.go => resource_types.go} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename app/{resource.go => resource_types.go} (100%) diff --git a/app/resource.go b/app/resource_types.go similarity index 100% rename from app/resource.go rename to app/resource_types.go From e0c2d9ffcda6ac43bb06c750cd773d2eab72eb2b Mon Sep 17 00:00:00 2001 From: purplenicole730 Date: Mon, 18 Nov 2024 14:47:22 -0500 Subject: [PATCH 52/75] changes to make it scalable --- app/app_client.go | 168 +++++++++++++++++++++-------------------- app/app_client_test.go | 2 +- app/log_stream.go | 2 +- app/resource_types.go | 2 - app/viam_client.go | 18 +++-- 5 files changed, 101 insertions(+), 91 deletions(-) diff --git a/app/app_client.go b/app/app_client.go index b730bfb15ed..e9381b52c07 100644 --- a/app/app_client.go +++ b/app/app_client.go @@ -16,21 +16,23 @@ import ( "go.viam.com/rdk/logging" ) -// Client is a gRPC client for method calls to the App API. -type Client struct { +// AppClient is a gRPC client for method calls to the App API. +// +//nolint:revive // stutter: Ignore the "stuttering" warning for this type name +type AppClient struct { client pb.AppServiceClient logger logging.Logger mu sync.Mutex } -// NewClientFromConn uses a connection to create a new AppClient. -func NewClientFromConn(conn rpc.ClientConn, logger logging.Logger) Client { - return Client{client: pb.NewAppServiceClient(conn), logger: logger} +// NewAppClient constructs a new AppClient using the connection passed in by the viamClient and the provided logger. +func NewAppClient(conn rpc.ClientConn, logger logging.Logger) *AppClient { + return &AppClient{client: pb.NewAppServiceClient(conn), logger: logger} } // GetUserIDByEmail gets the ID of the user with the given email. -func (c *Client) GetUserIDByEmail(ctx context.Context, email string) (string, error) { +func (c *AppClient) GetUserIDByEmail(ctx context.Context, email string) (string, error) { resp, err := c.client.GetUserIDByEmail(ctx, &pb.GetUserIDByEmailRequest{ Email: email, }) @@ -41,7 +43,7 @@ func (c *Client) GetUserIDByEmail(ctx context.Context, email string) (string, er } // CreateOrganization creates a new organization. -func (c *Client) CreateOrganization(ctx context.Context, name string) (*Organization, error) { +func (c *AppClient) CreateOrganization(ctx context.Context, name string) (*Organization, error) { resp, err := c.client.CreateOrganization(ctx, &pb.CreateOrganizationRequest{ Name: name, }) @@ -52,7 +54,7 @@ func (c *Client) CreateOrganization(ctx context.Context, name string) (*Organiza } // ListOrganizations lists all the organizations. -func (c *Client) ListOrganizations(ctx context.Context) ([]*Organization, error) { +func (c *AppClient) ListOrganizations(ctx context.Context) ([]*Organization, error) { resp, err := c.client.ListOrganizations(ctx, &pb.ListOrganizationsRequest{}) if err != nil { return nil, err @@ -66,7 +68,7 @@ func (c *Client) ListOrganizations(ctx context.Context) ([]*Organization, error) } // GetOrganizationsWithAccessToLocation gets all the organizations that have access to a location. -func (c *Client) GetOrganizationsWithAccessToLocation(ctx context.Context, locationID string) ([]*OrganizationIdentity, error) { +func (c *AppClient) GetOrganizationsWithAccessToLocation(ctx context.Context, locationID string) ([]*OrganizationIdentity, error) { resp, err := c.client.GetOrganizationsWithAccessToLocation(ctx, &pb.GetOrganizationsWithAccessToLocationRequest{ LocationId: locationID, }) @@ -82,7 +84,7 @@ func (c *Client) GetOrganizationsWithAccessToLocation(ctx context.Context, locat } // ListOrganizationsByUser lists all the organizations that a user belongs to. -func (c *Client) ListOrganizationsByUser(ctx context.Context, userID string) ([]*OrgDetails, error) { +func (c *AppClient) ListOrganizationsByUser(ctx context.Context, userID string) ([]*OrgDetails, error) { resp, err := c.client.ListOrganizationsByUser(ctx, &pb.ListOrganizationsByUserRequest{ UserId: userID, }) @@ -98,7 +100,7 @@ func (c *Client) ListOrganizationsByUser(ctx context.Context, userID string) ([] } // GetOrganization gets an organization. -func (c *Client) GetOrganization(ctx context.Context, orgID string) (*Organization, error) { +func (c *AppClient) GetOrganization(ctx context.Context, orgID string) (*Organization, error) { resp, err := c.client.GetOrganization(ctx, &pb.GetOrganizationRequest{ OrganizationId: orgID, }) @@ -109,7 +111,7 @@ func (c *Client) GetOrganization(ctx context.Context, orgID string) (*Organizati } // GetOrganizationNamespaceAvailability checks for namespace availability throughout all organizations. -func (c *Client) GetOrganizationNamespaceAvailability(ctx context.Context, namespace string) (bool, error) { +func (c *AppClient) GetOrganizationNamespaceAvailability(ctx context.Context, namespace string) (bool, error) { resp, err := c.client.GetOrganizationNamespaceAvailability(ctx, &pb.GetOrganizationNamespaceAvailabilityRequest{ PublicNamespace: namespace, }) @@ -120,7 +122,7 @@ func (c *Client) GetOrganizationNamespaceAvailability(ctx context.Context, names } // UpdateOrganization updates an organization. -func (c *Client) UpdateOrganization(ctx context.Context, orgID string, name, namespace, region, cid *string) (*Organization, error) { +func (c *AppClient) UpdateOrganization(ctx context.Context, orgID string, name, namespace, region, cid *string) (*Organization, error) { resp, err := c.client.UpdateOrganization(ctx, &pb.UpdateOrganizationRequest{ OrganizationId: orgID, Name: name, @@ -135,7 +137,7 @@ func (c *Client) UpdateOrganization(ctx context.Context, orgID string, name, nam } // DeleteOrganization deletes an organization. -func (c *Client) DeleteOrganization(ctx context.Context, orgID string) error { +func (c *AppClient) DeleteOrganization(ctx context.Context, orgID string) error { _, err := c.client.DeleteOrganization(ctx, &pb.DeleteOrganizationRequest{ OrganizationId: orgID, }) @@ -143,7 +145,7 @@ func (c *Client) DeleteOrganization(ctx context.Context, orgID string) error { } // ListOrganizationMembers lists all members of an organization and all invited members to the organization. -func (c *Client) ListOrganizationMembers(ctx context.Context, orgID string) ([]*OrganizationMember, []*OrganizationInvite, error) { +func (c *AppClient) ListOrganizationMembers(ctx context.Context, orgID string) ([]*OrganizationMember, []*OrganizationInvite, error) { resp, err := c.client.ListOrganizationMembers(ctx, &pb.ListOrganizationMembersRequest{ OrganizationId: orgID, }) @@ -163,7 +165,7 @@ func (c *Client) ListOrganizationMembers(ctx context.Context, orgID string) ([]* } // CreateOrganizationInvite creates an organization invite to an organization. -func (c *Client) CreateOrganizationInvite( +func (c *AppClient) CreateOrganizationInvite( ctx context.Context, orgID, email string, authorizations []*Authorization, sendEmailInvite *bool, ) (*OrganizationInvite, error) { var pbAuthorizations []*pb.Authorization @@ -183,7 +185,7 @@ func (c *Client) CreateOrganizationInvite( } // UpdateOrganizationInviteAuthorizations updates the authorizations attached to an organization invite. -func (c *Client) UpdateOrganizationInviteAuthorizations( +func (c *AppClient) UpdateOrganizationInviteAuthorizations( ctx context.Context, orgID, email string, addAuthorizations, removeAuthorizations []*Authorization, ) (*OrganizationInvite, error) { var pbAddAuthorizations []*pb.Authorization @@ -207,7 +209,7 @@ func (c *Client) UpdateOrganizationInviteAuthorizations( } // DeleteOrganizationMember deletes an organization member from an organization. -func (c *Client) DeleteOrganizationMember(ctx context.Context, orgID, userID string) error { +func (c *AppClient) DeleteOrganizationMember(ctx context.Context, orgID, userID string) error { _, err := c.client.DeleteOrganizationMember(ctx, &pb.DeleteOrganizationMemberRequest{ OrganizationId: orgID, UserId: userID, @@ -216,7 +218,7 @@ func (c *Client) DeleteOrganizationMember(ctx context.Context, orgID, userID str } // DeleteOrganizationInvite deletes an organization invite. -func (c *Client) DeleteOrganizationInvite(ctx context.Context, orgID, email string) error { +func (c *AppClient) DeleteOrganizationInvite(ctx context.Context, orgID, email string) error { _, err := c.client.DeleteOrganizationInvite(ctx, &pb.DeleteOrganizationInviteRequest{ OrganizationId: orgID, Email: email, @@ -225,7 +227,7 @@ func (c *Client) DeleteOrganizationInvite(ctx context.Context, orgID, email stri } // ResendOrganizationInvite resends an organization invite. -func (c *Client) ResendOrganizationInvite(ctx context.Context, orgID, email string) (*OrganizationInvite, error) { +func (c *AppClient) ResendOrganizationInvite(ctx context.Context, orgID, email string) (*OrganizationInvite, error) { resp, err := c.client.ResendOrganizationInvite(ctx, &pb.ResendOrganizationInviteRequest{ OrganizationId: orgID, Email: email, @@ -237,7 +239,7 @@ func (c *Client) ResendOrganizationInvite(ctx context.Context, orgID, email stri } // EnableBillingService enables a billing service to an address in an organization. -func (c *Client) EnableBillingService(ctx context.Context, orgID string, billingAddress *BillingAddress) error { +func (c *AppClient) EnableBillingService(ctx context.Context, orgID string, billingAddress *BillingAddress) error { _, err := c.client.EnableBillingService(ctx, &pb.EnableBillingServiceRequest{ OrgId: orgID, BillingAddress: billingAddressToProto(billingAddress), @@ -246,7 +248,7 @@ func (c *Client) EnableBillingService(ctx context.Context, orgID string, billing } // DisableBillingService disables the billing service for an organization. -func (c *Client) DisableBillingService(ctx context.Context, orgID string) error { +func (c *AppClient) DisableBillingService(ctx context.Context, orgID string) error { _, err := c.client.DisableBillingService(ctx, &pb.DisableBillingServiceRequest{ OrgId: orgID, }) @@ -254,7 +256,9 @@ func (c *Client) DisableBillingService(ctx context.Context, orgID string) error } // UpdateBillingService updates the billing service of an organization. -func (c *Client) UpdateBillingService(ctx context.Context, orgID string, billingAddress *BillingAddress, billingSupportEmail string) error { +func (c *AppClient) UpdateBillingService( + ctx context.Context, orgID string, billingAddress *BillingAddress, billingSupportEmail string, +) error { _, err := c.client.UpdateBillingService(ctx, &pb.UpdateBillingServiceRequest{ OrgId: orgID, BillingAddress: billingAddressToProto(billingAddress), @@ -264,7 +268,7 @@ func (c *Client) UpdateBillingService(ctx context.Context, orgID string, billing } // OrganizationSetSupportEmail sets an organization's support email. -func (c *Client) OrganizationSetSupportEmail(ctx context.Context, orgID, email string) error { +func (c *AppClient) OrganizationSetSupportEmail(ctx context.Context, orgID, email string) error { _, err := c.client.OrganizationSetSupportEmail(ctx, &pb.OrganizationSetSupportEmailRequest{ OrgId: orgID, Email: email, @@ -273,7 +277,7 @@ func (c *Client) OrganizationSetSupportEmail(ctx context.Context, orgID, email s } // OrganizationGetSupportEmail gets an organization's support email. -func (c *Client) OrganizationGetSupportEmail(ctx context.Context, orgID string) (string, error) { +func (c *AppClient) OrganizationGetSupportEmail(ctx context.Context, orgID string) (string, error) { resp, err := c.client.OrganizationGetSupportEmail(ctx, &pb.OrganizationGetSupportEmailRequest{ OrgId: orgID, }) @@ -284,7 +288,7 @@ func (c *Client) OrganizationGetSupportEmail(ctx context.Context, orgID string) } // CreateLocation creates a location. -func (c *Client) CreateLocation(ctx context.Context, orgID, name string, parentLocationID *string) (*Location, error) { +func (c *AppClient) CreateLocation(ctx context.Context, orgID, name string, parentLocationID *string) (*Location, error) { resp, err := c.client.CreateLocation(ctx, &pb.CreateLocationRequest{ OrganizationId: orgID, Name: name, @@ -297,7 +301,7 @@ func (c *Client) CreateLocation(ctx context.Context, orgID, name string, parentL } // GetLocation gets a location. -func (c *Client) GetLocation(ctx context.Context, locationID string) (*Location, error) { +func (c *AppClient) GetLocation(ctx context.Context, locationID string) (*Location, error) { resp, err := c.client.GetLocation(ctx, &pb.GetLocationRequest{ LocationId: locationID, }) @@ -308,7 +312,7 @@ func (c *Client) GetLocation(ctx context.Context, locationID string) (*Location, } // UpdateLocation updates a location. -func (c *Client) UpdateLocation(ctx context.Context, locationID string, name, parentLocationID, region *string) (*Location, error) { +func (c *AppClient) UpdateLocation(ctx context.Context, locationID string, name, parentLocationID, region *string) (*Location, error) { resp, err := c.client.UpdateLocation(ctx, &pb.UpdateLocationRequest{ LocationId: locationID, Name: name, @@ -322,7 +326,7 @@ func (c *Client) UpdateLocation(ctx context.Context, locationID string, name, pa } // DeleteLocation deletes a location. -func (c *Client) DeleteLocation(ctx context.Context, locationID string) error { +func (c *AppClient) DeleteLocation(ctx context.Context, locationID string) error { _, err := c.client.DeleteLocation(ctx, &pb.DeleteLocationRequest{ LocationId: locationID, }) @@ -330,7 +334,7 @@ func (c *Client) DeleteLocation(ctx context.Context, locationID string) error { } // ListLocations gets a list of locations under the specified organization. -func (c *Client) ListLocations(ctx context.Context, orgID string) ([]*Location, error) { +func (c *AppClient) ListLocations(ctx context.Context, orgID string) ([]*Location, error) { resp, err := c.client.ListLocations(ctx, &pb.ListLocationsRequest{ OrganizationId: orgID, }) @@ -346,7 +350,7 @@ func (c *Client) ListLocations(ctx context.Context, orgID string) ([]*Location, } // ShareLocation shares a location with an organization. -func (c *Client) ShareLocation(ctx context.Context, locationID, orgID string) error { +func (c *AppClient) ShareLocation(ctx context.Context, locationID, orgID string) error { _, err := c.client.ShareLocation(ctx, &pb.ShareLocationRequest{ LocationId: locationID, OrganizationId: orgID, @@ -355,7 +359,7 @@ func (c *Client) ShareLocation(ctx context.Context, locationID, orgID string) er } // UnshareLocation stops sharing a location with an organization. -func (c *Client) UnshareLocation(ctx context.Context, locationID, orgID string) error { +func (c *AppClient) UnshareLocation(ctx context.Context, locationID, orgID string) error { _, err := c.client.UnshareLocation(ctx, &pb.UnshareLocationRequest{ LocationId: locationID, OrganizationId: orgID, @@ -364,7 +368,7 @@ func (c *Client) UnshareLocation(ctx context.Context, locationID, orgID string) } // LocationAuth gets a location's authorization secrets. -func (c *Client) LocationAuth(ctx context.Context, locationID string) (*LocationAuth, error) { +func (c *AppClient) LocationAuth(ctx context.Context, locationID string) (*LocationAuth, error) { resp, err := c.client.LocationAuth(ctx, &pb.LocationAuthRequest{ LocationId: locationID, }) @@ -375,7 +379,7 @@ func (c *Client) LocationAuth(ctx context.Context, locationID string) (*Location } // CreateLocationSecret creates a new generated secret in the location. Succeeds if there are no more than 2 active secrets after creation. -func (c *Client) CreateLocationSecret(ctx context.Context, locationID string) (*LocationAuth, error) { +func (c *AppClient) CreateLocationSecret(ctx context.Context, locationID string) (*LocationAuth, error) { resp, err := c.client.CreateLocationSecret(ctx, &pb.CreateLocationSecretRequest{ LocationId: locationID, }) @@ -386,7 +390,7 @@ func (c *Client) CreateLocationSecret(ctx context.Context, locationID string) (* } // DeleteLocationSecret deletes a secret from the location. -func (c *Client) DeleteLocationSecret(ctx context.Context, locationID, secretID string) error { +func (c *AppClient) DeleteLocationSecret(ctx context.Context, locationID, secretID string) error { _, err := c.client.DeleteLocationSecret(ctx, &pb.DeleteLocationSecretRequest{ LocationId: locationID, SecretId: secretID, @@ -395,7 +399,7 @@ func (c *Client) DeleteLocationSecret(ctx context.Context, locationID, secretID } // GetRobot gets a specific robot by ID. -func (c *Client) GetRobot(ctx context.Context, id string) (*Robot, error) { +func (c *AppClient) GetRobot(ctx context.Context, id string) (*Robot, error) { resp, err := c.client.GetRobot(ctx, &pb.GetRobotRequest{ Id: id, }) @@ -406,7 +410,7 @@ func (c *Client) GetRobot(ctx context.Context, id string) (*Robot, error) { } // GetRoverRentalRobots gets rover rental robots within an organization. -func (c *Client) GetRoverRentalRobots(ctx context.Context, orgID string) ([]*RoverRentalRobot, error) { +func (c *AppClient) GetRoverRentalRobots(ctx context.Context, orgID string) ([]*RoverRentalRobot, error) { resp, err := c.client.GetRoverRentalRobots(ctx, &pb.GetRoverRentalRobotsRequest{ OrgId: orgID, }) @@ -421,7 +425,7 @@ func (c *Client) GetRoverRentalRobots(ctx context.Context, orgID string) ([]*Rov } // GetRobotParts gets a list of all the parts under a specific machine. -func (c *Client) GetRobotParts(ctx context.Context, robotID string) ([]*RobotPart, error) { +func (c *AppClient) GetRobotParts(ctx context.Context, robotID string) ([]*RobotPart, error) { resp, err := c.client.GetRobotParts(ctx, &pb.GetRobotPartsRequest{ RobotId: robotID, }) @@ -436,7 +440,7 @@ func (c *Client) GetRobotParts(ctx context.Context, robotID string) ([]*RobotPar } // GetRobotPart gets a specific robot part and its config by ID. -func (c *Client) GetRobotPart(ctx context.Context, id string) (*RobotPart, string, error) { +func (c *AppClient) GetRobotPart(ctx context.Context, id string) (*RobotPart, string, error) { resp, err := c.client.GetRobotPart(ctx, &pb.GetRobotPartRequest{ Id: id, }) @@ -448,7 +452,7 @@ func (c *Client) GetRobotPart(ctx context.Context, id string) (*RobotPart, strin // GetRobotPartLogs gets the logs associated with a robot part from a page, defaulting to the most recent page if pageToken is empty. // Logs of all levels are returned when levels is empty. -func (c *Client) GetRobotPartLogs( +func (c *AppClient) GetRobotPartLogs( ctx context.Context, id string, filter, @@ -480,7 +484,7 @@ func (c *Client) GetRobotPartLogs( } // TailRobotPartLogs gets a stream of log entries for a specific robot part. Logs are ordered by newest first. -func (c *Client) TailRobotPartLogs(ctx context.Context, id string, errorsOnly bool, filter *string, ch chan []*LogEntry) error { +func (c *AppClient) TailRobotPartLogs(ctx context.Context, id string, errorsOnly bool, filter *string, ch chan []*LogEntry) error { stream := &logStream{client: c} err := stream.startStream(ctx, id, errorsOnly, filter, ch) @@ -494,7 +498,7 @@ func (c *Client) TailRobotPartLogs(ctx context.Context, id string, errorsOnly bo } // GetRobotPartHistory gets a specific robot part history by ID. -func (c *Client) GetRobotPartHistory(ctx context.Context, id string) ([]*RobotPartHistoryEntry, error) { +func (c *AppClient) GetRobotPartHistory(ctx context.Context, id string) ([]*RobotPartHistoryEntry, error) { resp, err := c.client.GetRobotPartHistory(ctx, &pb.GetRobotPartHistoryRequest{ Id: id, }) @@ -509,7 +513,7 @@ func (c *Client) GetRobotPartHistory(ctx context.Context, id string) ([]*RobotPa } // UpdateRobotPart updates a robot part. -func (c *Client) UpdateRobotPart(ctx context.Context, id, name string, robotConfig interface{}) (*RobotPart, error) { +func (c *AppClient) UpdateRobotPart(ctx context.Context, id, name string, robotConfig interface{}) (*RobotPart, error) { config, err := protoutils.StructToStructPb(robotConfig) if err != nil { return nil, err @@ -526,7 +530,7 @@ func (c *Client) UpdateRobotPart(ctx context.Context, id, name string, robotConf } // NewRobotPart creates a new robot part. -func (c *Client) NewRobotPart(ctx context.Context, robotID, partName string) (string, error) { +func (c *AppClient) NewRobotPart(ctx context.Context, robotID, partName string) (string, error) { resp, err := c.client.NewRobotPart(ctx, &pb.NewRobotPartRequest{ RobotId: robotID, PartName: partName, @@ -538,7 +542,7 @@ func (c *Client) NewRobotPart(ctx context.Context, robotID, partName string) (st } // DeleteRobotPart deletes a robot part. -func (c *Client) DeleteRobotPart(ctx context.Context, partID string) error { +func (c *AppClient) DeleteRobotPart(ctx context.Context, partID string) error { _, err := c.client.DeleteRobotPart(ctx, &pb.DeleteRobotPartRequest{ PartId: partID, }) @@ -546,7 +550,7 @@ func (c *Client) DeleteRobotPart(ctx context.Context, partID string) error { } // GetRobotAPIKeys gets the robot API keys for the robot. -func (c *Client) GetRobotAPIKeys(ctx context.Context, robotID string) ([]*APIKeyWithAuthorizations, error) { +func (c *AppClient) GetRobotAPIKeys(ctx context.Context, robotID string) ([]*APIKeyWithAuthorizations, error) { resp, err := c.client.GetRobotAPIKeys(ctx, &pb.GetRobotAPIKeysRequest{ RobotId: robotID, }) @@ -561,7 +565,7 @@ func (c *Client) GetRobotAPIKeys(ctx context.Context, robotID string) ([]*APIKey } // MarkPartAsMain marks the given part as the main part, and all the others as not. -func (c *Client) MarkPartAsMain(ctx context.Context, partID string) error { +func (c *AppClient) MarkPartAsMain(ctx context.Context, partID string) error { _, err := c.client.MarkPartAsMain(ctx, &pb.MarkPartAsMainRequest{ PartId: partID, }) @@ -571,7 +575,7 @@ func (c *Client) MarkPartAsMain(ctx context.Context, partID string) error { // MarkPartForRestart marks the given part for restart. // Once the robot part checks-in with the app the flag is reset on the robot part. // Calling this multiple times before a robot part checks-in has no effect. -func (c *Client) MarkPartForRestart(ctx context.Context, partID string) error { +func (c *AppClient) MarkPartForRestart(ctx context.Context, partID string) error { _, err := c.client.MarkPartForRestart(ctx, &pb.MarkPartForRestartRequest{ PartId: partID, }) @@ -580,7 +584,7 @@ func (c *Client) MarkPartForRestart(ctx context.Context, partID string) error { // CreateRobotPartSecret creates a new generated secret in the robot part. // Succeeds if there are no more than 2 active secrets after creation. -func (c *Client) CreateRobotPartSecret(ctx context.Context, partID string) (*RobotPart, error) { +func (c *AppClient) CreateRobotPartSecret(ctx context.Context, partID string) (*RobotPart, error) { resp, err := c.client.CreateRobotPartSecret(ctx, &pb.CreateRobotPartSecretRequest{ PartId: partID, }) @@ -591,7 +595,7 @@ func (c *Client) CreateRobotPartSecret(ctx context.Context, partID string) (*Rob } // DeleteRobotPartSecret deletes a secret from the robot part. -func (c *Client) DeleteRobotPartSecret(ctx context.Context, partID, secretID string) error { +func (c *AppClient) DeleteRobotPartSecret(ctx context.Context, partID, secretID string) error { _, err := c.client.DeleteRobotPartSecret(ctx, &pb.DeleteRobotPartSecretRequest{ PartId: partID, SecretId: secretID, @@ -600,7 +604,7 @@ func (c *Client) DeleteRobotPartSecret(ctx context.Context, partID, secretID str } // ListRobots gets a list of robots under a location. -func (c *Client) ListRobots(ctx context.Context, locationID string) ([]*Robot, error) { +func (c *AppClient) ListRobots(ctx context.Context, locationID string) ([]*Robot, error) { resp, err := c.client.ListRobots(ctx, &pb.ListRobotsRequest{ LocationId: locationID, }) @@ -615,7 +619,7 @@ func (c *Client) ListRobots(ctx context.Context, locationID string) ([]*Robot, e } // NewRobot creates a new robot. -func (c *Client) NewRobot(ctx context.Context, name, location string) (string, error) { +func (c *AppClient) NewRobot(ctx context.Context, name, location string) (string, error) { resp, err := c.client.NewRobot(ctx, &pb.NewRobotRequest{ Name: name, Location: location, @@ -627,7 +631,7 @@ func (c *Client) NewRobot(ctx context.Context, name, location string) (string, e } // UpdateRobot updates a robot. -func (c *Client) UpdateRobot(ctx context.Context, id, name, location string) (*Robot, error) { +func (c *AppClient) UpdateRobot(ctx context.Context, id, name, location string) (*Robot, error) { resp, err := c.client.UpdateRobot(ctx, &pb.UpdateRobotRequest{ Id: id, Name: name, @@ -640,7 +644,7 @@ func (c *Client) UpdateRobot(ctx context.Context, id, name, location string) (*R } // DeleteRobot deletes a robot. -func (c *Client) DeleteRobot(ctx context.Context, id string) error { +func (c *AppClient) DeleteRobot(ctx context.Context, id string) error { _, err := c.client.DeleteRobot(ctx, &pb.DeleteRobotRequest{ Id: id, }) @@ -648,7 +652,7 @@ func (c *Client) DeleteRobot(ctx context.Context, id string) error { } // ListFragments gets a list of fragments. -func (c *Client) ListFragments( +func (c *AppClient) ListFragments( ctx context.Context, orgID string, showPublic bool, fragmentVisibility []FragmentVisibility, ) ([]*Fragment, error) { var visibilities []pb.FragmentVisibility @@ -672,7 +676,7 @@ func (c *Client) ListFragments( } // GetFragment gets a single fragment. -func (c *Client) GetFragment(ctx context.Context, id string) (*Fragment, error) { +func (c *AppClient) GetFragment(ctx context.Context, id string) (*Fragment, error) { resp, err := c.client.GetFragment(ctx, &pb.GetFragmentRequest{ Id: id, }) @@ -683,7 +687,7 @@ func (c *Client) GetFragment(ctx context.Context, id string) (*Fragment, error) } // CreateFragment creates a fragment. -func (c *Client) CreateFragment( +func (c *AppClient) CreateFragment( ctx context.Context, name string, config interface{}, orgID string, visibility *FragmentVisibility, ) (*Fragment, error) { cfg, err := protoutils.StructToStructPb(config) @@ -704,7 +708,7 @@ func (c *Client) CreateFragment( } // UpdateFragment updates a fragment. -func (c *Client) UpdateFragment( +func (c *AppClient) UpdateFragment( ctx context.Context, id, name string, config map[string]interface{}, public *bool, visibility *FragmentVisibility, ) (*Fragment, error) { cfg, err := protoutils.StructToStructPb(config) @@ -726,7 +730,7 @@ func (c *Client) UpdateFragment( } // DeleteFragment deletes a fragment. -func (c *Client) DeleteFragment(ctx context.Context, id string) error { +func (c *AppClient) DeleteFragment(ctx context.Context, id string) error { _, err := c.client.DeleteFragment(ctx, &pb.DeleteFragmentRequest{ Id: id, }) @@ -735,7 +739,7 @@ func (c *Client) DeleteFragment(ctx context.Context, id string) error { // ListMachineFragments gets top level and nested fragments for a amchine, as well as any other fragments specified by IDs. Additional // fragments are useful when needing to view fragments that will be provisionally added to the machine alongside existing fragments. -func (c *Client) ListMachineFragments(ctx context.Context, machineID string, additionalFragmentIDs []string) ([]*Fragment, error) { +func (c *AppClient) ListMachineFragments(ctx context.Context, machineID string, additionalFragmentIDs []string) ([]*Fragment, error) { resp, err := c.client.ListMachineFragments(ctx, &pb.ListMachineFragmentsRequest{ MachineId: machineID, AdditionalFragmentIds: additionalFragmentIDs, @@ -751,7 +755,7 @@ func (c *Client) ListMachineFragments(ctx context.Context, machineID string, add } // GetFragmentHistory gets the fragment's history. -func (c *Client) GetFragmentHistory( +func (c *AppClient) GetFragmentHistory( ctx context.Context, id string, pageToken *string, pageLimit *int64, ) ([]*FragmentHistoryEntry, string, error) { resp, err := c.client.GetFragmentHistory(ctx, &pb.GetFragmentHistoryRequest{ @@ -770,7 +774,7 @@ func (c *Client) GetFragmentHistory( } // AddRole creates an identity authorization. -func (c *Client) AddRole(ctx context.Context, orgID, identityID, role, resourceType, resourceID string) error { +func (c *AppClient) AddRole(ctx context.Context, orgID, identityID, role, resourceType, resourceID string) error { authorization, err := createAuthorization(orgID, identityID, "", role, resourceType, resourceID) if err != nil { return err @@ -782,7 +786,7 @@ func (c *Client) AddRole(ctx context.Context, orgID, identityID, role, resourceT } // RemoveRole deletes an identity authorization. -func (c *Client) RemoveRole(ctx context.Context, orgID, identityID, role, resourceType, resourceID string) error { +func (c *AppClient) RemoveRole(ctx context.Context, orgID, identityID, role, resourceType, resourceID string) error { authorization, err := createAuthorization(orgID, identityID, "", role, resourceType, resourceID) if err != nil { return err @@ -794,7 +798,7 @@ func (c *Client) RemoveRole(ctx context.Context, orgID, identityID, role, resour } // ChangeRole changes an identity authorization to a new identity authorization. -func (c *Client) ChangeRole( +func (c *AppClient) ChangeRole( ctx context.Context, oldOrgID, oldIdentityID, @@ -824,7 +828,7 @@ func (c *Client) ChangeRole( // ListAuthorizations returns all authorization roles for any given resources. // If no resources are given, all resources within the organization will be included. -func (c *Client) ListAuthorizations(ctx context.Context, orgID string, resourceIDs []string) ([]*Authorization, error) { +func (c *AppClient) ListAuthorizations(ctx context.Context, orgID string, resourceIDs []string) ([]*Authorization, error) { resp, err := c.client.ListAuthorizations(ctx, &pb.ListAuthorizationsRequest{ OrganizationId: orgID, ResourceIds: resourceIDs, @@ -840,7 +844,7 @@ func (c *Client) ListAuthorizations(ctx context.Context, orgID string, resourceI } // CheckPermissions checks the validity of a list of permissions. -func (c *Client) CheckPermissions(ctx context.Context, permissions []*AuthorizedPermissions) ([]*AuthorizedPermissions, error) { +func (c *AppClient) CheckPermissions(ctx context.Context, permissions []*AuthorizedPermissions) ([]*AuthorizedPermissions, error) { var pbPermissions []*pb.AuthorizedPermissions for _, permission := range permissions { pbPermissions = append(pbPermissions, authorizedPermissionsToProto(permission)) @@ -861,7 +865,7 @@ func (c *Client) CheckPermissions(ctx context.Context, permissions []*Authorized } // GetRegistryItem gets a registry item. -func (c *Client) GetRegistryItem(ctx context.Context, itemID string) (*RegistryItem, error) { +func (c *AppClient) GetRegistryItem(ctx context.Context, itemID string) (*RegistryItem, error) { resp, err := c.client.GetRegistryItem(ctx, &pb.GetRegistryItemRequest{ ItemId: itemID, }) @@ -876,7 +880,7 @@ func (c *Client) GetRegistryItem(ctx context.Context, itemID string) (*RegistryI } // CreateRegistryItem creates a registry item. -func (c *Client) CreateRegistryItem(ctx context.Context, orgID, name string, packageType PackageType) error { +func (c *AppClient) CreateRegistryItem(ctx context.Context, orgID, name string, packageType PackageType) error { _, err := c.client.CreateRegistryItem(ctx, &pb.CreateRegistryItemRequest{ OrganizationId: orgID, Name: name, @@ -886,7 +890,7 @@ func (c *Client) CreateRegistryItem(ctx context.Context, orgID, name string, pac } // UpdateRegistryItem updates a registry item. -func (c *Client) UpdateRegistryItem( +func (c *AppClient) UpdateRegistryItem( ctx context.Context, itemID string, packageType PackageType, description string, visibility Visibility, url *string, ) error { _, err := c.client.UpdateRegistryItem(ctx, &pb.UpdateRegistryItemRequest{ @@ -900,7 +904,7 @@ func (c *Client) UpdateRegistryItem( } // ListRegistryItems lists the registry items in an organization. -func (c *Client) ListRegistryItems( +func (c *AppClient) ListRegistryItems( ctx context.Context, orgID *string, types []PackageType, @@ -949,7 +953,7 @@ func (c *Client) ListRegistryItems( // DeleteRegistryItem deletes a registry item given an ID that is formatted as `prefix:name“ // where `prefix“ is the owner's organization ID or namespace. -func (c *Client) DeleteRegistryItem(ctx context.Context, itemID string) error { +func (c *AppClient) DeleteRegistryItem(ctx context.Context, itemID string) error { _, err := c.client.DeleteRegistryItem(ctx, &pb.DeleteRegistryItemRequest{ ItemId: itemID, }) @@ -957,7 +961,7 @@ func (c *Client) DeleteRegistryItem(ctx context.Context, itemID string) error { } // TransferRegistryItem transfers a registry item to a namespace. -func (c *Client) TransferRegistryItem(ctx context.Context, itemID, newPublicNamespace string) error { +func (c *AppClient) TransferRegistryItem(ctx context.Context, itemID, newPublicNamespace string) error { _, err := c.client.TransferRegistryItem(ctx, &pb.TransferRegistryItemRequest{ ItemId: itemID, NewPublicNamespace: newPublicNamespace, @@ -966,7 +970,7 @@ func (c *Client) TransferRegistryItem(ctx context.Context, itemID, newPublicName } // CreateModule creates a module. -func (c *Client) CreateModule(ctx context.Context, orgID, name string) (string, string, error) { +func (c *AppClient) CreateModule(ctx context.Context, orgID, name string) (string, string, error) { resp, err := c.client.CreateModule(ctx, &pb.CreateModuleRequest{ OrganizationId: orgID, Name: name, @@ -979,7 +983,7 @@ func (c *Client) CreateModule(ctx context.Context, orgID, name string) (string, // UpdateModule updates the documentation URL, description, models, entrypoint, and/or the visibility of a module. // A path to a setup script can be added that is run before a newly downloaded module starts. -func (c *Client) UpdateModule( +func (c *AppClient) UpdateModule( ctx context.Context, moduleID string, visibility Visibility, url, description string, models []*Model, entrypoint string, firstRun *string, ) (string, error) { var pbModels []*pb.Model @@ -1053,7 +1057,7 @@ func (c *Client) UpdateModule( // } // GetModule gets a module. -func (c *Client) GetModule(ctx context.Context, moduleID string) (*Module, error) { +func (c *AppClient) GetModule(ctx context.Context, moduleID string) (*Module, error) { resp, err := c.client.GetModule(ctx, &pb.GetModuleRequest{ ModuleId: moduleID, }) @@ -1064,7 +1068,7 @@ func (c *Client) GetModule(ctx context.Context, moduleID string) (*Module, error } // ListModules lists the modules in the organization. -func (c *Client) ListModules(ctx context.Context, orgID *string) ([]*Module, error) { +func (c *AppClient) ListModules(ctx context.Context, orgID *string) ([]*Module, error) { resp, err := c.client.ListModules(ctx, &pb.ListModulesRequest{ OrganizationId: orgID, }) @@ -1079,7 +1083,7 @@ func (c *Client) ListModules(ctx context.Context, orgID *string) ([]*Module, err } // CreateKey creates a new API key associated with a list of authorizations. -func (c *Client) CreateKey( +func (c *AppClient) CreateKey( ctx context.Context, orgID string, keyAuthorizations []APIKeyAuthorization, name string, ) (string, string, error) { var authorizations []*pb.Authorization @@ -1103,7 +1107,7 @@ func (c *Client) CreateKey( } // DeleteKey deletes an API key. -func (c *Client) DeleteKey(ctx context.Context, id string) error { +func (c *AppClient) DeleteKey(ctx context.Context, id string) error { _, err := c.client.DeleteKey(ctx, &pb.DeleteKeyRequest{ Id: id, }) @@ -1111,7 +1115,7 @@ func (c *Client) DeleteKey(ctx context.Context, id string) error { } // ListKeys lists all the keys for the organization. -func (c *Client) ListKeys(ctx context.Context, orgID string) ([]*APIKeyWithAuthorizations, error) { +func (c *AppClient) ListKeys(ctx context.Context, orgID string) ([]*APIKeyWithAuthorizations, error) { resp, err := c.client.ListKeys(ctx, &pb.ListKeysRequest{ OrgId: orgID, }) @@ -1126,7 +1130,7 @@ func (c *Client) ListKeys(ctx context.Context, orgID string) ([]*APIKeyWithAutho } // RenameKey renames an API key. -func (c *Client) RenameKey(ctx context.Context, id, name string) (string, string, error) { +func (c *AppClient) RenameKey(ctx context.Context, id, name string) (string, string, error) { resp, err := c.client.RenameKey(ctx, &pb.RenameKeyRequest{ Id: id, Name: name, @@ -1138,7 +1142,7 @@ func (c *Client) RenameKey(ctx context.Context, id, name string) (string, string } // RotateKey rotates an API key. -func (c *Client) RotateKey(ctx context.Context, id string) (string, string, error) { +func (c *AppClient) RotateKey(ctx context.Context, id string) (string, string, error) { resp, err := c.client.RotateKey(ctx, &pb.RotateKeyRequest{ Id: id, }) @@ -1149,7 +1153,7 @@ func (c *Client) RotateKey(ctx context.Context, id string) (string, string, erro } // CreateKeyFromExistingKeyAuthorizations creates a new API key with an existing key's authorizations. -func (c *Client) CreateKeyFromExistingKeyAuthorizations(ctx context.Context, id string) (string, string, error) { +func (c *AppClient) CreateKeyFromExistingKeyAuthorizations(ctx context.Context, id string) (string, string, error) { resp, err := c.client.CreateKeyFromExistingKeyAuthorizations(ctx, &pb.CreateKeyFromExistingKeyAuthorizationsRequest{ Id: id, }) diff --git a/app/app_client_test.go b/app/app_client_test.go index 2e4a70ba7d9..4cd913f80ac 100644 --- a/app/app_client_test.go +++ b/app/app_client_test.go @@ -676,7 +676,7 @@ func createGrpcClient() *inject.AppServiceClient { func TestAppClient(t *testing.T) { grpcClient := createGrpcClient() - client := Client{client: grpcClient} + client := AppClient{client: grpcClient} t.Run("GetUserIDByEmail", func(t *testing.T) { grpcClient.GetUserIDByEmailFunc = func( diff --git a/app/log_stream.go b/app/log_stream.go index 8044772ba88..8d4253b96c5 100644 --- a/app/log_stream.go +++ b/app/log_stream.go @@ -9,7 +9,7 @@ import ( ) type logStream struct { - client *Client + client *AppClient streamCancel context.CancelFunc streamMu sync.Mutex diff --git a/app/resource_types.go b/app/resource_types.go index e8b67ba8a6e..8ebe94202e3 100644 --- a/app/resource_types.go +++ b/app/resource_types.go @@ -111,7 +111,6 @@ func billingAddressToProto(addr *BillingAddress) *pb.BillingAddress { } } - // Location holds the information of a specific location. type Location struct { ID string @@ -404,7 +403,6 @@ func fragmentHistoryEntryFromProto(entry *pb.FragmentHistoryEntry) *FragmentHist } } - // Authorization has the information about a specific authorization. type Authorization struct { AuthorizationType string diff --git a/app/viam_client.go b/app/viam_client.go index 94c4a15520e..2a8af30c34f 100644 --- a/app/viam_client.go +++ b/app/viam_client.go @@ -15,7 +15,8 @@ import ( // ViamClient is a gRPC client for method calls to Viam app. type ViamClient struct { conn rpc.ClientConn - appClient Client + logger logging.Logger + appClient *AppClient } // Options has the options necessary to connect through gRPC. @@ -48,10 +49,7 @@ func CreateViamClientWithOptions(ctx context.Context, options Options, logger lo if err != nil { return nil, err } - return &ViamClient{ - conn: conn, - appClient: NewClientFromConn(conn, logger), - }, nil + return &ViamClient{conn: conn, logger: logger}, nil } // CreateViamClientWithAPIKey creates a ViamClient with an API key. @@ -66,6 +64,16 @@ func CreateViamClientWithAPIKey( return CreateViamClientWithOptions(ctx, options, logger) } +// AppClient initializes and returns a DataClient instance used to make data method calls. +// To use DataClient, you must first instantiate a ViamClient. +func (c *ViamClient) AppClient() *AppClient { + if c.appClient != nil { + return c.appClient + } + c.appClient = NewAppClient(c.conn, c.logger) + return c.appClient +} + // Close closes the gRPC connection. func (c *ViamClient) Close() error { return c.conn.Close() From 422c4337fb346ffa5a769e0b94916ec7b0ee89b6 Mon Sep 17 00:00:00 2001 From: purplenicole730 Date: Tue, 19 Nov 2024 12:52:16 -0500 Subject: [PATCH 53/75] add wrapper for uploadmodulefile --- app/app_client.go | 74 +++++++-------------- app/log_stream.go | 86 ------------------------- app/registry.go | 17 +++++ app/stream.go | 160 ++++++++++++++++++++++++++++++++++++++++++++++ 4 files changed, 200 insertions(+), 137 deletions(-) delete mode 100644 app/log_stream.go create mode 100644 app/stream.go diff --git a/app/app_client.go b/app/app_client.go index e9381b52c07..21578f0826a 100644 --- a/app/app_client.go +++ b/app/app_client.go @@ -485,7 +485,7 @@ func (c *AppClient) GetRobotPartLogs( // TailRobotPartLogs gets a stream of log entries for a specific robot part. Logs are ordered by newest first. func (c *AppClient) TailRobotPartLogs(ctx context.Context, id string, errorsOnly bool, filter *string, ch chan []*LogEntry) error { - stream := &logStream{client: c} + stream := &robotPartLogStream{client: c} err := stream.startStream(ctx, id, errorsOnly, filter, ch) if err != nil { @@ -1005,56 +1005,28 @@ func (c *AppClient) UpdateModule( return resp.Url, nil } -// type isModuleFile interface { -// isUploadModuleFileRequest_ModuleFile() -// } - -// type UploadModuleFileRequest_ModuleFileInfo struct { -// *pb.UploadModuleFileRequest_ModuleFileInfo -// } - -// func (UploadModuleFileRequest_ModuleFileInfo) isUploadModuleFileRequest_ModuleFile() {} - -// type UploadModuleFileRequest_File struct { -// *pb.UploadModuleFileRequest_File -// } - -// func (UploadModuleFileRequest_File) isUploadModuleFileRequest_ModuleFile() {} - -// type uploadStream struct { -// gostream. -// } - -// func (c *AppClient) UploadModuleFile(ctx context.Context, moduleFile isModuleFile, ch ) (string, error) { -// c.mu.Lock() -// streamCtx, stream, - -// stream := &uploadStream{client: c} - -// err = stream.startStream(ctx, moduleFile, ch) - -// var req *pb.UploadModuleFileRequest -// switch moduleFileInfo := moduleFile.(type) { -// case UploadModuleFileRequest_ModuleFileInfo: -// req = &pb.UploadModuleFileRequest{ -// ModuleFile: &pb.UploadModuleFileRequest_ModuleFileInfo{ -// ModuleFileInfo: moduleFileInfo.ModuleFileInfo, -// }, -// } -// case UploadModuleFileRequest_File: -// req = &pb.UploadModuleFileRequest{ -// ModuleFile: &pb.UploadModuleFileRequest_File{ -// File: moduleFileInfo.File, -// }, -// } -// } - -// resp, err := c.client.UploadModuleFile(ctx, req) -// if err != nil { -// return "", err -// } -// return resp.Url, nil -// } +// UploadModuleFile uploads a module file and returns the URL of the uploaded file. +func (c *AppClient) UploadModuleFile(ctx context.Context, fileInfo ModuleFileInfo, file []byte) (string, error) { + stream := &uploadModuleFileStream{client: c} + // reqModuleFileInfo := uploadModuleFileRequest{ + // ModuleFile: &uploadModuleFileRequestModuleFileInfo{ + // ModuleFileInfo: &fileInfo, + // }, + // } + // reqFile := uploadModuleFileRequest{ + // ModuleFile: &uploadModuleFileRequestFile{ + // File: file, + // }, + // } + url, err := stream.startStream(ctx, &fileInfo, file) + if err != nil { + return "", err + } + + c.mu.Lock() + defer c.mu.Unlock() + return url, nil +} // GetModule gets a module. func (c *AppClient) GetModule(ctx context.Context, moduleID string) (*Module, error) { diff --git a/app/log_stream.go b/app/log_stream.go deleted file mode 100644 index 8d4253b96c5..00000000000 --- a/app/log_stream.go +++ /dev/null @@ -1,86 +0,0 @@ -package app - -import ( - "context" - "sync" - - pb "go.viam.com/api/app/v1" - "go.viam.com/utils" -) - -type logStream struct { - client *AppClient - streamCancel context.CancelFunc - streamMu sync.Mutex - - activeBackgroundWorkers sync.WaitGroup -} - -func (s *logStream) startStream(ctx context.Context, id string, errorsOnly bool, filter *string, ch chan []*LogEntry) error { - s.streamMu.Lock() - defer s.streamMu.Unlock() - - if ctx.Err() != nil { - return ctx.Err() - } - - ctx, cancel := context.WithCancel(ctx) - s.streamCancel = cancel - - select { - case <-ctx.Done(): - return ctx.Err() - default: - } - - req := &pb.TailRobotPartLogsRequest{ - Id: id, - ErrorsOnly: errorsOnly, - Filter: filter, - } - - // This call won't return any errors it had until the client tries to receive. - //nolint:errcheck - stream, _ := s.client.client.TailRobotPartLogs(ctx, req) - _, err := stream.Recv() - if err != nil { - s.client.logger.CError(ctx, err) - return err - } - - // Create a background go routine to receive from the server stream. - // We rely on calling the Done function here rather than in close stream - // since managed go calls that function when the routine exits. - s.activeBackgroundWorkers.Add(1) - utils.ManagedGo(func() { - s.receiveFromStream(ctx, stream, ch) - }, - s.activeBackgroundWorkers.Done) - return nil -} - -func (s *logStream) receiveFromStream(ctx context.Context, stream pb.AppService_TailRobotPartLogsClient, ch chan []*LogEntry) { - defer s.streamCancel() - - // repeatly receive from the stream - for { - select { - case <-ctx.Done(): - s.client.logger.Debug(ctx.Err()) - return - default: - } - streamResp, err := stream.Recv() - if err != nil { - // only debug log the context canceled error - s.client.logger.Debug(err) - return - } - // If there is a response, send to the logs channel. - var logs []*LogEntry - for _, log := range streamResp.Logs { - logs = append(logs, logEntryFromProto(log)) - } - ch <- logs - } -} diff --git a/app/registry.go b/app/registry.go index 54e0417d00c..4c4349e82ae 100644 --- a/app/registry.go +++ b/app/registry.go @@ -442,6 +442,23 @@ func moduleFromProto(module *pb.Module) *Module { } } +// ModuleFileInfo holds the information of a module file. +type ModuleFileInfo struct { + ModuleID string + Version string + Platform string + PlatformTags []string +} + +func moduleFileInfoToProto(info *ModuleFileInfo) *pb.ModuleFileInfo { + return &pb.ModuleFileInfo{ + ModuleId: info.ModuleID, + Version: info.Version, + Platform: info.Platform, + PlatformTags: info.PlatformTags, + } +} + // VersionHistory holds the history of a version. type VersionHistory struct { Version string diff --git a/app/stream.go b/app/stream.go new file mode 100644 index 00000000000..b9034a93fcb --- /dev/null +++ b/app/stream.go @@ -0,0 +1,160 @@ +package app + +import ( + "context" + "sync" + + pb "go.viam.com/api/app/v1" + "go.viam.com/utils" +) + +type robotPartLogStream struct { + client *AppClient + streamCancel context.CancelFunc + streamMu sync.Mutex + + activeBackgroundWorkers sync.WaitGroup +} + +func (s *robotPartLogStream) startStream(ctx context.Context, id string, errorsOnly bool, filter *string, ch chan []*LogEntry) error { + s.streamMu.Lock() + defer s.streamMu.Unlock() + + if ctx.Err() != nil { + return ctx.Err() + } + + ctx, cancel := context.WithCancel(ctx) + s.streamCancel = cancel + + select { + case <-ctx.Done(): + return ctx.Err() + default: + } + + // This call won't return any errors it had until the client tries to receive. + //nolint:errcheck + stream, _ := s.client.client.TailRobotPartLogs(ctx, &pb.TailRobotPartLogsRequest{ + Id: id, + ErrorsOnly: errorsOnly, + Filter: filter, + }) + _, err := stream.Recv() + if err != nil { + s.client.logger.CError(ctx, err) + return err + } + + // Create a background go routine to receive from the server stream. + // We rely on calling the Done function here rather than in close stream + // since managed go calls that function when the routine exits. + s.activeBackgroundWorkers.Add(1) + utils.ManagedGo(func() { + s.receiveFromStream(ctx, stream, ch) + }, + s.activeBackgroundWorkers.Done) + return nil +} + +func (s *robotPartLogStream) receiveFromStream(ctx context.Context, stream pb.AppService_TailRobotPartLogsClient, ch chan []*LogEntry) { + defer s.streamCancel() + + // repeatly receive from the stream + for { + select { + case <-ctx.Done(): + s.client.logger.Debug(ctx.Err()) + return + default: + } + streamResp, err := stream.Recv() + if err != nil { + // only debug log the context canceled error + s.client.logger.Debug(err) + return + } + // If there is a response, send to the logs channel. + var logs []*LogEntry + for _, log := range streamResp.Logs { + logs = append(logs, logEntryFromProto(log)) + } + ch <- logs + } +} + +type uploadModuleFileStream struct { + client *AppClient + streamCancel context.CancelFunc + streamMu sync.Mutex + + activeBackgroundWorkers sync.WaitGroup +} + +func (s *uploadModuleFileStream) startStream( + ctx context.Context, info *ModuleFileInfo, file []byte, +) (string, error) { + s.streamMu.Lock() + defer s.streamMu.Unlock() + + if ctx.Err() != nil { + return "", ctx.Err() + } + + ctx, cancel := context.WithCancel(ctx) + s.streamCancel = cancel + + stream, err := s.client.client.UploadModuleFile(ctx) + if err != nil { + return "", err + } + + err = stream.Send(&pb.UploadModuleFileRequest{ + ModuleFile: &pb.UploadModuleFileRequest_ModuleFileInfo{ + ModuleFileInfo: moduleFileInfoToProto(info), + }, + }) + if err != nil { + s.client.logger.CError(ctx, err) + return "", err + } + + // Create a background go routine to send to the server stream. + // We rely on calling the Done function here rather than in close stream + // since managed go calls that function when the routine exits. + s.activeBackgroundWorkers.Add(1) + utils.ManagedGo(func() { + s.sendToStream(ctx, stream, file) + }, + s.activeBackgroundWorkers.Done) + + resp, err := stream.CloseAndRecv() + if err != nil { + return "", err + } + return resp.Url, err +} + +func (s *uploadModuleFileStream) sendToStream( + ctx context.Context, stream pb.AppService_UploadModuleFileClient, file []byte, +) { + defer s.streamCancel() + + select { + case <-ctx.Done(): + s.client.logger.Debug(ctx.Err()) + return + default: + } + + err := stream.Send(&pb.UploadModuleFileRequest{ + ModuleFile: &pb.UploadModuleFileRequest_File{ + File: file, + }, + }) + if err != nil { + // only debug log the context canceled error + s.client.logger.Debug(err) + return + } +} From 5ecd457b5e65bc9641780a5876c7223a0ce0ca32 Mon Sep 17 00:00:00 2001 From: purplenicole730 Date: Tue, 19 Nov 2024 12:54:01 -0500 Subject: [PATCH 54/75] erase comment --- app/app_client.go | 10 ---------- 1 file changed, 10 deletions(-) diff --git a/app/app_client.go b/app/app_client.go index 21578f0826a..35a7187d159 100644 --- a/app/app_client.go +++ b/app/app_client.go @@ -1008,16 +1008,6 @@ func (c *AppClient) UpdateModule( // UploadModuleFile uploads a module file and returns the URL of the uploaded file. func (c *AppClient) UploadModuleFile(ctx context.Context, fileInfo ModuleFileInfo, file []byte) (string, error) { stream := &uploadModuleFileStream{client: c} - // reqModuleFileInfo := uploadModuleFileRequest{ - // ModuleFile: &uploadModuleFileRequestModuleFileInfo{ - // ModuleFileInfo: &fileInfo, - // }, - // } - // reqFile := uploadModuleFileRequest{ - // ModuleFile: &uploadModuleFileRequestFile{ - // File: file, - // }, - // } url, err := stream.startStream(ctx, &fileInfo, file) if err != nil { return "", err From cb0d9fb4fbc94bfb9138d47238f302345dd10954 Mon Sep 17 00:00:00 2001 From: purplenicole730 Date: Tue, 19 Nov 2024 15:26:03 -0500 Subject: [PATCH 55/75] add streaming tests --- app/app_client_test.go | 103 +++++++++++++++++++++---- testutils/inject/app_service_client.go | 42 +++++----- 2 files changed, 110 insertions(+), 35 deletions(-) diff --git a/app/app_client_test.go b/app/app_client_test.go index 4cd913f80ac..0432103a34b 100644 --- a/app/app_client_test.go +++ b/app/app_client_test.go @@ -2,6 +2,7 @@ package app import ( "context" + "errors" "fmt" "testing" @@ -80,6 +81,7 @@ const ( api = "api" modelString = "model_string" entryPoint = "entry_point" + errorsOnly = true ) var ( @@ -320,6 +322,19 @@ var ( Stack: stack, Fields: []*map[string]interface{}{&field}, } + pbCaller, _ = protoutils.StructToStructPb(*logEntry.Caller) + pbField, _ = protoutils.StructToStructPb(field) + pbLogEntry = common.LogEntry{ + Host: logEntry.Host, + Level: logEntry.Level, + Time: logEntry.Time, + LoggerName: logEntry.LoggerName, + Message: logEntry.Message, + Caller: pbCaller, + Stack: logEntry.Stack, + Fields: []*structpb.Struct{pbField}, + } + logEntries = []*LogEntry{&logEntry} authenticatorInfo = AuthenticatorInfo{ Type: AuthenticationTypeAPIKey, Value: value, @@ -528,6 +543,14 @@ var ( resourceID: resourceID, } apiKeyAuthorizations = []APIKeyAuthorization{apiKeyAuthorization} + platformTags = []string{"platform", "tags"} + fileInfo = ModuleFileInfo{ + ModuleID: moduleID, + Version: version, + Platform: platform, + PlatformTags: platformTags, + } + file = []byte{1, 9} ) func sharedSecretStateToProto(state SharedSecretState) pb.SharedSecret_State { @@ -674,6 +697,34 @@ func createGrpcClient() *inject.AppServiceClient { return &inject.AppServiceClient{} } +type mockTailRobotPartLogsClient struct { + grpc.ClientStream + responses []*pb.TailRobotPartLogsResponse + count int +} + +func (c *mockTailRobotPartLogsClient) Recv() (*pb.TailRobotPartLogsResponse, error) { + if c.count >= len(c.responses) { + return nil, errors.New("end of reponses") + } + resp := c.responses[c.count] + c.count++ + return resp, nil +} + +type mockUploadModuleFileClient struct { + grpc.ClientStream + response *pb.UploadModuleFileResponse +} + +func (c *mockUploadModuleFileClient) Send(*pb.UploadModuleFileRequest) error { + return nil +} + +func (c *mockUploadModuleFileClient) CloseAndRecv() (*pb.UploadModuleFileResponse, error) { + return c.response, nil +} + func TestAppClient(t *testing.T) { grpcClient := createGrpcClient() client := AppClient{client: grpcClient} @@ -1175,19 +1226,6 @@ func TestAppClient(t *testing.T) { }) t.Run("GetRobotPartLogs", func(t *testing.T) { - expectedLogs := []*LogEntry{&logEntry} - pbCaller, _ := protoutils.StructToStructPb(*logEntry.Caller) - pbField, _ := protoutils.StructToStructPb(field) - pbLogEntry := common.LogEntry{ - Host: logEntry.Host, - Level: logEntry.Level, - Time: logEntry.Time, - LoggerName: logEntry.LoggerName, - Message: logEntry.Message, - Caller: pbCaller, - Stack: logEntry.Stack, - Fields: []*structpb.Struct{pbField}, - } grpcClient.GetRobotPartLogsFunc = func( ctx context.Context, in *pb.GetRobotPartLogsRequest, opts ...grpc.CallOption, ) (*pb.GetRobotPartLogsResponse, error) { @@ -1207,7 +1245,31 @@ func TestAppClient(t *testing.T) { logs, token, err := client.GetRobotPartLogs(context.Background(), partID, &filter, &pageToken, levels, &start, &end, &limit, &source) test.That(t, err, test.ShouldBeNil) test.That(t, token, test.ShouldEqual, pageToken) - test.That(t, logs, test.ShouldResemble, expectedLogs) + test.That(t, logs, test.ShouldResemble, logEntries) + }) + + t.Run("TailRobotPartLogs", func(t *testing.T) { + ch := make(chan []*LogEntry) + grpcClient.TailRobotPartLogsFunc = func( + ctx context.Context, in *pb.TailRobotPartLogsRequest, opts ...grpc.CallOption, + ) (pb.AppService_TailRobotPartLogsClient, error) { + test.That(t, in.Id, test.ShouldEqual, partID) + test.That(t, in.ErrorsOnly, test.ShouldEqual, errorsOnly) + test.That(t, in.Filter, test.ShouldEqual, &filter) + return &mockTailRobotPartLogsClient{ + responses: []*pb.TailRobotPartLogsResponse{ + {Logs: []*common.LogEntry{&pbLogEntry}}, + }, + }, nil + } + err := client.TailRobotPartLogs(context.Background(), partID, errorsOnly, &filter, ch) + test.That(t, err, test.ShouldBeNil) + + // var resp [][]*LogEntry + // for entries := range ch { + // resp = append(resp, entries) + // } + // test.That(t, resp, test.ShouldResemble, logEntries) }) t.Run("GetRobotPartHistory", func(t *testing.T) { @@ -1719,6 +1781,19 @@ func TestAppClient(t *testing.T) { test.That(t, resp, test.ShouldEqual, siteURL) }) + t.Run("UploadModuleFile", func(t *testing.T) { + grpcClient.UploadModuleFileFunc = func(ctx context.Context, opts ...grpc.CallOption) (pb.AppService_UploadModuleFileClient, error) { + return &mockUploadModuleFileClient{ + response: &pb.UploadModuleFileResponse{ + Url: siteURL, + }, + }, nil + } + resp, err := client.UploadModuleFile(context.Background(), fileInfo, file) + test.That(t, err, test.ShouldBeNil) + test.That(t, resp, test.ShouldEqual, siteURL) + }) + t.Run("GetModule", func(t *testing.T) { grpcClient.GetModuleFunc = func( ctx context.Context, in *pb.GetModuleRequest, opts ...grpc.CallOption, diff --git a/testutils/inject/app_service_client.go b/testutils/inject/app_service_client.go index 6ed3e5036ed..c518cb1d780 100644 --- a/testutils/inject/app_service_client.go +++ b/testutils/inject/app_service_client.go @@ -81,7 +81,7 @@ type AppServiceClient struct { GetRobotPartLogsFunc func(ctx context.Context, in *apppb.GetRobotPartLogsRequest, opts ...grpc.CallOption) (*apppb.GetRobotPartLogsResponse, error) TailRobotPartLogsFunc func(ctx context.Context, in *apppb.TailRobotPartLogsRequest, - opts ...grpc.CallOption) (*apppb.TailRobotPartLogsRequest, error) + opts ...grpc.CallOption) (apppb.AppService_TailRobotPartLogsClient, error) GetRobotPartHistoryFunc func(ctx context.Context, in *apppb.GetRobotPartHistoryRequest, opts ...grpc.CallOption) (*apppb.GetRobotPartHistoryResponse, error) UpdateRobotPartFunc func(ctx context.Context, in *apppb.UpdateRobotPartRequest, @@ -148,9 +148,8 @@ type AppServiceClient struct { opts ...grpc.CallOption) (*apppb.CreateModuleResponse, error) UpdateModuleFunc func(ctx context.Context, in *apppb.UpdateModuleRequest, opts ...grpc.CallOption) (*apppb.UpdateModuleResponse, error) - UploadModuleFileFunc func(ctx context.Context, in *apppb.UploadModuleFileRequest, - opts ...grpc.CallOption) (*apppb.UploadModuleFileRequest, error) - GetModuleFunc func(ctx context.Context, in *apppb.GetModuleRequest, + UploadModuleFileFunc func(ctx context.Context, opts ...grpc.CallOption) (apppb.AppService_UploadModuleFileClient, error) + GetModuleFunc func(ctx context.Context, in *apppb.GetModuleRequest, opts ...grpc.CallOption) (*apppb.GetModuleResponse, error) ListModulesFunc func(ctx context.Context, in *apppb.ListModulesRequest, opts ...grpc.CallOption) (*apppb.ListModulesResponse, error) @@ -518,14 +517,15 @@ func (asc *AppServiceClient) GetRobotPartLogs( return asc.GetRobotPartLogsFunc(ctx, in, opts...) } -// // TailRobotPartLogs calls the injected TailRobotPartLogsFunc or the real version. -// func (asc *AppServiceClient) TailRobotPartLogs(ctx context.Context, in *apppb.TailRobotPartLogsRequest// opts ...grpc.CallOption, -// ) (*apppb.TailRobotPartLogsResponse, error) { -// if asc.TailRobotPartLogsFunc == nil { -// return asc.AppServiceClient.TailRobotPartLogs(ctx, in, opts...) -// } -// return asc.TailRobotPartLogsFunc(ctx, in, opts...) -// } +// TailRobotPartLogs calls the injected TailRobotPartLogsFunc or the real version. +func (asc *AppServiceClient) TailRobotPartLogs( + ctx context.Context, in *apppb.TailRobotPartLogsRequest, opts ...grpc.CallOption, +) (apppb.AppService_TailRobotPartLogsClient, error) { + if asc.TailRobotPartLogsFunc == nil { + return asc.AppServiceClient.TailRobotPartLogs(ctx, in, opts...) + } + return asc.TailRobotPartLogsFunc(ctx, in, opts...) +} // GetRobotPartHistory calls the injected GetRobotPartHistoryFunc or the real version. func (asc *AppServiceClient) GetRobotPartHistory( @@ -857,15 +857,15 @@ func (asc *AppServiceClient) UpdateModule( return asc.UpdateModuleFunc(ctx, in, opts...) } -// // UploadModuleFile calls the injected UploadModuleFileFunc or the real version. -// func (asc *AppServiceClient) UploadModuleFile( -// ctx context.Context, in *apppb.UploadModuleFileRequest, opts ...grpc.CallOption, -// ) (*apppb.UploadModuleFileResponse, error) { -// if asc.UploadModuleFileFunc == nil { -// return asc.AppServiceClient.UploadModuleFile(ctx, in, opts...) -// } -// return asc.UploadModuleFileFunc(ctx, in, opts...) -// } +// UploadModuleFile calls the injected UploadModuleFileFunc or the real version. +func (asc *AppServiceClient) UploadModuleFile( + ctx context.Context, opts ...grpc.CallOption, +) (apppb.AppService_UploadModuleFileClient, error) { + if asc.UploadModuleFileFunc == nil { + return asc.AppServiceClient.UploadModuleFile(ctx, opts...) + } + return asc.UploadModuleFileFunc(ctx, opts...) +} // GetModule calls the injected GetModuleFunc or the real version. func (asc *AppServiceClient) GetModule( From f2cfc3c70572660d482ee8151d90df7e131b3292 Mon Sep 17 00:00:00 2001 From: purplenicole730 Date: Tue, 19 Nov 2024 15:38:04 -0500 Subject: [PATCH 56/75] make publicly unused types private --- app/app_client_test.go | 8 ++++---- app/registry.go | 21 +++++++++------------ 2 files changed, 13 insertions(+), 16 deletions(-) diff --git a/app/app_client_test.go b/app/app_client_test.go index 0432103a34b..921bab1d20e 100644 --- a/app/app_client_test.go +++ b/app/app_client_test.go @@ -437,7 +437,7 @@ var ( }, } siteURL = "url" - metadata = RegistryItemMLTrainingMetadata{ + metadata = registryItemMLTrainingMetadata{ MlTrainingMetadata: &MLTrainingMetadata{ Versions: []*MLTrainingVersion{ { @@ -633,7 +633,7 @@ func mlTrainingMetadataToProto(md MLTrainingMetadata) *pb.MLTrainingMetadata { func registryItemToProto(item *RegistryItem) (*pb.RegistryItem, error) { switch metadata := item.Metadata.(type) { - case *RegistryItemModuleMetadata: + case *registryItemModuleMetadata: return &pb.RegistryItem{ ItemId: item.ItemID, OrganizationId: item.OrganizationID, @@ -651,7 +651,7 @@ func registryItemToProto(item *RegistryItem) (*pb.RegistryItem, error) { CreatedAt: item.CreatedAt, UpdatedAt: item.UpdatedAt, }, nil - case *RegistryItemMLModelMetadata: + case *registryItemMLModelMetadata: return &pb.RegistryItem{ ItemId: item.ItemID, OrganizationId: item.OrganizationID, @@ -669,7 +669,7 @@ func registryItemToProto(item *RegistryItem) (*pb.RegistryItem, error) { CreatedAt: item.CreatedAt, UpdatedAt: item.UpdatedAt, }, nil - case *RegistryItemMLTrainingMetadata: + case *registryItemMLTrainingMetadata: protoMetadata := mlTrainingMetadataToProto(*metadata.MlTrainingMetadata) return &pb.RegistryItem{ ItemId: item.ItemID, diff --git a/app/registry.go b/app/registry.go index 4c4349e82ae..f4937b2c55c 100644 --- a/app/registry.go +++ b/app/registry.go @@ -32,11 +32,11 @@ func registryItemFromProto(item *pb.RegistryItem) (*RegistryItem, error) { var metadata isRegistryItemMetadata switch pbMetadata := item.Metadata.(type) { case *pb.RegistryItem_ModuleMetadata: - metadata = &RegistryItemModuleMetadata{ModuleMetadata: moduleMetadataFromProto(pbMetadata.ModuleMetadata)} + metadata = ®istryItemModuleMetadata{ModuleMetadata: moduleMetadataFromProto(pbMetadata.ModuleMetadata)} case *pb.RegistryItem_MlModelMetadata: - metadata = &RegistryItemMLModelMetadata{MlModelMetadata: mlModelMetadataFromProto(pbMetadata.MlModelMetadata)} + metadata = ®istryItemMLModelMetadata{MlModelMetadata: mlModelMetadataFromProto(pbMetadata.MlModelMetadata)} case *pb.RegistryItem_MlTrainingMetadata: - metadata = &RegistryItemMLTrainingMetadata{MlTrainingMetadata: mlTrainingMetadataFromProto(pbMetadata.MlTrainingMetadata)} + metadata = ®istryItemMLTrainingMetadata{MlTrainingMetadata: mlTrainingMetadataFromProto(pbMetadata.MlTrainingMetadata)} default: return nil, fmt.Errorf("unknown registry item metadata type: %T", item.Metadata) } @@ -184,26 +184,23 @@ type isRegistryItemMetadata interface { isRegistryItemMetadata() } -// RegistryItemModuleMetadata is a registry item's module metadata. -type RegistryItemModuleMetadata struct { +type registryItemModuleMetadata struct { ModuleMetadata *ModuleMetadata } -// RegistryItemMLModelMetadata is a registry item's ML model metadata. -type RegistryItemMLModelMetadata struct { +type registryItemMLModelMetadata struct { MlModelMetadata *MLModelMetadata } -// RegistryItemMLTrainingMetadata is a registry item's ML Training metadata. -type RegistryItemMLTrainingMetadata struct { +type registryItemMLTrainingMetadata struct { MlTrainingMetadata *MLTrainingMetadata } -func (*RegistryItemModuleMetadata) isRegistryItemMetadata() {} +func (*registryItemModuleMetadata) isRegistryItemMetadata() {} -func (*RegistryItemMLModelMetadata) isRegistryItemMetadata() {} +func (*registryItemMLModelMetadata) isRegistryItemMetadata() {} -func (*RegistryItemMLTrainingMetadata) isRegistryItemMetadata() {} +func (*registryItemMLTrainingMetadata) isRegistryItemMetadata() {} // ModuleMetadata holds the metadata of a module. type ModuleMetadata struct { From fd6b33ec22f37be3a4c77bd521a78c33b578339a Mon Sep 17 00:00:00 2001 From: purplenicole730 Date: Tue, 19 Nov 2024 15:45:55 -0500 Subject: [PATCH 57/75] fix errors from merge --- app/app_client_test.go | 37 ++++++++++++++++----------------- app/data_client_test.go | 45 ++++++++++++++++++++--------------------- app/viam_client.go | 6 +++--- 3 files changed, 42 insertions(+), 46 deletions(-) diff --git a/app/app_client_test.go b/app/app_client_test.go index 921bab1d20e..8740912af7d 100644 --- a/app/app_client_test.go +++ b/app/app_client_test.go @@ -23,7 +23,6 @@ const ( organizationID2 = "organization_id_2" email = "email" userID = "user_id" - locationID = "location_id" available = true authorizationType = "owner" authorizationType2 = "operator" @@ -39,9 +38,7 @@ const ( secretID = "secret_ids" primary = true robotCount = 1 - robotID = "robot_id" robotLocation = "robot_location" - partID = "part_id" dnsName = "dns_name" secret = "secret" mainPart = false @@ -302,20 +299,20 @@ var ( Secrets: pbSecrets, LastUpdated: robotPart.LastUpdated, } - pageToken = "page_token" - levels = []string{level} - start = timestamppb.Timestamp{Seconds: 92, Nanos: 0} - end = timestamppb.Timestamp{Seconds: 99, Nanos: 999} - limit int64 = 2 - source = "source" - filter = "filter" - time = timestamppb.Timestamp{Seconds: 11, Nanos: 15} - caller = map[string]interface{}{"name": name} - field = map[string]interface{}{"key": "value"} - logEntry = LogEntry{ + pageToken = "page_token" + levels = []string{level} + start = timestamppb.Timestamp{Seconds: 92, Nanos: 0} + end = timestamppb.Timestamp{Seconds: 99, Nanos: 999} + int64Limit int64 = 2 + source = "source" + filter = "filter" + timestamp = timestamppb.Timestamp{Seconds: 11, Nanos: 15} + caller = map[string]interface{}{"name": name} + field = map[string]interface{}{"key": "value"} + logEntry = LogEntry{ Host: host, Level: level, - Time: &time, + Time: ×tamp, LoggerName: loggerName, Message: message, Caller: &caller, @@ -348,7 +345,7 @@ var ( robotPartHistoryEntry = RobotPartHistoryEntry{ Part: partID, Robot: robotID, - When: &time, + When: ×tamp, Old: &robotPart, EditedBy: &authenticatorInfo, } @@ -693,7 +690,7 @@ func registryItemToProto(item *RegistryItem) (*pb.RegistryItem, error) { } } -func createGrpcClient() *inject.AppServiceClient { +func createAppGrpcClient() *inject.AppServiceClient { return &inject.AppServiceClient{} } @@ -726,7 +723,7 @@ func (c *mockUploadModuleFileClient) CloseAndRecv() (*pb.UploadModuleFileRespons } func TestAppClient(t *testing.T) { - grpcClient := createGrpcClient() + grpcClient := createAppGrpcClient() client := AppClient{client: grpcClient} t.Run("GetUserIDByEmail", func(t *testing.T) { @@ -1242,7 +1239,7 @@ func TestAppClient(t *testing.T) { NextPageToken: pageToken, }, nil } - logs, token, err := client.GetRobotPartLogs(context.Background(), partID, &filter, &pageToken, levels, &start, &end, &limit, &source) + logs, token, err := client.GetRobotPartLogs(context.Background(), partID, &filter, &pageToken, levels, &start, &end, &int64Limit, &source) test.That(t, err, test.ShouldBeNil) test.That(t, token, test.ShouldEqual, pageToken) test.That(t, logs, test.ShouldResemble, logEntries) @@ -1528,7 +1525,7 @@ func TestAppClient(t *testing.T) { NextPageToken: pageToken, }, nil } - resp, token, err := client.GetFragmentHistory(context.Background(), fragmentID, &pageToken, &limit) + resp, token, err := client.GetFragmentHistory(context.Background(), fragmentID, &pageToken, &int64Limit) test.That(t, err, test.ShouldBeNil) test.That(t, token, test.ShouldEqual, pageToken) test.That(t, resp, test.ShouldResemble, expectedHistory) diff --git a/app/data_client_test.go b/app/data_client_test.go index 5a3a22468a0..d16dd382639 100644 --- a/app/data_client_test.go +++ b/app/data_client_test.go @@ -16,27 +16,26 @@ import ( ) const ( - componentName = "component_name" - componentType = "component_type" - method = "method" - robotName = "robot_name" - robotID = "robot_id" - partName = "part_name" - partID = "part_id" - locationID = "location_id" - organizationID = "organization_id" - password = "password" - mimeType = "mime_type" - uri = "some.robot.uri" - bboxLabel = "bbox_label" - tag = "tag" - fileName = "file_name" - fileExt = "file_ext.ext" - datasetID = "dataset_id" - binaryMetaID = "binary_id" - mongodbURI = "mongo_uri" - hostName = "host_name" - last = "last" + componentName = "component_name" + componentType = "component_type" + method = "method" + robotName = "robot_name" + robotID = "robot_id" + partName = "part_name" + partID = "part_id" + locationID = "location_id" + password = "password" + mimeType = "mime_type" + uri = "some.robot.uri" + bboxLabel = "bbox_label" + tag = "tag" + fileName = "file_name" + fileExt = "file_ext.ext" + datasetID = "dataset_id" + binaryMetaID = "binary_id" + mongodbURI = "mongo_uri" + hostName = "host_name" + last = "last" ) var ( @@ -153,12 +152,12 @@ func dataRequestToProto(dataRequest DataRequest) *pb.DataRequest { } } -func createGrpcClient() *inject.DataServiceClient { +func createDataGrpcClient() *inject.DataServiceClient { return &inject.DataServiceClient{} } func TestDataClient(t *testing.T) { - grpcClient := createGrpcClient() + grpcClient := createDataGrpcClient() client := DataClient{client: grpcClient} captureInterval := CaptureInterval{ diff --git a/app/viam_client.go b/app/viam_client.go index 03792261d29..45fb151c8e2 100644 --- a/app/viam_client.go +++ b/app/viam_client.go @@ -14,10 +14,10 @@ import ( // ViamClient is a gRPC client for method calls to Viam app. type ViamClient struct { - conn rpc.ClientConn - logger logging.Logger + conn rpc.ClientConn + logger logging.Logger dataClient *DataClient - appClient *AppClient + appClient *AppClient } // Options has the options necessary to connect through gRPC. From 7854e076b6288a1b6c5029935ffcebb1c88ca7c2 Mon Sep 17 00:00:00 2001 From: purplenicole730 Date: Tue, 19 Nov 2024 16:09:14 -0500 Subject: [PATCH 58/75] fix test --- app/app_client_test.go | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/app/app_client_test.go b/app/app_client_test.go index 8740912af7d..0f84238687a 100644 --- a/app/app_client_test.go +++ b/app/app_client_test.go @@ -1232,7 +1232,7 @@ func TestAppClient(t *testing.T) { test.That(t, in.Levels, test.ShouldResemble, levels) test.That(t, in.Start, test.ShouldEqual, &start) test.That(t, in.End, test.ShouldEqual, &end) - test.That(t, in.Limit, test.ShouldEqual, &limit) + test.That(t, in.Limit, test.ShouldEqual, &int64Limit) test.That(t, in.Source, test.ShouldEqual, &source) return &pb.GetRobotPartLogsResponse{ Logs: []*common.LogEntry{&pbLogEntry}, @@ -1512,7 +1512,7 @@ func TestAppClient(t *testing.T) { ) (*pb.GetFragmentHistoryResponse, error) { test.That(t, in.Id, test.ShouldEqual, fragmentID) test.That(t, in.PageToken, test.ShouldResemble, &pageToken) - test.That(t, in.PageLimit, test.ShouldResemble, &limit) + test.That(t, in.PageLimit, test.ShouldResemble, &int64Limit) return &pb.GetFragmentHistoryResponse{ History: []*pb.FragmentHistoryEntry{ { From de432e1c851f2a577bc93dbb89b786b6b45285bc Mon Sep 17 00:00:00 2001 From: purplenicole730 Date: Wed, 20 Nov 2024 09:21:05 -0500 Subject: [PATCH 59/75] clarify return types --- app/app_client.go | 22 +++++++++++----------- 1 file changed, 11 insertions(+), 11 deletions(-) diff --git a/app/app_client.go b/app/app_client.go index 35a7187d159..34a682d1428 100644 --- a/app/app_client.go +++ b/app/app_client.go @@ -450,8 +450,8 @@ func (c *AppClient) GetRobotPart(ctx context.Context, id string) (*RobotPart, st return robotPartFromProto(resp.Part), resp.ConfigJson, nil } -// GetRobotPartLogs gets the logs associated with a robot part from a page, defaulting to the most recent page if pageToken is empty. -// Logs of all levels are returned when levels is empty. +// GetRobotPartLogs gets the logs associated with a robot part and the next page token, +// defaulting to the most recent page if pageToken is empty. Logs of all levels are returned when levels is empty. func (c *AppClient) GetRobotPartLogs( ctx context.Context, id string, @@ -529,7 +529,7 @@ func (c *AppClient) UpdateRobotPart(ctx context.Context, id, name string, robotC return robotPartFromProto(resp.Part), nil } -// NewRobotPart creates a new robot part. +// NewRobotPart creates a new robot part and returns its ID. func (c *AppClient) NewRobotPart(ctx context.Context, robotID, partName string) (string, error) { resp, err := c.client.NewRobotPart(ctx, &pb.NewRobotPartRequest{ RobotId: robotID, @@ -618,7 +618,7 @@ func (c *AppClient) ListRobots(ctx context.Context, locationID string) ([]*Robot return robots, nil } -// NewRobot creates a new robot. +// NewRobot creates a new robot and returns its ID. func (c *AppClient) NewRobot(ctx context.Context, name, location string) (string, error) { resp, err := c.client.NewRobot(ctx, &pb.NewRobotRequest{ Name: name, @@ -754,7 +754,7 @@ func (c *AppClient) ListMachineFragments(ctx context.Context, machineID string, return fragments, nil } -// GetFragmentHistory gets the fragment's history. +// GetFragmentHistory gets the fragment's history and the next page token. func (c *AppClient) GetFragmentHistory( ctx context.Context, id string, pageToken *string, pageLimit *int64, ) ([]*FragmentHistoryEntry, string, error) { @@ -969,7 +969,7 @@ func (c *AppClient) TransferRegistryItem(ctx context.Context, itemID, newPublicN return err } -// CreateModule creates a module. +// CreateModule creates a module and returns its ID and URL. func (c *AppClient) CreateModule(ctx context.Context, orgID, name string) (string, string, error) { resp, err := c.client.CreateModule(ctx, &pb.CreateModuleRequest{ OrganizationId: orgID, @@ -981,7 +981,7 @@ func (c *AppClient) CreateModule(ctx context.Context, orgID, name string) (strin return resp.ModuleId, resp.Url, nil } -// UpdateModule updates the documentation URL, description, models, entrypoint, and/or the visibility of a module. +// UpdateModule updates the documentation URL, description, models, entrypoint, and/or the visibility of a module and returns its URL. // A path to a setup script can be added that is run before a newly downloaded module starts. func (c *AppClient) UpdateModule( ctx context.Context, moduleID string, visibility Visibility, url, description string, models []*Model, entrypoint string, firstRun *string, @@ -1044,7 +1044,7 @@ func (c *AppClient) ListModules(ctx context.Context, orgID *string) ([]*Module, return modules, nil } -// CreateKey creates a new API key associated with a list of authorizations. +// CreateKey creates a new API key associated with a list of authorizations and returns its key and ID. func (c *AppClient) CreateKey( ctx context.Context, orgID string, keyAuthorizations []APIKeyAuthorization, name string, ) (string, string, error) { @@ -1091,7 +1091,7 @@ func (c *AppClient) ListKeys(ctx context.Context, orgID string) ([]*APIKeyWithAu return apiKeys, nil } -// RenameKey renames an API key. +// RenameKey renames an API key and returns its ID and name. func (c *AppClient) RenameKey(ctx context.Context, id, name string) (string, string, error) { resp, err := c.client.RenameKey(ctx, &pb.RenameKeyRequest{ Id: id, @@ -1103,7 +1103,7 @@ func (c *AppClient) RenameKey(ctx context.Context, id, name string) (string, str return resp.Id, resp.Name, nil } -// RotateKey rotates an API key. +// RotateKey rotates an API key and returns its ID and key. func (c *AppClient) RotateKey(ctx context.Context, id string) (string, string, error) { resp, err := c.client.RotateKey(ctx, &pb.RotateKeyRequest{ Id: id, @@ -1114,7 +1114,7 @@ func (c *AppClient) RotateKey(ctx context.Context, id string) (string, string, e return resp.Id, resp.Key, nil } -// CreateKeyFromExistingKeyAuthorizations creates a new API key with an existing key's authorizations. +// CreateKeyFromExistingKeyAuthorizations creates a new API key with an existing key's authorizations and returns its ID and key. func (c *AppClient) CreateKeyFromExistingKeyAuthorizations(ctx context.Context, id string) (string, string, error) { resp, err := c.client.CreateKeyFromExistingKeyAuthorizations(ctx, &pb.CreateKeyFromExistingKeyAuthorizationsRequest{ Id: id, From be40e73eec042f2da79841f745fe6b61599e1597 Mon Sep 17 00:00:00 2001 From: purplenicole730 Date: Wed, 20 Nov 2024 09:22:29 -0500 Subject: [PATCH 60/75] rename types file --- app/{resource_types.go => app_types.go} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename app/{resource_types.go => app_types.go} (100%) diff --git a/app/resource_types.go b/app/app_types.go similarity index 100% rename from app/resource_types.go rename to app/app_types.go From 29507c1c477221682fca3a240d3684fc03cac10e Mon Sep 17 00:00:00 2001 From: purplenicole730 Date: Wed, 20 Nov 2024 09:35:55 -0500 Subject: [PATCH 61/75] fix package comment --- app/app_client.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/app/app_client.go b/app/app_client.go index 34a682d1428..062861f2e93 100644 --- a/app/app_client.go +++ b/app/app_client.go @@ -1,4 +1,4 @@ -// Package app defines the interfaces that manage a machine fleet with code instead of with the graphical interface of the Viam App. +// Package app contains the interfaces that manage a machine fleet with code instead of with the graphical interface of the Viam App. // // [fleet management docs]: https://docs.viam.com/appendix/apis/fleet/ package app From a1e5b49771b267b540896cdd95dafcaf4108e86e Mon Sep 17 00:00:00 2001 From: purplenicole730 Date: Wed, 20 Nov 2024 15:01:16 -0500 Subject: [PATCH 62/75] fix comment --- app/viam_client.go | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/app/viam_client.go b/app/viam_client.go index 45fb151c8e2..a0f9e7789e6 100644 --- a/app/viam_client.go +++ b/app/viam_client.go @@ -75,8 +75,8 @@ func (c *ViamClient) DataClient() *DataClient { return c.dataClient } -// AppClient initializes and returns a DataClient instance used to make data method calls. -// To use DataClient, you must first instantiate a ViamClient. +// AppClient initializes and returns an AppClient instance used to make app method calls. +// To use AppClient, you must first instantiate a ViamClient. func (c *ViamClient) AppClient() *AppClient { if c.appClient != nil { return c.appClient From 8057428d54dfab5245a402f64ee1e329f3fead05 Mon Sep 17 00:00:00 2001 From: purplenicole730 Date: Wed, 20 Nov 2024 15:03:21 -0500 Subject: [PATCH 63/75] fix comments --- app/app_client.go | 2 +- app/data_client.go | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/app/app_client.go b/app/app_client.go index 062861f2e93..751ffa4f74c 100644 --- a/app/app_client.go +++ b/app/app_client.go @@ -26,7 +26,7 @@ type AppClient struct { mu sync.Mutex } -// NewAppClient constructs a new AppClient using the connection passed in by the viamClient and the provided logger. +// NewAppClient constructs a new AppClient using the connection passed in by the Viam client. func NewAppClient(conn rpc.ClientConn, logger logging.Logger) *AppClient { return &AppClient{client: pb.NewAppServiceClient(conn), logger: logger} } diff --git a/app/data_client.go b/app/data_client.go index 8578eefc9e2..2415852548b 100644 --- a/app/data_client.go +++ b/app/data_client.go @@ -177,7 +177,7 @@ type DatabaseConnReturn struct { HasDatabaseUser bool } -// NewDataClient constructs a new DataClient using the connection passed in by the viamClient. +// NewDataClient constructs a new DataClient using the connection passed in by the Viam client. func NewDataClient( conn rpc.ClientConn, ) *DataClient { From 3aafa8fababa50c935462a730105c5ef8446bfe4 Mon Sep 17 00:00:00 2001 From: purplenicole730 Date: Thu, 21 Nov 2024 12:10:56 -0500 Subject: [PATCH 64/75] put in alphabetical order --- app/viam_client.go | 22 +++++++++++----------- 1 file changed, 11 insertions(+), 11 deletions(-) diff --git a/app/viam_client.go b/app/viam_client.go index a0f9e7789e6..fb88275746d 100644 --- a/app/viam_client.go +++ b/app/viam_client.go @@ -16,8 +16,8 @@ import ( type ViamClient struct { conn rpc.ClientConn logger logging.Logger - dataClient *DataClient appClient *AppClient + dataClient *DataClient } // Options has the options necessary to connect through gRPC. @@ -65,16 +65,6 @@ func CreateViamClientWithAPIKey( return CreateViamClientWithOptions(ctx, options, logger) } -// DataClient initializes and returns a DataClient instance used to make data method calls. -// To use DataClient, you must first instantiate a ViamClient. -func (c *ViamClient) DataClient() *DataClient { - if c.dataClient != nil { - return c.dataClient - } - c.dataClient = NewDataClient(c.conn) - return c.dataClient -} - // AppClient initializes and returns an AppClient instance used to make app method calls. // To use AppClient, you must first instantiate a ViamClient. func (c *ViamClient) AppClient() *AppClient { @@ -85,6 +75,16 @@ func (c *ViamClient) AppClient() *AppClient { return c.appClient } +// DataClient initializes and returns a DataClient instance used to make data method calls. +// To use DataClient, you must first instantiate a ViamClient. +func (c *ViamClient) DataClient() *DataClient { + if c.dataClient != nil { + return c.dataClient + } + c.dataClient = NewDataClient(c.conn) + return c.dataClient +} + // Close closes the gRPC connection. func (c *ViamClient) Close() error { return c.conn.Close() From e79639586943105bc8d5b50001e5eb9f123d7480 Mon Sep 17 00:00:00 2001 From: purplenicole730 Date: Thu, 21 Nov 2024 12:27:51 -0500 Subject: [PATCH 65/75] upload file in chunks --- app/stream.go | 35 ++++++++++++++++++++++------------- 1 file changed, 22 insertions(+), 13 deletions(-) diff --git a/app/stream.go b/app/stream.go index b9034a93fcb..e9ab35dbe52 100644 --- a/app/stream.go +++ b/app/stream.go @@ -140,21 +140,30 @@ func (s *uploadModuleFileStream) sendToStream( ) { defer s.streamCancel() - select { - case <-ctx.Done(): - s.client.logger.Debug(ctx.Err()) - return - default: - } + uploadChunkSize := 64 * 1024 //64 kB in bytes + for start := 0; start < len(file); start += uploadChunkSize { + select { + case <- ctx.Done(): + s.client.logger.Debug(ctx.Err()) + return + default: + } - err := stream.Send(&pb.UploadModuleFileRequest{ - ModuleFile: &pb.UploadModuleFileRequest_File{ - File: file, - }, - }) - if err != nil { - // only debug log the context canceled error + end := start + uploadChunkSize + if end > len(file) { + end = len(file) + } + + chunk := file[start:end] + err := stream.Send(&pb.UploadModuleFileRequest{ + ModuleFile: &pb.UploadModuleFileRequest_File{ + File: chunk, + }, + }) + if err != nil { + // only debug log the context canceled error s.client.logger.Debug(err) return + } } } From e4d66a82755ca13723058b8fdd2b7fa7532c60cc Mon Sep 17 00:00:00 2001 From: purplenicole730 Date: Thu, 21 Nov 2024 12:29:05 -0500 Subject: [PATCH 66/75] make lint --- app/stream.go | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/app/stream.go b/app/stream.go index e9ab35dbe52..f846a941781 100644 --- a/app/stream.go +++ b/app/stream.go @@ -140,10 +140,10 @@ func (s *uploadModuleFileStream) sendToStream( ) { defer s.streamCancel() - uploadChunkSize := 64 * 1024 //64 kB in bytes + uploadChunkSize := 64 * 1024 // 64 kB in bytes for start := 0; start < len(file); start += uploadChunkSize { select { - case <- ctx.Done(): + case <-ctx.Done(): s.client.logger.Debug(ctx.Err()) return default: @@ -162,8 +162,8 @@ func (s *uploadModuleFileStream) sendToStream( }) if err != nil { // only debug log the context canceled error - s.client.logger.Debug(err) - return + s.client.logger.Debug(err) + return } } } From fa86145dee1ed146b3bf0cc366623cb45aafb708 Mon Sep 17 00:00:00 2001 From: purplenicole730 Date: Thu, 21 Nov 2024 13:13:31 -0500 Subject: [PATCH 67/75] change stream tests --- app/app_client_test.go | 68 +++++++++++--------------- testutils/inject/app_service_client.go | 37 ++++++++++++++ 2 files changed, 65 insertions(+), 40 deletions(-) diff --git a/app/app_client_test.go b/app/app_client_test.go index 0f84238687a..77045b27c29 100644 --- a/app/app_client_test.go +++ b/app/app_client_test.go @@ -2,7 +2,6 @@ package app import ( "context" - "errors" "fmt" "testing" @@ -694,34 +693,6 @@ func createAppGrpcClient() *inject.AppServiceClient { return &inject.AppServiceClient{} } -type mockTailRobotPartLogsClient struct { - grpc.ClientStream - responses []*pb.TailRobotPartLogsResponse - count int -} - -func (c *mockTailRobotPartLogsClient) Recv() (*pb.TailRobotPartLogsResponse, error) { - if c.count >= len(c.responses) { - return nil, errors.New("end of reponses") - } - resp := c.responses[c.count] - c.count++ - return resp, nil -} - -type mockUploadModuleFileClient struct { - grpc.ClientStream - response *pb.UploadModuleFileResponse -} - -func (c *mockUploadModuleFileClient) Send(*pb.UploadModuleFileRequest) error { - return nil -} - -func (c *mockUploadModuleFileClient) CloseAndRecv() (*pb.UploadModuleFileResponse, error) { - return c.response, nil -} - func TestAppClient(t *testing.T) { grpcClient := createAppGrpcClient() client := AppClient{client: grpcClient} @@ -1246,6 +1217,13 @@ func TestAppClient(t *testing.T) { }) t.Run("TailRobotPartLogs", func(t *testing.T) { + mockStream := &inject.AppServiceTailRobotPartLogsClient{ + RecvFunc: func() (*pb.TailRobotPartLogsResponse, error) { + return &pb.TailRobotPartLogsResponse{ + Logs: []*common.LogEntry{&pbLogEntry}, + }, nil + }, + } ch := make(chan []*LogEntry) grpcClient.TailRobotPartLogsFunc = func( ctx context.Context, in *pb.TailRobotPartLogsRequest, opts ...grpc.CallOption, @@ -1253,11 +1231,7 @@ func TestAppClient(t *testing.T) { test.That(t, in.Id, test.ShouldEqual, partID) test.That(t, in.ErrorsOnly, test.ShouldEqual, errorsOnly) test.That(t, in.Filter, test.ShouldEqual, &filter) - return &mockTailRobotPartLogsClient{ - responses: []*pb.TailRobotPartLogsResponse{ - {Logs: []*common.LogEntry{&pbLogEntry}}, - }, - }, nil + return mockStream, nil } err := client.TailRobotPartLogs(context.Background(), partID, errorsOnly, &filter, ch) test.That(t, err, test.ShouldBeNil) @@ -1266,7 +1240,7 @@ func TestAppClient(t *testing.T) { // for entries := range ch { // resp = append(resp, entries) // } - // test.That(t, resp, test.ShouldResemble, logEntries) + // test.That(t, resp, test.ShouldResemble, [][]*LogEntry{logEntries}) }) t.Run("GetRobotPartHistory", func(t *testing.T) { @@ -1779,12 +1753,26 @@ func TestAppClient(t *testing.T) { }) t.Run("UploadModuleFile", func(t *testing.T) { - grpcClient.UploadModuleFileFunc = func(ctx context.Context, opts ...grpc.CallOption) (pb.AppService_UploadModuleFileClient, error) { - return &mockUploadModuleFileClient{ - response: &pb.UploadModuleFileResponse{ + mockStream := &inject.AppServiceUploadModuleFileClient{ + SendFunc: func(req *pb.UploadModuleFileRequest) error { + switch moduleFile := req.ModuleFile.(type) { + case *pb.UploadModuleFileRequest_ModuleFileInfo: + test.That(t, moduleFile.ModuleFileInfo, test.ShouldResemble, moduleFileInfoToProto(&fileInfo)) + case *pb.UploadModuleFileRequest_File: + test.That(t, moduleFile.File, test.ShouldResemble, file) + default: + t.Error("unexpected module file type") + } + return nil + }, + CloseAndRecvFunc: func() (*pb.UploadModuleFileResponse, error) { + return &pb.UploadModuleFileResponse{ Url: siteURL, - }, - }, nil + }, nil + }, + } + grpcClient.UploadModuleFileFunc = func(ctx context.Context, opts ...grpc.CallOption) (pb.AppService_UploadModuleFileClient, error) { + return mockStream, nil } resp, err := client.UploadModuleFile(context.Background(), fileInfo, file) test.That(t, err, test.ShouldBeNil) diff --git a/testutils/inject/app_service_client.go b/testutils/inject/app_service_client.go index c518cb1d780..cd86a913ddb 100644 --- a/testutils/inject/app_service_client.go +++ b/testutils/inject/app_service_client.go @@ -527,6 +527,20 @@ func (asc *AppServiceClient) TailRobotPartLogs( return asc.TailRobotPartLogsFunc(ctx, in, opts...) } +// AppServiceTailRobotPartLogsClient represents a fake instance of a pb.AppService_TailRobotPartLogsClient. +type AppServiceTailRobotPartLogsClient struct { + apppb.AppService_TailRobotPartLogsClient + RecvFunc func() (*apppb.TailRobotPartLogsResponse, error) +} + +// Recv calls the injected RecvFunc or the real version. +func (c *AppServiceTailRobotPartLogsClient) Recv() (*apppb.TailRobotPartLogsResponse, error) { + if c.RecvFunc == nil { + return c.AppService_TailRobotPartLogsClient.Recv() + } + return c.RecvFunc() +} + // GetRobotPartHistory calls the injected GetRobotPartHistoryFunc or the real version. func (asc *AppServiceClient) GetRobotPartHistory( ctx context.Context, in *apppb.GetRobotPartHistoryRequest, opts ...grpc.CallOption, @@ -867,6 +881,29 @@ func (asc *AppServiceClient) UploadModuleFile( return asc.UploadModuleFileFunc(ctx, opts...) } +// AppServiceUploadModuleFileClient represents a fake instance of a pb.AppService_UploadModuleFileClient. +type AppServiceUploadModuleFileClient struct { + apppb.AppService_UploadModuleFileClient + SendFunc func(*apppb.UploadModuleFileRequest) error + CloseAndRecvFunc func() (*apppb.UploadModuleFileResponse, error) +} + +// Send calls the injected SendFunc or the real version. +func (c *AppServiceUploadModuleFileClient) Send(req *apppb.UploadModuleFileRequest) error { + if c.SendFunc == nil { + return c.AppService_UploadModuleFileClient.Send(req) + } + return c.SendFunc(req) +} + +// CloseAndRecv calls the injected CloseAndRecvFunc or the real version. +func (c *AppServiceUploadModuleFileClient) CloseAndRecv() (*apppb.UploadModuleFileResponse, error) { + if c.CloseAndRecvFunc == nil { + return c.AppService_UploadModuleFileClient.CloseAndRecv() + } + return c.CloseAndRecvFunc() +} + // GetModule calls the injected GetModuleFunc or the real version. func (asc *AppServiceClient) GetModule( ctx context.Context, in *apppb.GetModuleRequest, opts ...grpc.CallOption, From d3e027a3e3c27eb2861202911c0b52820ef0c53f Mon Sep 17 00:00:00 2001 From: purplenicole730 Date: Thu, 21 Nov 2024 13:20:37 -0500 Subject: [PATCH 68/75] change comments --- testutils/inject/app_service_client.go | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/testutils/inject/app_service_client.go b/testutils/inject/app_service_client.go index cd86a913ddb..bc31925078b 100644 --- a/testutils/inject/app_service_client.go +++ b/testutils/inject/app_service_client.go @@ -527,7 +527,7 @@ func (asc *AppServiceClient) TailRobotPartLogs( return asc.TailRobotPartLogsFunc(ctx, in, opts...) } -// AppServiceTailRobotPartLogsClient represents a fake instance of a pb.AppService_TailRobotPartLogsClient. +// AppServiceTailRobotPartLogsClient represents a fake instance of a proto AppService_TailRobotPartLogsClient. type AppServiceTailRobotPartLogsClient struct { apppb.AppService_TailRobotPartLogsClient RecvFunc func() (*apppb.TailRobotPartLogsResponse, error) @@ -881,7 +881,7 @@ func (asc *AppServiceClient) UploadModuleFile( return asc.UploadModuleFileFunc(ctx, opts...) } -// AppServiceUploadModuleFileClient represents a fake instance of a pb.AppService_UploadModuleFileClient. +// AppServiceUploadModuleFileClient represents a fake instance of a proto AppService_UploadModuleFileClient. type AppServiceUploadModuleFileClient struct { apppb.AppService_UploadModuleFileClient SendFunc func(*apppb.UploadModuleFileRequest) error From cd03c535975b75a080bd3c2937aa0119155b5bd6 Mon Sep 17 00:00:00 2001 From: purplenicole730 Date: Thu, 21 Nov 2024 13:34:45 -0500 Subject: [PATCH 69/75] use ellipsis --- app/app_client_test.go | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/app/app_client_test.go b/app/app_client_test.go index 77045b27c29..21092f4c52f 100644 --- a/app/app_client_test.go +++ b/app/app_client_test.go @@ -1236,11 +1236,11 @@ func TestAppClient(t *testing.T) { err := client.TailRobotPartLogs(context.Background(), partID, errorsOnly, &filter, ch) test.That(t, err, test.ShouldBeNil) - // var resp [][]*LogEntry + // var resp []*LogEntry // for entries := range ch { - // resp = append(resp, entries) + // resp = append(resp, entries...) // } - // test.That(t, resp, test.ShouldResemble, [][]*LogEntry{logEntries}) + // test.That(t, resp, test.ShouldResemble, logEntries) }) t.Run("GetRobotPartHistory", func(t *testing.T) { From 0fad2a60dda8e39e25c9843b838086378cd455cd Mon Sep 17 00:00:00 2001 From: purplenicole730 Date: Thu, 21 Nov 2024 13:46:13 -0500 Subject: [PATCH 70/75] rename files --- app/{app_types.go => app_proto_conversions.go} | 0 app/{registry.go => registry_proto_conversions.go} | 0 2 files changed, 0 insertions(+), 0 deletions(-) rename app/{app_types.go => app_proto_conversions.go} (100%) rename app/{registry.go => registry_proto_conversions.go} (100%) diff --git a/app/app_types.go b/app/app_proto_conversions.go similarity index 100% rename from app/app_types.go rename to app/app_proto_conversions.go diff --git a/app/registry.go b/app/registry_proto_conversions.go similarity index 100% rename from app/registry.go rename to app/registry_proto_conversions.go From 7c45587e340b194f88dfda2c73b0e42cd2c00fb1 Mon Sep 17 00:00:00 2001 From: purplenicole730 Date: Thu, 21 Nov 2024 15:50:17 -0500 Subject: [PATCH 71/75] use functional options --- app/app_client.go | 247 ++++++++++++++++++++++++++--------------- app/app_client_test.go | 85 ++++++++------ 2 files changed, 211 insertions(+), 121 deletions(-) diff --git a/app/app_client.go b/app/app_client.go index 751ffa4f74c..035ab3ea9d7 100644 --- a/app/app_client.go +++ b/app/app_client.go @@ -121,14 +121,22 @@ func (c *AppClient) GetOrganizationNamespaceAvailability(ctx context.Context, na return resp.Available, nil } +// UpdateOrganizationOptions contains optional parameters for UpdateOrganization. +type UpdateOrganizationOptions struct { + Name *string + Namespace *string + Region *string + CID *string +} + // UpdateOrganization updates an organization. -func (c *AppClient) UpdateOrganization(ctx context.Context, orgID string, name, namespace, region, cid *string) (*Organization, error) { +func (c *AppClient) UpdateOrganization(ctx context.Context, orgID string, opts UpdateOrganizationOptions) (*Organization, error) { resp, err := c.client.UpdateOrganization(ctx, &pb.UpdateOrganizationRequest{ OrganizationId: orgID, - Name: name, - PublicNamespace: namespace, - Region: region, - Cid: cid, + Name: opts.Name, + PublicNamespace: opts.Namespace, + Region: opts.Region, + Cid: opts.CID, }) if err != nil { return nil, err @@ -164,9 +172,14 @@ func (c *AppClient) ListOrganizationMembers(ctx context.Context, orgID string) ( return members, invites, nil } +// CreateOrganizationInviteOptions contains optional parameters for CreateOrganizationInvite. +type CreateOrganizationInviteOptions struct { + SendEmailInvite *bool +} + // CreateOrganizationInvite creates an organization invite to an organization. func (c *AppClient) CreateOrganizationInvite( - ctx context.Context, orgID, email string, authorizations []*Authorization, sendEmailInvite *bool, + ctx context.Context, orgID, email string, authorizations []*Authorization, opts CreateOrganizationInviteOptions, ) (*OrganizationInvite, error) { var pbAuthorizations []*pb.Authorization for _, authorization := range authorizations { @@ -176,7 +189,7 @@ func (c *AppClient) CreateOrganizationInvite( OrganizationId: orgID, Email: email, Authorizations: pbAuthorizations, - SendEmailInvite: sendEmailInvite, + SendEmailInvite: opts.SendEmailInvite, }) if err != nil { return nil, err @@ -287,12 +300,17 @@ func (c *AppClient) OrganizationGetSupportEmail(ctx context.Context, orgID strin return resp.Email, nil } +// CreateLocationOptions contains optional parameters for CreateLocation. +type CreateLocationOptions struct { + ParentLocationID *string +} + // CreateLocation creates a location. -func (c *AppClient) CreateLocation(ctx context.Context, orgID, name string, parentLocationID *string) (*Location, error) { +func (c *AppClient) CreateLocation(ctx context.Context, orgID, name string, opts CreateLocationOptions) (*Location, error) { resp, err := c.client.CreateLocation(ctx, &pb.CreateLocationRequest{ OrganizationId: orgID, Name: name, - ParentLocationId: parentLocationID, + ParentLocationId: opts.ParentLocationID, }) if err != nil { return nil, err @@ -311,13 +329,20 @@ func (c *AppClient) GetLocation(ctx context.Context, locationID string) (*Locati return locationFromProto(resp.Location), nil } +// UpdateLocationOptions contains optional parameters for UpdateLocation. +type UpdateLocationOptions struct { + Name *string + ParentLocationID *string + Region *string +} + // UpdateLocation updates a location. -func (c *AppClient) UpdateLocation(ctx context.Context, locationID string, name, parentLocationID, region *string) (*Location, error) { +func (c *AppClient) UpdateLocation(ctx context.Context, locationID string, opts UpdateLocationOptions) (*Location, error) { resp, err := c.client.UpdateLocation(ctx, &pb.UpdateLocationRequest{ LocationId: locationID, - Name: name, - ParentLocationId: parentLocationID, - Region: region, + Name: opts.Name, + ParentLocationId: opts.ParentLocationID, + Region: opts.Region, }) if err != nil { return nil, err @@ -450,28 +475,29 @@ func (c *AppClient) GetRobotPart(ctx context.Context, id string) (*RobotPart, st return robotPartFromProto(resp.Part), resp.ConfigJson, nil } +// GetRobotPartLogsOptions contains optional parameters for GetRobotPartLogs. +type GetRobotPartLogsOptions struct { + Filter *string + PageToken *string + Levels []string + Start *timestamppb.Timestamp + End *timestamppb.Timestamp + Limit *int64 + Source *string +} + // GetRobotPartLogs gets the logs associated with a robot part and the next page token, // defaulting to the most recent page if pageToken is empty. Logs of all levels are returned when levels is empty. -func (c *AppClient) GetRobotPartLogs( - ctx context.Context, - id string, - filter, - pageToken *string, - levels []string, - start, - end *timestamppb.Timestamp, - limit *int64, - source *string, -) ([]*LogEntry, string, error) { +func (c *AppClient) GetRobotPartLogs(ctx context.Context, id string, opts GetRobotPartLogsOptions) ([]*LogEntry, string, error) { resp, err := c.client.GetRobotPartLogs(ctx, &pb.GetRobotPartLogsRequest{ Id: id, - Filter: filter, - PageToken: pageToken, - Levels: levels, - Start: start, - End: end, - Limit: limit, - Source: source, + Filter: opts.Filter, + PageToken: opts.PageToken, + Levels: opts.Levels, + Start: opts.Start, + End: opts.End, + Limit: opts.Limit, + Source: opts.Source, }) if err != nil { return nil, "", err @@ -483,11 +509,18 @@ func (c *AppClient) GetRobotPartLogs( return logs, resp.NextPageToken, nil } +// TailRobotPartLogsOptions contains optional parameters for TailRobotPartLogs. +type TailRobotPartLogsOptions struct { + Filter *string +} + // TailRobotPartLogs gets a stream of log entries for a specific robot part. Logs are ordered by newest first. -func (c *AppClient) TailRobotPartLogs(ctx context.Context, id string, errorsOnly bool, filter *string, ch chan []*LogEntry) error { +func (c *AppClient) TailRobotPartLogs( + ctx context.Context, id string, errorsOnly bool, ch chan []*LogEntry, opts TailRobotPartLogsOptions, +) error { stream := &robotPartLogStream{client: c} - err := stream.startStream(ctx, id, errorsOnly, filter, ch) + err := stream.startStream(ctx, id, errorsOnly, opts.Filter, ch) if err != nil { return err } @@ -686,18 +719,23 @@ func (c *AppClient) GetFragment(ctx context.Context, id string) (*Fragment, erro return fragmentFromProto(resp.Fragment), nil } +// CreateFragmentOptions contains optional parameters for CreateFragment. +type CreateFragmentOptions struct { + Visibility *FragmentVisibility +} + // CreateFragment creates a fragment. func (c *AppClient) CreateFragment( - ctx context.Context, name string, config interface{}, orgID string, visibility *FragmentVisibility, + ctx context.Context, orgID, name string, config map[string]interface{}, opts CreateFragmentOptions, ) (*Fragment, error) { - cfg, err := protoutils.StructToStructPb(config) + pbConfig, err := protoutils.StructToStructPb(config) if err != nil { return nil, err } - pbFragmentVisibility := fragmentVisibilityToProto(*visibility) + pbFragmentVisibility := fragmentVisibilityToProto(*opts.Visibility) resp, err := c.client.CreateFragment(ctx, &pb.CreateFragmentRequest{ Name: name, - Config: cfg, + Config: pbConfig, OrganizationId: orgID, Visibility: &pbFragmentVisibility, }) @@ -707,20 +745,26 @@ func (c *AppClient) CreateFragment( return fragmentFromProto(resp.Fragment), nil } +// UpdateFragmentOptions contains optional parameters for UpdateFragment. +type UpdateFragmentOptions struct { + public *bool + visibility *FragmentVisibility +} + // UpdateFragment updates a fragment. func (c *AppClient) UpdateFragment( - ctx context.Context, id, name string, config map[string]interface{}, public *bool, visibility *FragmentVisibility, + ctx context.Context, id, name string, config map[string]interface{}, opts UpdateFragmentOptions, ) (*Fragment, error) { cfg, err := protoutils.StructToStructPb(config) if err != nil { return nil, err } - pbVisibility := fragmentVisibilityToProto(*visibility) + pbVisibility := fragmentVisibilityToProto(*opts.visibility) resp, err := c.client.UpdateFragment(ctx, &pb.UpdateFragmentRequest{ Id: id, Name: name, Config: cfg, - Public: public, + Public: opts.public, Visibility: &pbVisibility, }) if err != nil { @@ -737,12 +781,17 @@ func (c *AppClient) DeleteFragment(ctx context.Context, id string) error { return err } +// ListMachineFragmentsOptions contains optional parameters for ListMachineFragments. +type ListMachineFragmentsOptions struct { + AdditionalFragmentIDs []string +} + // ListMachineFragments gets top level and nested fragments for a amchine, as well as any other fragments specified by IDs. Additional // fragments are useful when needing to view fragments that will be provisionally added to the machine alongside existing fragments. -func (c *AppClient) ListMachineFragments(ctx context.Context, machineID string, additionalFragmentIDs []string) ([]*Fragment, error) { +func (c *AppClient) ListMachineFragments(ctx context.Context, machineID string, opts ListMachineFragmentsOptions) ([]*Fragment, error) { resp, err := c.client.ListMachineFragments(ctx, &pb.ListMachineFragmentsRequest{ MachineId: machineID, - AdditionalFragmentIds: additionalFragmentIDs, + AdditionalFragmentIds: opts.AdditionalFragmentIDs, }) if err != nil { return nil, err @@ -754,14 +803,20 @@ func (c *AppClient) ListMachineFragments(ctx context.Context, machineID string, return fragments, nil } +// GetFragmentHistoryOptions contains optional parameters for GetFragmentHistory. +type GetFragmentHistoryOptions struct { + PageToken *string + PageLimit *int64 +} + // GetFragmentHistory gets the fragment's history and the next page token. func (c *AppClient) GetFragmentHistory( - ctx context.Context, id string, pageToken *string, pageLimit *int64, + ctx context.Context, id string, opts GetFragmentHistoryOptions, ) ([]*FragmentHistoryEntry, string, error) { resp, err := c.client.GetFragmentHistory(ctx, &pb.GetFragmentHistoryRequest{ Id: id, - PageToken: pageToken, - PageLimit: pageLimit, + PageToken: opts.PageToken, + PageLimit: opts.PageLimit, }) if err != nil { return nil, "", err @@ -786,13 +841,9 @@ func (c *AppClient) AddRole(ctx context.Context, orgID, identityID, role, resour } // RemoveRole deletes an identity authorization. -func (c *AppClient) RemoveRole(ctx context.Context, orgID, identityID, role, resourceType, resourceID string) error { - authorization, err := createAuthorization(orgID, identityID, "", role, resourceType, resourceID) - if err != nil { - return err - } - _, err = c.client.RemoveRole(ctx, &pb.RemoveRoleRequest{ - Authorization: authorization, +func (c *AppClient) RemoveRole(ctx context.Context, authorization *Authorization) error { + _, err := c.client.RemoveRole(ctx, &pb.RemoveRoleRequest{ + Authorization: authorizationToProto(authorization), }) return err } @@ -800,38 +851,35 @@ func (c *AppClient) RemoveRole(ctx context.Context, orgID, identityID, role, res // ChangeRole changes an identity authorization to a new identity authorization. func (c *AppClient) ChangeRole( ctx context.Context, - oldOrgID, - oldIdentityID, - oldRole, - oldResourceType, - oldResourceID, + oldAuthorization *Authorization, newOrgID, newIdentityID, newRole, newResourceType, newResourceID string, ) error { - oldAuthorization, err := createAuthorization(oldOrgID, oldIdentityID, "", oldRole, oldResourceType, oldResourceID) - if err != nil { - return err - } newAuthorization, err := createAuthorization(newOrgID, newIdentityID, "", newRole, newResourceType, newResourceID) if err != nil { return err } _, err = c.client.ChangeRole(ctx, &pb.ChangeRoleRequest{ - OldAuthorization: oldAuthorization, + OldAuthorization: authorizationToProto(oldAuthorization), NewAuthorization: newAuthorization, }) return err } +// ListAuthorizationsOptions contains optional parameters for ListAuthorizations. +type ListAuthorizationsOptions struct { + ResourceIDs []string +} + // ListAuthorizations returns all authorization roles for any given resources. // If no resources are given, all resources within the organization will be included. -func (c *AppClient) ListAuthorizations(ctx context.Context, orgID string, resourceIDs []string) ([]*Authorization, error) { +func (c *AppClient) ListAuthorizations(ctx context.Context, orgID string, opts ListAuthorizationsOptions) ([]*Authorization, error) { resp, err := c.client.ListAuthorizations(ctx, &pb.ListAuthorizationsRequest{ OrganizationId: orgID, - ResourceIds: resourceIDs, + ResourceIds: opts.ResourceIDs, }) if err != nil { return nil, err @@ -889,53 +937,59 @@ func (c *AppClient) CreateRegistryItem(ctx context.Context, orgID, name string, return err } +// UpdateRegistryItemOptions contains optional parameters for UpdateRegistryItem. +type UpdateRegistryItemOptions struct { + URL *string +} + // UpdateRegistryItem updates a registry item. func (c *AppClient) UpdateRegistryItem( - ctx context.Context, itemID string, packageType PackageType, description string, visibility Visibility, url *string, + ctx context.Context, itemID string, packageType PackageType, description string, visibility Visibility, opts UpdateRegistryItemOptions, ) error { _, err := c.client.UpdateRegistryItem(ctx, &pb.UpdateRegistryItemRequest{ ItemId: itemID, Type: packageTypeToProto(packageType), Description: description, Visibility: visibilityToProto(visibility), - Url: url, + Url: opts.URL, }) return err } +// ListRegistryItemsOptions contains optional parameters for ListRegistryItems. +type ListRegistryItemsOptions struct { + Types []PackageType + Visibilities []Visibility + Platforms []string + Statuses []RegistryItemStatus + SearchTerm *string + PageToken *string + PublicNamespaces []string +} + // ListRegistryItems lists the registry items in an organization. -func (c *AppClient) ListRegistryItems( - ctx context.Context, - orgID *string, - types []PackageType, - visibilities []Visibility, - platforms []string, - statuses []RegistryItemStatus, - searchTerm, - pageToken *string, - publicNamespaces []string, -) ([]*RegistryItem, error) { +func (c *AppClient) ListRegistryItems(ctx context.Context, orgID *string, opts ListRegistryItemsOptions) ([]*RegistryItem, error) { var pbTypes []packages.PackageType - for _, packageType := range types { + for _, packageType := range opts.Types { pbTypes = append(pbTypes, packageTypeToProto(packageType)) } var pbVisibilities []pb.Visibility - for _, visibility := range visibilities { + for _, visibility := range opts.Visibilities { pbVisibilities = append(pbVisibilities, visibilityToProto(visibility)) } var pbStatuses []pb.RegistryItemStatus - for _, status := range statuses { + for _, status := range opts.Statuses { pbStatuses = append(pbStatuses, registryItemStatusToProto(status)) } resp, err := c.client.ListRegistryItems(ctx, &pb.ListRegistryItemsRequest{ OrganizationId: orgID, Types: pbTypes, Visibilities: pbVisibilities, - Platforms: platforms, + Platforms: opts.Platforms, Statuses: pbStatuses, - SearchTerm: searchTerm, - PageToken: pageToken, - PublicNamespaces: publicNamespaces, + SearchTerm: opts.SearchTerm, + PageToken: opts.PageToken, + PublicNamespaces: opts.PublicNamespaces, }) if err != nil { return nil, err @@ -981,10 +1035,22 @@ func (c *AppClient) CreateModule(ctx context.Context, orgID, name string) (strin return resp.ModuleId, resp.Url, nil } +// UpdateModuleOptions contains optional parameters for UpdateModule. +type UpdateModuleOptions struct { + firstRun *string +} + // UpdateModule updates the documentation URL, description, models, entrypoint, and/or the visibility of a module and returns its URL. // A path to a setup script can be added that is run before a newly downloaded module starts. func (c *AppClient) UpdateModule( - ctx context.Context, moduleID string, visibility Visibility, url, description string, models []*Model, entrypoint string, firstRun *string, + ctx context.Context, + moduleID string, + visibility Visibility, + url, + description string, + models []*Model, + entrypoint string, + opts UpdateModuleOptions, ) (string, error) { var pbModels []*pb.Model for _, model := range models { @@ -997,7 +1063,7 @@ func (c *AppClient) UpdateModule( Description: description, Models: pbModels, Entrypoint: entrypoint, - FirstRun: firstRun, + FirstRun: opts.firstRun, }) if err != nil { return "", err @@ -1029,10 +1095,15 @@ func (c *AppClient) GetModule(ctx context.Context, moduleID string) (*Module, er return moduleFromProto(resp.Module), nil } +// ListModulesOptions contains optional parameters for ListModules. +type ListModulesOptions struct { + orgID *string +} + // ListModules lists the modules in the organization. -func (c *AppClient) ListModules(ctx context.Context, orgID *string) ([]*Module, error) { +func (c *AppClient) ListModules(ctx context.Context, opts ListModulesOptions) ([]*Module, error) { resp, err := c.client.ListModules(ctx, &pb.ListModulesRequest{ - OrganizationId: orgID, + OrganizationId: opts.orgID, }) if err != nil { return nil, err diff --git a/app/app_client_test.go b/app/app_client_test.go index 21092f4c52f..d63bc9d3430 100644 --- a/app/app_client_test.go +++ b/app/app_client_test.go @@ -386,6 +386,8 @@ var ( pbAPIKeysWithAuthorizations = []*pb.APIKeyWithAuthorizations{&pbAPIKeyWithAuthorizations} public = true fragmentVisibility = FragmentVisibilityPublic + pbFragmentConfig, _ = protoutils.StructToStructPb(fragmentConfig) + pbFragmentVisibility = fragmentVisibilityToProto(fragmentVisibility) f = map[string]interface{}{"name": name, "id": fragmentID} pbF, _ = protoutils.StructToStructPb(f) fragment = Fragment{ @@ -413,7 +415,7 @@ var ( RobotPartCount: fragment.RobotPartCount, OrganizationCount: fragment.OrganizationCount, OnlyUsedByOwner: fragment.OnlyUsedByOwner, - Visibility: fragmentVisibilityToProto(fragment.Visibility), + Visibility: pbFragmentVisibility, LastUpdated: fragment.LastUpdated, } fragmentConfig = map[string]interface{}{"organizationCount": 4} @@ -811,12 +813,18 @@ func TestAppClient(t *testing.T) { grpcClient.UpdateOrganizationFunc = func( ctx context.Context, in *pb.UpdateOrganizationRequest, opts ...grpc.CallOption, ) (*pb.UpdateOrganizationResponse, error) { + test.That(t, in.OrganizationId, test.ShouldEqual, organizationID) + test.That(t, in.Name, test.ShouldEqual, &name) test.That(t, in.PublicNamespace, test.ShouldEqual, &namespace) + test.That(t, in.Region, test.ShouldEqual, ®ion) + test.That(t, in.Cid, test.ShouldEqual, &cid) return &pb.UpdateOrganizationResponse{ Organization: &pbOrganization, }, nil } - resp, err := client.UpdateOrganization(context.Background(), organizationID, &name, &namespace, ®ion, &cid) + resp, err := client.UpdateOrganization(context.Background(), organizationID, UpdateOrganizationOptions{ + &name, &namespace, ®ion, &cid, + }) test.That(t, err, test.ShouldBeNil) test.That(t, resp, test.ShouldResemble, &organization) }) @@ -869,7 +877,9 @@ func TestAppClient(t *testing.T) { Invite: &pbInvite, }, nil } - resp, err := client.CreateOrganizationInvite(context.Background(), organizationID, email, authorizations, &sendEmailInvite) + resp, err := client.CreateOrganizationInvite(context.Background(), organizationID, email, authorizations, CreateOrganizationInviteOptions{ + &sendEmailInvite, + }) test.That(t, err, test.ShouldBeNil) test.That(t, resp, test.ShouldResemble, &invite) }) @@ -1000,7 +1010,7 @@ func TestAppClient(t *testing.T) { Location: &pbLocation, }, nil } - resp, err := client.CreateLocation(context.Background(), organizationID, name, &parentLocationID) + resp, err := client.CreateLocation(context.Background(), organizationID, name, CreateLocationOptions{&parentLocationID}) test.That(t, err, test.ShouldBeNil) test.That(t, resp, test.ShouldResemble, &location) }) @@ -1031,7 +1041,7 @@ func TestAppClient(t *testing.T) { Location: &pbLocation, }, nil } - resp, err := client.UpdateLocation(context.Background(), locationID, &name, &parentLocationID, ®ion) + resp, err := client.UpdateLocation(context.Background(), locationID, UpdateLocationOptions{&name, &parentLocationID, ®ion}) test.That(t, err, test.ShouldBeNil) test.That(t, resp, test.ShouldResemble, &location) }) @@ -1210,7 +1220,9 @@ func TestAppClient(t *testing.T) { NextPageToken: pageToken, }, nil } - logs, token, err := client.GetRobotPartLogs(context.Background(), partID, &filter, &pageToken, levels, &start, &end, &int64Limit, &source) + logs, token, err := client.GetRobotPartLogs(context.Background(), partID, GetRobotPartLogsOptions{ + &filter, &pageToken, levels, &start, &end, &int64Limit, &source, + }) test.That(t, err, test.ShouldBeNil) test.That(t, token, test.ShouldEqual, pageToken) test.That(t, logs, test.ShouldResemble, logEntries) @@ -1233,7 +1245,7 @@ func TestAppClient(t *testing.T) { test.That(t, in.Filter, test.ShouldEqual, &filter) return mockStream, nil } - err := client.TailRobotPartLogs(context.Background(), partID, errorsOnly, &filter, ch) + err := client.TailRobotPartLogs(context.Background(), partID, errorsOnly, ch, TailRobotPartLogsOptions{&filter}) test.That(t, err, test.ShouldBeNil) // var resp []*LogEntry @@ -1431,9 +1443,23 @@ func TestAppClient(t *testing.T) { test.That(t, resp, test.ShouldResemble, &fragment) }) + t.Run("CreateFragment", func(t *testing.T) { + grpcClient.CreateFragmentFunc = func( + ctx context.Context, in *pb.CreateFragmentRequest, opts ...grpc.CallOption, + ) (*pb.CreateFragmentResponse, error) { + test.That(t, in.Name, test.ShouldEqual, name) + test.That(t, in.Config, test.ShouldResemble, pbFragmentConfig) + test.That(t, in.Visibility, test.ShouldResemble, &pbFragmentVisibility) + return &pb.CreateFragmentResponse{ + Fragment: &pbFragment, + }, nil + } + resp, err := client.CreateFragment(context.Background(), organizationID, name, fragmentConfig, CreateFragmentOptions{&fragmentVisibility}) + test.That(t, err, test.ShouldBeNil) + test.That(t, resp, test.ShouldResemble, &fragment) + }) + t.Run("UpdateFragment", func(t *testing.T) { - pbFragmentConfig, _ := protoutils.StructToStructPb(fragmentConfig) - pbFragmentVisibility := fragmentVisibilityToProto(fragmentVisibility) grpcClient.UpdateFragmentFunc = func( ctx context.Context, in *pb.UpdateFragmentRequest, opts ...grpc.CallOption, ) (*pb.UpdateFragmentResponse, error) { @@ -1446,7 +1472,9 @@ func TestAppClient(t *testing.T) { Fragment: &pbFragment, }, nil } - resp, err := client.UpdateFragment(context.Background(), fragmentID, name, fragmentConfig, &public, &fragmentVisibility) + resp, err := client.UpdateFragment( + context.Background(), fragmentID, name, fragmentConfig, UpdateFragmentOptions{&public, &fragmentVisibility}, + ) test.That(t, err, test.ShouldBeNil) test.That(t, resp, test.ShouldResemble, &fragment) }) @@ -1474,7 +1502,7 @@ func TestAppClient(t *testing.T) { Fragments: []*pb.Fragment{&pbFragment}, }, nil } - resp, err := client.ListMachineFragments(context.Background(), robotID, additionalFragmentIDs) + resp, err := client.ListMachineFragments(context.Background(), robotID, ListMachineFragmentsOptions{additionalFragmentIDs}) test.That(t, err, test.ShouldBeNil) test.That(t, resp, test.ShouldResemble, expectedFragments) }) @@ -1499,7 +1527,7 @@ func TestAppClient(t *testing.T) { NextPageToken: pageToken, }, nil } - resp, token, err := client.GetFragmentHistory(context.Background(), fragmentID, &pageToken, &int64Limit) + resp, token, err := client.GetFragmentHistory(context.Background(), fragmentID, GetFragmentHistoryOptions{&pageToken, &int64Limit}) test.That(t, err, test.ShouldBeNil) test.That(t, token, test.ShouldEqual, pageToken) test.That(t, resp, test.ShouldResemble, expectedHistory) @@ -1562,14 +1590,7 @@ func TestAppClient(t *testing.T) { test.That(t, in.Authorization, test.ShouldResemble, &pbAuthorization) return &pb.RemoveRoleResponse{}, nil } - err := client.RemoveRole( - context.Background(), - authorization.OrganizationID, - authorization.IdentityID, - authorization.AuthorizationType, - authorization.ResourceType, - authorization.ResourceID, - ) + err := client.RemoveRole(context.Background(), &authorization) test.That(t, err, test.ShouldBeNil) }) @@ -1583,11 +1604,7 @@ func TestAppClient(t *testing.T) { } err := client.ChangeRole( context.Background(), - authorization.OrganizationID, - authorization.IdentityID, - authorization.AuthorizationType, - authorization.ResourceType, - authorization.ResourceID, + &authorization, authorization2.OrganizationID, authorization2.IdentityID, authorization2.AuthorizationType, @@ -1607,7 +1624,7 @@ func TestAppClient(t *testing.T) { Authorizations: pbAuthorizations, }, nil } - resp, err := client.ListAuthorizations(context.Background(), organizationID, resourceIDs) + resp, err := client.ListAuthorizations(context.Background(), organizationID, ListAuthorizationsOptions{resourceIDs}) test.That(t, err, test.ShouldBeNil) test.That(t, resp, test.ShouldResemble, authorizations) }) @@ -1671,7 +1688,9 @@ func TestAppClient(t *testing.T) { test.That(t, in.Url, test.ShouldResemble, &siteURL) return &pb.UpdateRegistryItemResponse{}, nil } - err := client.UpdateRegistryItem(context.Background(), registryItem.ItemID, packageType, description, visibility, &siteURL) + err := client.UpdateRegistryItem( + context.Background(), registryItem.ItemID, packageType, description, visibility, UpdateRegistryItemOptions{&siteURL}, + ) test.That(t, err, test.ShouldBeNil) }) @@ -1694,9 +1713,7 @@ func TestAppClient(t *testing.T) { Items: []*pb.RegistryItem{pbRegistryItem}, }, nil } - resp, err := client.ListRegistryItems( - context.Background(), - &organizationID, + resp, err := client.ListRegistryItems(context.Background(), &organizationID, ListRegistryItemsOptions{ []PackageType{packageType}, []Visibility{visibility}, platforms, @@ -1704,7 +1721,7 @@ func TestAppClient(t *testing.T) { &searchTerm, &pageToken, namespaces, - ) + }) test.That(t, err, test.ShouldBeNil) test.That(t, resp, test.ShouldResemble, expectedRegistryItems) }) @@ -1747,7 +1764,9 @@ func TestAppClient(t *testing.T) { Url: siteURL, }, nil } - resp, err := client.UpdateModule(context.Background(), moduleID, visibility, siteURL, description, models, entryPoint, &firstRun) + resp, err := client.UpdateModule( + context.Background(), moduleID, visibility, siteURL, description, models, entryPoint, UpdateModuleOptions{&firstRun}, + ) test.That(t, err, test.ShouldBeNil) test.That(t, resp, test.ShouldEqual, siteURL) }) @@ -1803,7 +1822,7 @@ func TestAppClient(t *testing.T) { Modules: []*pb.Module{&pbModule}, }, nil } - resp, err := client.ListModules(context.Background(), &organizationID) + resp, err := client.ListModules(context.Background(), ListModulesOptions{&organizationID}) test.That(t, err, test.ShouldBeNil) test.That(t, resp, test.ShouldResemble, expectedModules) }) From f388ce10f5971309d77daae1a2d78cc8e53e0e5e Mon Sep 17 00:00:00 2001 From: purplenicole730 Date: Thu, 21 Nov 2024 16:15:58 -0500 Subject: [PATCH 72/75] add app client testing --- app/viam_client_test.go | 17 ++++++++++++++--- 1 file changed, 14 insertions(+), 3 deletions(-) diff --git a/app/viam_client_test.go b/app/viam_client_test.go index 08b93ad1c31..e644d5dbda2 100644 --- a/app/viam_client_test.go +++ b/app/viam_client_test.go @@ -5,7 +5,8 @@ import ( "testing" "github.com/viamrobotics/webrtc/v3" - pb "go.viam.com/api/app/data/v1" + datapb "go.viam.com/api/app/data/v1" + apppb "go.viam.com/api/app/v1" "go.viam.com/test" "go.viam.com/utils" "go.viam.com/utils/rpc" @@ -119,7 +120,7 @@ func TestCreateViamClientWithAPIKeyTests(t *testing.T) { } } -func TestNewDataClient(t *testing.T) { +func TestNewAppClients(t *testing.T) { originalDialDirectGRPC := dialDirectGRPC dialDirectGRPC = mockDialDirectGRPC defer func() { dialDirectGRPC = originalDialDirectGRPC }() @@ -138,10 +139,20 @@ func TestNewDataClient(t *testing.T) { dataClient := client.DataClient() test.That(t, dataClient, test.ShouldNotBeNil) test.That(t, dataClient, test.ShouldHaveSameTypeAs, &DataClient{}) - test.That(t, dataClient.client, test.ShouldImplement, (*pb.DataServiceClient)(nil)) + test.That(t, dataClient.client, test.ShouldImplement, (*datapb.DataServiceClient)(nil)) // Testing that a second call to DataClient() returns the same instance dataClient2 := client.DataClient() test.That(t, dataClient2, test.ShouldNotBeNil) test.That(t, dataClient, test.ShouldResemble, dataClient2) + + appClient := client.AppClient() + test.That(t, appClient, test.ShouldNotBeNil) + test.That(t, appClient, test.ShouldHaveSameTypeAs, &AppClient{}) + test.That(t, appClient.client, test.ShouldImplement, (*apppb.AppServiceClient)(nil)) + + // Testing that a second call to AppClient() returns the same instance + appClient2 := client.AppClient() + test.That(t, appClient2, test.ShouldNotBeNil) + test.That(t, appClient, test.ShouldResemble, appClient2) } From 650b90c98e5d1424243067f51c4e520444a237f4 Mon Sep 17 00:00:00 2001 From: purplenicole730 Date: Thu, 21 Nov 2024 16:56:49 -0500 Subject: [PATCH 73/75] change streams --- app/app_client.go | 90 ++++++++++++++++------ app/app_client_test.go | 12 +-- app/stream.go | 169 ----------------------------------------- app/viam_client.go | 2 +- 4 files changed, 72 insertions(+), 201 deletions(-) delete mode 100644 app/stream.go diff --git a/app/app_client.go b/app/app_client.go index 035ab3ea9d7..a75fa392f39 100644 --- a/app/app_client.go +++ b/app/app_client.go @@ -5,15 +5,12 @@ package app import ( "context" - "sync" packages "go.viam.com/api/app/packages/v1" pb "go.viam.com/api/app/v1" "go.viam.com/utils/protoutils" "go.viam.com/utils/rpc" "google.golang.org/protobuf/types/known/timestamppb" - - "go.viam.com/rdk/logging" ) // AppClient is a gRPC client for method calls to the App API. @@ -21,14 +18,11 @@ import ( //nolint:revive // stutter: Ignore the "stuttering" warning for this type name type AppClient struct { client pb.AppServiceClient - logger logging.Logger - - mu sync.Mutex } // NewAppClient constructs a new AppClient using the connection passed in by the Viam client. -func NewAppClient(conn rpc.ClientConn, logger logging.Logger) *AppClient { - return &AppClient{client: pb.NewAppServiceClient(conn), logger: logger} +func NewAppClient(conn rpc.ClientConn) *AppClient { + return &AppClient{client: pb.NewAppServiceClient(conn)} } // GetUserIDByEmail gets the ID of the user with the given email. @@ -509,6 +503,25 @@ func (c *AppClient) GetRobotPartLogs(ctx context.Context, id string, opts GetRob return logs, resp.NextPageToken, nil } +// RobotPartLogStream is a stream with robot part logs. +type RobotPartLogStream struct { + stream pb.AppService_TailRobotPartLogsClient +} + +// Next gets the next robot part log entry. +func (s *RobotPartLogStream) Next() ([]*LogEntry, error) { + streamResp, err := s.stream.Recv() + if err != nil { + return nil, err + } + + var logs []*LogEntry + for _, log := range streamResp.Logs { + logs = append(logs, logEntryFromProto(log)) + } + return logs, nil +} + // TailRobotPartLogsOptions contains optional parameters for TailRobotPartLogs. type TailRobotPartLogsOptions struct { Filter *string @@ -516,18 +529,17 @@ type TailRobotPartLogsOptions struct { // TailRobotPartLogs gets a stream of log entries for a specific robot part. Logs are ordered by newest first. func (c *AppClient) TailRobotPartLogs( - ctx context.Context, id string, errorsOnly bool, ch chan []*LogEntry, opts TailRobotPartLogsOptions, -) error { - stream := &robotPartLogStream{client: c} - - err := stream.startStream(ctx, id, errorsOnly, opts.Filter, ch) + ctx context.Context, id string, errorsOnly bool, opts TailRobotPartLogsOptions, +) (*RobotPartLogStream, error) { + stream, err := c.client.TailRobotPartLogs(ctx, &pb.TailRobotPartLogsRequest{ + Id: id, + ErrorsOnly: errorsOnly, + Filter: opts.Filter, + }) if err != nil { - return err + return nil, err } - - c.mu.Lock() - defer c.mu.Unlock() - return nil + return &RobotPartLogStream{stream: stream}, nil } // GetRobotPartHistory gets a specific robot part history by ID. @@ -1073,15 +1085,47 @@ func (c *AppClient) UpdateModule( // UploadModuleFile uploads a module file and returns the URL of the uploaded file. func (c *AppClient) UploadModuleFile(ctx context.Context, fileInfo ModuleFileInfo, file []byte) (string, error) { - stream := &uploadModuleFileStream{client: c} - url, err := stream.startStream(ctx, &fileInfo, file) + stream, err := c.client.UploadModuleFile(ctx) if err != nil { return "", err } - c.mu.Lock() - defer c.mu.Unlock() - return url, nil + err = stream.Send(&pb.UploadModuleFileRequest{ + ModuleFile: &pb.UploadModuleFileRequest_ModuleFileInfo{ + ModuleFileInfo: moduleFileInfoToProto(&fileInfo), + }, + }) + if err != nil { + return "", err + } + + uploadChunkSize := 64 * 1024 // 64 kB in bytes + for start := 0; start < len(file); start += uploadChunkSize { + if ctx.Err() != nil { + return "", ctx.Err() + } + + end := start + uploadChunkSize + if end > len(file) { + end = len(file) + } + + chunk := file[start:end] + err := stream.Send(&pb.UploadModuleFileRequest{ + ModuleFile: &pb.UploadModuleFileRequest_File{ + File: chunk, + }, + }) + if err != nil { + return "", err + } + } + + resp, err := stream.CloseAndRecv() + if err != nil { + return "", err + } + return resp.Url, err } // GetModule gets a module. diff --git a/app/app_client_test.go b/app/app_client_test.go index d63bc9d3430..bb03da0e075 100644 --- a/app/app_client_test.go +++ b/app/app_client_test.go @@ -1236,7 +1236,6 @@ func TestAppClient(t *testing.T) { }, nil }, } - ch := make(chan []*LogEntry) grpcClient.TailRobotPartLogsFunc = func( ctx context.Context, in *pb.TailRobotPartLogsRequest, opts ...grpc.CallOption, ) (pb.AppService_TailRobotPartLogsClient, error) { @@ -1245,14 +1244,11 @@ func TestAppClient(t *testing.T) { test.That(t, in.Filter, test.ShouldEqual, &filter) return mockStream, nil } - err := client.TailRobotPartLogs(context.Background(), partID, errorsOnly, ch, TailRobotPartLogsOptions{&filter}) + stream, err := client.TailRobotPartLogs(context.Background(), partID, errorsOnly, TailRobotPartLogsOptions{&filter}) test.That(t, err, test.ShouldBeNil) - - // var resp []*LogEntry - // for entries := range ch { - // resp = append(resp, entries...) - // } - // test.That(t, resp, test.ShouldResemble, logEntries) + resp, err := stream.Next() + test.That(t, err, test.ShouldBeNil) + test.That(t, resp, test.ShouldResemble, []*LogEntry{&logEntry}) }) t.Run("GetRobotPartHistory", func(t *testing.T) { diff --git a/app/stream.go b/app/stream.go deleted file mode 100644 index f846a941781..00000000000 --- a/app/stream.go +++ /dev/null @@ -1,169 +0,0 @@ -package app - -import ( - "context" - "sync" - - pb "go.viam.com/api/app/v1" - "go.viam.com/utils" -) - -type robotPartLogStream struct { - client *AppClient - streamCancel context.CancelFunc - streamMu sync.Mutex - - activeBackgroundWorkers sync.WaitGroup -} - -func (s *robotPartLogStream) startStream(ctx context.Context, id string, errorsOnly bool, filter *string, ch chan []*LogEntry) error { - s.streamMu.Lock() - defer s.streamMu.Unlock() - - if ctx.Err() != nil { - return ctx.Err() - } - - ctx, cancel := context.WithCancel(ctx) - s.streamCancel = cancel - - select { - case <-ctx.Done(): - return ctx.Err() - default: - } - - // This call won't return any errors it had until the client tries to receive. - //nolint:errcheck - stream, _ := s.client.client.TailRobotPartLogs(ctx, &pb.TailRobotPartLogsRequest{ - Id: id, - ErrorsOnly: errorsOnly, - Filter: filter, - }) - _, err := stream.Recv() - if err != nil { - s.client.logger.CError(ctx, err) - return err - } - - // Create a background go routine to receive from the server stream. - // We rely on calling the Done function here rather than in close stream - // since managed go calls that function when the routine exits. - s.activeBackgroundWorkers.Add(1) - utils.ManagedGo(func() { - s.receiveFromStream(ctx, stream, ch) - }, - s.activeBackgroundWorkers.Done) - return nil -} - -func (s *robotPartLogStream) receiveFromStream(ctx context.Context, stream pb.AppService_TailRobotPartLogsClient, ch chan []*LogEntry) { - defer s.streamCancel() - - // repeatly receive from the stream - for { - select { - case <-ctx.Done(): - s.client.logger.Debug(ctx.Err()) - return - default: - } - streamResp, err := stream.Recv() - if err != nil { - // only debug log the context canceled error - s.client.logger.Debug(err) - return - } - // If there is a response, send to the logs channel. - var logs []*LogEntry - for _, log := range streamResp.Logs { - logs = append(logs, logEntryFromProto(log)) - } - ch <- logs - } -} - -type uploadModuleFileStream struct { - client *AppClient - streamCancel context.CancelFunc - streamMu sync.Mutex - - activeBackgroundWorkers sync.WaitGroup -} - -func (s *uploadModuleFileStream) startStream( - ctx context.Context, info *ModuleFileInfo, file []byte, -) (string, error) { - s.streamMu.Lock() - defer s.streamMu.Unlock() - - if ctx.Err() != nil { - return "", ctx.Err() - } - - ctx, cancel := context.WithCancel(ctx) - s.streamCancel = cancel - - stream, err := s.client.client.UploadModuleFile(ctx) - if err != nil { - return "", err - } - - err = stream.Send(&pb.UploadModuleFileRequest{ - ModuleFile: &pb.UploadModuleFileRequest_ModuleFileInfo{ - ModuleFileInfo: moduleFileInfoToProto(info), - }, - }) - if err != nil { - s.client.logger.CError(ctx, err) - return "", err - } - - // Create a background go routine to send to the server stream. - // We rely on calling the Done function here rather than in close stream - // since managed go calls that function when the routine exits. - s.activeBackgroundWorkers.Add(1) - utils.ManagedGo(func() { - s.sendToStream(ctx, stream, file) - }, - s.activeBackgroundWorkers.Done) - - resp, err := stream.CloseAndRecv() - if err != nil { - return "", err - } - return resp.Url, err -} - -func (s *uploadModuleFileStream) sendToStream( - ctx context.Context, stream pb.AppService_UploadModuleFileClient, file []byte, -) { - defer s.streamCancel() - - uploadChunkSize := 64 * 1024 // 64 kB in bytes - for start := 0; start < len(file); start += uploadChunkSize { - select { - case <-ctx.Done(): - s.client.logger.Debug(ctx.Err()) - return - default: - } - - end := start + uploadChunkSize - if end > len(file) { - end = len(file) - } - - chunk := file[start:end] - err := stream.Send(&pb.UploadModuleFileRequest{ - ModuleFile: &pb.UploadModuleFileRequest_File{ - File: chunk, - }, - }) - if err != nil { - // only debug log the context canceled error - s.client.logger.Debug(err) - return - } - } -} diff --git a/app/viam_client.go b/app/viam_client.go index fb88275746d..9031c590a38 100644 --- a/app/viam_client.go +++ b/app/viam_client.go @@ -71,7 +71,7 @@ func (c *ViamClient) AppClient() *AppClient { if c.appClient != nil { return c.appClient } - c.appClient = NewAppClient(c.conn, c.logger) + c.appClient = NewAppClient(c.conn) return c.appClient } From a5ab0c71f363d24eb72f7b70946c377b89c80557 Mon Sep 17 00:00:00 2001 From: purplenicole730 Date: Thu, 21 Nov 2024 17:05:53 -0500 Subject: [PATCH 74/75] remove unnecessary logger --- app/viam_client.go | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/app/viam_client.go b/app/viam_client.go index 9031c590a38..4c69c45c31a 100644 --- a/app/viam_client.go +++ b/app/viam_client.go @@ -15,7 +15,6 @@ import ( // ViamClient is a gRPC client for method calls to Viam app. type ViamClient struct { conn rpc.ClientConn - logger logging.Logger appClient *AppClient dataClient *DataClient } @@ -50,7 +49,7 @@ func CreateViamClientWithOptions(ctx context.Context, options Options, logger lo if err != nil { return nil, err } - return &ViamClient{conn: conn, logger: logger}, nil + return &ViamClient{conn: conn}, nil } // CreateViamClientWithAPIKey creates a ViamClient with an API key. From 02b2adb9be068315958c19876417781bdd5b137e Mon Sep 17 00:00:00 2001 From: purplenicole730 Date: Thu, 21 Nov 2024 18:48:02 -0500 Subject: [PATCH 75/75] actually test if clients are the same --- app/viam_client_test.go | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/app/viam_client_test.go b/app/viam_client_test.go index e644d5dbda2..51a624371cd 100644 --- a/app/viam_client_test.go +++ b/app/viam_client_test.go @@ -144,7 +144,7 @@ func TestNewAppClients(t *testing.T) { // Testing that a second call to DataClient() returns the same instance dataClient2 := client.DataClient() test.That(t, dataClient2, test.ShouldNotBeNil) - test.That(t, dataClient, test.ShouldResemble, dataClient2) + test.That(t, dataClient, test.ShouldEqual, dataClient2) appClient := client.AppClient() test.That(t, appClient, test.ShouldNotBeNil) @@ -154,5 +154,5 @@ func TestNewAppClients(t *testing.T) { // Testing that a second call to AppClient() returns the same instance appClient2 := client.AppClient() test.That(t, appClient2, test.ShouldNotBeNil) - test.That(t, appClient, test.ShouldResemble, appClient2) + test.That(t, appClient, test.ShouldEqual, appClient2) }