feat: create application service based off of api keys service
Brijesh Wawdhane ops@brijesh.dev
Sat, 21 Dec 2024 04:50:23 +0530
17 files changed,
3848 insertions(+),
3011 deletions(-)
jump to
M
db.cql
→
db.cql
@@ -19,3 +19,13 @@ is_active boolean,
PRIMARY KEY (id, created_at) ) WITH CLUSTERING ORDER BY (created_at DESC); +CREATE TABLE IF NOT EXISTS argus.applications ( + id uuid, + user_id uuid, + name text, + description text, + key_hash text, + created_at timestamp, + updated_at timestamp, + PRIMARY KEY (id, created_at) +) WITH CLUSTERING ORDER BY (created_at DESC);
D
internal/apikeys/errors.go
@@ -1,10 +0,0 @@
-package apikeys - -import "errors" - -var ( - ErrAPIKeyInvalid = errors.New("invalid API key") - ErrAPIKeyExpired = errors.New("API key expired") - ErrAPIKeyRevoked = errors.New("API key revoked") - ErrUnauthorized = errors.New("unauthorized") -)
D
internal/apikeys/twirp_server.go
@@ -1,172 +0,0 @@
-package apikeys - -import ( - "context" - "time" - - "argus-core/internal/auth" - "argus-core/internal/database" - pb "argus-core/rpc/apikeys" - - "github.com/gocql/gocql" - "github.com/twitchtv/twirp" -) - -// TwirpServer implements the APIKeysService for managing API keys -type TwirpServer struct { - authService auth.Service - db database.Service -} - -// NewTwirpServer creates a new Twirp server wrapper around the existing services -func NewTwirpServer(authService auth.Service, db database.Service) pb.APIKeysService { - return &TwirpServer{authService: authService, db: db} -} - -// formatAPIKeyResponse converts a database API key to a protobuf API key -func formatAPIKeyResponse(apiKey *database.APIKey) *pb.APIKey { - response := &pb.APIKey{ - Id: apiKey.ID.String(), - UserId: apiKey.UserID.String(), - Name: apiKey.Name, - CreatedAt: apiKey.CreatedAt.Format(time.RFC3339), - IsActive: apiKey.IsActive, - } - - if apiKey.LastUsedAt != nil { - response.LastUsedAt = apiKey.LastUsedAt.Format(time.RFC3339) - } - - if apiKey.ExpiresAt != nil { - response.ExpiresAt = apiKey.ExpiresAt.Format(time.RFC3339) - } - - return response -} - -// CreateAPIKey implements the Twirp APIKeysService CreateAPIKey method -func (s *TwirpServer) CreateAPIKey(ctx context.Context, req *pb.CreateAPIKeyRequest) (*pb.CreateAPIKeyResponse, error) { - if req.Token == "" { - return nil, twirp.NewError(twirp.Unauthenticated, "token is required") - } - if req.Name == "" { - return nil, twirp.NewError(twirp.InvalidArgument, "name is required") - } - - // Validate token and get user - user, err := s.authService.ValidateToken(req.Token) - if err != nil { - return nil, twirp.NewError(twirp.Unauthenticated, "invalid token") - } - - // Parse expiration date if provided - var expiresAt *time.Time - if req.ExpiresAt != "" { - t, err := time.Parse(time.RFC3339, req.ExpiresAt) - if err != nil { - return nil, twirp.NewError(twirp.InvalidArgument, "expires_at must be in RFC3339 format") - } - if t.Before(time.Now()) { - return nil, twirp.NewError(twirp.InvalidArgument, "expiration date cannot be in the past") - } - expiresAt = &t - } - - // Create API key - apiKey, keyString, err := s.authService.CreateAPIKey(user.ID, req.Name, expiresAt) - if err != nil { - return nil, twirp.InternalErrorWith(err) - } - - return &pb.CreateAPIKeyResponse{ - ApiKey: formatAPIKeyResponse(apiKey), - Key: keyString, - }, nil -} - -// ListAPIKeys implements the Twirp APIKeysService ListAPIKeys method -func (s *TwirpServer) ListAPIKeys(ctx context.Context, req *pb.ListAPIKeysRequest) (*pb.ListAPIKeysResponse, error) { - if req.Token == "" { - return nil, twirp.NewError(twirp.Unauthenticated, "token is required") - } - - // Validate token and get user - user, err := s.authService.ValidateToken(req.Token) - if err != nil { - return nil, twirp.NewError(twirp.Unauthenticated, "invalid token") - } - - apiKeys, err := s.authService.ListAPIKeys(user.ID) - if err != nil { - return nil, twirp.InternalErrorWith(err) - } - - var pbAPIKeys []*pb.APIKey - for _, apiKey := range apiKeys { - pbAPIKeys = append(pbAPIKeys, formatAPIKeyResponse(&apiKey)) - } - - return &pb.ListAPIKeysResponse{ApiKeys: pbAPIKeys}, nil -} - -// RevokeAPIKey implements the Twirp APIKeysService RevokeAPIKey method -func (s *TwirpServer) RevokeAPIKey(ctx context.Context, req *pb.RevokeAPIKeyRequest) (*pb.RevokeAPIKeyResponse, error) { - if req.Token == "" { - return nil, twirp.NewError(twirp.Unauthenticated, "token is required") - } - if req.KeyId == "" { - return nil, twirp.NewError(twirp.InvalidArgument, "key_id is required") - } - - // Validate token and get user - user, err := s.authService.ValidateToken(req.Token) - if err != nil { - return nil, twirp.NewError(twirp.Unauthenticated, "invalid token") - } - - keyID, err := gocql.ParseUUID(req.KeyId) - if err != nil { - return nil, twirp.NewError(twirp.InvalidArgument, "invalid key ID format") - } - - err = s.authService.RevokeAPIKey(user.ID, keyID) - if err != nil { - if err == ErrAPIKeyInvalid { - return nil, twirp.NewError(twirp.NotFound, "API key not found") - } - return nil, twirp.InternalErrorWith(err) - } - - return &pb.RevokeAPIKeyResponse{}, nil -} - -// DeleteAPIKey implements the Twirp APIKeysService DeleteAPIKey method -func (s *TwirpServer) DeleteAPIKey(ctx context.Context, req *pb.DeleteAPIKeyRequest) (*pb.DeleteAPIKeyResponse, error) { - if req.Token == "" { - return nil, twirp.NewError(twirp.Unauthenticated, "token is required") - } - if req.KeyId == "" { - return nil, twirp.NewError(twirp.InvalidArgument, "key_id is required") - } - - // Validate token and get user - user, err := s.authService.ValidateToken(req.Token) - if err != nil { - return nil, twirp.NewError(twirp.Unauthenticated, "invalid token") - } - - keyID, err := gocql.ParseUUID(req.KeyId) - if err != nil { - return nil, twirp.NewError(twirp.InvalidArgument, "invalid key ID format") - } - - err = s.authService.DeleteAPIKey(user.ID, keyID) - if err != nil { - if err == ErrAPIKeyInvalid { - return nil, twirp.NewError(twirp.NotFound, "API key not found") - } - return nil, twirp.InternalErrorWith(err) - } - - return &pb.DeleteAPIKeyResponse{}, nil -}
D
internal/apikeys/validation.go
@@ -1,16 +0,0 @@
-package apikeys - -import ( - pb "argus-core/rpc/apikeys" - "fmt" -) - -func validateCreateAPIKeyRequest(req *pb.CreateAPIKeyRequest) error { - if req.Name == "" { - return fmt.Errorf("name is required") - } - if len(req.Name) > 255 { - return fmt.Errorf("name must be less than 256 characters") - } - return nil -}
A
internal/applications/errors.go
@@ -0,0 +1,9 @@
+package applications + +import "errors" + +var ( + ErrApplicationNotFound = errors.New("application not found") + ErrUnauthorized = errors.New("unauthorized") + ErrInvalidInput = errors.New("invalid input") +)
A
internal/applications/twirp_server.go
@@ -0,0 +1,214 @@
+package applications + +import ( + "context" + "time" + + "argus-core/internal/auth" + "argus-core/internal/database" + pb "argus-core/rpc/applications" + + "github.com/gocql/gocql" + "github.com/twitchtv/twirp" +) + +type TwirpServer struct { + authService auth.Service + db database.Service +} + +func NewTwirpServer(authService auth.Service, db database.Service) pb.ApplicationsService { + return &TwirpServer{ + authService: authService, + db: db, + } +} + +func formatApplicationResponse(app *database.Application) *pb.Application { + return &pb.Application{ + Id: app.ID.String(), + UserId: app.UserID.String(), + Name: app.Name, + Description: app.Description, + CreatedAt: app.CreatedAt.Format(time.RFC3339), + UpdatedAt: app.UpdatedAt.Format(time.RFC3339), + } +} + +func (s *TwirpServer) CreateApplication(ctx context.Context, req *pb.CreateApplicationRequest) (*pb.CreateApplicationResponse, error) { + if err := validateCreateApplicationRequest(req); err != nil { + return nil, twirp.InvalidArgumentError("validation_error", err.Error()) + } + + user, err := s.authService.ValidateToken(req.Token) + if err != nil { + return nil, twirp.NewError(twirp.Unauthenticated, "invalid token") + } + + // Generate API key for the application + apiKey, err := auth.GenerateAPIKey() + if err != nil { + return nil, twirp.InternalErrorWith(err) + } + keyHash := auth.HashAPIKey(apiKey) + + // Create the application + app, err := s.db.CreateApplication(user.ID, req.Name, req.Description, keyHash) + if err != nil { + return nil, twirp.InternalErrorWith(err) + } + + return &pb.CreateApplicationResponse{ + Application: formatApplicationResponse(app), + Key: apiKey, + }, nil +} + +func (s *TwirpServer) ListApplications(ctx context.Context, req *pb.ListApplicationsRequest) (*pb.ListApplicationsResponse, error) { + user, err := s.authService.ValidateToken(req.Token) + if err != nil { + return nil, twirp.NewError(twirp.Unauthenticated, "invalid token") + } + + apps, err := s.db.ListApplications(user.ID) + if err != nil { + return nil, twirp.InternalErrorWith(err) + } + + var pbApps []*pb.Application + for _, app := range apps { + pbApps = append(pbApps, formatApplicationResponse(&app)) + } + + return &pb.ListApplicationsResponse{ + Applications: pbApps, + }, nil +} + +func (s *TwirpServer) GetApplication(ctx context.Context, req *pb.GetApplicationRequest) (*pb.GetApplicationResponse, error) { + user, err := s.authService.ValidateToken(req.Token) + if err != nil { + return nil, twirp.NewError(twirp.Unauthenticated, "invalid token") + } + + appID, err := gocql.ParseUUID(req.ApplicationId) + if err != nil { + return nil, twirp.InvalidArgumentError("application_id", "invalid UUID format") + } + + app, err := s.db.GetApplication(appID) + if err != nil { + return nil, twirp.NotFoundError("application not found") + } + + if app.UserID != user.ID { + return nil, twirp.NewError(twirp.PermissionDenied, "not authorized to access this application") + } + + return &pb.GetApplicationResponse{ + Application: formatApplicationResponse(app), + }, nil +} + +func (s *TwirpServer) UpdateApplication(ctx context.Context, req *pb.UpdateApplicationRequest) (*pb.UpdateApplicationResponse, error) { + if err := validateUpdateApplicationRequest(req); err != nil { + return nil, twirp.InvalidArgumentError("validation_error", err.Error()) + } + + user, err := s.authService.ValidateToken(req.Token) + if err != nil { + return nil, twirp.NewError(twirp.Unauthenticated, "invalid token") + } + + appID, err := gocql.ParseUUID(req.ApplicationId) + if err != nil { + return nil, twirp.InvalidArgumentError("application_id", "invalid UUID format") + } + + // Verify ownership + currentApp, err := s.db.GetApplication(appID) + if err != nil { + return nil, twirp.NotFoundError("application not found") + } + + if currentApp.UserID != user.ID { + return nil, twirp.NewError(twirp.PermissionDenied, "not authorized to modify this application") + } + + // Update the application + updatedApp, err := s.db.UpdateApplication(appID, req.Name, req.Description) + if err != nil { + return nil, twirp.InternalErrorWith(err) + } + + return &pb.UpdateApplicationResponse{ + Application: formatApplicationResponse(updatedApp), + }, nil +} + +func (s *TwirpServer) DeleteApplication(ctx context.Context, req *pb.DeleteApplicationRequest) (*pb.DeleteApplicationResponse, error) { + user, err := s.authService.ValidateToken(req.Token) + if err != nil { + return nil, twirp.NewError(twirp.Unauthenticated, "invalid token") + } + + appID, err := gocql.ParseUUID(req.ApplicationId) + if err != nil { + return nil, twirp.InvalidArgumentError("application_id", "invalid UUID format") + } + + // Verify ownership + app, err := s.db.GetApplication(appID) + if err != nil { + return nil, twirp.NotFoundError("application not found") + } + + if app.UserID != user.ID { + return nil, twirp.NewError(twirp.PermissionDenied, "not authorized to delete this application") + } + + // Delete the application + if err := s.db.DeleteApplication(appID); err != nil { + return nil, twirp.InternalErrorWith(err) + } + + return &pb.DeleteApplicationResponse{}, nil +} + +func (s *TwirpServer) RegenerateKey(ctx context.Context, req *pb.RegenerateKeyRequest) (*pb.RegenerateKeyResponse, error) { + user, err := s.authService.ValidateToken(req.Token) + if err != nil { + return nil, twirp.NewError(twirp.Unauthenticated, "invalid token") + } + + appID, err := gocql.ParseUUID(req.ApplicationId) + if err != nil { + return nil, twirp.InvalidArgumentError("application_id", "invalid UUID format") + } + + // Verify ownership + app, err := s.db.GetApplication(appID) + if err != nil { + return nil, twirp.NotFoundError("application not found") + } + + if app.UserID != user.ID { + return nil, twirp.NewError(twirp.PermissionDenied, "not authorized to modify this application") + } + + // Generate new API key + newKey, err := auth.GenerateAPIKey() + if err != nil { + return nil, twirp.InternalErrorWith(err) + } + keyHash := auth.HashAPIKey(newKey) + + // Update the application with new key hash + if err := s.db.RegenerateApplicationKey(appID, keyHash); err != nil { + return nil, twirp.InternalErrorWith(err) + } + + return &pb.RegenerateKeyResponse{ + Key: newKey, + }, nil +}
A
internal/applications/validation.go
@@ -0,0 +1,35 @@
+package applications + +import ( + pb "argus-core/rpc/applications" + "fmt" +) + +func validateCreateApplicationRequest(req *pb.CreateApplicationRequest) error { + if req.Name == "" { + return fmt.Errorf("name is required") + } + if len(req.Name) > 255 { + return fmt.Errorf("name must be less than 256 characters") + } + if len(req.Description) > 1000 { + return fmt.Errorf("description must be less than 1000 characters") + } + return nil +} + +func validateUpdateApplicationRequest(req *pb.UpdateApplicationRequest) error { + if req.ApplicationId == "" { + return fmt.Errorf("application ID is required") + } + if req.Name == "" { + return fmt.Errorf("name is required") + } + if len(req.Name) > 255 { + return fmt.Errorf("name must be less than 256 characters") + } + if len(req.Description) > 1000 { + return fmt.Errorf("description must be less than 1000 characters") + } + return nil +}
M
internal/auth/auth.go
→
internal/auth/auth.go
@@ -2,7 +2,6 @@ package auth
import ( "errors" - "fmt" "time" "github.com/gocql/gocql"@@ -39,12 +38,6 @@ type Service interface {
Register(email, password string) (*database.User, error) Login(email, password string) (string, *database.User, error) // Returns JWT token and user ValidateToken(token string) (*database.User, error) - - CreateAPIKey(userID gocql.UUID, name string, expiresAt *time.Time) (*database.APIKey, string, error) // Returns APIKey and the actual key - ValidateAPIKey(key string) (*database.APIKey, error) - ListAPIKeys(userID gocql.UUID) ([]database.APIKey, error) - RevokeAPIKey(userID, keyID gocql.UUID) error - DeleteAPIKey(userID, keyID gocql.UUID) error } type service struct {@@ -147,60 +140,3 @@ }
return user, nil } - -func (s *service) CreateAPIKey(userID gocql.UUID, name string, expiresAt *time.Time) (*database.APIKey, string, error) { - // Generate random API key - apiKeyStr, err := generateAPIKey() - if err != nil { - return nil, "", fmt.Errorf("failed to generate API key: %w", err) - } - - // Hash the API key - keyHash := hashAPIKey(apiKeyStr) - - // Create API key in database - apiKey, err := s.db.CreateAPIKey(userID, name, keyHash, expiresAt) - if err != nil { - return nil, "", fmt.Errorf("failed to create API key: %w", err) - } - - return apiKey, apiKeyStr, nil -} - -func (s *service) ValidateAPIKey(key string) (*database.APIKey, error) { - // Validate key format - if !validateAPIKeyFormat(key) { - return nil, ErrAPIKeyNotFound - } - - keyHash := hashAPIKey(key) - - apiKey, err := s.db.GetAPIKeyByHash(keyHash) - if err != nil { - return nil, ErrAPIKeyNotFound - } - - // Check if key is expired - if apiKey.ExpiresAt != nil && time.Now().After(*apiKey.ExpiresAt) { - return nil, ErrAPIKeyNotFound - } - - // Check if key is active - if !apiKey.IsActive { - return nil, ErrAPIKeyNotFound - } - - return apiKey, nil -} - -func (s *service) ListAPIKeys(userID gocql.UUID) ([]database.APIKey, error) { - return s.db.ListAPIKeys(userID) -} - -func (s *service) RevokeAPIKey(userID, keyID gocql.UUID) error { - return s.db.RevokeAPIKey(userID, keyID) -} - -func (s *service) DeleteAPIKey(userID, keyID gocql.UUID) error { - return s.db.DeleteAPIKey(userID, keyID) -}
M
internal/auth/utils.go
→
internal/auth/utils.go
@@ -13,9 +13,9 @@ APIKeyPrefix = "argus"
APIKeyBytes = 32 ) -// generateAPIKey generates a new API key with format: argus_<random-string> base64 encoded +// GenerateAPIKey generates a new API key with format: argus_<random-string> base64 encoded // The random string is base64 encoded and URL safe -func generateAPIKey() (string, error) { +func GenerateAPIKey() (string, error) { // Generate random bytes randomBytes := make([]byte, APIKeyBytes) _, err := rand.Read(randomBytes)@@ -31,9 +31,9 @@ // Format: argus_<random-string>
return fmt.Sprintf("%s_%s", APIKeyPrefix, randomString), nil } -// hashAPIKey creates a SHA-256 hash of the API key +// HashAPIKey creates a SHA-256 hash of the API key // This is what we'll store in the database -func hashAPIKey(key string) string { +func HashAPIKey(key string) string { // Create SHA-256 hash hasher := sha256.New() hasher.Write([]byte(key))
M
internal/database/database.go
→
internal/database/database.go
@@ -18,15 +18,14 @@ CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"` } -type APIKey struct { - ID gocql.UUID `json:"id"` - UserID gocql.UUID `json:"user_id"` - Name string `json:"name"` - KeyHash string `json:"-"` - CreatedAt time.Time `json:"created_at"` - LastUsedAt *time.Time `json:"last_used_at,omitempty"` - ExpiresAt *time.Time `json:"expires_at,omitempty"` - IsActive bool `json:"is_active"` +type Application struct { + ID gocql.UUID `json:"id"` + UserID gocql.UUID `json:"user_id"` + Name string `json:"name"` + Description string `json:"description"` + KeyHash string `json:"-"` + CreatedAt time.Time `json:"created_at"` + UpdatedAt time.Time `json:"updated_at"` } type Service interface {@@ -37,12 +36,12 @@ CreateUser(email, passwordHash string) (*User, error)
GetUserByEmail(email string) (*User, error) GetUserByID(id gocql.UUID) (*User, error) - CreateAPIKey(userID gocql.UUID, name, keyHash string, expiresAt *time.Time) (*APIKey, error) - GetAPIKeyByHash(keyHash string) (*APIKey, error) - ListAPIKeys(userID gocql.UUID) ([]APIKey, error) - UpdateAPIKeyLastUsed(keyID gocql.UUID) error - RevokeAPIKey(userID, keyID gocql.UUID) error - DeleteAPIKey(userID, keyID gocql.UUID) error + CreateApplication(userID gocql.UUID, name, description, keyHash string) (*Application, error) + GetApplication(id gocql.UUID) (*Application, error) + ListApplications(userID gocql.UUID) ([]Application, error) + UpdateApplication(id gocql.UUID, name, description string) (*Application, error) + DeleteApplication(id gocql.UUID) error + RegenerateApplicationKey(appID gocql.UUID, newKeyHash string) error } type service struct {@@ -142,128 +141,103 @@ }
return &user, nil } -// API Key-related query implementations -func (s *service) CreateAPIKey(userID gocql.UUID, name, keyHash string, expiresAt *time.Time) (*APIKey, error) { - apiKey := &APIKey{ - ID: gocql.TimeUUID(), - UserID: userID, - Name: name, - KeyHash: keyHash, - CreatedAt: time.Now(), - ExpiresAt: expiresAt, - IsActive: true, +func (s *service) CreateApplication(userID gocql.UUID, name, description, keyHash string) (*Application, error) { + app := &Application{ + ID: gocql.TimeUUID(), + UserID: userID, + Name: name, + Description: description, + KeyHash: keyHash, + CreatedAt: time.Now(), + UpdatedAt: time.Now(), } if err := s.session.Query(` - INSERT INTO api_keys (id, user_id, name, key_hash, created_at, expires_at, is_active) + INSERT INTO applications (id, user_id, name, description, key_hash, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?)`, - apiKey.ID, apiKey.UserID, apiKey.Name, apiKey.KeyHash, - apiKey.CreatedAt, apiKey.ExpiresAt, apiKey.IsActive, + app.ID, app.UserID, app.Name, app.Description, app.KeyHash, app.CreatedAt, app.UpdatedAt, ).Exec(); err != nil { - return nil, fmt.Errorf("error creating API key: %w", err) + return nil, fmt.Errorf("error creating application: %w", err) } - return apiKey, nil + return app, nil } -func (s *service) GetAPIKeyByHash(keyHash string) (*APIKey, error) { - var apiKey APIKey +func (s *service) GetApplication(id gocql.UUID) (*Application, error) { + var app Application if err := s.session.Query(` - SELECT id, user_id, name, key_hash, created_at, last_used_at, expires_at, is_active - FROM api_keys WHERE key_hash = ? ALLOW FILTERING`, - keyHash, + SELECT id, user_id, name, description, key_hash, created_at, updated_at + FROM applications WHERE id = ?`, + id, ).Scan( - &apiKey.ID, &apiKey.UserID, &apiKey.Name, &apiKey.KeyHash, - &apiKey.CreatedAt, &apiKey.LastUsedAt, &apiKey.ExpiresAt, &apiKey.IsActive, + &app.ID, &app.UserID, &app.Name, &app.Description, + &app.KeyHash, &app.CreatedAt, &app.UpdatedAt, ); err != nil { - return nil, fmt.Errorf("API key not found: %w", err) + return nil, fmt.Errorf("application not found: %w", err) } - return &apiKey, nil + return &app, nil } -func (s *service) ListAPIKeys(userID gocql.UUID) ([]APIKey, error) { +func (s *service) ListApplications(userID gocql.UUID) ([]Application, error) { iter := s.session.Query(` - SELECT id, user_id, name, key_hash, created_at, last_used_at, expires_at, is_active - FROM api_keys WHERE user_id = ? ALLOW FILTERING`, + SELECT id, user_id, name, description, key_hash, created_at, updated_at + FROM applications WHERE user_id = ? ALLOW FILTERING`, userID, ).Iter() - var apiKeys []APIKey - var apiKey APIKey - + var apps []Application + var app Application for iter.Scan( - &apiKey.ID, &apiKey.UserID, &apiKey.Name, &apiKey.KeyHash, - &apiKey.CreatedAt, &apiKey.LastUsedAt, &apiKey.ExpiresAt, &apiKey.IsActive, + &app.ID, &app.UserID, &app.Name, &app.Description, + &app.KeyHash, &app.CreatedAt, &app.UpdatedAt, ) { - apiKeys = append(apiKeys, apiKey) + apps = append(apps, app) } if err := iter.Close(); err != nil { - return nil, fmt.Errorf("error listing API keys: %w", err) + return nil, fmt.Errorf("error listing applications: %w", err) } - return apiKeys, nil + return apps, nil } -func (s *service) UpdateAPIKeyLastUsed(keyID gocql.UUID) error { +func (s *service) UpdateApplication(id gocql.UUID, name, description string) (*Application, error) { now := time.Now() if err := s.session.Query(` - UPDATE api_keys SET last_used_at = ? WHERE id = ?`, - now, keyID, + UPDATE applications + SET name = ?, + description = ?, + updated_at = ? + WHERE id = ?`, + name, description, now, id, ).Exec(); err != nil { - return fmt.Errorf("error updating API key last used: %w", err) + return nil, fmt.Errorf("error updating application: %w", err) } - return nil + + return s.GetApplication(id) } -func (s *service) RevokeAPIKey(userID, keyID gocql.UUID) error { - // First verify the API key belongs to the user - var count int +func (s *service) DeleteApplication(id gocql.UUID) error { if err := s.session.Query(` - SELECT COUNT(*) FROM api_keys - WHERE id = ? AND user_id = ? ALLOW FILTERING`, - keyID, userID, - ).Scan(&count); err != nil { - return fmt.Errorf("error verifying API key ownership: %w", err) - } - - if count == 0 { - return fmt.Errorf("API key not found or not owned by user") - } - - // Update the is_active status - if err := s.session.Query(` - UPDATE api_keys SET is_active = ? WHERE id = ?`, - false, keyID, + DELETE FROM applications WHERE id = ?`, + id, ).Exec(); err != nil { - return fmt.Errorf("error revoking API key: %w", err) + return fmt.Errorf("error deleting application: %w", err) } return nil } -func (s *service) DeleteAPIKey(userID, keyID gocql.UUID) error { - // First verify the API key belongs to the user - var apiKey APIKey - if err := s.session.Query(` - SELECT id, user_id FROM api_keys - WHERE id = ? ALLOW FILTERING`, - keyID, - ).Scan(&apiKey.ID, &apiKey.UserID); err != nil { - return fmt.Errorf("API key not found: %w", err) - } - - if apiKey.UserID != userID { - return fmt.Errorf("API key not owned by user") - } - - // Delete the API key +func (s *service) RegenerateApplicationKey(appID gocql.UUID, newKeyHash string) error { + now := time.Now() if err := s.session.Query(` - DELETE FROM api_keys WHERE id = ?`, - keyID, + UPDATE applications + SET key_hash = ?, + updated_at = ? + WHERE id = ?`, + newKeyHash, now, appID, ).Exec(); err != nil { - return fmt.Errorf("error deleting API key: %w", err) + return fmt.Errorf("error regenerating application key: %w", err) } - return nil }
M
internal/server/server.go
→
internal/server/server.go
@@ -9,10 +9,10 @@ "time"
_ "github.com/joho/godotenv/autoload" - "argus-core/internal/apikeys" + "argus-core/internal/applications" "argus-core/internal/auth" "argus-core/internal/database" - apikeyspb "argus-core/rpc/apikeys" + applicationspb "argus-core/rpc/applications" authpb "argus-core/rpc/auth" )@@ -55,15 +55,12 @@ })
// Create Twirp Server handlers authHandler := authpb.NewAuthServiceServer(auth.NewTwirpServer(authService)) - apiKeysHandler := apikeyspb.NewAPIKeysServiceServer(apikeys.NewTwirpServer(authService, db)) - - fmt.Println("auth prefix: " + authHandler.PathPrefix()) - fmt.Println("apiKeys prefix: " + apiKeysHandler.PathPrefix()) + applicationsHandler := applicationspb.NewApplicationsServiceServer(applications.NewTwirpServer(authService, db)) // Combine handlers mux := http.NewServeMux() mux.Handle(authHandler.PathPrefix(), authHandler) - mux.Handle(apiKeysHandler.PathPrefix(), apiKeysHandler) + mux.Handle(applicationsHandler.PathPrefix(), applicationsHandler) // Wrap the mux with CORS middleware handler := CORSMiddleware(mux)
D
rpc/apikeys/service.pb.go
@@ -1,635 +0,0 @@
-// Code generated by protoc-gen-go. DO NOT EDIT. -// versions: -// protoc-gen-go v1.35.2 -// protoc v5.29.1 -// source: rpc/apikeys/service.proto - -package apikeys - -import ( - protoreflect "google.golang.org/protobuf/reflect/protoreflect" - protoimpl "google.golang.org/protobuf/runtime/protoimpl" - reflect "reflect" - sync "sync" -) - -const ( - // Verify that this generated code is sufficiently up-to-date. - _ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion) - // Verify that runtime/protoimpl is sufficiently up-to-date. - _ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20) -) - -type CreateAPIKeyRequest struct { - state protoimpl.MessageState - sizeCache protoimpl.SizeCache - unknownFields protoimpl.UnknownFields - - Token string `protobuf:"bytes,1,opt,name=token,proto3" json:"token,omitempty"` - Name string `protobuf:"bytes,2,opt,name=name,proto3" json:"name,omitempty"` - ExpiresAt string `protobuf:"bytes,3,opt,name=expires_at,json=expiresAt,proto3" json:"expires_at,omitempty"` -} - -func (x *CreateAPIKeyRequest) Reset() { - *x = CreateAPIKeyRequest{} - mi := &file_rpc_apikeys_service_proto_msgTypes[0] - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - ms.StoreMessageInfo(mi) -} - -func (x *CreateAPIKeyRequest) String() string { - return protoimpl.X.MessageStringOf(x) -} - -func (*CreateAPIKeyRequest) ProtoMessage() {} - -func (x *CreateAPIKeyRequest) ProtoReflect() protoreflect.Message { - mi := &file_rpc_apikeys_service_proto_msgTypes[0] - if x != nil { - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - if ms.LoadMessageInfo() == nil { - ms.StoreMessageInfo(mi) - } - return ms - } - return mi.MessageOf(x) -} - -// Deprecated: Use CreateAPIKeyRequest.ProtoReflect.Descriptor instead. -func (*CreateAPIKeyRequest) Descriptor() ([]byte, []int) { - return file_rpc_apikeys_service_proto_rawDescGZIP(), []int{0} -} - -func (x *CreateAPIKeyRequest) GetToken() string { - if x != nil { - return x.Token - } - return "" -} - -func (x *CreateAPIKeyRequest) GetName() string { - if x != nil { - return x.Name - } - return "" -} - -func (x *CreateAPIKeyRequest) GetExpiresAt() string { - if x != nil { - return x.ExpiresAt - } - return "" -} - -type CreateAPIKeyResponse struct { - state protoimpl.MessageState - sizeCache protoimpl.SizeCache - unknownFields protoimpl.UnknownFields - - ApiKey *APIKey `protobuf:"bytes,1,opt,name=api_key,json=apiKey,proto3" json:"api_key,omitempty"` - Key string `protobuf:"bytes,2,opt,name=key,proto3" json:"key,omitempty"` -} - -func (x *CreateAPIKeyResponse) Reset() { - *x = CreateAPIKeyResponse{} - mi := &file_rpc_apikeys_service_proto_msgTypes[1] - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - ms.StoreMessageInfo(mi) -} - -func (x *CreateAPIKeyResponse) String() string { - return protoimpl.X.MessageStringOf(x) -} - -func (*CreateAPIKeyResponse) ProtoMessage() {} - -func (x *CreateAPIKeyResponse) ProtoReflect() protoreflect.Message { - mi := &file_rpc_apikeys_service_proto_msgTypes[1] - if x != nil { - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - if ms.LoadMessageInfo() == nil { - ms.StoreMessageInfo(mi) - } - return ms - } - return mi.MessageOf(x) -} - -// Deprecated: Use CreateAPIKeyResponse.ProtoReflect.Descriptor instead. -func (*CreateAPIKeyResponse) Descriptor() ([]byte, []int) { - return file_rpc_apikeys_service_proto_rawDescGZIP(), []int{1} -} - -func (x *CreateAPIKeyResponse) GetApiKey() *APIKey { - if x != nil { - return x.ApiKey - } - return nil -} - -func (x *CreateAPIKeyResponse) GetKey() string { - if x != nil { - return x.Key - } - return "" -} - -type ListAPIKeysRequest struct { - state protoimpl.MessageState - sizeCache protoimpl.SizeCache - unknownFields protoimpl.UnknownFields - - Token string `protobuf:"bytes,1,opt,name=token,proto3" json:"token,omitempty"` -} - -func (x *ListAPIKeysRequest) Reset() { - *x = ListAPIKeysRequest{} - mi := &file_rpc_apikeys_service_proto_msgTypes[2] - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - ms.StoreMessageInfo(mi) -} - -func (x *ListAPIKeysRequest) String() string { - return protoimpl.X.MessageStringOf(x) -} - -func (*ListAPIKeysRequest) ProtoMessage() {} - -func (x *ListAPIKeysRequest) ProtoReflect() protoreflect.Message { - mi := &file_rpc_apikeys_service_proto_msgTypes[2] - if x != nil { - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - if ms.LoadMessageInfo() == nil { - ms.StoreMessageInfo(mi) - } - return ms - } - return mi.MessageOf(x) -} - -// Deprecated: Use ListAPIKeysRequest.ProtoReflect.Descriptor instead. -func (*ListAPIKeysRequest) Descriptor() ([]byte, []int) { - return file_rpc_apikeys_service_proto_rawDescGZIP(), []int{2} -} - -func (x *ListAPIKeysRequest) GetToken() string { - if x != nil { - return x.Token - } - return "" -} - -type ListAPIKeysResponse struct { - state protoimpl.MessageState - sizeCache protoimpl.SizeCache - unknownFields protoimpl.UnknownFields - - ApiKeys []*APIKey `protobuf:"bytes,1,rep,name=api_keys,json=apiKeys,proto3" json:"api_keys,omitempty"` -} - -func (x *ListAPIKeysResponse) Reset() { - *x = ListAPIKeysResponse{} - mi := &file_rpc_apikeys_service_proto_msgTypes[3] - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - ms.StoreMessageInfo(mi) -} - -func (x *ListAPIKeysResponse) String() string { - return protoimpl.X.MessageStringOf(x) -} - -func (*ListAPIKeysResponse) ProtoMessage() {} - -func (x *ListAPIKeysResponse) ProtoReflect() protoreflect.Message { - mi := &file_rpc_apikeys_service_proto_msgTypes[3] - if x != nil { - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - if ms.LoadMessageInfo() == nil { - ms.StoreMessageInfo(mi) - } - return ms - } - return mi.MessageOf(x) -} - -// Deprecated: Use ListAPIKeysResponse.ProtoReflect.Descriptor instead. -func (*ListAPIKeysResponse) Descriptor() ([]byte, []int) { - return file_rpc_apikeys_service_proto_rawDescGZIP(), []int{3} -} - -func (x *ListAPIKeysResponse) GetApiKeys() []*APIKey { - if x != nil { - return x.ApiKeys - } - return nil -} - -type RevokeAPIKeyRequest struct { - state protoimpl.MessageState - sizeCache protoimpl.SizeCache - unknownFields protoimpl.UnknownFields - - Token string `protobuf:"bytes,1,opt,name=token,proto3" json:"token,omitempty"` - KeyId string `protobuf:"bytes,2,opt,name=key_id,json=keyId,proto3" json:"key_id,omitempty"` -} - -func (x *RevokeAPIKeyRequest) Reset() { - *x = RevokeAPIKeyRequest{} - mi := &file_rpc_apikeys_service_proto_msgTypes[4] - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - ms.StoreMessageInfo(mi) -} - -func (x *RevokeAPIKeyRequest) String() string { - return protoimpl.X.MessageStringOf(x) -} - -func (*RevokeAPIKeyRequest) ProtoMessage() {} - -func (x *RevokeAPIKeyRequest) ProtoReflect() protoreflect.Message { - mi := &file_rpc_apikeys_service_proto_msgTypes[4] - if x != nil { - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - if ms.LoadMessageInfo() == nil { - ms.StoreMessageInfo(mi) - } - return ms - } - return mi.MessageOf(x) -} - -// Deprecated: Use RevokeAPIKeyRequest.ProtoReflect.Descriptor instead. -func (*RevokeAPIKeyRequest) Descriptor() ([]byte, []int) { - return file_rpc_apikeys_service_proto_rawDescGZIP(), []int{4} -} - -func (x *RevokeAPIKeyRequest) GetToken() string { - if x != nil { - return x.Token - } - return "" -} - -func (x *RevokeAPIKeyRequest) GetKeyId() string { - if x != nil { - return x.KeyId - } - return "" -} - -type RevokeAPIKeyResponse struct { - state protoimpl.MessageState - sizeCache protoimpl.SizeCache - unknownFields protoimpl.UnknownFields -} - -func (x *RevokeAPIKeyResponse) Reset() { - *x = RevokeAPIKeyResponse{} - mi := &file_rpc_apikeys_service_proto_msgTypes[5] - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - ms.StoreMessageInfo(mi) -} - -func (x *RevokeAPIKeyResponse) String() string { - return protoimpl.X.MessageStringOf(x) -} - -func (*RevokeAPIKeyResponse) ProtoMessage() {} - -func (x *RevokeAPIKeyResponse) ProtoReflect() protoreflect.Message { - mi := &file_rpc_apikeys_service_proto_msgTypes[5] - if x != nil { - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - if ms.LoadMessageInfo() == nil { - ms.StoreMessageInfo(mi) - } - return ms - } - return mi.MessageOf(x) -} - -// Deprecated: Use RevokeAPIKeyResponse.ProtoReflect.Descriptor instead. -func (*RevokeAPIKeyResponse) Descriptor() ([]byte, []int) { - return file_rpc_apikeys_service_proto_rawDescGZIP(), []int{5} -} - -type DeleteAPIKeyRequest struct { - state protoimpl.MessageState - sizeCache protoimpl.SizeCache - unknownFields protoimpl.UnknownFields - - Token string `protobuf:"bytes,1,opt,name=token,proto3" json:"token,omitempty"` - KeyId string `protobuf:"bytes,2,opt,name=key_id,json=keyId,proto3" json:"key_id,omitempty"` -} - -func (x *DeleteAPIKeyRequest) Reset() { - *x = DeleteAPIKeyRequest{} - mi := &file_rpc_apikeys_service_proto_msgTypes[6] - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - ms.StoreMessageInfo(mi) -} - -func (x *DeleteAPIKeyRequest) String() string { - return protoimpl.X.MessageStringOf(x) -} - -func (*DeleteAPIKeyRequest) ProtoMessage() {} - -func (x *DeleteAPIKeyRequest) ProtoReflect() protoreflect.Message { - mi := &file_rpc_apikeys_service_proto_msgTypes[6] - if x != nil { - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - if ms.LoadMessageInfo() == nil { - ms.StoreMessageInfo(mi) - } - return ms - } - return mi.MessageOf(x) -} - -// Deprecated: Use DeleteAPIKeyRequest.ProtoReflect.Descriptor instead. -func (*DeleteAPIKeyRequest) Descriptor() ([]byte, []int) { - return file_rpc_apikeys_service_proto_rawDescGZIP(), []int{6} -} - -func (x *DeleteAPIKeyRequest) GetToken() string { - if x != nil { - return x.Token - } - return "" -} - -func (x *DeleteAPIKeyRequest) GetKeyId() string { - if x != nil { - return x.KeyId - } - return "" -} - -type DeleteAPIKeyResponse struct { - state protoimpl.MessageState - sizeCache protoimpl.SizeCache - unknownFields protoimpl.UnknownFields -} - -func (x *DeleteAPIKeyResponse) Reset() { - *x = DeleteAPIKeyResponse{} - mi := &file_rpc_apikeys_service_proto_msgTypes[7] - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - ms.StoreMessageInfo(mi) -} - -func (x *DeleteAPIKeyResponse) String() string { - return protoimpl.X.MessageStringOf(x) -} - -func (*DeleteAPIKeyResponse) ProtoMessage() {} - -func (x *DeleteAPIKeyResponse) ProtoReflect() protoreflect.Message { - mi := &file_rpc_apikeys_service_proto_msgTypes[7] - if x != nil { - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - if ms.LoadMessageInfo() == nil { - ms.StoreMessageInfo(mi) - } - return ms - } - return mi.MessageOf(x) -} - -// Deprecated: Use DeleteAPIKeyResponse.ProtoReflect.Descriptor instead. -func (*DeleteAPIKeyResponse) Descriptor() ([]byte, []int) { - return file_rpc_apikeys_service_proto_rawDescGZIP(), []int{7} -} - -type APIKey struct { - state protoimpl.MessageState - sizeCache protoimpl.SizeCache - unknownFields protoimpl.UnknownFields - - Id string `protobuf:"bytes,1,opt,name=id,proto3" json:"id,omitempty"` - UserId string `protobuf:"bytes,2,opt,name=user_id,json=userId,proto3" json:"user_id,omitempty"` - Name string `protobuf:"bytes,3,opt,name=name,proto3" json:"name,omitempty"` - CreatedAt string `protobuf:"bytes,4,opt,name=created_at,json=createdAt,proto3" json:"created_at,omitempty"` - LastUsedAt string `protobuf:"bytes,5,opt,name=last_used_at,json=lastUsedAt,proto3" json:"last_used_at,omitempty"` - ExpiresAt string `protobuf:"bytes,6,opt,name=expires_at,json=expiresAt,proto3" json:"expires_at,omitempty"` - IsActive bool `protobuf:"varint,7,opt,name=is_active,json=isActive,proto3" json:"is_active,omitempty"` -} - -func (x *APIKey) Reset() { - *x = APIKey{} - mi := &file_rpc_apikeys_service_proto_msgTypes[8] - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - ms.StoreMessageInfo(mi) -} - -func (x *APIKey) String() string { - return protoimpl.X.MessageStringOf(x) -} - -func (*APIKey) ProtoMessage() {} - -func (x *APIKey) ProtoReflect() protoreflect.Message { - mi := &file_rpc_apikeys_service_proto_msgTypes[8] - if x != nil { - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - if ms.LoadMessageInfo() == nil { - ms.StoreMessageInfo(mi) - } - return ms - } - return mi.MessageOf(x) -} - -// Deprecated: Use APIKey.ProtoReflect.Descriptor instead. -func (*APIKey) Descriptor() ([]byte, []int) { - return file_rpc_apikeys_service_proto_rawDescGZIP(), []int{8} -} - -func (x *APIKey) GetId() string { - if x != nil { - return x.Id - } - return "" -} - -func (x *APIKey) GetUserId() string { - if x != nil { - return x.UserId - } - return "" -} - -func (x *APIKey) GetName() string { - if x != nil { - return x.Name - } - return "" -} - -func (x *APIKey) GetCreatedAt() string { - if x != nil { - return x.CreatedAt - } - return "" -} - -func (x *APIKey) GetLastUsedAt() string { - if x != nil { - return x.LastUsedAt - } - return "" -} - -func (x *APIKey) GetExpiresAt() string { - if x != nil { - return x.ExpiresAt - } - return "" -} - -func (x *APIKey) GetIsActive() bool { - if x != nil { - return x.IsActive - } - return false -} - -var File_rpc_apikeys_service_proto protoreflect.FileDescriptor - -var file_rpc_apikeys_service_proto_rawDesc = []byte{ - 0x0a, 0x19, 0x72, 0x70, 0x63, 0x2f, 0x61, 0x70, 0x69, 0x6b, 0x65, 0x79, 0x73, 0x2f, 0x73, 0x65, - 0x72, 0x76, 0x69, 0x63, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x12, 0x07, 0x61, 0x70, 0x69, - 0x6b, 0x65, 0x79, 0x73, 0x22, 0x5e, 0x0a, 0x13, 0x43, 0x72, 0x65, 0x61, 0x74, 0x65, 0x41, 0x50, - 0x49, 0x4b, 0x65, 0x79, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x12, 0x14, 0x0a, 0x05, 0x74, - 0x6f, 0x6b, 0x65, 0x6e, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x05, 0x74, 0x6f, 0x6b, 0x65, - 0x6e, 0x12, 0x12, 0x0a, 0x04, 0x6e, 0x61, 0x6d, 0x65, 0x18, 0x02, 0x20, 0x01, 0x28, 0x09, 0x52, - 0x04, 0x6e, 0x61, 0x6d, 0x65, 0x12, 0x1d, 0x0a, 0x0a, 0x65, 0x78, 0x70, 0x69, 0x72, 0x65, 0x73, - 0x5f, 0x61, 0x74, 0x18, 0x03, 0x20, 0x01, 0x28, 0x09, 0x52, 0x09, 0x65, 0x78, 0x70, 0x69, 0x72, - 0x65, 0x73, 0x41, 0x74, 0x22, 0x52, 0x0a, 0x14, 0x43, 0x72, 0x65, 0x61, 0x74, 0x65, 0x41, 0x50, - 0x49, 0x4b, 0x65, 0x79, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x28, 0x0a, 0x07, - 0x61, 0x70, 0x69, 0x5f, 0x6b, 0x65, 0x79, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x0f, 0x2e, - 0x61, 0x70, 0x69, 0x6b, 0x65, 0x79, 0x73, 0x2e, 0x41, 0x50, 0x49, 0x4b, 0x65, 0x79, 0x52, 0x06, - 0x61, 0x70, 0x69, 0x4b, 0x65, 0x79, 0x12, 0x10, 0x0a, 0x03, 0x6b, 0x65, 0x79, 0x18, 0x02, 0x20, - 0x01, 0x28, 0x09, 0x52, 0x03, 0x6b, 0x65, 0x79, 0x22, 0x2a, 0x0a, 0x12, 0x4c, 0x69, 0x73, 0x74, - 0x41, 0x50, 0x49, 0x4b, 0x65, 0x79, 0x73, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x12, 0x14, - 0x0a, 0x05, 0x74, 0x6f, 0x6b, 0x65, 0x6e, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x05, 0x74, - 0x6f, 0x6b, 0x65, 0x6e, 0x22, 0x41, 0x0a, 0x13, 0x4c, 0x69, 0x73, 0x74, 0x41, 0x50, 0x49, 0x4b, - 0x65, 0x79, 0x73, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x2a, 0x0a, 0x08, 0x61, - 0x70, 0x69, 0x5f, 0x6b, 0x65, 0x79, 0x73, 0x18, 0x01, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x0f, 0x2e, - 0x61, 0x70, 0x69, 0x6b, 0x65, 0x79, 0x73, 0x2e, 0x41, 0x50, 0x49, 0x4b, 0x65, 0x79, 0x52, 0x07, - 0x61, 0x70, 0x69, 0x4b, 0x65, 0x79, 0x73, 0x22, 0x42, 0x0a, 0x13, 0x52, 0x65, 0x76, 0x6f, 0x6b, - 0x65, 0x41, 0x50, 0x49, 0x4b, 0x65, 0x79, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x12, 0x14, - 0x0a, 0x05, 0x74, 0x6f, 0x6b, 0x65, 0x6e, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x05, 0x74, - 0x6f, 0x6b, 0x65, 0x6e, 0x12, 0x15, 0x0a, 0x06, 0x6b, 0x65, 0x79, 0x5f, 0x69, 0x64, 0x18, 0x02, - 0x20, 0x01, 0x28, 0x09, 0x52, 0x05, 0x6b, 0x65, 0x79, 0x49, 0x64, 0x22, 0x16, 0x0a, 0x14, 0x52, - 0x65, 0x76, 0x6f, 0x6b, 0x65, 0x41, 0x50, 0x49, 0x4b, 0x65, 0x79, 0x52, 0x65, 0x73, 0x70, 0x6f, - 0x6e, 0x73, 0x65, 0x22, 0x42, 0x0a, 0x13, 0x44, 0x65, 0x6c, 0x65, 0x74, 0x65, 0x41, 0x50, 0x49, - 0x4b, 0x65, 0x79, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x12, 0x14, 0x0a, 0x05, 0x74, 0x6f, - 0x6b, 0x65, 0x6e, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x05, 0x74, 0x6f, 0x6b, 0x65, 0x6e, - 0x12, 0x15, 0x0a, 0x06, 0x6b, 0x65, 0x79, 0x5f, 0x69, 0x64, 0x18, 0x02, 0x20, 0x01, 0x28, 0x09, - 0x52, 0x05, 0x6b, 0x65, 0x79, 0x49, 0x64, 0x22, 0x16, 0x0a, 0x14, 0x44, 0x65, 0x6c, 0x65, 0x74, - 0x65, 0x41, 0x50, 0x49, 0x4b, 0x65, 0x79, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x22, - 0xc2, 0x01, 0x0a, 0x06, 0x41, 0x50, 0x49, 0x4b, 0x65, 0x79, 0x12, 0x0e, 0x0a, 0x02, 0x69, 0x64, - 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x02, 0x69, 0x64, 0x12, 0x17, 0x0a, 0x07, 0x75, 0x73, - 0x65, 0x72, 0x5f, 0x69, 0x64, 0x18, 0x02, 0x20, 0x01, 0x28, 0x09, 0x52, 0x06, 0x75, 0x73, 0x65, - 0x72, 0x49, 0x64, 0x12, 0x12, 0x0a, 0x04, 0x6e, 0x61, 0x6d, 0x65, 0x18, 0x03, 0x20, 0x01, 0x28, - 0x09, 0x52, 0x04, 0x6e, 0x61, 0x6d, 0x65, 0x12, 0x1d, 0x0a, 0x0a, 0x63, 0x72, 0x65, 0x61, 0x74, - 0x65, 0x64, 0x5f, 0x61, 0x74, 0x18, 0x04, 0x20, 0x01, 0x28, 0x09, 0x52, 0x09, 0x63, 0x72, 0x65, - 0x61, 0x74, 0x65, 0x64, 0x41, 0x74, 0x12, 0x20, 0x0a, 0x0c, 0x6c, 0x61, 0x73, 0x74, 0x5f, 0x75, - 0x73, 0x65, 0x64, 0x5f, 0x61, 0x74, 0x18, 0x05, 0x20, 0x01, 0x28, 0x09, 0x52, 0x0a, 0x6c, 0x61, - 0x73, 0x74, 0x55, 0x73, 0x65, 0x64, 0x41, 0x74, 0x12, 0x1d, 0x0a, 0x0a, 0x65, 0x78, 0x70, 0x69, - 0x72, 0x65, 0x73, 0x5f, 0x61, 0x74, 0x18, 0x06, 0x20, 0x01, 0x28, 0x09, 0x52, 0x09, 0x65, 0x78, - 0x70, 0x69, 0x72, 0x65, 0x73, 0x41, 0x74, 0x12, 0x1b, 0x0a, 0x09, 0x69, 0x73, 0x5f, 0x61, 0x63, - 0x74, 0x69, 0x76, 0x65, 0x18, 0x07, 0x20, 0x01, 0x28, 0x08, 0x52, 0x08, 0x69, 0x73, 0x41, 0x63, - 0x74, 0x69, 0x76, 0x65, 0x32, 0xc1, 0x02, 0x0a, 0x0e, 0x41, 0x50, 0x49, 0x4b, 0x65, 0x79, 0x73, - 0x53, 0x65, 0x72, 0x76, 0x69, 0x63, 0x65, 0x12, 0x4b, 0x0a, 0x0c, 0x43, 0x72, 0x65, 0x61, 0x74, - 0x65, 0x41, 0x50, 0x49, 0x4b, 0x65, 0x79, 0x12, 0x1c, 0x2e, 0x61, 0x70, 0x69, 0x6b, 0x65, 0x79, - 0x73, 0x2e, 0x43, 0x72, 0x65, 0x61, 0x74, 0x65, 0x41, 0x50, 0x49, 0x4b, 0x65, 0x79, 0x52, 0x65, - 0x71, 0x75, 0x65, 0x73, 0x74, 0x1a, 0x1d, 0x2e, 0x61, 0x70, 0x69, 0x6b, 0x65, 0x79, 0x73, 0x2e, - 0x43, 0x72, 0x65, 0x61, 0x74, 0x65, 0x41, 0x50, 0x49, 0x4b, 0x65, 0x79, 0x52, 0x65, 0x73, 0x70, - 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x48, 0x0a, 0x0b, 0x4c, 0x69, 0x73, 0x74, 0x41, 0x50, 0x49, 0x4b, - 0x65, 0x79, 0x73, 0x12, 0x1b, 0x2e, 0x61, 0x70, 0x69, 0x6b, 0x65, 0x79, 0x73, 0x2e, 0x4c, 0x69, - 0x73, 0x74, 0x41, 0x50, 0x49, 0x4b, 0x65, 0x79, 0x73, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, - 0x1a, 0x1c, 0x2e, 0x61, 0x70, 0x69, 0x6b, 0x65, 0x79, 0x73, 0x2e, 0x4c, 0x69, 0x73, 0x74, 0x41, - 0x50, 0x49, 0x4b, 0x65, 0x79, 0x73, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x4b, - 0x0a, 0x0c, 0x52, 0x65, 0x76, 0x6f, 0x6b, 0x65, 0x41, 0x50, 0x49, 0x4b, 0x65, 0x79, 0x12, 0x1c, - 0x2e, 0x61, 0x70, 0x69, 0x6b, 0x65, 0x79, 0x73, 0x2e, 0x52, 0x65, 0x76, 0x6f, 0x6b, 0x65, 0x41, - 0x50, 0x49, 0x4b, 0x65, 0x79, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x1a, 0x1d, 0x2e, 0x61, - 0x70, 0x69, 0x6b, 0x65, 0x79, 0x73, 0x2e, 0x52, 0x65, 0x76, 0x6f, 0x6b, 0x65, 0x41, 0x50, 0x49, - 0x4b, 0x65, 0x79, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x4b, 0x0a, 0x0c, 0x44, - 0x65, 0x6c, 0x65, 0x74, 0x65, 0x41, 0x50, 0x49, 0x4b, 0x65, 0x79, 0x12, 0x1c, 0x2e, 0x61, 0x70, - 0x69, 0x6b, 0x65, 0x79, 0x73, 0x2e, 0x44, 0x65, 0x6c, 0x65, 0x74, 0x65, 0x41, 0x50, 0x49, 0x4b, - 0x65, 0x79, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x1a, 0x1d, 0x2e, 0x61, 0x70, 0x69, 0x6b, - 0x65, 0x79, 0x73, 0x2e, 0x44, 0x65, 0x6c, 0x65, 0x74, 0x65, 0x41, 0x50, 0x49, 0x4b, 0x65, 0x79, - 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x42, 0x18, 0x5a, 0x16, 0x61, 0x72, 0x67, 0x75, - 0x73, 0x2d, 0x63, 0x6f, 0x72, 0x65, 0x2f, 0x72, 0x70, 0x63, 0x2f, 0x61, 0x70, 0x69, 0x6b, 0x65, - 0x79, 0x73, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33, -} - -var ( - file_rpc_apikeys_service_proto_rawDescOnce sync.Once - file_rpc_apikeys_service_proto_rawDescData = file_rpc_apikeys_service_proto_rawDesc -) - -func file_rpc_apikeys_service_proto_rawDescGZIP() []byte { - file_rpc_apikeys_service_proto_rawDescOnce.Do(func() { - file_rpc_apikeys_service_proto_rawDescData = protoimpl.X.CompressGZIP(file_rpc_apikeys_service_proto_rawDescData) - }) - return file_rpc_apikeys_service_proto_rawDescData -} - -var file_rpc_apikeys_service_proto_msgTypes = make([]protoimpl.MessageInfo, 9) -var file_rpc_apikeys_service_proto_goTypes = []any{ - (*CreateAPIKeyRequest)(nil), // 0: apikeys.CreateAPIKeyRequest - (*CreateAPIKeyResponse)(nil), // 1: apikeys.CreateAPIKeyResponse - (*ListAPIKeysRequest)(nil), // 2: apikeys.ListAPIKeysRequest - (*ListAPIKeysResponse)(nil), // 3: apikeys.ListAPIKeysResponse - (*RevokeAPIKeyRequest)(nil), // 4: apikeys.RevokeAPIKeyRequest - (*RevokeAPIKeyResponse)(nil), // 5: apikeys.RevokeAPIKeyResponse - (*DeleteAPIKeyRequest)(nil), // 6: apikeys.DeleteAPIKeyRequest - (*DeleteAPIKeyResponse)(nil), // 7: apikeys.DeleteAPIKeyResponse - (*APIKey)(nil), // 8: apikeys.APIKey -} -var file_rpc_apikeys_service_proto_depIdxs = []int32{ - 8, // 0: apikeys.CreateAPIKeyResponse.api_key:type_name -> apikeys.APIKey - 8, // 1: apikeys.ListAPIKeysResponse.api_keys:type_name -> apikeys.APIKey - 0, // 2: apikeys.APIKeysService.CreateAPIKey:input_type -> apikeys.CreateAPIKeyRequest - 2, // 3: apikeys.APIKeysService.ListAPIKeys:input_type -> apikeys.ListAPIKeysRequest - 4, // 4: apikeys.APIKeysService.RevokeAPIKey:input_type -> apikeys.RevokeAPIKeyRequest - 6, // 5: apikeys.APIKeysService.DeleteAPIKey:input_type -> apikeys.DeleteAPIKeyRequest - 1, // 6: apikeys.APIKeysService.CreateAPIKey:output_type -> apikeys.CreateAPIKeyResponse - 3, // 7: apikeys.APIKeysService.ListAPIKeys:output_type -> apikeys.ListAPIKeysResponse - 5, // 8: apikeys.APIKeysService.RevokeAPIKey:output_type -> apikeys.RevokeAPIKeyResponse - 7, // 9: apikeys.APIKeysService.DeleteAPIKey:output_type -> apikeys.DeleteAPIKeyResponse - 6, // [6:10] is the sub-list for method output_type - 2, // [2:6] is the sub-list for method input_type - 2, // [2:2] is the sub-list for extension type_name - 2, // [2:2] is the sub-list for extension extendee - 0, // [0:2] is the sub-list for field type_name -} - -func init() { file_rpc_apikeys_service_proto_init() } -func file_rpc_apikeys_service_proto_init() { - if File_rpc_apikeys_service_proto != nil { - return - } - type x struct{} - out := protoimpl.TypeBuilder{ - File: protoimpl.DescBuilder{ - GoPackagePath: reflect.TypeOf(x{}).PkgPath(), - RawDescriptor: file_rpc_apikeys_service_proto_rawDesc, - NumEnums: 0, - NumMessages: 9, - NumExtensions: 0, - NumServices: 1, - }, - GoTypes: file_rpc_apikeys_service_proto_goTypes, - DependencyIndexes: file_rpc_apikeys_service_proto_depIdxs, - MessageInfos: file_rpc_apikeys_service_proto_msgTypes, - }.Build() - File_rpc_apikeys_service_proto = out.File - file_rpc_apikeys_service_proto_rawDesc = nil - file_rpc_apikeys_service_proto_goTypes = nil - file_rpc_apikeys_service_proto_depIdxs = nil -}
D
rpc/apikeys/service.proto
@@ -1,53 +0,0 @@
-syntax = "proto3"; - -package apikeys; -option go_package = "argus-core/rpc/apikeys"; - -service APIKeysService { - rpc CreateAPIKey(CreateAPIKeyRequest) returns (CreateAPIKeyResponse); - rpc ListAPIKeys(ListAPIKeysRequest) returns (ListAPIKeysResponse); - rpc RevokeAPIKey(RevokeAPIKeyRequest) returns (RevokeAPIKeyResponse); - rpc DeleteAPIKey(DeleteAPIKeyRequest) returns (DeleteAPIKeyResponse); -} -message CreateAPIKeyRequest { - string token = 1; - string name = 2; - string expires_at = 3; -} - -message CreateAPIKeyResponse { - APIKey api_key = 1; - string key = 2; -} - -message ListAPIKeysRequest { - string token = 1; -} - -message ListAPIKeysResponse { - repeated APIKey api_keys = 1; -} - -message RevokeAPIKeyRequest { - string token = 1; - string key_id = 2; -} - -message RevokeAPIKeyResponse {} - -message DeleteAPIKeyRequest { - string token = 1; - string key_id = 2; -} - -message DeleteAPIKeyResponse {} - -message APIKey { - string id = 1; - string user_id = 2; - string name = 3; - string created_at = 4; - string last_used_at = 5; - string expires_at = 6; - bool is_active = 7; -}
D
rpc/apikeys/service.twirp.go
@@ -1,1956 +0,0 @@
-// Code generated by protoc-gen-twirp v8.1.3, DO NOT EDIT. -// source: rpc/apikeys/service.proto - -package apikeys - -import context "context" -import fmt "fmt" -import http "net/http" -import io "io" -import json "encoding/json" -import strconv "strconv" -import strings "strings" - -import protojson "google.golang.org/protobuf/encoding/protojson" -import proto "google.golang.org/protobuf/proto" -import twirp "github.com/twitchtv/twirp" -import ctxsetters "github.com/twitchtv/twirp/ctxsetters" - -import bytes "bytes" -import errors "errors" -import path "path" -import url "net/url" - -// Version compatibility assertion. -// If the constant is not defined in the package, that likely means -// the package needs to be updated to work with this generated code. -// See https://twitchtv.github.io/twirp/docs/version_matrix.html -const _ = twirp.TwirpPackageMinVersion_8_1_0 - -// ======================== -// APIKeysService Interface -// ======================== - -type APIKeysService interface { - CreateAPIKey(context.Context, *CreateAPIKeyRequest) (*CreateAPIKeyResponse, error) - - ListAPIKeys(context.Context, *ListAPIKeysRequest) (*ListAPIKeysResponse, error) - - RevokeAPIKey(context.Context, *RevokeAPIKeyRequest) (*RevokeAPIKeyResponse, error) - - DeleteAPIKey(context.Context, *DeleteAPIKeyRequest) (*DeleteAPIKeyResponse, error) -} - -// ============================== -// APIKeysService Protobuf Client -// ============================== - -type aPIKeysServiceProtobufClient struct { - client HTTPClient - urls [4]string - interceptor twirp.Interceptor - opts twirp.ClientOptions -} - -// NewAPIKeysServiceProtobufClient creates a Protobuf client that implements the APIKeysService interface. -// It communicates using Protobuf and can be configured with a custom HTTPClient. -func NewAPIKeysServiceProtobufClient(baseURL string, client HTTPClient, opts ...twirp.ClientOption) APIKeysService { - if c, ok := client.(*http.Client); ok { - client = withoutRedirects(c) - } - - clientOpts := twirp.ClientOptions{} - for _, o := range opts { - o(&clientOpts) - } - - // Using ReadOpt allows backwards and forwards compatibility with new options in the future - literalURLs := false - _ = clientOpts.ReadOpt("literalURLs", &literalURLs) - var pathPrefix string - if ok := clientOpts.ReadOpt("pathPrefix", &pathPrefix); !ok { - pathPrefix = "/twirp" // default prefix - } - - // Build method URLs: <baseURL>[<prefix>]/<package>.<Service>/<Method> - serviceURL := sanitizeBaseURL(baseURL) - serviceURL += baseServicePath(pathPrefix, "apikeys", "APIKeysService") - urls := [4]string{ - serviceURL + "CreateAPIKey", - serviceURL + "ListAPIKeys", - serviceURL + "RevokeAPIKey", - serviceURL + "DeleteAPIKey", - } - - return &aPIKeysServiceProtobufClient{ - client: client, - urls: urls, - interceptor: twirp.ChainInterceptors(clientOpts.Interceptors...), - opts: clientOpts, - } -} - -func (c *aPIKeysServiceProtobufClient) CreateAPIKey(ctx context.Context, in *CreateAPIKeyRequest) (*CreateAPIKeyResponse, error) { - ctx = ctxsetters.WithPackageName(ctx, "apikeys") - ctx = ctxsetters.WithServiceName(ctx, "APIKeysService") - ctx = ctxsetters.WithMethodName(ctx, "CreateAPIKey") - caller := c.callCreateAPIKey - if c.interceptor != nil { - caller = func(ctx context.Context, req *CreateAPIKeyRequest) (*CreateAPIKeyResponse, error) { - resp, err := c.interceptor( - func(ctx context.Context, req interface{}) (interface{}, error) { - typedReq, ok := req.(*CreateAPIKeyRequest) - if !ok { - return nil, twirp.InternalError("failed type assertion req.(*CreateAPIKeyRequest) when calling interceptor") - } - return c.callCreateAPIKey(ctx, typedReq) - }, - )(ctx, req) - if resp != nil { - typedResp, ok := resp.(*CreateAPIKeyResponse) - if !ok { - return nil, twirp.InternalError("failed type assertion resp.(*CreateAPIKeyResponse) when calling interceptor") - } - return typedResp, err - } - return nil, err - } - } - return caller(ctx, in) -} - -func (c *aPIKeysServiceProtobufClient) callCreateAPIKey(ctx context.Context, in *CreateAPIKeyRequest) (*CreateAPIKeyResponse, error) { - out := new(CreateAPIKeyResponse) - ctx, err := doProtobufRequest(ctx, c.client, c.opts.Hooks, c.urls[0], in, out) - if err != nil { - twerr, ok := err.(twirp.Error) - if !ok { - twerr = twirp.InternalErrorWith(err) - } - callClientError(ctx, c.opts.Hooks, twerr) - return nil, err - } - - callClientResponseReceived(ctx, c.opts.Hooks) - - return out, nil -} - -func (c *aPIKeysServiceProtobufClient) ListAPIKeys(ctx context.Context, in *ListAPIKeysRequest) (*ListAPIKeysResponse, error) { - ctx = ctxsetters.WithPackageName(ctx, "apikeys") - ctx = ctxsetters.WithServiceName(ctx, "APIKeysService") - ctx = ctxsetters.WithMethodName(ctx, "ListAPIKeys") - caller := c.callListAPIKeys - if c.interceptor != nil { - caller = func(ctx context.Context, req *ListAPIKeysRequest) (*ListAPIKeysResponse, error) { - resp, err := c.interceptor( - func(ctx context.Context, req interface{}) (interface{}, error) { - typedReq, ok := req.(*ListAPIKeysRequest) - if !ok { - return nil, twirp.InternalError("failed type assertion req.(*ListAPIKeysRequest) when calling interceptor") - } - return c.callListAPIKeys(ctx, typedReq) - }, - )(ctx, req) - if resp != nil { - typedResp, ok := resp.(*ListAPIKeysResponse) - if !ok { - return nil, twirp.InternalError("failed type assertion resp.(*ListAPIKeysResponse) when calling interceptor") - } - return typedResp, err - } - return nil, err - } - } - return caller(ctx, in) -} - -func (c *aPIKeysServiceProtobufClient) callListAPIKeys(ctx context.Context, in *ListAPIKeysRequest) (*ListAPIKeysResponse, error) { - out := new(ListAPIKeysResponse) - ctx, err := doProtobufRequest(ctx, c.client, c.opts.Hooks, c.urls[1], in, out) - if err != nil { - twerr, ok := err.(twirp.Error) - if !ok { - twerr = twirp.InternalErrorWith(err) - } - callClientError(ctx, c.opts.Hooks, twerr) - return nil, err - } - - callClientResponseReceived(ctx, c.opts.Hooks) - - return out, nil -} - -func (c *aPIKeysServiceProtobufClient) RevokeAPIKey(ctx context.Context, in *RevokeAPIKeyRequest) (*RevokeAPIKeyResponse, error) { - ctx = ctxsetters.WithPackageName(ctx, "apikeys") - ctx = ctxsetters.WithServiceName(ctx, "APIKeysService") - ctx = ctxsetters.WithMethodName(ctx, "RevokeAPIKey") - caller := c.callRevokeAPIKey - if c.interceptor != nil { - caller = func(ctx context.Context, req *RevokeAPIKeyRequest) (*RevokeAPIKeyResponse, error) { - resp, err := c.interceptor( - func(ctx context.Context, req interface{}) (interface{}, error) { - typedReq, ok := req.(*RevokeAPIKeyRequest) - if !ok { - return nil, twirp.InternalError("failed type assertion req.(*RevokeAPIKeyRequest) when calling interceptor") - } - return c.callRevokeAPIKey(ctx, typedReq) - }, - )(ctx, req) - if resp != nil { - typedResp, ok := resp.(*RevokeAPIKeyResponse) - if !ok { - return nil, twirp.InternalError("failed type assertion resp.(*RevokeAPIKeyResponse) when calling interceptor") - } - return typedResp, err - } - return nil, err - } - } - return caller(ctx, in) -} - -func (c *aPIKeysServiceProtobufClient) callRevokeAPIKey(ctx context.Context, in *RevokeAPIKeyRequest) (*RevokeAPIKeyResponse, error) { - out := new(RevokeAPIKeyResponse) - ctx, err := doProtobufRequest(ctx, c.client, c.opts.Hooks, c.urls[2], in, out) - if err != nil { - twerr, ok := err.(twirp.Error) - if !ok { - twerr = twirp.InternalErrorWith(err) - } - callClientError(ctx, c.opts.Hooks, twerr) - return nil, err - } - - callClientResponseReceived(ctx, c.opts.Hooks) - - return out, nil -} - -func (c *aPIKeysServiceProtobufClient) DeleteAPIKey(ctx context.Context, in *DeleteAPIKeyRequest) (*DeleteAPIKeyResponse, error) { - ctx = ctxsetters.WithPackageName(ctx, "apikeys") - ctx = ctxsetters.WithServiceName(ctx, "APIKeysService") - ctx = ctxsetters.WithMethodName(ctx, "DeleteAPIKey") - caller := c.callDeleteAPIKey - if c.interceptor != nil { - caller = func(ctx context.Context, req *DeleteAPIKeyRequest) (*DeleteAPIKeyResponse, error) { - resp, err := c.interceptor( - func(ctx context.Context, req interface{}) (interface{}, error) { - typedReq, ok := req.(*DeleteAPIKeyRequest) - if !ok { - return nil, twirp.InternalError("failed type assertion req.(*DeleteAPIKeyRequest) when calling interceptor") - } - return c.callDeleteAPIKey(ctx, typedReq) - }, - )(ctx, req) - if resp != nil { - typedResp, ok := resp.(*DeleteAPIKeyResponse) - if !ok { - return nil, twirp.InternalError("failed type assertion resp.(*DeleteAPIKeyResponse) when calling interceptor") - } - return typedResp, err - } - return nil, err - } - } - return caller(ctx, in) -} - -func (c *aPIKeysServiceProtobufClient) callDeleteAPIKey(ctx context.Context, in *DeleteAPIKeyRequest) (*DeleteAPIKeyResponse, error) { - out := new(DeleteAPIKeyResponse) - ctx, err := doProtobufRequest(ctx, c.client, c.opts.Hooks, c.urls[3], in, out) - if err != nil { - twerr, ok := err.(twirp.Error) - if !ok { - twerr = twirp.InternalErrorWith(err) - } - callClientError(ctx, c.opts.Hooks, twerr) - return nil, err - } - - callClientResponseReceived(ctx, c.opts.Hooks) - - return out, nil -} - -// ========================== -// APIKeysService JSON Client -// ========================== - -type aPIKeysServiceJSONClient struct { - client HTTPClient - urls [4]string - interceptor twirp.Interceptor - opts twirp.ClientOptions -} - -// NewAPIKeysServiceJSONClient creates a JSON client that implements the APIKeysService interface. -// It communicates using JSON and can be configured with a custom HTTPClient. -func NewAPIKeysServiceJSONClient(baseURL string, client HTTPClient, opts ...twirp.ClientOption) APIKeysService { - if c, ok := client.(*http.Client); ok { - client = withoutRedirects(c) - } - - clientOpts := twirp.ClientOptions{} - for _, o := range opts { - o(&clientOpts) - } - - // Using ReadOpt allows backwards and forwards compatibility with new options in the future - literalURLs := false - _ = clientOpts.ReadOpt("literalURLs", &literalURLs) - var pathPrefix string - if ok := clientOpts.ReadOpt("pathPrefix", &pathPrefix); !ok { - pathPrefix = "/twirp" // default prefix - } - - // Build method URLs: <baseURL>[<prefix>]/<package>.<Service>/<Method> - serviceURL := sanitizeBaseURL(baseURL) - serviceURL += baseServicePath(pathPrefix, "apikeys", "APIKeysService") - urls := [4]string{ - serviceURL + "CreateAPIKey", - serviceURL + "ListAPIKeys", - serviceURL + "RevokeAPIKey", - serviceURL + "DeleteAPIKey", - } - - return &aPIKeysServiceJSONClient{ - client: client, - urls: urls, - interceptor: twirp.ChainInterceptors(clientOpts.Interceptors...), - opts: clientOpts, - } -} - -func (c *aPIKeysServiceJSONClient) CreateAPIKey(ctx context.Context, in *CreateAPIKeyRequest) (*CreateAPIKeyResponse, error) { - ctx = ctxsetters.WithPackageName(ctx, "apikeys") - ctx = ctxsetters.WithServiceName(ctx, "APIKeysService") - ctx = ctxsetters.WithMethodName(ctx, "CreateAPIKey") - caller := c.callCreateAPIKey - if c.interceptor != nil { - caller = func(ctx context.Context, req *CreateAPIKeyRequest) (*CreateAPIKeyResponse, error) { - resp, err := c.interceptor( - func(ctx context.Context, req interface{}) (interface{}, error) { - typedReq, ok := req.(*CreateAPIKeyRequest) - if !ok { - return nil, twirp.InternalError("failed type assertion req.(*CreateAPIKeyRequest) when calling interceptor") - } - return c.callCreateAPIKey(ctx, typedReq) - }, - )(ctx, req) - if resp != nil { - typedResp, ok := resp.(*CreateAPIKeyResponse) - if !ok { - return nil, twirp.InternalError("failed type assertion resp.(*CreateAPIKeyResponse) when calling interceptor") - } - return typedResp, err - } - return nil, err - } - } - return caller(ctx, in) -} - -func (c *aPIKeysServiceJSONClient) callCreateAPIKey(ctx context.Context, in *CreateAPIKeyRequest) (*CreateAPIKeyResponse, error) { - out := new(CreateAPIKeyResponse) - ctx, err := doJSONRequest(ctx, c.client, c.opts.Hooks, c.urls[0], in, out) - if err != nil { - twerr, ok := err.(twirp.Error) - if !ok { - twerr = twirp.InternalErrorWith(err) - } - callClientError(ctx, c.opts.Hooks, twerr) - return nil, err - } - - callClientResponseReceived(ctx, c.opts.Hooks) - - return out, nil -} - -func (c *aPIKeysServiceJSONClient) ListAPIKeys(ctx context.Context, in *ListAPIKeysRequest) (*ListAPIKeysResponse, error) { - ctx = ctxsetters.WithPackageName(ctx, "apikeys") - ctx = ctxsetters.WithServiceName(ctx, "APIKeysService") - ctx = ctxsetters.WithMethodName(ctx, "ListAPIKeys") - caller := c.callListAPIKeys - if c.interceptor != nil { - caller = func(ctx context.Context, req *ListAPIKeysRequest) (*ListAPIKeysResponse, error) { - resp, err := c.interceptor( - func(ctx context.Context, req interface{}) (interface{}, error) { - typedReq, ok := req.(*ListAPIKeysRequest) - if !ok { - return nil, twirp.InternalError("failed type assertion req.(*ListAPIKeysRequest) when calling interceptor") - } - return c.callListAPIKeys(ctx, typedReq) - }, - )(ctx, req) - if resp != nil { - typedResp, ok := resp.(*ListAPIKeysResponse) - if !ok { - return nil, twirp.InternalError("failed type assertion resp.(*ListAPIKeysResponse) when calling interceptor") - } - return typedResp, err - } - return nil, err - } - } - return caller(ctx, in) -} - -func (c *aPIKeysServiceJSONClient) callListAPIKeys(ctx context.Context, in *ListAPIKeysRequest) (*ListAPIKeysResponse, error) { - out := new(ListAPIKeysResponse) - ctx, err := doJSONRequest(ctx, c.client, c.opts.Hooks, c.urls[1], in, out) - if err != nil { - twerr, ok := err.(twirp.Error) - if !ok { - twerr = twirp.InternalErrorWith(err) - } - callClientError(ctx, c.opts.Hooks, twerr) - return nil, err - } - - callClientResponseReceived(ctx, c.opts.Hooks) - - return out, nil -} - -func (c *aPIKeysServiceJSONClient) RevokeAPIKey(ctx context.Context, in *RevokeAPIKeyRequest) (*RevokeAPIKeyResponse, error) { - ctx = ctxsetters.WithPackageName(ctx, "apikeys") - ctx = ctxsetters.WithServiceName(ctx, "APIKeysService") - ctx = ctxsetters.WithMethodName(ctx, "RevokeAPIKey") - caller := c.callRevokeAPIKey - if c.interceptor != nil { - caller = func(ctx context.Context, req *RevokeAPIKeyRequest) (*RevokeAPIKeyResponse, error) { - resp, err := c.interceptor( - func(ctx context.Context, req interface{}) (interface{}, error) { - typedReq, ok := req.(*RevokeAPIKeyRequest) - if !ok { - return nil, twirp.InternalError("failed type assertion req.(*RevokeAPIKeyRequest) when calling interceptor") - } - return c.callRevokeAPIKey(ctx, typedReq) - }, - )(ctx, req) - if resp != nil { - typedResp, ok := resp.(*RevokeAPIKeyResponse) - if !ok { - return nil, twirp.InternalError("failed type assertion resp.(*RevokeAPIKeyResponse) when calling interceptor") - } - return typedResp, err - } - return nil, err - } - } - return caller(ctx, in) -} - -func (c *aPIKeysServiceJSONClient) callRevokeAPIKey(ctx context.Context, in *RevokeAPIKeyRequest) (*RevokeAPIKeyResponse, error) { - out := new(RevokeAPIKeyResponse) - ctx, err := doJSONRequest(ctx, c.client, c.opts.Hooks, c.urls[2], in, out) - if err != nil { - twerr, ok := err.(twirp.Error) - if !ok { - twerr = twirp.InternalErrorWith(err) - } - callClientError(ctx, c.opts.Hooks, twerr) - return nil, err - } - - callClientResponseReceived(ctx, c.opts.Hooks) - - return out, nil -} - -func (c *aPIKeysServiceJSONClient) DeleteAPIKey(ctx context.Context, in *DeleteAPIKeyRequest) (*DeleteAPIKeyResponse, error) { - ctx = ctxsetters.WithPackageName(ctx, "apikeys") - ctx = ctxsetters.WithServiceName(ctx, "APIKeysService") - ctx = ctxsetters.WithMethodName(ctx, "DeleteAPIKey") - caller := c.callDeleteAPIKey - if c.interceptor != nil { - caller = func(ctx context.Context, req *DeleteAPIKeyRequest) (*DeleteAPIKeyResponse, error) { - resp, err := c.interceptor( - func(ctx context.Context, req interface{}) (interface{}, error) { - typedReq, ok := req.(*DeleteAPIKeyRequest) - if !ok { - return nil, twirp.InternalError("failed type assertion req.(*DeleteAPIKeyRequest) when calling interceptor") - } - return c.callDeleteAPIKey(ctx, typedReq) - }, - )(ctx, req) - if resp != nil { - typedResp, ok := resp.(*DeleteAPIKeyResponse) - if !ok { - return nil, twirp.InternalError("failed type assertion resp.(*DeleteAPIKeyResponse) when calling interceptor") - } - return typedResp, err - } - return nil, err - } - } - return caller(ctx, in) -} - -func (c *aPIKeysServiceJSONClient) callDeleteAPIKey(ctx context.Context, in *DeleteAPIKeyRequest) (*DeleteAPIKeyResponse, error) { - out := new(DeleteAPIKeyResponse) - ctx, err := doJSONRequest(ctx, c.client, c.opts.Hooks, c.urls[3], in, out) - if err != nil { - twerr, ok := err.(twirp.Error) - if !ok { - twerr = twirp.InternalErrorWith(err) - } - callClientError(ctx, c.opts.Hooks, twerr) - return nil, err - } - - callClientResponseReceived(ctx, c.opts.Hooks) - - return out, nil -} - -// ============================= -// APIKeysService Server Handler -// ============================= - -type aPIKeysServiceServer struct { - APIKeysService - interceptor twirp.Interceptor - hooks *twirp.ServerHooks - pathPrefix string // prefix for routing - jsonSkipDefaults bool // do not include unpopulated fields (default values) in the response - jsonCamelCase bool // JSON fields are serialized as lowerCamelCase rather than keeping the original proto names -} - -// NewAPIKeysServiceServer builds a TwirpServer that can be used as an http.Handler to handle -// HTTP requests that are routed to the right method in the provided svc implementation. -// The opts are twirp.ServerOption modifiers, for example twirp.WithServerHooks(hooks). -func NewAPIKeysServiceServer(svc APIKeysService, opts ...interface{}) TwirpServer { - serverOpts := newServerOpts(opts) - - // Using ReadOpt allows backwards and forwards compatibility with new options in the future - jsonSkipDefaults := false - _ = serverOpts.ReadOpt("jsonSkipDefaults", &jsonSkipDefaults) - jsonCamelCase := false - _ = serverOpts.ReadOpt("jsonCamelCase", &jsonCamelCase) - var pathPrefix string - if ok := serverOpts.ReadOpt("pathPrefix", &pathPrefix); !ok { - pathPrefix = "/twirp" // default prefix - } - - return &aPIKeysServiceServer{ - APIKeysService: svc, - hooks: serverOpts.Hooks, - interceptor: twirp.ChainInterceptors(serverOpts.Interceptors...), - pathPrefix: pathPrefix, - jsonSkipDefaults: jsonSkipDefaults, - jsonCamelCase: jsonCamelCase, - } -} - -// writeError writes an HTTP response with a valid Twirp error format, and triggers hooks. -// If err is not a twirp.Error, it will get wrapped with twirp.InternalErrorWith(err) -func (s *aPIKeysServiceServer) writeError(ctx context.Context, resp http.ResponseWriter, err error) { - writeError(ctx, resp, err, s.hooks) -} - -// handleRequestBodyError is used to handle error when the twirp server cannot read request -func (s *aPIKeysServiceServer) handleRequestBodyError(ctx context.Context, resp http.ResponseWriter, msg string, err error) { - if context.Canceled == ctx.Err() { - s.writeError(ctx, resp, twirp.NewError(twirp.Canceled, "failed to read request: context canceled")) - return - } - if context.DeadlineExceeded == ctx.Err() { - s.writeError(ctx, resp, twirp.NewError(twirp.DeadlineExceeded, "failed to read request: deadline exceeded")) - return - } - s.writeError(ctx, resp, twirp.WrapError(malformedRequestError(msg), err)) -} - -// APIKeysServicePathPrefix is a convenience constant that may identify URL paths. -// Should be used with caution, it only matches routes generated by Twirp Go clients, -// with the default "/twirp" prefix and default CamelCase service and method names. -// More info: https://twitchtv.github.io/twirp/docs/routing.html -const APIKeysServicePathPrefix = "/twirp/apikeys.APIKeysService/" - -func (s *aPIKeysServiceServer) ServeHTTP(resp http.ResponseWriter, req *http.Request) { - ctx := req.Context() - ctx = ctxsetters.WithPackageName(ctx, "apikeys") - ctx = ctxsetters.WithServiceName(ctx, "APIKeysService") - ctx = ctxsetters.WithResponseWriter(ctx, resp) - - var err error - ctx, err = callRequestReceived(ctx, s.hooks) - if err != nil { - s.writeError(ctx, resp, err) - return - } - - if req.Method != "POST" { - msg := fmt.Sprintf("unsupported method %q (only POST is allowed)", req.Method) - s.writeError(ctx, resp, badRouteError(msg, req.Method, req.URL.Path)) - return - } - - // Verify path format: [<prefix>]/<package>.<Service>/<Method> - prefix, pkgService, method := parseTwirpPath(req.URL.Path) - if pkgService != "apikeys.APIKeysService" { - msg := fmt.Sprintf("no handler for path %q", req.URL.Path) - s.writeError(ctx, resp, badRouteError(msg, req.Method, req.URL.Path)) - return - } - if prefix != s.pathPrefix { - msg := fmt.Sprintf("invalid path prefix %q, expected %q, on path %q", prefix, s.pathPrefix, req.URL.Path) - s.writeError(ctx, resp, badRouteError(msg, req.Method, req.URL.Path)) - return - } - - switch method { - case "CreateAPIKey": - s.serveCreateAPIKey(ctx, resp, req) - return - case "ListAPIKeys": - s.serveListAPIKeys(ctx, resp, req) - return - case "RevokeAPIKey": - s.serveRevokeAPIKey(ctx, resp, req) - return - case "DeleteAPIKey": - s.serveDeleteAPIKey(ctx, resp, req) - return - default: - msg := fmt.Sprintf("no handler for path %q", req.URL.Path) - s.writeError(ctx, resp, badRouteError(msg, req.Method, req.URL.Path)) - return - } -} - -func (s *aPIKeysServiceServer) serveCreateAPIKey(ctx context.Context, resp http.ResponseWriter, req *http.Request) { - header := req.Header.Get("Content-Type") - i := strings.Index(header, ";") - if i == -1 { - i = len(header) - } - switch strings.TrimSpace(strings.ToLower(header[:i])) { - case "application/json": - s.serveCreateAPIKeyJSON(ctx, resp, req) - case "application/protobuf": - s.serveCreateAPIKeyProtobuf(ctx, resp, req) - default: - msg := fmt.Sprintf("unexpected Content-Type: %q", req.Header.Get("Content-Type")) - twerr := badRouteError(msg, req.Method, req.URL.Path) - s.writeError(ctx, resp, twerr) - } -} - -func (s *aPIKeysServiceServer) serveCreateAPIKeyJSON(ctx context.Context, resp http.ResponseWriter, req *http.Request) { - var err error - ctx = ctxsetters.WithMethodName(ctx, "CreateAPIKey") - ctx, err = callRequestRouted(ctx, s.hooks) - if err != nil { - s.writeError(ctx, resp, err) - return - } - - d := json.NewDecoder(req.Body) - rawReqBody := json.RawMessage{} - if err := d.Decode(&rawReqBody); err != nil { - s.handleRequestBodyError(ctx, resp, "the json request could not be decoded", err) - return - } - reqContent := new(CreateAPIKeyRequest) - unmarshaler := protojson.UnmarshalOptions{DiscardUnknown: true} - if err = unmarshaler.Unmarshal(rawReqBody, reqContent); err != nil { - s.handleRequestBodyError(ctx, resp, "the json request could not be decoded", err) - return - } - - handler := s.APIKeysService.CreateAPIKey - if s.interceptor != nil { - handler = func(ctx context.Context, req *CreateAPIKeyRequest) (*CreateAPIKeyResponse, error) { - resp, err := s.interceptor( - func(ctx context.Context, req interface{}) (interface{}, error) { - typedReq, ok := req.(*CreateAPIKeyRequest) - if !ok { - return nil, twirp.InternalError("failed type assertion req.(*CreateAPIKeyRequest) when calling interceptor") - } - return s.APIKeysService.CreateAPIKey(ctx, typedReq) - }, - )(ctx, req) - if resp != nil { - typedResp, ok := resp.(*CreateAPIKeyResponse) - if !ok { - return nil, twirp.InternalError("failed type assertion resp.(*CreateAPIKeyResponse) when calling interceptor") - } - return typedResp, err - } - return nil, err - } - } - - // Call service method - var respContent *CreateAPIKeyResponse - func() { - defer ensurePanicResponses(ctx, resp, s.hooks) - respContent, err = handler(ctx, reqContent) - }() - - if err != nil { - s.writeError(ctx, resp, err) - return - } - if respContent == nil { - s.writeError(ctx, resp, twirp.InternalError("received a nil *CreateAPIKeyResponse and nil error while calling CreateAPIKey. nil responses are not supported")) - return - } - - ctx = callResponsePrepared(ctx, s.hooks) - - marshaler := &protojson.MarshalOptions{UseProtoNames: !s.jsonCamelCase, EmitUnpopulated: !s.jsonSkipDefaults} - respBytes, err := marshaler.Marshal(respContent) - if err != nil { - s.writeError(ctx, resp, wrapInternal(err, "failed to marshal json response")) - return - } - - ctx = ctxsetters.WithStatusCode(ctx, http.StatusOK) - resp.Header().Set("Content-Type", "application/json") - resp.Header().Set("Content-Length", strconv.Itoa(len(respBytes))) - resp.WriteHeader(http.StatusOK) - - if n, err := resp.Write(respBytes); err != nil { - msg := fmt.Sprintf("failed to write response, %d of %d bytes written: %s", n, len(respBytes), err.Error()) - twerr := twirp.NewError(twirp.Unknown, msg) - ctx = callError(ctx, s.hooks, twerr) - } - callResponseSent(ctx, s.hooks) -} - -func (s *aPIKeysServiceServer) serveCreateAPIKeyProtobuf(ctx context.Context, resp http.ResponseWriter, req *http.Request) { - var err error - ctx = ctxsetters.WithMethodName(ctx, "CreateAPIKey") - ctx, err = callRequestRouted(ctx, s.hooks) - if err != nil { - s.writeError(ctx, resp, err) - return - } - - buf, err := io.ReadAll(req.Body) - if err != nil { - s.handleRequestBodyError(ctx, resp, "failed to read request body", err) - return - } - reqContent := new(CreateAPIKeyRequest) - if err = proto.Unmarshal(buf, reqContent); err != nil { - s.writeError(ctx, resp, malformedRequestError("the protobuf request could not be decoded")) - return - } - - handler := s.APIKeysService.CreateAPIKey - if s.interceptor != nil { - handler = func(ctx context.Context, req *CreateAPIKeyRequest) (*CreateAPIKeyResponse, error) { - resp, err := s.interceptor( - func(ctx context.Context, req interface{}) (interface{}, error) { - typedReq, ok := req.(*CreateAPIKeyRequest) - if !ok { - return nil, twirp.InternalError("failed type assertion req.(*CreateAPIKeyRequest) when calling interceptor") - } - return s.APIKeysService.CreateAPIKey(ctx, typedReq) - }, - )(ctx, req) - if resp != nil { - typedResp, ok := resp.(*CreateAPIKeyResponse) - if !ok { - return nil, twirp.InternalError("failed type assertion resp.(*CreateAPIKeyResponse) when calling interceptor") - } - return typedResp, err - } - return nil, err - } - } - - // Call service method - var respContent *CreateAPIKeyResponse - func() { - defer ensurePanicResponses(ctx, resp, s.hooks) - respContent, err = handler(ctx, reqContent) - }() - - if err != nil { - s.writeError(ctx, resp, err) - return - } - if respContent == nil { - s.writeError(ctx, resp, twirp.InternalError("received a nil *CreateAPIKeyResponse and nil error while calling CreateAPIKey. nil responses are not supported")) - return - } - - ctx = callResponsePrepared(ctx, s.hooks) - - respBytes, err := proto.Marshal(respContent) - if err != nil { - s.writeError(ctx, resp, wrapInternal(err, "failed to marshal proto response")) - return - } - - ctx = ctxsetters.WithStatusCode(ctx, http.StatusOK) - resp.Header().Set("Content-Type", "application/protobuf") - resp.Header().Set("Content-Length", strconv.Itoa(len(respBytes))) - resp.WriteHeader(http.StatusOK) - if n, err := resp.Write(respBytes); err != nil { - msg := fmt.Sprintf("failed to write response, %d of %d bytes written: %s", n, len(respBytes), err.Error()) - twerr := twirp.NewError(twirp.Unknown, msg) - ctx = callError(ctx, s.hooks, twerr) - } - callResponseSent(ctx, s.hooks) -} - -func (s *aPIKeysServiceServer) serveListAPIKeys(ctx context.Context, resp http.ResponseWriter, req *http.Request) { - header := req.Header.Get("Content-Type") - i := strings.Index(header, ";") - if i == -1 { - i = len(header) - } - switch strings.TrimSpace(strings.ToLower(header[:i])) { - case "application/json": - s.serveListAPIKeysJSON(ctx, resp, req) - case "application/protobuf": - s.serveListAPIKeysProtobuf(ctx, resp, req) - default: - msg := fmt.Sprintf("unexpected Content-Type: %q", req.Header.Get("Content-Type")) - twerr := badRouteError(msg, req.Method, req.URL.Path) - s.writeError(ctx, resp, twerr) - } -} - -func (s *aPIKeysServiceServer) serveListAPIKeysJSON(ctx context.Context, resp http.ResponseWriter, req *http.Request) { - var err error - ctx = ctxsetters.WithMethodName(ctx, "ListAPIKeys") - ctx, err = callRequestRouted(ctx, s.hooks) - if err != nil { - s.writeError(ctx, resp, err) - return - } - - d := json.NewDecoder(req.Body) - rawReqBody := json.RawMessage{} - if err := d.Decode(&rawReqBody); err != nil { - s.handleRequestBodyError(ctx, resp, "the json request could not be decoded", err) - return - } - reqContent := new(ListAPIKeysRequest) - unmarshaler := protojson.UnmarshalOptions{DiscardUnknown: true} - if err = unmarshaler.Unmarshal(rawReqBody, reqContent); err != nil { - s.handleRequestBodyError(ctx, resp, "the json request could not be decoded", err) - return - } - - handler := s.APIKeysService.ListAPIKeys - if s.interceptor != nil { - handler = func(ctx context.Context, req *ListAPIKeysRequest) (*ListAPIKeysResponse, error) { - resp, err := s.interceptor( - func(ctx context.Context, req interface{}) (interface{}, error) { - typedReq, ok := req.(*ListAPIKeysRequest) - if !ok { - return nil, twirp.InternalError("failed type assertion req.(*ListAPIKeysRequest) when calling interceptor") - } - return s.APIKeysService.ListAPIKeys(ctx, typedReq) - }, - )(ctx, req) - if resp != nil { - typedResp, ok := resp.(*ListAPIKeysResponse) - if !ok { - return nil, twirp.InternalError("failed type assertion resp.(*ListAPIKeysResponse) when calling interceptor") - } - return typedResp, err - } - return nil, err - } - } - - // Call service method - var respContent *ListAPIKeysResponse - func() { - defer ensurePanicResponses(ctx, resp, s.hooks) - respContent, err = handler(ctx, reqContent) - }() - - if err != nil { - s.writeError(ctx, resp, err) - return - } - if respContent == nil { - s.writeError(ctx, resp, twirp.InternalError("received a nil *ListAPIKeysResponse and nil error while calling ListAPIKeys. nil responses are not supported")) - return - } - - ctx = callResponsePrepared(ctx, s.hooks) - - marshaler := &protojson.MarshalOptions{UseProtoNames: !s.jsonCamelCase, EmitUnpopulated: !s.jsonSkipDefaults} - respBytes, err := marshaler.Marshal(respContent) - if err != nil { - s.writeError(ctx, resp, wrapInternal(err, "failed to marshal json response")) - return - } - - ctx = ctxsetters.WithStatusCode(ctx, http.StatusOK) - resp.Header().Set("Content-Type", "application/json") - resp.Header().Set("Content-Length", strconv.Itoa(len(respBytes))) - resp.WriteHeader(http.StatusOK) - - if n, err := resp.Write(respBytes); err != nil { - msg := fmt.Sprintf("failed to write response, %d of %d bytes written: %s", n, len(respBytes), err.Error()) - twerr := twirp.NewError(twirp.Unknown, msg) - ctx = callError(ctx, s.hooks, twerr) - } - callResponseSent(ctx, s.hooks) -} - -func (s *aPIKeysServiceServer) serveListAPIKeysProtobuf(ctx context.Context, resp http.ResponseWriter, req *http.Request) { - var err error - ctx = ctxsetters.WithMethodName(ctx, "ListAPIKeys") - ctx, err = callRequestRouted(ctx, s.hooks) - if err != nil { - s.writeError(ctx, resp, err) - return - } - - buf, err := io.ReadAll(req.Body) - if err != nil { - s.handleRequestBodyError(ctx, resp, "failed to read request body", err) - return - } - reqContent := new(ListAPIKeysRequest) - if err = proto.Unmarshal(buf, reqContent); err != nil { - s.writeError(ctx, resp, malformedRequestError("the protobuf request could not be decoded")) - return - } - - handler := s.APIKeysService.ListAPIKeys - if s.interceptor != nil { - handler = func(ctx context.Context, req *ListAPIKeysRequest) (*ListAPIKeysResponse, error) { - resp, err := s.interceptor( - func(ctx context.Context, req interface{}) (interface{}, error) { - typedReq, ok := req.(*ListAPIKeysRequest) - if !ok { - return nil, twirp.InternalError("failed type assertion req.(*ListAPIKeysRequest) when calling interceptor") - } - return s.APIKeysService.ListAPIKeys(ctx, typedReq) - }, - )(ctx, req) - if resp != nil { - typedResp, ok := resp.(*ListAPIKeysResponse) - if !ok { - return nil, twirp.InternalError("failed type assertion resp.(*ListAPIKeysResponse) when calling interceptor") - } - return typedResp, err - } - return nil, err - } - } - - // Call service method - var respContent *ListAPIKeysResponse - func() { - defer ensurePanicResponses(ctx, resp, s.hooks) - respContent, err = handler(ctx, reqContent) - }() - - if err != nil { - s.writeError(ctx, resp, err) - return - } - if respContent == nil { - s.writeError(ctx, resp, twirp.InternalError("received a nil *ListAPIKeysResponse and nil error while calling ListAPIKeys. nil responses are not supported")) - return - } - - ctx = callResponsePrepared(ctx, s.hooks) - - respBytes, err := proto.Marshal(respContent) - if err != nil { - s.writeError(ctx, resp, wrapInternal(err, "failed to marshal proto response")) - return - } - - ctx = ctxsetters.WithStatusCode(ctx, http.StatusOK) - resp.Header().Set("Content-Type", "application/protobuf") - resp.Header().Set("Content-Length", strconv.Itoa(len(respBytes))) - resp.WriteHeader(http.StatusOK) - if n, err := resp.Write(respBytes); err != nil { - msg := fmt.Sprintf("failed to write response, %d of %d bytes written: %s", n, len(respBytes), err.Error()) - twerr := twirp.NewError(twirp.Unknown, msg) - ctx = callError(ctx, s.hooks, twerr) - } - callResponseSent(ctx, s.hooks) -} - -func (s *aPIKeysServiceServer) serveRevokeAPIKey(ctx context.Context, resp http.ResponseWriter, req *http.Request) { - header := req.Header.Get("Content-Type") - i := strings.Index(header, ";") - if i == -1 { - i = len(header) - } - switch strings.TrimSpace(strings.ToLower(header[:i])) { - case "application/json": - s.serveRevokeAPIKeyJSON(ctx, resp, req) - case "application/protobuf": - s.serveRevokeAPIKeyProtobuf(ctx, resp, req) - default: - msg := fmt.Sprintf("unexpected Content-Type: %q", req.Header.Get("Content-Type")) - twerr := badRouteError(msg, req.Method, req.URL.Path) - s.writeError(ctx, resp, twerr) - } -} - -func (s *aPIKeysServiceServer) serveRevokeAPIKeyJSON(ctx context.Context, resp http.ResponseWriter, req *http.Request) { - var err error - ctx = ctxsetters.WithMethodName(ctx, "RevokeAPIKey") - ctx, err = callRequestRouted(ctx, s.hooks) - if err != nil { - s.writeError(ctx, resp, err) - return - } - - d := json.NewDecoder(req.Body) - rawReqBody := json.RawMessage{} - if err := d.Decode(&rawReqBody); err != nil { - s.handleRequestBodyError(ctx, resp, "the json request could not be decoded", err) - return - } - reqContent := new(RevokeAPIKeyRequest) - unmarshaler := protojson.UnmarshalOptions{DiscardUnknown: true} - if err = unmarshaler.Unmarshal(rawReqBody, reqContent); err != nil { - s.handleRequestBodyError(ctx, resp, "the json request could not be decoded", err) - return - } - - handler := s.APIKeysService.RevokeAPIKey - if s.interceptor != nil { - handler = func(ctx context.Context, req *RevokeAPIKeyRequest) (*RevokeAPIKeyResponse, error) { - resp, err := s.interceptor( - func(ctx context.Context, req interface{}) (interface{}, error) { - typedReq, ok := req.(*RevokeAPIKeyRequest) - if !ok { - return nil, twirp.InternalError("failed type assertion req.(*RevokeAPIKeyRequest) when calling interceptor") - } - return s.APIKeysService.RevokeAPIKey(ctx, typedReq) - }, - )(ctx, req) - if resp != nil { - typedResp, ok := resp.(*RevokeAPIKeyResponse) - if !ok { - return nil, twirp.InternalError("failed type assertion resp.(*RevokeAPIKeyResponse) when calling interceptor") - } - return typedResp, err - } - return nil, err - } - } - - // Call service method - var respContent *RevokeAPIKeyResponse - func() { - defer ensurePanicResponses(ctx, resp, s.hooks) - respContent, err = handler(ctx, reqContent) - }() - - if err != nil { - s.writeError(ctx, resp, err) - return - } - if respContent == nil { - s.writeError(ctx, resp, twirp.InternalError("received a nil *RevokeAPIKeyResponse and nil error while calling RevokeAPIKey. nil responses are not supported")) - return - } - - ctx = callResponsePrepared(ctx, s.hooks) - - marshaler := &protojson.MarshalOptions{UseProtoNames: !s.jsonCamelCase, EmitUnpopulated: !s.jsonSkipDefaults} - respBytes, err := marshaler.Marshal(respContent) - if err != nil { - s.writeError(ctx, resp, wrapInternal(err, "failed to marshal json response")) - return - } - - ctx = ctxsetters.WithStatusCode(ctx, http.StatusOK) - resp.Header().Set("Content-Type", "application/json") - resp.Header().Set("Content-Length", strconv.Itoa(len(respBytes))) - resp.WriteHeader(http.StatusOK) - - if n, err := resp.Write(respBytes); err != nil { - msg := fmt.Sprintf("failed to write response, %d of %d bytes written: %s", n, len(respBytes), err.Error()) - twerr := twirp.NewError(twirp.Unknown, msg) - ctx = callError(ctx, s.hooks, twerr) - } - callResponseSent(ctx, s.hooks) -} - -func (s *aPIKeysServiceServer) serveRevokeAPIKeyProtobuf(ctx context.Context, resp http.ResponseWriter, req *http.Request) { - var err error - ctx = ctxsetters.WithMethodName(ctx, "RevokeAPIKey") - ctx, err = callRequestRouted(ctx, s.hooks) - if err != nil { - s.writeError(ctx, resp, err) - return - } - - buf, err := io.ReadAll(req.Body) - if err != nil { - s.handleRequestBodyError(ctx, resp, "failed to read request body", err) - return - } - reqContent := new(RevokeAPIKeyRequest) - if err = proto.Unmarshal(buf, reqContent); err != nil { - s.writeError(ctx, resp, malformedRequestError("the protobuf request could not be decoded")) - return - } - - handler := s.APIKeysService.RevokeAPIKey - if s.interceptor != nil { - handler = func(ctx context.Context, req *RevokeAPIKeyRequest) (*RevokeAPIKeyResponse, error) { - resp, err := s.interceptor( - func(ctx context.Context, req interface{}) (interface{}, error) { - typedReq, ok := req.(*RevokeAPIKeyRequest) - if !ok { - return nil, twirp.InternalError("failed type assertion req.(*RevokeAPIKeyRequest) when calling interceptor") - } - return s.APIKeysService.RevokeAPIKey(ctx, typedReq) - }, - )(ctx, req) - if resp != nil { - typedResp, ok := resp.(*RevokeAPIKeyResponse) - if !ok { - return nil, twirp.InternalError("failed type assertion resp.(*RevokeAPIKeyResponse) when calling interceptor") - } - return typedResp, err - } - return nil, err - } - } - - // Call service method - var respContent *RevokeAPIKeyResponse - func() { - defer ensurePanicResponses(ctx, resp, s.hooks) - respContent, err = handler(ctx, reqContent) - }() - - if err != nil { - s.writeError(ctx, resp, err) - return - } - if respContent == nil { - s.writeError(ctx, resp, twirp.InternalError("received a nil *RevokeAPIKeyResponse and nil error while calling RevokeAPIKey. nil responses are not supported")) - return - } - - ctx = callResponsePrepared(ctx, s.hooks) - - respBytes, err := proto.Marshal(respContent) - if err != nil { - s.writeError(ctx, resp, wrapInternal(err, "failed to marshal proto response")) - return - } - - ctx = ctxsetters.WithStatusCode(ctx, http.StatusOK) - resp.Header().Set("Content-Type", "application/protobuf") - resp.Header().Set("Content-Length", strconv.Itoa(len(respBytes))) - resp.WriteHeader(http.StatusOK) - if n, err := resp.Write(respBytes); err != nil { - msg := fmt.Sprintf("failed to write response, %d of %d bytes written: %s", n, len(respBytes), err.Error()) - twerr := twirp.NewError(twirp.Unknown, msg) - ctx = callError(ctx, s.hooks, twerr) - } - callResponseSent(ctx, s.hooks) -} - -func (s *aPIKeysServiceServer) serveDeleteAPIKey(ctx context.Context, resp http.ResponseWriter, req *http.Request) { - header := req.Header.Get("Content-Type") - i := strings.Index(header, ";") - if i == -1 { - i = len(header) - } - switch strings.TrimSpace(strings.ToLower(header[:i])) { - case "application/json": - s.serveDeleteAPIKeyJSON(ctx, resp, req) - case "application/protobuf": - s.serveDeleteAPIKeyProtobuf(ctx, resp, req) - default: - msg := fmt.Sprintf("unexpected Content-Type: %q", req.Header.Get("Content-Type")) - twerr := badRouteError(msg, req.Method, req.URL.Path) - s.writeError(ctx, resp, twerr) - } -} - -func (s *aPIKeysServiceServer) serveDeleteAPIKeyJSON(ctx context.Context, resp http.ResponseWriter, req *http.Request) { - var err error - ctx = ctxsetters.WithMethodName(ctx, "DeleteAPIKey") - ctx, err = callRequestRouted(ctx, s.hooks) - if err != nil { - s.writeError(ctx, resp, err) - return - } - - d := json.NewDecoder(req.Body) - rawReqBody := json.RawMessage{} - if err := d.Decode(&rawReqBody); err != nil { - s.handleRequestBodyError(ctx, resp, "the json request could not be decoded", err) - return - } - reqContent := new(DeleteAPIKeyRequest) - unmarshaler := protojson.UnmarshalOptions{DiscardUnknown: true} - if err = unmarshaler.Unmarshal(rawReqBody, reqContent); err != nil { - s.handleRequestBodyError(ctx, resp, "the json request could not be decoded", err) - return - } - - handler := s.APIKeysService.DeleteAPIKey - if s.interceptor != nil { - handler = func(ctx context.Context, req *DeleteAPIKeyRequest) (*DeleteAPIKeyResponse, error) { - resp, err := s.interceptor( - func(ctx context.Context, req interface{}) (interface{}, error) { - typedReq, ok := req.(*DeleteAPIKeyRequest) - if !ok { - return nil, twirp.InternalError("failed type assertion req.(*DeleteAPIKeyRequest) when calling interceptor") - } - return s.APIKeysService.DeleteAPIKey(ctx, typedReq) - }, - )(ctx, req) - if resp != nil { - typedResp, ok := resp.(*DeleteAPIKeyResponse) - if !ok { - return nil, twirp.InternalError("failed type assertion resp.(*DeleteAPIKeyResponse) when calling interceptor") - } - return typedResp, err - } - return nil, err - } - } - - // Call service method - var respContent *DeleteAPIKeyResponse - func() { - defer ensurePanicResponses(ctx, resp, s.hooks) - respContent, err = handler(ctx, reqContent) - }() - - if err != nil { - s.writeError(ctx, resp, err) - return - } - if respContent == nil { - s.writeError(ctx, resp, twirp.InternalError("received a nil *DeleteAPIKeyResponse and nil error while calling DeleteAPIKey. nil responses are not supported")) - return - } - - ctx = callResponsePrepared(ctx, s.hooks) - - marshaler := &protojson.MarshalOptions{UseProtoNames: !s.jsonCamelCase, EmitUnpopulated: !s.jsonSkipDefaults} - respBytes, err := marshaler.Marshal(respContent) - if err != nil { - s.writeError(ctx, resp, wrapInternal(err, "failed to marshal json response")) - return - } - - ctx = ctxsetters.WithStatusCode(ctx, http.StatusOK) - resp.Header().Set("Content-Type", "application/json") - resp.Header().Set("Content-Length", strconv.Itoa(len(respBytes))) - resp.WriteHeader(http.StatusOK) - - if n, err := resp.Write(respBytes); err != nil { - msg := fmt.Sprintf("failed to write response, %d of %d bytes written: %s", n, len(respBytes), err.Error()) - twerr := twirp.NewError(twirp.Unknown, msg) - ctx = callError(ctx, s.hooks, twerr) - } - callResponseSent(ctx, s.hooks) -} - -func (s *aPIKeysServiceServer) serveDeleteAPIKeyProtobuf(ctx context.Context, resp http.ResponseWriter, req *http.Request) { - var err error - ctx = ctxsetters.WithMethodName(ctx, "DeleteAPIKey") - ctx, err = callRequestRouted(ctx, s.hooks) - if err != nil { - s.writeError(ctx, resp, err) - return - } - - buf, err := io.ReadAll(req.Body) - if err != nil { - s.handleRequestBodyError(ctx, resp, "failed to read request body", err) - return - } - reqContent := new(DeleteAPIKeyRequest) - if err = proto.Unmarshal(buf, reqContent); err != nil { - s.writeError(ctx, resp, malformedRequestError("the protobuf request could not be decoded")) - return - } - - handler := s.APIKeysService.DeleteAPIKey - if s.interceptor != nil { - handler = func(ctx context.Context, req *DeleteAPIKeyRequest) (*DeleteAPIKeyResponse, error) { - resp, err := s.interceptor( - func(ctx context.Context, req interface{}) (interface{}, error) { - typedReq, ok := req.(*DeleteAPIKeyRequest) - if !ok { - return nil, twirp.InternalError("failed type assertion req.(*DeleteAPIKeyRequest) when calling interceptor") - } - return s.APIKeysService.DeleteAPIKey(ctx, typedReq) - }, - )(ctx, req) - if resp != nil { - typedResp, ok := resp.(*DeleteAPIKeyResponse) - if !ok { - return nil, twirp.InternalError("failed type assertion resp.(*DeleteAPIKeyResponse) when calling interceptor") - } - return typedResp, err - } - return nil, err - } - } - - // Call service method - var respContent *DeleteAPIKeyResponse - func() { - defer ensurePanicResponses(ctx, resp, s.hooks) - respContent, err = handler(ctx, reqContent) - }() - - if err != nil { - s.writeError(ctx, resp, err) - return - } - if respContent == nil { - s.writeError(ctx, resp, twirp.InternalError("received a nil *DeleteAPIKeyResponse and nil error while calling DeleteAPIKey. nil responses are not supported")) - return - } - - ctx = callResponsePrepared(ctx, s.hooks) - - respBytes, err := proto.Marshal(respContent) - if err != nil { - s.writeError(ctx, resp, wrapInternal(err, "failed to marshal proto response")) - return - } - - ctx = ctxsetters.WithStatusCode(ctx, http.StatusOK) - resp.Header().Set("Content-Type", "application/protobuf") - resp.Header().Set("Content-Length", strconv.Itoa(len(respBytes))) - resp.WriteHeader(http.StatusOK) - if n, err := resp.Write(respBytes); err != nil { - msg := fmt.Sprintf("failed to write response, %d of %d bytes written: %s", n, len(respBytes), err.Error()) - twerr := twirp.NewError(twirp.Unknown, msg) - ctx = callError(ctx, s.hooks, twerr) - } - callResponseSent(ctx, s.hooks) -} - -func (s *aPIKeysServiceServer) ServiceDescriptor() ([]byte, int) { - return twirpFileDescriptor0, 0 -} - -func (s *aPIKeysServiceServer) ProtocGenTwirpVersion() string { - return "v8.1.3" -} - -// PathPrefix returns the base service path, in the form: "/<prefix>/<package>.<Service>/" -// that is everything in a Twirp route except for the <Method>. This can be used for routing, -// for example to identify the requests that are targeted to this service in a mux. -func (s *aPIKeysServiceServer) PathPrefix() string { - return baseServicePath(s.pathPrefix, "apikeys", "APIKeysService") -} - -// ===== -// Utils -// ===== - -// HTTPClient is the interface used by generated clients to send HTTP requests. -// It is fulfilled by *(net/http).Client, which is sufficient for most users. -// Users can provide their own implementation for special retry policies. -// -// HTTPClient implementations should not follow redirects. Redirects are -// automatically disabled if *(net/http).Client is passed to client -// constructors. See the withoutRedirects function in this file for more -// details. -type HTTPClient interface { - Do(req *http.Request) (*http.Response, error) -} - -// TwirpServer is the interface generated server structs will support: they're -// HTTP handlers with additional methods for accessing metadata about the -// service. Those accessors are a low-level API for building reflection tools. -// Most people can think of TwirpServers as just http.Handlers. -type TwirpServer interface { - http.Handler - - // ServiceDescriptor returns gzipped bytes describing the .proto file that - // this service was generated from. Once unzipped, the bytes can be - // unmarshalled as a - // google.golang.org/protobuf/types/descriptorpb.FileDescriptorProto. - // - // The returned integer is the index of this particular service within that - // FileDescriptorProto's 'Service' slice of ServiceDescriptorProtos. This is a - // low-level field, expected to be used for reflection. - ServiceDescriptor() ([]byte, int) - - // ProtocGenTwirpVersion is the semantic version string of the version of - // twirp used to generate this file. - ProtocGenTwirpVersion() string - - // PathPrefix returns the HTTP URL path prefix for all methods handled by this - // service. This can be used with an HTTP mux to route Twirp requests. - // The path prefix is in the form: "/<prefix>/<package>.<Service>/" - // that is, everything in a Twirp route except for the <Method> at the end. - PathPrefix() string -} - -func newServerOpts(opts []interface{}) *twirp.ServerOptions { - serverOpts := &twirp.ServerOptions{} - for _, opt := range opts { - switch o := opt.(type) { - case twirp.ServerOption: - o(serverOpts) - case *twirp.ServerHooks: // backwards compatibility, allow to specify hooks as an argument - twirp.WithServerHooks(o)(serverOpts) - case nil: // backwards compatibility, allow nil value for the argument - continue - default: - panic(fmt.Sprintf("Invalid option type %T, please use a twirp.ServerOption", o)) - } - } - return serverOpts -} - -// WriteError writes an HTTP response with a valid Twirp error format (code, msg, meta). -// Useful outside of the Twirp server (e.g. http middleware), but does not trigger hooks. -// If err is not a twirp.Error, it will get wrapped with twirp.InternalErrorWith(err) -func WriteError(resp http.ResponseWriter, err error) { - writeError(context.Background(), resp, err, nil) -} - -// writeError writes Twirp errors in the response and triggers hooks. -func writeError(ctx context.Context, resp http.ResponseWriter, err error, hooks *twirp.ServerHooks) { - // Convert to a twirp.Error. Non-twirp errors are converted to internal errors. - var twerr twirp.Error - if !errors.As(err, &twerr) { - twerr = twirp.InternalErrorWith(err) - } - - statusCode := twirp.ServerHTTPStatusFromErrorCode(twerr.Code()) - ctx = ctxsetters.WithStatusCode(ctx, statusCode) - ctx = callError(ctx, hooks, twerr) - - respBody := marshalErrorToJSON(twerr) - - resp.Header().Set("Content-Type", "application/json") // Error responses are always JSON - resp.Header().Set("Content-Length", strconv.Itoa(len(respBody))) - resp.WriteHeader(statusCode) // set HTTP status code and send response - - _, writeErr := resp.Write(respBody) - if writeErr != nil { - // We have three options here. We could log the error, call the Error - // hook, or just silently ignore the error. - // - // Logging is unacceptable because we don't have a user-controlled - // logger; writing out to stderr without permission is too rude. - // - // Calling the Error hook would confuse users: it would mean the Error - // hook got called twice for one request, which is likely to lead to - // duplicated log messages and metrics, no matter how well we document - // the behavior. - // - // Silently ignoring the error is our least-bad option. It's highly - // likely that the connection is broken and the original 'err' says - // so anyway. - _ = writeErr - } - - callResponseSent(ctx, hooks) -} - -// sanitizeBaseURL parses the the baseURL, and adds the "http" scheme if needed. -// If the URL is unparsable, the baseURL is returned unchanged. -func sanitizeBaseURL(baseURL string) string { - u, err := url.Parse(baseURL) - if err != nil { - return baseURL // invalid URL will fail later when making requests - } - if u.Scheme == "" { - u.Scheme = "http" - } - return u.String() -} - -// baseServicePath composes the path prefix for the service (without <Method>). -// e.g.: baseServicePath("/twirp", "my.pkg", "MyService") -// -// returns => "/twirp/my.pkg.MyService/" -// -// e.g.: baseServicePath("", "", "MyService") -// -// returns => "/MyService/" -func baseServicePath(prefix, pkg, service string) string { - fullServiceName := service - if pkg != "" { - fullServiceName = pkg + "." + service - } - return path.Join("/", prefix, fullServiceName) + "/" -} - -// parseTwirpPath extracts path components form a valid Twirp route. -// Expected format: "[<prefix>]/<package>.<Service>/<Method>" -// e.g.: prefix, pkgService, method := parseTwirpPath("/twirp/pkg.Svc/MakeHat") -func parseTwirpPath(path string) (string, string, string) { - parts := strings.Split(path, "/") - if len(parts) < 2 { - return "", "", "" - } - method := parts[len(parts)-1] - pkgService := parts[len(parts)-2] - prefix := strings.Join(parts[0:len(parts)-2], "/") - return prefix, pkgService, method -} - -// getCustomHTTPReqHeaders retrieves a copy of any headers that are set in -// a context through the twirp.WithHTTPRequestHeaders function. -// If there are no headers set, or if they have the wrong type, nil is returned. -func getCustomHTTPReqHeaders(ctx context.Context) http.Header { - header, ok := twirp.HTTPRequestHeaders(ctx) - if !ok || header == nil { - return nil - } - copied := make(http.Header) - for k, vv := range header { - if vv == nil { - copied[k] = nil - continue - } - copied[k] = make([]string, len(vv)) - copy(copied[k], vv) - } - return copied -} - -// newRequest makes an http.Request from a client, adding common headers. -func newRequest(ctx context.Context, url string, reqBody io.Reader, contentType string) (*http.Request, error) { - req, err := http.NewRequest("POST", url, reqBody) - if err != nil { - return nil, err - } - req = req.WithContext(ctx) - if customHeader := getCustomHTTPReqHeaders(ctx); customHeader != nil { - req.Header = customHeader - } - req.Header.Set("Accept", contentType) - req.Header.Set("Content-Type", contentType) - req.Header.Set("Twirp-Version", "v8.1.3") - return req, nil -} - -// JSON serialization for errors -type twerrJSON struct { - Code string `json:"code"` - Msg string `json:"msg"` - Meta map[string]string `json:"meta,omitempty"` -} - -// marshalErrorToJSON returns JSON from a twirp.Error, that can be used as HTTP error response body. -// If serialization fails, it will use a descriptive Internal error instead. -func marshalErrorToJSON(twerr twirp.Error) []byte { - // make sure that msg is not too large - msg := twerr.Msg() - if len(msg) > 1e6 { - msg = msg[:1e6] - } - - tj := twerrJSON{ - Code: string(twerr.Code()), - Msg: msg, - Meta: twerr.MetaMap(), - } - - buf, err := json.Marshal(&tj) - if err != nil { - buf = []byte("{\"type\": \"" + twirp.Internal + "\", \"msg\": \"There was an error but it could not be serialized into JSON\"}") // fallback - } - - return buf -} - -// errorFromResponse builds a twirp.Error from a non-200 HTTP response. -// If the response has a valid serialized Twirp error, then it's returned. -// If not, the response status code is used to generate a similar twirp -// error. See twirpErrorFromIntermediary for more info on intermediary errors. -func errorFromResponse(resp *http.Response) twirp.Error { - statusCode := resp.StatusCode - statusText := http.StatusText(statusCode) - - if isHTTPRedirect(statusCode) { - // Unexpected redirect: it must be an error from an intermediary. - // Twirp clients don't follow redirects automatically, Twirp only handles - // POST requests, redirects should only happen on GET and HEAD requests. - location := resp.Header.Get("Location") - msg := fmt.Sprintf("unexpected HTTP status code %d %q received, Location=%q", statusCode, statusText, location) - return twirpErrorFromIntermediary(statusCode, msg, location) - } - - respBodyBytes, err := io.ReadAll(resp.Body) - if err != nil { - return wrapInternal(err, "failed to read server error response body") - } - - var tj twerrJSON - dec := json.NewDecoder(bytes.NewReader(respBodyBytes)) - dec.DisallowUnknownFields() - if err := dec.Decode(&tj); err != nil || tj.Code == "" { - // Invalid JSON response; it must be an error from an intermediary. - msg := fmt.Sprintf("Error from intermediary with HTTP status code %d %q", statusCode, statusText) - return twirpErrorFromIntermediary(statusCode, msg, string(respBodyBytes)) - } - - errorCode := twirp.ErrorCode(tj.Code) - if !twirp.IsValidErrorCode(errorCode) { - msg := "invalid type returned from server error response: " + tj.Code - return twirp.InternalError(msg).WithMeta("body", string(respBodyBytes)) - } - - twerr := twirp.NewError(errorCode, tj.Msg) - for k, v := range tj.Meta { - twerr = twerr.WithMeta(k, v) - } - return twerr -} - -// twirpErrorFromIntermediary maps HTTP errors from non-twirp sources to twirp errors. -// The mapping is similar to gRPC: https://github.com/grpc/grpc/blob/master/doc/http-grpc-status-mapping.md. -// Returned twirp Errors have some additional metadata for inspection. -func twirpErrorFromIntermediary(status int, msg string, bodyOrLocation string) twirp.Error { - var code twirp.ErrorCode - if isHTTPRedirect(status) { // 3xx - code = twirp.Internal - } else { - switch status { - case 400: // Bad Request - code = twirp.Internal - case 401: // Unauthorized - code = twirp.Unauthenticated - case 403: // Forbidden - code = twirp.PermissionDenied - case 404: // Not Found - code = twirp.BadRoute - case 429: // Too Many Requests - code = twirp.ResourceExhausted - case 502, 503, 504: // Bad Gateway, Service Unavailable, Gateway Timeout - code = twirp.Unavailable - default: // All other codes - code = twirp.Unknown - } - } - - twerr := twirp.NewError(code, msg) - twerr = twerr.WithMeta("http_error_from_intermediary", "true") // to easily know if this error was from intermediary - twerr = twerr.WithMeta("status_code", strconv.Itoa(status)) - if isHTTPRedirect(status) { - twerr = twerr.WithMeta("location", bodyOrLocation) - } else { - twerr = twerr.WithMeta("body", bodyOrLocation) - } - return twerr -} - -func isHTTPRedirect(status int) bool { - return status >= 300 && status <= 399 -} - -// wrapInternal wraps an error with a prefix as an Internal error. -// The original error cause is accessible by github.com/pkg/errors.Cause. -func wrapInternal(err error, prefix string) twirp.Error { - return twirp.InternalErrorWith(&wrappedError{prefix: prefix, cause: err}) -} - -type wrappedError struct { - prefix string - cause error -} - -func (e *wrappedError) Error() string { return e.prefix + ": " + e.cause.Error() } -func (e *wrappedError) Unwrap() error { return e.cause } // for go1.13 + errors.Is/As -func (e *wrappedError) Cause() error { return e.cause } // for github.com/pkg/errors - -// ensurePanicResponses makes sure that rpc methods causing a panic still result in a Twirp Internal -// error response (status 500), and error hooks are properly called with the panic wrapped as an error. -// The panic is re-raised so it can be handled normally with middleware. -func ensurePanicResponses(ctx context.Context, resp http.ResponseWriter, hooks *twirp.ServerHooks) { - if r := recover(); r != nil { - // Wrap the panic as an error so it can be passed to error hooks. - // The original error is accessible from error hooks, but not visible in the response. - err := errFromPanic(r) - twerr := &internalWithCause{msg: "Internal service panic", cause: err} - // Actually write the error - writeError(ctx, resp, twerr, hooks) - // If possible, flush the error to the wire. - f, ok := resp.(http.Flusher) - if ok { - f.Flush() - } - - panic(r) - } -} - -// errFromPanic returns the typed error if the recovered panic is an error, otherwise formats as error. -func errFromPanic(p interface{}) error { - if err, ok := p.(error); ok { - return err - } - return fmt.Errorf("panic: %v", p) -} - -// internalWithCause is a Twirp Internal error wrapping an original error cause, -// but the original error message is not exposed on Msg(). The original error -// can be checked with go1.13+ errors.Is/As, and also by (github.com/pkg/errors).Unwrap -type internalWithCause struct { - msg string - cause error -} - -func (e *internalWithCause) Unwrap() error { return e.cause } // for go1.13 + errors.Is/As -func (e *internalWithCause) Cause() error { return e.cause } // for github.com/pkg/errors -func (e *internalWithCause) Error() string { return e.msg + ": " + e.cause.Error() } -func (e *internalWithCause) Code() twirp.ErrorCode { return twirp.Internal } -func (e *internalWithCause) Msg() string { return e.msg } -func (e *internalWithCause) Meta(key string) string { return "" } -func (e *internalWithCause) MetaMap() map[string]string { return nil } -func (e *internalWithCause) WithMeta(key string, val string) twirp.Error { return e } - -// malformedRequestError is used when the twirp server cannot unmarshal a request -func malformedRequestError(msg string) twirp.Error { - return twirp.NewError(twirp.Malformed, msg) -} - -// badRouteError is used when the twirp server cannot route a request -func badRouteError(msg string, method, url string) twirp.Error { - err := twirp.NewError(twirp.BadRoute, msg) - err = err.WithMeta("twirp_invalid_route", method+" "+url) - return err -} - -// withoutRedirects makes sure that the POST request can not be redirected. -// The standard library will, by default, redirect requests (including POSTs) if it gets a 302 or -// 303 response, and also 301s in go1.8. It redirects by making a second request, changing the -// method to GET and removing the body. This produces very confusing error messages, so instead we -// set a redirect policy that always errors. This stops Go from executing the redirect. -// -// We have to be a little careful in case the user-provided http.Client has its own CheckRedirect -// policy - if so, we'll run through that policy first. -// -// Because this requires modifying the http.Client, we make a new copy of the client and return it. -func withoutRedirects(in *http.Client) *http.Client { - copy := *in - copy.CheckRedirect = func(req *http.Request, via []*http.Request) error { - if in.CheckRedirect != nil { - // Run the input's redirect if it exists, in case it has side effects, but ignore any error it - // returns, since we want to use ErrUseLastResponse. - err := in.CheckRedirect(req, via) - _ = err // Silly, but this makes sure generated code passes errcheck -blank, which some people use. - } - return http.ErrUseLastResponse - } - return © -} - -// doProtobufRequest makes a Protobuf request to the remote Twirp service. -func doProtobufRequest(ctx context.Context, client HTTPClient, hooks *twirp.ClientHooks, url string, in, out proto.Message) (_ context.Context, err error) { - reqBodyBytes, err := proto.Marshal(in) - if err != nil { - return ctx, wrapInternal(err, "failed to marshal proto request") - } - reqBody := bytes.NewBuffer(reqBodyBytes) - if err = ctx.Err(); err != nil { - return ctx, wrapInternal(err, "aborted because context was done") - } - - req, err := newRequest(ctx, url, reqBody, "application/protobuf") - if err != nil { - return ctx, wrapInternal(err, "could not build request") - } - ctx, err = callClientRequestPrepared(ctx, hooks, req) - if err != nil { - return ctx, err - } - - req = req.WithContext(ctx) - resp, err := client.Do(req) - if err != nil { - return ctx, wrapInternal(err, "failed to do request") - } - defer func() { _ = resp.Body.Close() }() - - if err = ctx.Err(); err != nil { - return ctx, wrapInternal(err, "aborted because context was done") - } - - if resp.StatusCode != 200 { - return ctx, errorFromResponse(resp) - } - - respBodyBytes, err := io.ReadAll(resp.Body) - if err != nil { - return ctx, wrapInternal(err, "failed to read response body") - } - if err = ctx.Err(); err != nil { - return ctx, wrapInternal(err, "aborted because context was done") - } - - if err = proto.Unmarshal(respBodyBytes, out); err != nil { - return ctx, wrapInternal(err, "failed to unmarshal proto response") - } - return ctx, nil -} - -// doJSONRequest makes a JSON request to the remote Twirp service. -func doJSONRequest(ctx context.Context, client HTTPClient, hooks *twirp.ClientHooks, url string, in, out proto.Message) (_ context.Context, err error) { - marshaler := &protojson.MarshalOptions{UseProtoNames: true} - reqBytes, err := marshaler.Marshal(in) - if err != nil { - return ctx, wrapInternal(err, "failed to marshal json request") - } - if err = ctx.Err(); err != nil { - return ctx, wrapInternal(err, "aborted because context was done") - } - - req, err := newRequest(ctx, url, bytes.NewReader(reqBytes), "application/json") - if err != nil { - return ctx, wrapInternal(err, "could not build request") - } - ctx, err = callClientRequestPrepared(ctx, hooks, req) - if err != nil { - return ctx, err - } - - req = req.WithContext(ctx) - resp, err := client.Do(req) - if err != nil { - return ctx, wrapInternal(err, "failed to do request") - } - - defer func() { - cerr := resp.Body.Close() - if err == nil && cerr != nil { - err = wrapInternal(cerr, "failed to close response body") - } - }() - - if err = ctx.Err(); err != nil { - return ctx, wrapInternal(err, "aborted because context was done") - } - - if resp.StatusCode != 200 { - return ctx, errorFromResponse(resp) - } - - d := json.NewDecoder(resp.Body) - rawRespBody := json.RawMessage{} - if err := d.Decode(&rawRespBody); err != nil { - return ctx, wrapInternal(err, "failed to unmarshal json response") - } - unmarshaler := protojson.UnmarshalOptions{DiscardUnknown: true} - if err = unmarshaler.Unmarshal(rawRespBody, out); err != nil { - return ctx, wrapInternal(err, "failed to unmarshal json response") - } - if err = ctx.Err(); err != nil { - return ctx, wrapInternal(err, "aborted because context was done") - } - return ctx, nil -} - -// Call twirp.ServerHooks.RequestReceived if the hook is available -func callRequestReceived(ctx context.Context, h *twirp.ServerHooks) (context.Context, error) { - if h == nil || h.RequestReceived == nil { - return ctx, nil - } - return h.RequestReceived(ctx) -} - -// Call twirp.ServerHooks.RequestRouted if the hook is available -func callRequestRouted(ctx context.Context, h *twirp.ServerHooks) (context.Context, error) { - if h == nil || h.RequestRouted == nil { - return ctx, nil - } - return h.RequestRouted(ctx) -} - -// Call twirp.ServerHooks.ResponsePrepared if the hook is available -func callResponsePrepared(ctx context.Context, h *twirp.ServerHooks) context.Context { - if h == nil || h.ResponsePrepared == nil { - return ctx - } - return h.ResponsePrepared(ctx) -} - -// Call twirp.ServerHooks.ResponseSent if the hook is available -func callResponseSent(ctx context.Context, h *twirp.ServerHooks) { - if h == nil || h.ResponseSent == nil { - return - } - h.ResponseSent(ctx) -} - -// Call twirp.ServerHooks.Error if the hook is available -func callError(ctx context.Context, h *twirp.ServerHooks, err twirp.Error) context.Context { - if h == nil || h.Error == nil { - return ctx - } - return h.Error(ctx, err) -} - -func callClientResponseReceived(ctx context.Context, h *twirp.ClientHooks) { - if h == nil || h.ResponseReceived == nil { - return - } - h.ResponseReceived(ctx) -} - -func callClientRequestPrepared(ctx context.Context, h *twirp.ClientHooks, req *http.Request) (context.Context, error) { - if h == nil || h.RequestPrepared == nil { - return ctx, nil - } - return h.RequestPrepared(ctx, req) -} - -func callClientError(ctx context.Context, h *twirp.ClientHooks, err twirp.Error) { - if h == nil || h.Error == nil { - return - } - h.Error(ctx, err) -} - -var twirpFileDescriptor0 = []byte{ - // 445 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xa4, 0x94, 0x5f, 0x8b, 0xd3, 0x40, - 0x14, 0xc5, 0x49, 0xbb, 0x4d, 0xdb, 0xbb, 0x65, 0x95, 0x69, 0x5d, 0xe3, 0xfe, 0x81, 0x92, 0xa7, - 0xb2, 0x60, 0x0b, 0xeb, 0x27, 0xc8, 0xea, 0x83, 0xa5, 0x3e, 0x48, 0xc4, 0x17, 0x1f, 0x0c, 0x63, - 0x72, 0x91, 0x21, 0x6b, 0x13, 0xe7, 0x4e, 0x8a, 0xf9, 0x78, 0xfa, 0xc9, 0x64, 0xfe, 0x50, 0x27, - 0x1a, 0x45, 0xd8, 0xb7, 0xcc, 0x9d, 0xc3, 0xb9, 0x87, 0x9c, 0x1f, 0x03, 0xcf, 0x64, 0x9d, 0x6f, - 0x78, 0x2d, 0x4a, 0x6c, 0x69, 0x43, 0x28, 0x0f, 0x22, 0xc7, 0x75, 0x2d, 0x2b, 0x55, 0xb1, 0xb1, - 0x1b, 0xc7, 0x1f, 0x61, 0xfe, 0x52, 0x22, 0x57, 0x98, 0xbc, 0xdd, 0xee, 0xb0, 0x4d, 0xf1, 0x6b, - 0x83, 0xa4, 0xd8, 0x02, 0x46, 0xaa, 0x2a, 0x71, 0x1f, 0x05, 0xcb, 0x60, 0x35, 0x4d, 0xed, 0x81, - 0x31, 0x38, 0xd9, 0xf3, 0x2f, 0x18, 0x0d, 0xcc, 0xd0, 0x7c, 0xb3, 0x6b, 0x00, 0xfc, 0x56, 0x0b, - 0x89, 0x94, 0x71, 0x15, 0x0d, 0xcd, 0xcd, 0xd4, 0x4d, 0x12, 0x15, 0xa7, 0xb0, 0xe8, 0xfa, 0x53, - 0x5d, 0xed, 0x09, 0xd9, 0x0a, 0x74, 0x84, 0xac, 0xc4, 0xd6, 0xac, 0x38, 0xbd, 0x7d, 0xb4, 0x76, - 0x91, 0xd6, 0x4e, 0x19, 0xf2, 0x5a, 0xec, 0xb0, 0x65, 0x8f, 0x61, 0xa8, 0x55, 0x76, 0xa7, 0xfe, - 0x8c, 0x6f, 0x80, 0xbd, 0x11, 0xa4, 0xac, 0x8e, 0xfe, 0x19, 0x39, 0x4e, 0x60, 0xde, 0xd1, 0xba, - 0xf5, 0x37, 0x30, 0x71, 0xeb, 0x29, 0x0a, 0x96, 0xc3, 0xbe, 0xfd, 0x63, 0xbb, 0x9f, 0xe2, 0x3b, - 0x98, 0xa7, 0x78, 0xa8, 0xca, 0xff, 0xfa, 0x45, 0x4f, 0x20, 0x2c, 0xb1, 0xcd, 0x44, 0xe1, 0x02, - 0x8f, 0x4a, 0x6c, 0xb7, 0x45, 0x7c, 0x0e, 0x8b, 0xae, 0x87, 0xcd, 0xa1, 0xbd, 0x5f, 0xe1, 0x3d, - 0xaa, 0x07, 0x7a, 0x77, 0x3d, 0x9c, 0xf7, 0x8f, 0x00, 0x42, 0x3b, 0x62, 0x67, 0x30, 0x10, 0x85, - 0x33, 0x1b, 0x88, 0x82, 0x3d, 0x85, 0x71, 0x43, 0x28, 0x7f, 0x59, 0x85, 0xfa, 0xb8, 0x2d, 0x8e, - 0x0d, 0x0f, 0xbb, 0x0d, 0xe7, 0xa6, 0xc2, 0x42, 0x37, 0x7c, 0x62, 0x1b, 0x76, 0x93, 0x44, 0xb1, - 0x25, 0xcc, 0xee, 0x39, 0xa9, 0xac, 0x21, 0x2b, 0x18, 0x19, 0x01, 0xe8, 0xd9, 0x7b, 0x32, 0x8a, - 0x2e, 0x22, 0xe1, 0x6f, 0x88, 0xb0, 0x4b, 0x98, 0x0a, 0xca, 0x78, 0xae, 0xc4, 0x01, 0xa3, 0xf1, - 0x32, 0x58, 0x4d, 0xd2, 0x89, 0xa0, 0xc4, 0x9c, 0x6f, 0xbf, 0x0f, 0xe0, 0xcc, 0x95, 0xf7, 0xce, - 0x12, 0xcc, 0x76, 0x30, 0xf3, 0x91, 0x62, 0x57, 0xc7, 0xe6, 0x7a, 0x48, 0xbe, 0xb8, 0xfe, 0xcb, - 0xad, 0x03, 0xe1, 0x35, 0x9c, 0x7a, 0x7c, 0xb0, 0xcb, 0xa3, 0xfa, 0x4f, 0xc2, 0x2e, 0xae, 0xfa, - 0x2f, 0x9d, 0xd3, 0x0e, 0x66, 0x7e, 0xc5, 0x5e, 0xac, 0x1e, 0x7a, 0xbc, 0x58, 0x7d, 0x5c, 0x68, - 0x33, 0xbf, 0x53, 0xcf, 0xac, 0x07, 0x17, 0xcf, 0xac, 0x0f, 0x84, 0xbb, 0xe8, 0xc3, 0x39, 0x97, - 0x9f, 0x1b, 0x7a, 0x9e, 0x57, 0x12, 0x37, 0xde, 0xa3, 0xf0, 0x29, 0x34, 0xaf, 0xc1, 0x8b, 0x9f, - 0x01, 0x00, 0x00, 0xff, 0xff, 0xd9, 0xf3, 0xfa, 0xf6, 0x2a, 0x04, 0x00, 0x00, -}
A
rpc/applications/service.pb.go
@@ -0,0 +1,909 @@
+// Code generated by protoc-gen-go. DO NOT EDIT. +// versions: +// protoc-gen-go v1.35.2 +// protoc v5.29.1 +// source: rpc/applications/service.proto + +package applications + +import ( + protoreflect "google.golang.org/protobuf/reflect/protoreflect" + protoimpl "google.golang.org/protobuf/runtime/protoimpl" + reflect "reflect" + sync "sync" +) + +const ( + // Verify that this generated code is sufficiently up-to-date. + _ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion) + // Verify that runtime/protoimpl is sufficiently up-to-date. + _ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20) +) + +type Application struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + + Id string `protobuf:"bytes,1,opt,name=id,proto3" json:"id,omitempty"` + UserId string `protobuf:"bytes,2,opt,name=user_id,json=userId,proto3" json:"user_id,omitempty"` + Name string `protobuf:"bytes,3,opt,name=name,proto3" json:"name,omitempty"` + Description string `protobuf:"bytes,4,opt,name=description,proto3" json:"description,omitempty"` + CreatedAt string `protobuf:"bytes,5,opt,name=created_at,json=createdAt,proto3" json:"created_at,omitempty"` + UpdatedAt string `protobuf:"bytes,6,opt,name=updated_at,json=updatedAt,proto3" json:"updated_at,omitempty"` +} + +func (x *Application) Reset() { + *x = Application{} + mi := &file_rpc_applications_service_proto_msgTypes[0] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *Application) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*Application) ProtoMessage() {} + +func (x *Application) ProtoReflect() protoreflect.Message { + mi := &file_rpc_applications_service_proto_msgTypes[0] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use Application.ProtoReflect.Descriptor instead. +func (*Application) Descriptor() ([]byte, []int) { + return file_rpc_applications_service_proto_rawDescGZIP(), []int{0} +} + +func (x *Application) GetId() string { + if x != nil { + return x.Id + } + return "" +} + +func (x *Application) GetUserId() string { + if x != nil { + return x.UserId + } + return "" +} + +func (x *Application) GetName() string { + if x != nil { + return x.Name + } + return "" +} + +func (x *Application) GetDescription() string { + if x != nil { + return x.Description + } + return "" +} + +func (x *Application) GetCreatedAt() string { + if x != nil { + return x.CreatedAt + } + return "" +} + +func (x *Application) GetUpdatedAt() string { + if x != nil { + return x.UpdatedAt + } + return "" +} + +type CreateApplicationRequest struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + + Token string `protobuf:"bytes,1,opt,name=token,proto3" json:"token,omitempty"` + Name string `protobuf:"bytes,2,opt,name=name,proto3" json:"name,omitempty"` + Description string `protobuf:"bytes,3,opt,name=description,proto3" json:"description,omitempty"` +} + +func (x *CreateApplicationRequest) Reset() { + *x = CreateApplicationRequest{} + mi := &file_rpc_applications_service_proto_msgTypes[1] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *CreateApplicationRequest) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*CreateApplicationRequest) ProtoMessage() {} + +func (x *CreateApplicationRequest) ProtoReflect() protoreflect.Message { + mi := &file_rpc_applications_service_proto_msgTypes[1] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use CreateApplicationRequest.ProtoReflect.Descriptor instead. +func (*CreateApplicationRequest) Descriptor() ([]byte, []int) { + return file_rpc_applications_service_proto_rawDescGZIP(), []int{1} +} + +func (x *CreateApplicationRequest) GetToken() string { + if x != nil { + return x.Token + } + return "" +} + +func (x *CreateApplicationRequest) GetName() string { + if x != nil { + return x.Name + } + return "" +} + +func (x *CreateApplicationRequest) GetDescription() string { + if x != nil { + return x.Description + } + return "" +} + +type CreateApplicationResponse struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + + Application *Application `protobuf:"bytes,1,opt,name=application,proto3" json:"application,omitempty"` + Key string `protobuf:"bytes,2,opt,name=key,proto3" json:"key,omitempty"` // The API key for the application +} + +func (x *CreateApplicationResponse) Reset() { + *x = CreateApplicationResponse{} + mi := &file_rpc_applications_service_proto_msgTypes[2] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *CreateApplicationResponse) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*CreateApplicationResponse) ProtoMessage() {} + +func (x *CreateApplicationResponse) ProtoReflect() protoreflect.Message { + mi := &file_rpc_applications_service_proto_msgTypes[2] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use CreateApplicationResponse.ProtoReflect.Descriptor instead. +func (*CreateApplicationResponse) Descriptor() ([]byte, []int) { + return file_rpc_applications_service_proto_rawDescGZIP(), []int{2} +} + +func (x *CreateApplicationResponse) GetApplication() *Application { + if x != nil { + return x.Application + } + return nil +} + +func (x *CreateApplicationResponse) GetKey() string { + if x != nil { + return x.Key + } + return "" +} + +type ListApplicationsRequest struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + + Token string `protobuf:"bytes,1,opt,name=token,proto3" json:"token,omitempty"` +} + +func (x *ListApplicationsRequest) Reset() { + *x = ListApplicationsRequest{} + mi := &file_rpc_applications_service_proto_msgTypes[3] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *ListApplicationsRequest) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*ListApplicationsRequest) ProtoMessage() {} + +func (x *ListApplicationsRequest) ProtoReflect() protoreflect.Message { + mi := &file_rpc_applications_service_proto_msgTypes[3] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use ListApplicationsRequest.ProtoReflect.Descriptor instead. +func (*ListApplicationsRequest) Descriptor() ([]byte, []int) { + return file_rpc_applications_service_proto_rawDescGZIP(), []int{3} +} + +func (x *ListApplicationsRequest) GetToken() string { + if x != nil { + return x.Token + } + return "" +} + +type ListApplicationsResponse struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + + Applications []*Application `protobuf:"bytes,1,rep,name=applications,proto3" json:"applications,omitempty"` +} + +func (x *ListApplicationsResponse) Reset() { + *x = ListApplicationsResponse{} + mi := &file_rpc_applications_service_proto_msgTypes[4] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *ListApplicationsResponse) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*ListApplicationsResponse) ProtoMessage() {} + +func (x *ListApplicationsResponse) ProtoReflect() protoreflect.Message { + mi := &file_rpc_applications_service_proto_msgTypes[4] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use ListApplicationsResponse.ProtoReflect.Descriptor instead. +func (*ListApplicationsResponse) Descriptor() ([]byte, []int) { + return file_rpc_applications_service_proto_rawDescGZIP(), []int{4} +} + +func (x *ListApplicationsResponse) GetApplications() []*Application { + if x != nil { + return x.Applications + } + return nil +} + +type GetApplicationRequest struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + + Token string `protobuf:"bytes,1,opt,name=token,proto3" json:"token,omitempty"` + ApplicationId string `protobuf:"bytes,2,opt,name=application_id,json=applicationId,proto3" json:"application_id,omitempty"` +} + +func (x *GetApplicationRequest) Reset() { + *x = GetApplicationRequest{} + mi := &file_rpc_applications_service_proto_msgTypes[5] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *GetApplicationRequest) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*GetApplicationRequest) ProtoMessage() {} + +func (x *GetApplicationRequest) ProtoReflect() protoreflect.Message { + mi := &file_rpc_applications_service_proto_msgTypes[5] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use GetApplicationRequest.ProtoReflect.Descriptor instead. +func (*GetApplicationRequest) Descriptor() ([]byte, []int) { + return file_rpc_applications_service_proto_rawDescGZIP(), []int{5} +} + +func (x *GetApplicationRequest) GetToken() string { + if x != nil { + return x.Token + } + return "" +} + +func (x *GetApplicationRequest) GetApplicationId() string { + if x != nil { + return x.ApplicationId + } + return "" +} + +type GetApplicationResponse struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + + Application *Application `protobuf:"bytes,1,opt,name=application,proto3" json:"application,omitempty"` +} + +func (x *GetApplicationResponse) Reset() { + *x = GetApplicationResponse{} + mi := &file_rpc_applications_service_proto_msgTypes[6] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *GetApplicationResponse) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*GetApplicationResponse) ProtoMessage() {} + +func (x *GetApplicationResponse) ProtoReflect() protoreflect.Message { + mi := &file_rpc_applications_service_proto_msgTypes[6] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use GetApplicationResponse.ProtoReflect.Descriptor instead. +func (*GetApplicationResponse) Descriptor() ([]byte, []int) { + return file_rpc_applications_service_proto_rawDescGZIP(), []int{6} +} + +func (x *GetApplicationResponse) GetApplication() *Application { + if x != nil { + return x.Application + } + return nil +} + +type UpdateApplicationRequest struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + + Token string `protobuf:"bytes,1,opt,name=token,proto3" json:"token,omitempty"` + ApplicationId string `protobuf:"bytes,2,opt,name=application_id,json=applicationId,proto3" json:"application_id,omitempty"` + Name string `protobuf:"bytes,3,opt,name=name,proto3" json:"name,omitempty"` + Description string `protobuf:"bytes,4,opt,name=description,proto3" json:"description,omitempty"` +} + +func (x *UpdateApplicationRequest) Reset() { + *x = UpdateApplicationRequest{} + mi := &file_rpc_applications_service_proto_msgTypes[7] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *UpdateApplicationRequest) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*UpdateApplicationRequest) ProtoMessage() {} + +func (x *UpdateApplicationRequest) ProtoReflect() protoreflect.Message { + mi := &file_rpc_applications_service_proto_msgTypes[7] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use UpdateApplicationRequest.ProtoReflect.Descriptor instead. +func (*UpdateApplicationRequest) Descriptor() ([]byte, []int) { + return file_rpc_applications_service_proto_rawDescGZIP(), []int{7} +} + +func (x *UpdateApplicationRequest) GetToken() string { + if x != nil { + return x.Token + } + return "" +} + +func (x *UpdateApplicationRequest) GetApplicationId() string { + if x != nil { + return x.ApplicationId + } + return "" +} + +func (x *UpdateApplicationRequest) GetName() string { + if x != nil { + return x.Name + } + return "" +} + +func (x *UpdateApplicationRequest) GetDescription() string { + if x != nil { + return x.Description + } + return "" +} + +type UpdateApplicationResponse struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + + Application *Application `protobuf:"bytes,1,opt,name=application,proto3" json:"application,omitempty"` +} + +func (x *UpdateApplicationResponse) Reset() { + *x = UpdateApplicationResponse{} + mi := &file_rpc_applications_service_proto_msgTypes[8] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *UpdateApplicationResponse) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*UpdateApplicationResponse) ProtoMessage() {} + +func (x *UpdateApplicationResponse) ProtoReflect() protoreflect.Message { + mi := &file_rpc_applications_service_proto_msgTypes[8] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use UpdateApplicationResponse.ProtoReflect.Descriptor instead. +func (*UpdateApplicationResponse) Descriptor() ([]byte, []int) { + return file_rpc_applications_service_proto_rawDescGZIP(), []int{8} +} + +func (x *UpdateApplicationResponse) GetApplication() *Application { + if x != nil { + return x.Application + } + return nil +} + +type DeleteApplicationRequest struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + + Token string `protobuf:"bytes,1,opt,name=token,proto3" json:"token,omitempty"` + ApplicationId string `protobuf:"bytes,2,opt,name=application_id,json=applicationId,proto3" json:"application_id,omitempty"` +} + +func (x *DeleteApplicationRequest) Reset() { + *x = DeleteApplicationRequest{} + mi := &file_rpc_applications_service_proto_msgTypes[9] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *DeleteApplicationRequest) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*DeleteApplicationRequest) ProtoMessage() {} + +func (x *DeleteApplicationRequest) ProtoReflect() protoreflect.Message { + mi := &file_rpc_applications_service_proto_msgTypes[9] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use DeleteApplicationRequest.ProtoReflect.Descriptor instead. +func (*DeleteApplicationRequest) Descriptor() ([]byte, []int) { + return file_rpc_applications_service_proto_rawDescGZIP(), []int{9} +} + +func (x *DeleteApplicationRequest) GetToken() string { + if x != nil { + return x.Token + } + return "" +} + +func (x *DeleteApplicationRequest) GetApplicationId() string { + if x != nil { + return x.ApplicationId + } + return "" +} + +type DeleteApplicationResponse struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields +} + +func (x *DeleteApplicationResponse) Reset() { + *x = DeleteApplicationResponse{} + mi := &file_rpc_applications_service_proto_msgTypes[10] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *DeleteApplicationResponse) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*DeleteApplicationResponse) ProtoMessage() {} + +func (x *DeleteApplicationResponse) ProtoReflect() protoreflect.Message { + mi := &file_rpc_applications_service_proto_msgTypes[10] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use DeleteApplicationResponse.ProtoReflect.Descriptor instead. +func (*DeleteApplicationResponse) Descriptor() ([]byte, []int) { + return file_rpc_applications_service_proto_rawDescGZIP(), []int{10} +} + +type RegenerateKeyRequest struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + + Token string `protobuf:"bytes,1,opt,name=token,proto3" json:"token,omitempty"` + ApplicationId string `protobuf:"bytes,2,opt,name=application_id,json=applicationId,proto3" json:"application_id,omitempty"` +} + +func (x *RegenerateKeyRequest) Reset() { + *x = RegenerateKeyRequest{} + mi := &file_rpc_applications_service_proto_msgTypes[11] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *RegenerateKeyRequest) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*RegenerateKeyRequest) ProtoMessage() {} + +func (x *RegenerateKeyRequest) ProtoReflect() protoreflect.Message { + mi := &file_rpc_applications_service_proto_msgTypes[11] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use RegenerateKeyRequest.ProtoReflect.Descriptor instead. +func (*RegenerateKeyRequest) Descriptor() ([]byte, []int) { + return file_rpc_applications_service_proto_rawDescGZIP(), []int{11} +} + +func (x *RegenerateKeyRequest) GetToken() string { + if x != nil { + return x.Token + } + return "" +} + +func (x *RegenerateKeyRequest) GetApplicationId() string { + if x != nil { + return x.ApplicationId + } + return "" +} + +type RegenerateKeyResponse struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + + Key string `protobuf:"bytes,1,opt,name=key,proto3" json:"key,omitempty"` // The new API key +} + +func (x *RegenerateKeyResponse) Reset() { + *x = RegenerateKeyResponse{} + mi := &file_rpc_applications_service_proto_msgTypes[12] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *RegenerateKeyResponse) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*RegenerateKeyResponse) ProtoMessage() {} + +func (x *RegenerateKeyResponse) ProtoReflect() protoreflect.Message { + mi := &file_rpc_applications_service_proto_msgTypes[12] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use RegenerateKeyResponse.ProtoReflect.Descriptor instead. +func (*RegenerateKeyResponse) Descriptor() ([]byte, []int) { + return file_rpc_applications_service_proto_rawDescGZIP(), []int{12} +} + +func (x *RegenerateKeyResponse) GetKey() string { + if x != nil { + return x.Key + } + return "" +} + +var File_rpc_applications_service_proto protoreflect.FileDescriptor + +var file_rpc_applications_service_proto_rawDesc = []byte{ + 0x0a, 0x1e, 0x72, 0x70, 0x63, 0x2f, 0x61, 0x70, 0x70, 0x6c, 0x69, 0x63, 0x61, 0x74, 0x69, 0x6f, + 0x6e, 0x73, 0x2f, 0x73, 0x65, 0x72, 0x76, 0x69, 0x63, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, + 0x12, 0x0c, 0x61, 0x70, 0x70, 0x6c, 0x69, 0x63, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x22, 0xaa, + 0x01, 0x0a, 0x0b, 0x41, 0x70, 0x70, 0x6c, 0x69, 0x63, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x12, 0x0e, + 0x0a, 0x02, 0x69, 0x64, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x02, 0x69, 0x64, 0x12, 0x17, + 0x0a, 0x07, 0x75, 0x73, 0x65, 0x72, 0x5f, 0x69, 0x64, 0x18, 0x02, 0x20, 0x01, 0x28, 0x09, 0x52, + 0x06, 0x75, 0x73, 0x65, 0x72, 0x49, 0x64, 0x12, 0x12, 0x0a, 0x04, 0x6e, 0x61, 0x6d, 0x65, 0x18, + 0x03, 0x20, 0x01, 0x28, 0x09, 0x52, 0x04, 0x6e, 0x61, 0x6d, 0x65, 0x12, 0x20, 0x0a, 0x0b, 0x64, + 0x65, 0x73, 0x63, 0x72, 0x69, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x18, 0x04, 0x20, 0x01, 0x28, 0x09, + 0x52, 0x0b, 0x64, 0x65, 0x73, 0x63, 0x72, 0x69, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x12, 0x1d, 0x0a, + 0x0a, 0x63, 0x72, 0x65, 0x61, 0x74, 0x65, 0x64, 0x5f, 0x61, 0x74, 0x18, 0x05, 0x20, 0x01, 0x28, + 0x09, 0x52, 0x09, 0x63, 0x72, 0x65, 0x61, 0x74, 0x65, 0x64, 0x41, 0x74, 0x12, 0x1d, 0x0a, 0x0a, + 0x75, 0x70, 0x64, 0x61, 0x74, 0x65, 0x64, 0x5f, 0x61, 0x74, 0x18, 0x06, 0x20, 0x01, 0x28, 0x09, + 0x52, 0x09, 0x75, 0x70, 0x64, 0x61, 0x74, 0x65, 0x64, 0x41, 0x74, 0x22, 0x66, 0x0a, 0x18, 0x43, + 0x72, 0x65, 0x61, 0x74, 0x65, 0x41, 0x70, 0x70, 0x6c, 0x69, 0x63, 0x61, 0x74, 0x69, 0x6f, 0x6e, + 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x12, 0x14, 0x0a, 0x05, 0x74, 0x6f, 0x6b, 0x65, 0x6e, + 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x05, 0x74, 0x6f, 0x6b, 0x65, 0x6e, 0x12, 0x12, 0x0a, + 0x04, 0x6e, 0x61, 0x6d, 0x65, 0x18, 0x02, 0x20, 0x01, 0x28, 0x09, 0x52, 0x04, 0x6e, 0x61, 0x6d, + 0x65, 0x12, 0x20, 0x0a, 0x0b, 0x64, 0x65, 0x73, 0x63, 0x72, 0x69, 0x70, 0x74, 0x69, 0x6f, 0x6e, + 0x18, 0x03, 0x20, 0x01, 0x28, 0x09, 0x52, 0x0b, 0x64, 0x65, 0x73, 0x63, 0x72, 0x69, 0x70, 0x74, + 0x69, 0x6f, 0x6e, 0x22, 0x6a, 0x0a, 0x19, 0x43, 0x72, 0x65, 0x61, 0x74, 0x65, 0x41, 0x70, 0x70, + 0x6c, 0x69, 0x63, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, + 0x12, 0x3b, 0x0a, 0x0b, 0x61, 0x70, 0x70, 0x6c, 0x69, 0x63, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x18, + 0x01, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x19, 0x2e, 0x61, 0x70, 0x70, 0x6c, 0x69, 0x63, 0x61, 0x74, + 0x69, 0x6f, 0x6e, 0x73, 0x2e, 0x41, 0x70, 0x70, 0x6c, 0x69, 0x63, 0x61, 0x74, 0x69, 0x6f, 0x6e, + 0x52, 0x0b, 0x61, 0x70, 0x70, 0x6c, 0x69, 0x63, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x12, 0x10, 0x0a, + 0x03, 0x6b, 0x65, 0x79, 0x18, 0x02, 0x20, 0x01, 0x28, 0x09, 0x52, 0x03, 0x6b, 0x65, 0x79, 0x22, + 0x2f, 0x0a, 0x17, 0x4c, 0x69, 0x73, 0x74, 0x41, 0x70, 0x70, 0x6c, 0x69, 0x63, 0x61, 0x74, 0x69, + 0x6f, 0x6e, 0x73, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x12, 0x14, 0x0a, 0x05, 0x74, 0x6f, + 0x6b, 0x65, 0x6e, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x05, 0x74, 0x6f, 0x6b, 0x65, 0x6e, + 0x22, 0x59, 0x0a, 0x18, 0x4c, 0x69, 0x73, 0x74, 0x41, 0x70, 0x70, 0x6c, 0x69, 0x63, 0x61, 0x74, + 0x69, 0x6f, 0x6e, 0x73, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x3d, 0x0a, 0x0c, + 0x61, 0x70, 0x70, 0x6c, 0x69, 0x63, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x18, 0x01, 0x20, 0x03, + 0x28, 0x0b, 0x32, 0x19, 0x2e, 0x61, 0x70, 0x70, 0x6c, 0x69, 0x63, 0x61, 0x74, 0x69, 0x6f, 0x6e, + 0x73, 0x2e, 0x41, 0x70, 0x70, 0x6c, 0x69, 0x63, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x52, 0x0c, 0x61, + 0x70, 0x70, 0x6c, 0x69, 0x63, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x22, 0x54, 0x0a, 0x15, 0x47, + 0x65, 0x74, 0x41, 0x70, 0x70, 0x6c, 0x69, 0x63, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x52, 0x65, 0x71, + 0x75, 0x65, 0x73, 0x74, 0x12, 0x14, 0x0a, 0x05, 0x74, 0x6f, 0x6b, 0x65, 0x6e, 0x18, 0x01, 0x20, + 0x01, 0x28, 0x09, 0x52, 0x05, 0x74, 0x6f, 0x6b, 0x65, 0x6e, 0x12, 0x25, 0x0a, 0x0e, 0x61, 0x70, + 0x70, 0x6c, 0x69, 0x63, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x5f, 0x69, 0x64, 0x18, 0x02, 0x20, 0x01, + 0x28, 0x09, 0x52, 0x0d, 0x61, 0x70, 0x70, 0x6c, 0x69, 0x63, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x49, + 0x64, 0x22, 0x55, 0x0a, 0x16, 0x47, 0x65, 0x74, 0x41, 0x70, 0x70, 0x6c, 0x69, 0x63, 0x61, 0x74, + 0x69, 0x6f, 0x6e, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x3b, 0x0a, 0x0b, 0x61, + 0x70, 0x70, 0x6c, 0x69, 0x63, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0b, + 0x32, 0x19, 0x2e, 0x61, 0x70, 0x70, 0x6c, 0x69, 0x63, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x2e, + 0x41, 0x70, 0x70, 0x6c, 0x69, 0x63, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x52, 0x0b, 0x61, 0x70, 0x70, + 0x6c, 0x69, 0x63, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x22, 0x8d, 0x01, 0x0a, 0x18, 0x55, 0x70, 0x64, + 0x61, 0x74, 0x65, 0x41, 0x70, 0x70, 0x6c, 0x69, 0x63, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x52, 0x65, + 0x71, 0x75, 0x65, 0x73, 0x74, 0x12, 0x14, 0x0a, 0x05, 0x74, 0x6f, 0x6b, 0x65, 0x6e, 0x18, 0x01, + 0x20, 0x01, 0x28, 0x09, 0x52, 0x05, 0x74, 0x6f, 0x6b, 0x65, 0x6e, 0x12, 0x25, 0x0a, 0x0e, 0x61, + 0x70, 0x70, 0x6c, 0x69, 0x63, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x5f, 0x69, 0x64, 0x18, 0x02, 0x20, + 0x01, 0x28, 0x09, 0x52, 0x0d, 0x61, 0x70, 0x70, 0x6c, 0x69, 0x63, 0x61, 0x74, 0x69, 0x6f, 0x6e, + 0x49, 0x64, 0x12, 0x12, 0x0a, 0x04, 0x6e, 0x61, 0x6d, 0x65, 0x18, 0x03, 0x20, 0x01, 0x28, 0x09, + 0x52, 0x04, 0x6e, 0x61, 0x6d, 0x65, 0x12, 0x20, 0x0a, 0x0b, 0x64, 0x65, 0x73, 0x63, 0x72, 0x69, + 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x18, 0x04, 0x20, 0x01, 0x28, 0x09, 0x52, 0x0b, 0x64, 0x65, 0x73, + 0x63, 0x72, 0x69, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x22, 0x58, 0x0a, 0x19, 0x55, 0x70, 0x64, 0x61, + 0x74, 0x65, 0x41, 0x70, 0x70, 0x6c, 0x69, 0x63, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x52, 0x65, 0x73, + 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x3b, 0x0a, 0x0b, 0x61, 0x70, 0x70, 0x6c, 0x69, 0x63, 0x61, + 0x74, 0x69, 0x6f, 0x6e, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x19, 0x2e, 0x61, 0x70, 0x70, + 0x6c, 0x69, 0x63, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x2e, 0x41, 0x70, 0x70, 0x6c, 0x69, 0x63, + 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x52, 0x0b, 0x61, 0x70, 0x70, 0x6c, 0x69, 0x63, 0x61, 0x74, 0x69, + 0x6f, 0x6e, 0x22, 0x57, 0x0a, 0x18, 0x44, 0x65, 0x6c, 0x65, 0x74, 0x65, 0x41, 0x70, 0x70, 0x6c, + 0x69, 0x63, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x12, 0x14, + 0x0a, 0x05, 0x74, 0x6f, 0x6b, 0x65, 0x6e, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x05, 0x74, + 0x6f, 0x6b, 0x65, 0x6e, 0x12, 0x25, 0x0a, 0x0e, 0x61, 0x70, 0x70, 0x6c, 0x69, 0x63, 0x61, 0x74, + 0x69, 0x6f, 0x6e, 0x5f, 0x69, 0x64, 0x18, 0x02, 0x20, 0x01, 0x28, 0x09, 0x52, 0x0d, 0x61, 0x70, + 0x70, 0x6c, 0x69, 0x63, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x49, 0x64, 0x22, 0x1b, 0x0a, 0x19, 0x44, + 0x65, 0x6c, 0x65, 0x74, 0x65, 0x41, 0x70, 0x70, 0x6c, 0x69, 0x63, 0x61, 0x74, 0x69, 0x6f, 0x6e, + 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x22, 0x53, 0x0a, 0x14, 0x52, 0x65, 0x67, 0x65, + 0x6e, 0x65, 0x72, 0x61, 0x74, 0x65, 0x4b, 0x65, 0x79, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, + 0x12, 0x14, 0x0a, 0x05, 0x74, 0x6f, 0x6b, 0x65, 0x6e, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, + 0x05, 0x74, 0x6f, 0x6b, 0x65, 0x6e, 0x12, 0x25, 0x0a, 0x0e, 0x61, 0x70, 0x70, 0x6c, 0x69, 0x63, + 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x5f, 0x69, 0x64, 0x18, 0x02, 0x20, 0x01, 0x28, 0x09, 0x52, 0x0d, + 0x61, 0x70, 0x70, 0x6c, 0x69, 0x63, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x49, 0x64, 0x22, 0x29, 0x0a, + 0x15, 0x52, 0x65, 0x67, 0x65, 0x6e, 0x65, 0x72, 0x61, 0x74, 0x65, 0x4b, 0x65, 0x79, 0x52, 0x65, + 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x10, 0x0a, 0x03, 0x6b, 0x65, 0x79, 0x18, 0x01, 0x20, + 0x01, 0x28, 0x09, 0x52, 0x03, 0x6b, 0x65, 0x79, 0x32, 0xe1, 0x04, 0x0a, 0x13, 0x41, 0x70, 0x70, + 0x6c, 0x69, 0x63, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x53, 0x65, 0x72, 0x76, 0x69, 0x63, 0x65, + 0x12, 0x64, 0x0a, 0x11, 0x43, 0x72, 0x65, 0x61, 0x74, 0x65, 0x41, 0x70, 0x70, 0x6c, 0x69, 0x63, + 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x12, 0x26, 0x2e, 0x61, 0x70, 0x70, 0x6c, 0x69, 0x63, 0x61, 0x74, + 0x69, 0x6f, 0x6e, 0x73, 0x2e, 0x43, 0x72, 0x65, 0x61, 0x74, 0x65, 0x41, 0x70, 0x70, 0x6c, 0x69, + 0x63, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x1a, 0x27, 0x2e, + 0x61, 0x70, 0x70, 0x6c, 0x69, 0x63, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x2e, 0x43, 0x72, 0x65, + 0x61, 0x74, 0x65, 0x41, 0x70, 0x70, 0x6c, 0x69, 0x63, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x52, 0x65, + 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x61, 0x0a, 0x10, 0x4c, 0x69, 0x73, 0x74, 0x41, 0x70, + 0x70, 0x6c, 0x69, 0x63, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x12, 0x25, 0x2e, 0x61, 0x70, 0x70, + 0x6c, 0x69, 0x63, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x2e, 0x4c, 0x69, 0x73, 0x74, 0x41, 0x70, + 0x70, 0x6c, 0x69, 0x63, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, + 0x74, 0x1a, 0x26, 0x2e, 0x61, 0x70, 0x70, 0x6c, 0x69, 0x63, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x73, + 0x2e, 0x4c, 0x69, 0x73, 0x74, 0x41, 0x70, 0x70, 0x6c, 0x69, 0x63, 0x61, 0x74, 0x69, 0x6f, 0x6e, + 0x73, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x5b, 0x0a, 0x0e, 0x47, 0x65, 0x74, + 0x41, 0x70, 0x70, 0x6c, 0x69, 0x63, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x12, 0x23, 0x2e, 0x61, 0x70, + 0x70, 0x6c, 0x69, 0x63, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x2e, 0x47, 0x65, 0x74, 0x41, 0x70, + 0x70, 0x6c, 0x69, 0x63, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, + 0x1a, 0x24, 0x2e, 0x61, 0x70, 0x70, 0x6c, 0x69, 0x63, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x2e, + 0x47, 0x65, 0x74, 0x41, 0x70, 0x70, 0x6c, 0x69, 0x63, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x52, 0x65, + 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x64, 0x0a, 0x11, 0x55, 0x70, 0x64, 0x61, 0x74, 0x65, + 0x41, 0x70, 0x70, 0x6c, 0x69, 0x63, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x12, 0x26, 0x2e, 0x61, 0x70, + 0x70, 0x6c, 0x69, 0x63, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x2e, 0x55, 0x70, 0x64, 0x61, 0x74, + 0x65, 0x41, 0x70, 0x70, 0x6c, 0x69, 0x63, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x52, 0x65, 0x71, 0x75, + 0x65, 0x73, 0x74, 0x1a, 0x27, 0x2e, 0x61, 0x70, 0x70, 0x6c, 0x69, 0x63, 0x61, 0x74, 0x69, 0x6f, + 0x6e, 0x73, 0x2e, 0x55, 0x70, 0x64, 0x61, 0x74, 0x65, 0x41, 0x70, 0x70, 0x6c, 0x69, 0x63, 0x61, + 0x74, 0x69, 0x6f, 0x6e, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x64, 0x0a, 0x11, + 0x44, 0x65, 0x6c, 0x65, 0x74, 0x65, 0x41, 0x70, 0x70, 0x6c, 0x69, 0x63, 0x61, 0x74, 0x69, 0x6f, + 0x6e, 0x12, 0x26, 0x2e, 0x61, 0x70, 0x70, 0x6c, 0x69, 0x63, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x73, + 0x2e, 0x44, 0x65, 0x6c, 0x65, 0x74, 0x65, 0x41, 0x70, 0x70, 0x6c, 0x69, 0x63, 0x61, 0x74, 0x69, + 0x6f, 0x6e, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x1a, 0x27, 0x2e, 0x61, 0x70, 0x70, 0x6c, + 0x69, 0x63, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x2e, 0x44, 0x65, 0x6c, 0x65, 0x74, 0x65, 0x41, + 0x70, 0x70, 0x6c, 0x69, 0x63, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, + 0x73, 0x65, 0x12, 0x58, 0x0a, 0x0d, 0x52, 0x65, 0x67, 0x65, 0x6e, 0x65, 0x72, 0x61, 0x74, 0x65, + 0x4b, 0x65, 0x79, 0x12, 0x22, 0x2e, 0x61, 0x70, 0x70, 0x6c, 0x69, 0x63, 0x61, 0x74, 0x69, 0x6f, + 0x6e, 0x73, 0x2e, 0x52, 0x65, 0x67, 0x65, 0x6e, 0x65, 0x72, 0x61, 0x74, 0x65, 0x4b, 0x65, 0x79, + 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x1a, 0x23, 0x2e, 0x61, 0x70, 0x70, 0x6c, 0x69, 0x63, + 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x2e, 0x52, 0x65, 0x67, 0x65, 0x6e, 0x65, 0x72, 0x61, 0x74, + 0x65, 0x4b, 0x65, 0x79, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x42, 0x1d, 0x5a, 0x1b, + 0x61, 0x72, 0x67, 0x75, 0x73, 0x2d, 0x63, 0x6f, 0x72, 0x65, 0x2f, 0x72, 0x70, 0x63, 0x2f, 0x61, + 0x70, 0x70, 0x6c, 0x69, 0x63, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x62, 0x06, 0x70, 0x72, 0x6f, + 0x74, 0x6f, 0x33, +} + +var ( + file_rpc_applications_service_proto_rawDescOnce sync.Once + file_rpc_applications_service_proto_rawDescData = file_rpc_applications_service_proto_rawDesc +) + +func file_rpc_applications_service_proto_rawDescGZIP() []byte { + file_rpc_applications_service_proto_rawDescOnce.Do(func() { + file_rpc_applications_service_proto_rawDescData = protoimpl.X.CompressGZIP(file_rpc_applications_service_proto_rawDescData) + }) + return file_rpc_applications_service_proto_rawDescData +} + +var file_rpc_applications_service_proto_msgTypes = make([]protoimpl.MessageInfo, 13) +var file_rpc_applications_service_proto_goTypes = []any{ + (*Application)(nil), // 0: applications.Application + (*CreateApplicationRequest)(nil), // 1: applications.CreateApplicationRequest + (*CreateApplicationResponse)(nil), // 2: applications.CreateApplicationResponse + (*ListApplicationsRequest)(nil), // 3: applications.ListApplicationsRequest + (*ListApplicationsResponse)(nil), // 4: applications.ListApplicationsResponse + (*GetApplicationRequest)(nil), // 5: applications.GetApplicationRequest + (*GetApplicationResponse)(nil), // 6: applications.GetApplicationResponse + (*UpdateApplicationRequest)(nil), // 7: applications.UpdateApplicationRequest + (*UpdateApplicationResponse)(nil), // 8: applications.UpdateApplicationResponse + (*DeleteApplicationRequest)(nil), // 9: applications.DeleteApplicationRequest + (*DeleteApplicationResponse)(nil), // 10: applications.DeleteApplicationResponse + (*RegenerateKeyRequest)(nil), // 11: applications.RegenerateKeyRequest + (*RegenerateKeyResponse)(nil), // 12: applications.RegenerateKeyResponse +} +var file_rpc_applications_service_proto_depIdxs = []int32{ + 0, // 0: applications.CreateApplicationResponse.application:type_name -> applications.Application + 0, // 1: applications.ListApplicationsResponse.applications:type_name -> applications.Application + 0, // 2: applications.GetApplicationResponse.application:type_name -> applications.Application + 0, // 3: applications.UpdateApplicationResponse.application:type_name -> applications.Application + 1, // 4: applications.ApplicationsService.CreateApplication:input_type -> applications.CreateApplicationRequest + 3, // 5: applications.ApplicationsService.ListApplications:input_type -> applications.ListApplicationsRequest + 5, // 6: applications.ApplicationsService.GetApplication:input_type -> applications.GetApplicationRequest + 7, // 7: applications.ApplicationsService.UpdateApplication:input_type -> applications.UpdateApplicationRequest + 9, // 8: applications.ApplicationsService.DeleteApplication:input_type -> applications.DeleteApplicationRequest + 11, // 9: applications.ApplicationsService.RegenerateKey:input_type -> applications.RegenerateKeyRequest + 2, // 10: applications.ApplicationsService.CreateApplication:output_type -> applications.CreateApplicationResponse + 4, // 11: applications.ApplicationsService.ListApplications:output_type -> applications.ListApplicationsResponse + 6, // 12: applications.ApplicationsService.GetApplication:output_type -> applications.GetApplicationResponse + 8, // 13: applications.ApplicationsService.UpdateApplication:output_type -> applications.UpdateApplicationResponse + 10, // 14: applications.ApplicationsService.DeleteApplication:output_type -> applications.DeleteApplicationResponse + 12, // 15: applications.ApplicationsService.RegenerateKey:output_type -> applications.RegenerateKeyResponse + 10, // [10:16] is the sub-list for method output_type + 4, // [4:10] is the sub-list for method input_type + 4, // [4:4] is the sub-list for extension type_name + 4, // [4:4] is the sub-list for extension extendee + 0, // [0:4] is the sub-list for field type_name +} + +func init() { file_rpc_applications_service_proto_init() } +func file_rpc_applications_service_proto_init() { + if File_rpc_applications_service_proto != nil { + return + } + type x struct{} + out := protoimpl.TypeBuilder{ + File: protoimpl.DescBuilder{ + GoPackagePath: reflect.TypeOf(x{}).PkgPath(), + RawDescriptor: file_rpc_applications_service_proto_rawDesc, + NumEnums: 0, + NumMessages: 13, + NumExtensions: 0, + NumServices: 1, + }, + GoTypes: file_rpc_applications_service_proto_goTypes, + DependencyIndexes: file_rpc_applications_service_proto_depIdxs, + MessageInfos: file_rpc_applications_service_proto_msgTypes, + }.Build() + File_rpc_applications_service_proto = out.File + file_rpc_applications_service_proto_rawDesc = nil + file_rpc_applications_service_proto_goTypes = nil + file_rpc_applications_service_proto_depIdxs = nil +}
A
rpc/applications/service.proto
@@ -0,0 +1,77 @@
+syntax = "proto3"; + +package applications; +option go_package = "argus-core/rpc/applications"; + +service ApplicationsService { + rpc CreateApplication(CreateApplicationRequest) returns (CreateApplicationResponse); + rpc ListApplications(ListApplicationsRequest) returns (ListApplicationsResponse); + rpc GetApplication(GetApplicationRequest) returns (GetApplicationResponse); + rpc UpdateApplication(UpdateApplicationRequest) returns (UpdateApplicationResponse); + rpc DeleteApplication(DeleteApplicationRequest) returns (DeleteApplicationResponse); + rpc RegenerateKey(RegenerateKeyRequest) returns (RegenerateKeyResponse); +} + +message Application { + string id = 1; + string user_id = 2; + string name = 3; + string description = 4; + string created_at = 5; + string updated_at = 6; +} + +message CreateApplicationRequest { + string token = 1; + string name = 2; + string description = 3; +} + +message CreateApplicationResponse { + Application application = 1; + string key = 2; // The API key for the application +} + +message ListApplicationsRequest { + string token = 1; +} + +message ListApplicationsResponse { + repeated Application applications = 1; +} + +message GetApplicationRequest { + string token = 1; + string application_id = 2; +} + +message GetApplicationResponse { + Application application = 1; +} + +message UpdateApplicationRequest { + string token = 1; + string application_id = 2; + string name = 3; + string description = 4; +} + +message UpdateApplicationResponse { + Application application = 1; +} + +message DeleteApplicationRequest { + string token = 1; + string application_id = 2; +} + +message DeleteApplicationResponse {} + +message RegenerateKeyRequest { + string token = 1; + string application_id = 2; +} + +message RegenerateKeyResponse { + string key = 1; // The new API key +}
A
rpc/applications/service.twirp.go
@@ -0,0 +1,2518 @@
+// Code generated by protoc-gen-twirp v8.1.3, DO NOT EDIT. +// source: rpc/applications/service.proto + +package applications + +import context "context" +import fmt "fmt" +import http "net/http" +import io "io" +import json "encoding/json" +import strconv "strconv" +import strings "strings" + +import protojson "google.golang.org/protobuf/encoding/protojson" +import proto "google.golang.org/protobuf/proto" +import twirp "github.com/twitchtv/twirp" +import ctxsetters "github.com/twitchtv/twirp/ctxsetters" + +import bytes "bytes" +import errors "errors" +import path "path" +import url "net/url" + +// Version compatibility assertion. +// If the constant is not defined in the package, that likely means +// the package needs to be updated to work with this generated code. +// See https://twitchtv.github.io/twirp/docs/version_matrix.html +const _ = twirp.TwirpPackageMinVersion_8_1_0 + +// ============================= +// ApplicationsService Interface +// ============================= + +type ApplicationsService interface { + CreateApplication(context.Context, *CreateApplicationRequest) (*CreateApplicationResponse, error) + + ListApplications(context.Context, *ListApplicationsRequest) (*ListApplicationsResponse, error) + + GetApplication(context.Context, *GetApplicationRequest) (*GetApplicationResponse, error) + + UpdateApplication(context.Context, *UpdateApplicationRequest) (*UpdateApplicationResponse, error) + + DeleteApplication(context.Context, *DeleteApplicationRequest) (*DeleteApplicationResponse, error) + + RegenerateKey(context.Context, *RegenerateKeyRequest) (*RegenerateKeyResponse, error) +} + +// =================================== +// ApplicationsService Protobuf Client +// =================================== + +type applicationsServiceProtobufClient struct { + client HTTPClient + urls [6]string + interceptor twirp.Interceptor + opts twirp.ClientOptions +} + +// NewApplicationsServiceProtobufClient creates a Protobuf client that implements the ApplicationsService interface. +// It communicates using Protobuf and can be configured with a custom HTTPClient. +func NewApplicationsServiceProtobufClient(baseURL string, client HTTPClient, opts ...twirp.ClientOption) ApplicationsService { + if c, ok := client.(*http.Client); ok { + client = withoutRedirects(c) + } + + clientOpts := twirp.ClientOptions{} + for _, o := range opts { + o(&clientOpts) + } + + // Using ReadOpt allows backwards and forwards compatibility with new options in the future + literalURLs := false + _ = clientOpts.ReadOpt("literalURLs", &literalURLs) + var pathPrefix string + if ok := clientOpts.ReadOpt("pathPrefix", &pathPrefix); !ok { + pathPrefix = "/twirp" // default prefix + } + + // Build method URLs: <baseURL>[<prefix>]/<package>.<Service>/<Method> + serviceURL := sanitizeBaseURL(baseURL) + serviceURL += baseServicePath(pathPrefix, "applications", "ApplicationsService") + urls := [6]string{ + serviceURL + "CreateApplication", + serviceURL + "ListApplications", + serviceURL + "GetApplication", + serviceURL + "UpdateApplication", + serviceURL + "DeleteApplication", + serviceURL + "RegenerateKey", + } + + return &applicationsServiceProtobufClient{ + client: client, + urls: urls, + interceptor: twirp.ChainInterceptors(clientOpts.Interceptors...), + opts: clientOpts, + } +} + +func (c *applicationsServiceProtobufClient) CreateApplication(ctx context.Context, in *CreateApplicationRequest) (*CreateApplicationResponse, error) { + ctx = ctxsetters.WithPackageName(ctx, "applications") + ctx = ctxsetters.WithServiceName(ctx, "ApplicationsService") + ctx = ctxsetters.WithMethodName(ctx, "CreateApplication") + caller := c.callCreateApplication + if c.interceptor != nil { + caller = func(ctx context.Context, req *CreateApplicationRequest) (*CreateApplicationResponse, error) { + resp, err := c.interceptor( + func(ctx context.Context, req interface{}) (interface{}, error) { + typedReq, ok := req.(*CreateApplicationRequest) + if !ok { + return nil, twirp.InternalError("failed type assertion req.(*CreateApplicationRequest) when calling interceptor") + } + return c.callCreateApplication(ctx, typedReq) + }, + )(ctx, req) + if resp != nil { + typedResp, ok := resp.(*CreateApplicationResponse) + if !ok { + return nil, twirp.InternalError("failed type assertion resp.(*CreateApplicationResponse) when calling interceptor") + } + return typedResp, err + } + return nil, err + } + } + return caller(ctx, in) +} + +func (c *applicationsServiceProtobufClient) callCreateApplication(ctx context.Context, in *CreateApplicationRequest) (*CreateApplicationResponse, error) { + out := new(CreateApplicationResponse) + ctx, err := doProtobufRequest(ctx, c.client, c.opts.Hooks, c.urls[0], in, out) + if err != nil { + twerr, ok := err.(twirp.Error) + if !ok { + twerr = twirp.InternalErrorWith(err) + } + callClientError(ctx, c.opts.Hooks, twerr) + return nil, err + } + + callClientResponseReceived(ctx, c.opts.Hooks) + + return out, nil +} + +func (c *applicationsServiceProtobufClient) ListApplications(ctx context.Context, in *ListApplicationsRequest) (*ListApplicationsResponse, error) { + ctx = ctxsetters.WithPackageName(ctx, "applications") + ctx = ctxsetters.WithServiceName(ctx, "ApplicationsService") + ctx = ctxsetters.WithMethodName(ctx, "ListApplications") + caller := c.callListApplications + if c.interceptor != nil { + caller = func(ctx context.Context, req *ListApplicationsRequest) (*ListApplicationsResponse, error) { + resp, err := c.interceptor( + func(ctx context.Context, req interface{}) (interface{}, error) { + typedReq, ok := req.(*ListApplicationsRequest) + if !ok { + return nil, twirp.InternalError("failed type assertion req.(*ListApplicationsRequest) when calling interceptor") + } + return c.callListApplications(ctx, typedReq) + }, + )(ctx, req) + if resp != nil { + typedResp, ok := resp.(*ListApplicationsResponse) + if !ok { + return nil, twirp.InternalError("failed type assertion resp.(*ListApplicationsResponse) when calling interceptor") + } + return typedResp, err + } + return nil, err + } + } + return caller(ctx, in) +} + +func (c *applicationsServiceProtobufClient) callListApplications(ctx context.Context, in *ListApplicationsRequest) (*ListApplicationsResponse, error) { + out := new(ListApplicationsResponse) + ctx, err := doProtobufRequest(ctx, c.client, c.opts.Hooks, c.urls[1], in, out) + if err != nil { + twerr, ok := err.(twirp.Error) + if !ok { + twerr = twirp.InternalErrorWith(err) + } + callClientError(ctx, c.opts.Hooks, twerr) + return nil, err + } + + callClientResponseReceived(ctx, c.opts.Hooks) + + return out, nil +} + +func (c *applicationsServiceProtobufClient) GetApplication(ctx context.Context, in *GetApplicationRequest) (*GetApplicationResponse, error) { + ctx = ctxsetters.WithPackageName(ctx, "applications") + ctx = ctxsetters.WithServiceName(ctx, "ApplicationsService") + ctx = ctxsetters.WithMethodName(ctx, "GetApplication") + caller := c.callGetApplication + if c.interceptor != nil { + caller = func(ctx context.Context, req *GetApplicationRequest) (*GetApplicationResponse, error) { + resp, err := c.interceptor( + func(ctx context.Context, req interface{}) (interface{}, error) { + typedReq, ok := req.(*GetApplicationRequest) + if !ok { + return nil, twirp.InternalError("failed type assertion req.(*GetApplicationRequest) when calling interceptor") + } + return c.callGetApplication(ctx, typedReq) + }, + )(ctx, req) + if resp != nil { + typedResp, ok := resp.(*GetApplicationResponse) + if !ok { + return nil, twirp.InternalError("failed type assertion resp.(*GetApplicationResponse) when calling interceptor") + } + return typedResp, err + } + return nil, err + } + } + return caller(ctx, in) +} + +func (c *applicationsServiceProtobufClient) callGetApplication(ctx context.Context, in *GetApplicationRequest) (*GetApplicationResponse, error) { + out := new(GetApplicationResponse) + ctx, err := doProtobufRequest(ctx, c.client, c.opts.Hooks, c.urls[2], in, out) + if err != nil { + twerr, ok := err.(twirp.Error) + if !ok { + twerr = twirp.InternalErrorWith(err) + } + callClientError(ctx, c.opts.Hooks, twerr) + return nil, err + } + + callClientResponseReceived(ctx, c.opts.Hooks) + + return out, nil +} + +func (c *applicationsServiceProtobufClient) UpdateApplication(ctx context.Context, in *UpdateApplicationRequest) (*UpdateApplicationResponse, error) { + ctx = ctxsetters.WithPackageName(ctx, "applications") + ctx = ctxsetters.WithServiceName(ctx, "ApplicationsService") + ctx = ctxsetters.WithMethodName(ctx, "UpdateApplication") + caller := c.callUpdateApplication + if c.interceptor != nil { + caller = func(ctx context.Context, req *UpdateApplicationRequest) (*UpdateApplicationResponse, error) { + resp, err := c.interceptor( + func(ctx context.Context, req interface{}) (interface{}, error) { + typedReq, ok := req.(*UpdateApplicationRequest) + if !ok { + return nil, twirp.InternalError("failed type assertion req.(*UpdateApplicationRequest) when calling interceptor") + } + return c.callUpdateApplication(ctx, typedReq) + }, + )(ctx, req) + if resp != nil { + typedResp, ok := resp.(*UpdateApplicationResponse) + if !ok { + return nil, twirp.InternalError("failed type assertion resp.(*UpdateApplicationResponse) when calling interceptor") + } + return typedResp, err + } + return nil, err + } + } + return caller(ctx, in) +} + +func (c *applicationsServiceProtobufClient) callUpdateApplication(ctx context.Context, in *UpdateApplicationRequest) (*UpdateApplicationResponse, error) { + out := new(UpdateApplicationResponse) + ctx, err := doProtobufRequest(ctx, c.client, c.opts.Hooks, c.urls[3], in, out) + if err != nil { + twerr, ok := err.(twirp.Error) + if !ok { + twerr = twirp.InternalErrorWith(err) + } + callClientError(ctx, c.opts.Hooks, twerr) + return nil, err + } + + callClientResponseReceived(ctx, c.opts.Hooks) + + return out, nil +} + +func (c *applicationsServiceProtobufClient) DeleteApplication(ctx context.Context, in *DeleteApplicationRequest) (*DeleteApplicationResponse, error) { + ctx = ctxsetters.WithPackageName(ctx, "applications") + ctx = ctxsetters.WithServiceName(ctx, "ApplicationsService") + ctx = ctxsetters.WithMethodName(ctx, "DeleteApplication") + caller := c.callDeleteApplication + if c.interceptor != nil { + caller = func(ctx context.Context, req *DeleteApplicationRequest) (*DeleteApplicationResponse, error) { + resp, err := c.interceptor( + func(ctx context.Context, req interface{}) (interface{}, error) { + typedReq, ok := req.(*DeleteApplicationRequest) + if !ok { + return nil, twirp.InternalError("failed type assertion req.(*DeleteApplicationRequest) when calling interceptor") + } + return c.callDeleteApplication(ctx, typedReq) + }, + )(ctx, req) + if resp != nil { + typedResp, ok := resp.(*DeleteApplicationResponse) + if !ok { + return nil, twirp.InternalError("failed type assertion resp.(*DeleteApplicationResponse) when calling interceptor") + } + return typedResp, err + } + return nil, err + } + } + return caller(ctx, in) +} + +func (c *applicationsServiceProtobufClient) callDeleteApplication(ctx context.Context, in *DeleteApplicationRequest) (*DeleteApplicationResponse, error) { + out := new(DeleteApplicationResponse) + ctx, err := doProtobufRequest(ctx, c.client, c.opts.Hooks, c.urls[4], in, out) + if err != nil { + twerr, ok := err.(twirp.Error) + if !ok { + twerr = twirp.InternalErrorWith(err) + } + callClientError(ctx, c.opts.Hooks, twerr) + return nil, err + } + + callClientResponseReceived(ctx, c.opts.Hooks) + + return out, nil +} + +func (c *applicationsServiceProtobufClient) RegenerateKey(ctx context.Context, in *RegenerateKeyRequest) (*RegenerateKeyResponse, error) { + ctx = ctxsetters.WithPackageName(ctx, "applications") + ctx = ctxsetters.WithServiceName(ctx, "ApplicationsService") + ctx = ctxsetters.WithMethodName(ctx, "RegenerateKey") + caller := c.callRegenerateKey + if c.interceptor != nil { + caller = func(ctx context.Context, req *RegenerateKeyRequest) (*RegenerateKeyResponse, error) { + resp, err := c.interceptor( + func(ctx context.Context, req interface{}) (interface{}, error) { + typedReq, ok := req.(*RegenerateKeyRequest) + if !ok { + return nil, twirp.InternalError("failed type assertion req.(*RegenerateKeyRequest) when calling interceptor") + } + return c.callRegenerateKey(ctx, typedReq) + }, + )(ctx, req) + if resp != nil { + typedResp, ok := resp.(*RegenerateKeyResponse) + if !ok { + return nil, twirp.InternalError("failed type assertion resp.(*RegenerateKeyResponse) when calling interceptor") + } + return typedResp, err + } + return nil, err + } + } + return caller(ctx, in) +} + +func (c *applicationsServiceProtobufClient) callRegenerateKey(ctx context.Context, in *RegenerateKeyRequest) (*RegenerateKeyResponse, error) { + out := new(RegenerateKeyResponse) + ctx, err := doProtobufRequest(ctx, c.client, c.opts.Hooks, c.urls[5], in, out) + if err != nil { + twerr, ok := err.(twirp.Error) + if !ok { + twerr = twirp.InternalErrorWith(err) + } + callClientError(ctx, c.opts.Hooks, twerr) + return nil, err + } + + callClientResponseReceived(ctx, c.opts.Hooks) + + return out, nil +} + +// =============================== +// ApplicationsService JSON Client +// =============================== + +type applicationsServiceJSONClient struct { + client HTTPClient + urls [6]string + interceptor twirp.Interceptor + opts twirp.ClientOptions +} + +// NewApplicationsServiceJSONClient creates a JSON client that implements the ApplicationsService interface. +// It communicates using JSON and can be configured with a custom HTTPClient. +func NewApplicationsServiceJSONClient(baseURL string, client HTTPClient, opts ...twirp.ClientOption) ApplicationsService { + if c, ok := client.(*http.Client); ok { + client = withoutRedirects(c) + } + + clientOpts := twirp.ClientOptions{} + for _, o := range opts { + o(&clientOpts) + } + + // Using ReadOpt allows backwards and forwards compatibility with new options in the future + literalURLs := false + _ = clientOpts.ReadOpt("literalURLs", &literalURLs) + var pathPrefix string + if ok := clientOpts.ReadOpt("pathPrefix", &pathPrefix); !ok { + pathPrefix = "/twirp" // default prefix + } + + // Build method URLs: <baseURL>[<prefix>]/<package>.<Service>/<Method> + serviceURL := sanitizeBaseURL(baseURL) + serviceURL += baseServicePath(pathPrefix, "applications", "ApplicationsService") + urls := [6]string{ + serviceURL + "CreateApplication", + serviceURL + "ListApplications", + serviceURL + "GetApplication", + serviceURL + "UpdateApplication", + serviceURL + "DeleteApplication", + serviceURL + "RegenerateKey", + } + + return &applicationsServiceJSONClient{ + client: client, + urls: urls, + interceptor: twirp.ChainInterceptors(clientOpts.Interceptors...), + opts: clientOpts, + } +} + +func (c *applicationsServiceJSONClient) CreateApplication(ctx context.Context, in *CreateApplicationRequest) (*CreateApplicationResponse, error) { + ctx = ctxsetters.WithPackageName(ctx, "applications") + ctx = ctxsetters.WithServiceName(ctx, "ApplicationsService") + ctx = ctxsetters.WithMethodName(ctx, "CreateApplication") + caller := c.callCreateApplication + if c.interceptor != nil { + caller = func(ctx context.Context, req *CreateApplicationRequest) (*CreateApplicationResponse, error) { + resp, err := c.interceptor( + func(ctx context.Context, req interface{}) (interface{}, error) { + typedReq, ok := req.(*CreateApplicationRequest) + if !ok { + return nil, twirp.InternalError("failed type assertion req.(*CreateApplicationRequest) when calling interceptor") + } + return c.callCreateApplication(ctx, typedReq) + }, + )(ctx, req) + if resp != nil { + typedResp, ok := resp.(*CreateApplicationResponse) + if !ok { + return nil, twirp.InternalError("failed type assertion resp.(*CreateApplicationResponse) when calling interceptor") + } + return typedResp, err + } + return nil, err + } + } + return caller(ctx, in) +} + +func (c *applicationsServiceJSONClient) callCreateApplication(ctx context.Context, in *CreateApplicationRequest) (*CreateApplicationResponse, error) { + out := new(CreateApplicationResponse) + ctx, err := doJSONRequest(ctx, c.client, c.opts.Hooks, c.urls[0], in, out) + if err != nil { + twerr, ok := err.(twirp.Error) + if !ok { + twerr = twirp.InternalErrorWith(err) + } + callClientError(ctx, c.opts.Hooks, twerr) + return nil, err + } + + callClientResponseReceived(ctx, c.opts.Hooks) + + return out, nil +} + +func (c *applicationsServiceJSONClient) ListApplications(ctx context.Context, in *ListApplicationsRequest) (*ListApplicationsResponse, error) { + ctx = ctxsetters.WithPackageName(ctx, "applications") + ctx = ctxsetters.WithServiceName(ctx, "ApplicationsService") + ctx = ctxsetters.WithMethodName(ctx, "ListApplications") + caller := c.callListApplications + if c.interceptor != nil { + caller = func(ctx context.Context, req *ListApplicationsRequest) (*ListApplicationsResponse, error) { + resp, err := c.interceptor( + func(ctx context.Context, req interface{}) (interface{}, error) { + typedReq, ok := req.(*ListApplicationsRequest) + if !ok { + return nil, twirp.InternalError("failed type assertion req.(*ListApplicationsRequest) when calling interceptor") + } + return c.callListApplications(ctx, typedReq) + }, + )(ctx, req) + if resp != nil { + typedResp, ok := resp.(*ListApplicationsResponse) + if !ok { + return nil, twirp.InternalError("failed type assertion resp.(*ListApplicationsResponse) when calling interceptor") + } + return typedResp, err + } + return nil, err + } + } + return caller(ctx, in) +} + +func (c *applicationsServiceJSONClient) callListApplications(ctx context.Context, in *ListApplicationsRequest) (*ListApplicationsResponse, error) { + out := new(ListApplicationsResponse) + ctx, err := doJSONRequest(ctx, c.client, c.opts.Hooks, c.urls[1], in, out) + if err != nil { + twerr, ok := err.(twirp.Error) + if !ok { + twerr = twirp.InternalErrorWith(err) + } + callClientError(ctx, c.opts.Hooks, twerr) + return nil, err + } + + callClientResponseReceived(ctx, c.opts.Hooks) + + return out, nil +} + +func (c *applicationsServiceJSONClient) GetApplication(ctx context.Context, in *GetApplicationRequest) (*GetApplicationResponse, error) { + ctx = ctxsetters.WithPackageName(ctx, "applications") + ctx = ctxsetters.WithServiceName(ctx, "ApplicationsService") + ctx = ctxsetters.WithMethodName(ctx, "GetApplication") + caller := c.callGetApplication + if c.interceptor != nil { + caller = func(ctx context.Context, req *GetApplicationRequest) (*GetApplicationResponse, error) { + resp, err := c.interceptor( + func(ctx context.Context, req interface{}) (interface{}, error) { + typedReq, ok := req.(*GetApplicationRequest) + if !ok { + return nil, twirp.InternalError("failed type assertion req.(*GetApplicationRequest) when calling interceptor") + } + return c.callGetApplication(ctx, typedReq) + }, + )(ctx, req) + if resp != nil { + typedResp, ok := resp.(*GetApplicationResponse) + if !ok { + return nil, twirp.InternalError("failed type assertion resp.(*GetApplicationResponse) when calling interceptor") + } + return typedResp, err + } + return nil, err + } + } + return caller(ctx, in) +} + +func (c *applicationsServiceJSONClient) callGetApplication(ctx context.Context, in *GetApplicationRequest) (*GetApplicationResponse, error) { + out := new(GetApplicationResponse) + ctx, err := doJSONRequest(ctx, c.client, c.opts.Hooks, c.urls[2], in, out) + if err != nil { + twerr, ok := err.(twirp.Error) + if !ok { + twerr = twirp.InternalErrorWith(err) + } + callClientError(ctx, c.opts.Hooks, twerr) + return nil, err + } + + callClientResponseReceived(ctx, c.opts.Hooks) + + return out, nil +} + +func (c *applicationsServiceJSONClient) UpdateApplication(ctx context.Context, in *UpdateApplicationRequest) (*UpdateApplicationResponse, error) { + ctx = ctxsetters.WithPackageName(ctx, "applications") + ctx = ctxsetters.WithServiceName(ctx, "ApplicationsService") + ctx = ctxsetters.WithMethodName(ctx, "UpdateApplication") + caller := c.callUpdateApplication + if c.interceptor != nil { + caller = func(ctx context.Context, req *UpdateApplicationRequest) (*UpdateApplicationResponse, error) { + resp, err := c.interceptor( + func(ctx context.Context, req interface{}) (interface{}, error) { + typedReq, ok := req.(*UpdateApplicationRequest) + if !ok { + return nil, twirp.InternalError("failed type assertion req.(*UpdateApplicationRequest) when calling interceptor") + } + return c.callUpdateApplication(ctx, typedReq) + }, + )(ctx, req) + if resp != nil { + typedResp, ok := resp.(*UpdateApplicationResponse) + if !ok { + return nil, twirp.InternalError("failed type assertion resp.(*UpdateApplicationResponse) when calling interceptor") + } + return typedResp, err + } + return nil, err + } + } + return caller(ctx, in) +} + +func (c *applicationsServiceJSONClient) callUpdateApplication(ctx context.Context, in *UpdateApplicationRequest) (*UpdateApplicationResponse, error) { + out := new(UpdateApplicationResponse) + ctx, err := doJSONRequest(ctx, c.client, c.opts.Hooks, c.urls[3], in, out) + if err != nil { + twerr, ok := err.(twirp.Error) + if !ok { + twerr = twirp.InternalErrorWith(err) + } + callClientError(ctx, c.opts.Hooks, twerr) + return nil, err + } + + callClientResponseReceived(ctx, c.opts.Hooks) + + return out, nil +} + +func (c *applicationsServiceJSONClient) DeleteApplication(ctx context.Context, in *DeleteApplicationRequest) (*DeleteApplicationResponse, error) { + ctx = ctxsetters.WithPackageName(ctx, "applications") + ctx = ctxsetters.WithServiceName(ctx, "ApplicationsService") + ctx = ctxsetters.WithMethodName(ctx, "DeleteApplication") + caller := c.callDeleteApplication + if c.interceptor != nil { + caller = func(ctx context.Context, req *DeleteApplicationRequest) (*DeleteApplicationResponse, error) { + resp, err := c.interceptor( + func(ctx context.Context, req interface{}) (interface{}, error) { + typedReq, ok := req.(*DeleteApplicationRequest) + if !ok { + return nil, twirp.InternalError("failed type assertion req.(*DeleteApplicationRequest) when calling interceptor") + } + return c.callDeleteApplication(ctx, typedReq) + }, + )(ctx, req) + if resp != nil { + typedResp, ok := resp.(*DeleteApplicationResponse) + if !ok { + return nil, twirp.InternalError("failed type assertion resp.(*DeleteApplicationResponse) when calling interceptor") + } + return typedResp, err + } + return nil, err + } + } + return caller(ctx, in) +} + +func (c *applicationsServiceJSONClient) callDeleteApplication(ctx context.Context, in *DeleteApplicationRequest) (*DeleteApplicationResponse, error) { + out := new(DeleteApplicationResponse) + ctx, err := doJSONRequest(ctx, c.client, c.opts.Hooks, c.urls[4], in, out) + if err != nil { + twerr, ok := err.(twirp.Error) + if !ok { + twerr = twirp.InternalErrorWith(err) + } + callClientError(ctx, c.opts.Hooks, twerr) + return nil, err + } + + callClientResponseReceived(ctx, c.opts.Hooks) + + return out, nil +} + +func (c *applicationsServiceJSONClient) RegenerateKey(ctx context.Context, in *RegenerateKeyRequest) (*RegenerateKeyResponse, error) { + ctx = ctxsetters.WithPackageName(ctx, "applications") + ctx = ctxsetters.WithServiceName(ctx, "ApplicationsService") + ctx = ctxsetters.WithMethodName(ctx, "RegenerateKey") + caller := c.callRegenerateKey + if c.interceptor != nil { + caller = func(ctx context.Context, req *RegenerateKeyRequest) (*RegenerateKeyResponse, error) { + resp, err := c.interceptor( + func(ctx context.Context, req interface{}) (interface{}, error) { + typedReq, ok := req.(*RegenerateKeyRequest) + if !ok { + return nil, twirp.InternalError("failed type assertion req.(*RegenerateKeyRequest) when calling interceptor") + } + return c.callRegenerateKey(ctx, typedReq) + }, + )(ctx, req) + if resp != nil { + typedResp, ok := resp.(*RegenerateKeyResponse) + if !ok { + return nil, twirp.InternalError("failed type assertion resp.(*RegenerateKeyResponse) when calling interceptor") + } + return typedResp, err + } + return nil, err + } + } + return caller(ctx, in) +} + +func (c *applicationsServiceJSONClient) callRegenerateKey(ctx context.Context, in *RegenerateKeyRequest) (*RegenerateKeyResponse, error) { + out := new(RegenerateKeyResponse) + ctx, err := doJSONRequest(ctx, c.client, c.opts.Hooks, c.urls[5], in, out) + if err != nil { + twerr, ok := err.(twirp.Error) + if !ok { + twerr = twirp.InternalErrorWith(err) + } + callClientError(ctx, c.opts.Hooks, twerr) + return nil, err + } + + callClientResponseReceived(ctx, c.opts.Hooks) + + return out, nil +} + +// ================================== +// ApplicationsService Server Handler +// ================================== + +type applicationsServiceServer struct { + ApplicationsService + interceptor twirp.Interceptor + hooks *twirp.ServerHooks + pathPrefix string // prefix for routing + jsonSkipDefaults bool // do not include unpopulated fields (default values) in the response + jsonCamelCase bool // JSON fields are serialized as lowerCamelCase rather than keeping the original proto names +} + +// NewApplicationsServiceServer builds a TwirpServer that can be used as an http.Handler to handle +// HTTP requests that are routed to the right method in the provided svc implementation. +// The opts are twirp.ServerOption modifiers, for example twirp.WithServerHooks(hooks). +func NewApplicationsServiceServer(svc ApplicationsService, opts ...interface{}) TwirpServer { + serverOpts := newServerOpts(opts) + + // Using ReadOpt allows backwards and forwards compatibility with new options in the future + jsonSkipDefaults := false + _ = serverOpts.ReadOpt("jsonSkipDefaults", &jsonSkipDefaults) + jsonCamelCase := false + _ = serverOpts.ReadOpt("jsonCamelCase", &jsonCamelCase) + var pathPrefix string + if ok := serverOpts.ReadOpt("pathPrefix", &pathPrefix); !ok { + pathPrefix = "/twirp" // default prefix + } + + return &applicationsServiceServer{ + ApplicationsService: svc, + hooks: serverOpts.Hooks, + interceptor: twirp.ChainInterceptors(serverOpts.Interceptors...), + pathPrefix: pathPrefix, + jsonSkipDefaults: jsonSkipDefaults, + jsonCamelCase: jsonCamelCase, + } +} + +// writeError writes an HTTP response with a valid Twirp error format, and triggers hooks. +// If err is not a twirp.Error, it will get wrapped with twirp.InternalErrorWith(err) +func (s *applicationsServiceServer) writeError(ctx context.Context, resp http.ResponseWriter, err error) { + writeError(ctx, resp, err, s.hooks) +} + +// handleRequestBodyError is used to handle error when the twirp server cannot read request +func (s *applicationsServiceServer) handleRequestBodyError(ctx context.Context, resp http.ResponseWriter, msg string, err error) { + if context.Canceled == ctx.Err() { + s.writeError(ctx, resp, twirp.NewError(twirp.Canceled, "failed to read request: context canceled")) + return + } + if context.DeadlineExceeded == ctx.Err() { + s.writeError(ctx, resp, twirp.NewError(twirp.DeadlineExceeded, "failed to read request: deadline exceeded")) + return + } + s.writeError(ctx, resp, twirp.WrapError(malformedRequestError(msg), err)) +} + +// ApplicationsServicePathPrefix is a convenience constant that may identify URL paths. +// Should be used with caution, it only matches routes generated by Twirp Go clients, +// with the default "/twirp" prefix and default CamelCase service and method names. +// More info: https://twitchtv.github.io/twirp/docs/routing.html +const ApplicationsServicePathPrefix = "/twirp/applications.ApplicationsService/" + +func (s *applicationsServiceServer) ServeHTTP(resp http.ResponseWriter, req *http.Request) { + ctx := req.Context() + ctx = ctxsetters.WithPackageName(ctx, "applications") + ctx = ctxsetters.WithServiceName(ctx, "ApplicationsService") + ctx = ctxsetters.WithResponseWriter(ctx, resp) + + var err error + ctx, err = callRequestReceived(ctx, s.hooks) + if err != nil { + s.writeError(ctx, resp, err) + return + } + + if req.Method != "POST" { + msg := fmt.Sprintf("unsupported method %q (only POST is allowed)", req.Method) + s.writeError(ctx, resp, badRouteError(msg, req.Method, req.URL.Path)) + return + } + + // Verify path format: [<prefix>]/<package>.<Service>/<Method> + prefix, pkgService, method := parseTwirpPath(req.URL.Path) + if pkgService != "applications.ApplicationsService" { + msg := fmt.Sprintf("no handler for path %q", req.URL.Path) + s.writeError(ctx, resp, badRouteError(msg, req.Method, req.URL.Path)) + return + } + if prefix != s.pathPrefix { + msg := fmt.Sprintf("invalid path prefix %q, expected %q, on path %q", prefix, s.pathPrefix, req.URL.Path) + s.writeError(ctx, resp, badRouteError(msg, req.Method, req.URL.Path)) + return + } + + switch method { + case "CreateApplication": + s.serveCreateApplication(ctx, resp, req) + return + case "ListApplications": + s.serveListApplications(ctx, resp, req) + return + case "GetApplication": + s.serveGetApplication(ctx, resp, req) + return + case "UpdateApplication": + s.serveUpdateApplication(ctx, resp, req) + return + case "DeleteApplication": + s.serveDeleteApplication(ctx, resp, req) + return + case "RegenerateKey": + s.serveRegenerateKey(ctx, resp, req) + return + default: + msg := fmt.Sprintf("no handler for path %q", req.URL.Path) + s.writeError(ctx, resp, badRouteError(msg, req.Method, req.URL.Path)) + return + } +} + +func (s *applicationsServiceServer) serveCreateApplication(ctx context.Context, resp http.ResponseWriter, req *http.Request) { + header := req.Header.Get("Content-Type") + i := strings.Index(header, ";") + if i == -1 { + i = len(header) + } + switch strings.TrimSpace(strings.ToLower(header[:i])) { + case "application/json": + s.serveCreateApplicationJSON(ctx, resp, req) + case "application/protobuf": + s.serveCreateApplicationProtobuf(ctx, resp, req) + default: + msg := fmt.Sprintf("unexpected Content-Type: %q", req.Header.Get("Content-Type")) + twerr := badRouteError(msg, req.Method, req.URL.Path) + s.writeError(ctx, resp, twerr) + } +} + +func (s *applicationsServiceServer) serveCreateApplicationJSON(ctx context.Context, resp http.ResponseWriter, req *http.Request) { + var err error + ctx = ctxsetters.WithMethodName(ctx, "CreateApplication") + ctx, err = callRequestRouted(ctx, s.hooks) + if err != nil { + s.writeError(ctx, resp, err) + return + } + + d := json.NewDecoder(req.Body) + rawReqBody := json.RawMessage{} + if err := d.Decode(&rawReqBody); err != nil { + s.handleRequestBodyError(ctx, resp, "the json request could not be decoded", err) + return + } + reqContent := new(CreateApplicationRequest) + unmarshaler := protojson.UnmarshalOptions{DiscardUnknown: true} + if err = unmarshaler.Unmarshal(rawReqBody, reqContent); err != nil { + s.handleRequestBodyError(ctx, resp, "the json request could not be decoded", err) + return + } + + handler := s.ApplicationsService.CreateApplication + if s.interceptor != nil { + handler = func(ctx context.Context, req *CreateApplicationRequest) (*CreateApplicationResponse, error) { + resp, err := s.interceptor( + func(ctx context.Context, req interface{}) (interface{}, error) { + typedReq, ok := req.(*CreateApplicationRequest) + if !ok { + return nil, twirp.InternalError("failed type assertion req.(*CreateApplicationRequest) when calling interceptor") + } + return s.ApplicationsService.CreateApplication(ctx, typedReq) + }, + )(ctx, req) + if resp != nil { + typedResp, ok := resp.(*CreateApplicationResponse) + if !ok { + return nil, twirp.InternalError("failed type assertion resp.(*CreateApplicationResponse) when calling interceptor") + } + return typedResp, err + } + return nil, err + } + } + + // Call service method + var respContent *CreateApplicationResponse + func() { + defer ensurePanicResponses(ctx, resp, s.hooks) + respContent, err = handler(ctx, reqContent) + }() + + if err != nil { + s.writeError(ctx, resp, err) + return + } + if respContent == nil { + s.writeError(ctx, resp, twirp.InternalError("received a nil *CreateApplicationResponse and nil error while calling CreateApplication. nil responses are not supported")) + return + } + + ctx = callResponsePrepared(ctx, s.hooks) + + marshaler := &protojson.MarshalOptions{UseProtoNames: !s.jsonCamelCase, EmitUnpopulated: !s.jsonSkipDefaults} + respBytes, err := marshaler.Marshal(respContent) + if err != nil { + s.writeError(ctx, resp, wrapInternal(err, "failed to marshal json response")) + return + } + + ctx = ctxsetters.WithStatusCode(ctx, http.StatusOK) + resp.Header().Set("Content-Type", "application/json") + resp.Header().Set("Content-Length", strconv.Itoa(len(respBytes))) + resp.WriteHeader(http.StatusOK) + + if n, err := resp.Write(respBytes); err != nil { + msg := fmt.Sprintf("failed to write response, %d of %d bytes written: %s", n, len(respBytes), err.Error()) + twerr := twirp.NewError(twirp.Unknown, msg) + ctx = callError(ctx, s.hooks, twerr) + } + callResponseSent(ctx, s.hooks) +} + +func (s *applicationsServiceServer) serveCreateApplicationProtobuf(ctx context.Context, resp http.ResponseWriter, req *http.Request) { + var err error + ctx = ctxsetters.WithMethodName(ctx, "CreateApplication") + ctx, err = callRequestRouted(ctx, s.hooks) + if err != nil { + s.writeError(ctx, resp, err) + return + } + + buf, err := io.ReadAll(req.Body) + if err != nil { + s.handleRequestBodyError(ctx, resp, "failed to read request body", err) + return + } + reqContent := new(CreateApplicationRequest) + if err = proto.Unmarshal(buf, reqContent); err != nil { + s.writeError(ctx, resp, malformedRequestError("the protobuf request could not be decoded")) + return + } + + handler := s.ApplicationsService.CreateApplication + if s.interceptor != nil { + handler = func(ctx context.Context, req *CreateApplicationRequest) (*CreateApplicationResponse, error) { + resp, err := s.interceptor( + func(ctx context.Context, req interface{}) (interface{}, error) { + typedReq, ok := req.(*CreateApplicationRequest) + if !ok { + return nil, twirp.InternalError("failed type assertion req.(*CreateApplicationRequest) when calling interceptor") + } + return s.ApplicationsService.CreateApplication(ctx, typedReq) + }, + )(ctx, req) + if resp != nil { + typedResp, ok := resp.(*CreateApplicationResponse) + if !ok { + return nil, twirp.InternalError("failed type assertion resp.(*CreateApplicationResponse) when calling interceptor") + } + return typedResp, err + } + return nil, err + } + } + + // Call service method + var respContent *CreateApplicationResponse + func() { + defer ensurePanicResponses(ctx, resp, s.hooks) + respContent, err = handler(ctx, reqContent) + }() + + if err != nil { + s.writeError(ctx, resp, err) + return + } + if respContent == nil { + s.writeError(ctx, resp, twirp.InternalError("received a nil *CreateApplicationResponse and nil error while calling CreateApplication. nil responses are not supported")) + return + } + + ctx = callResponsePrepared(ctx, s.hooks) + + respBytes, err := proto.Marshal(respContent) + if err != nil { + s.writeError(ctx, resp, wrapInternal(err, "failed to marshal proto response")) + return + } + + ctx = ctxsetters.WithStatusCode(ctx, http.StatusOK) + resp.Header().Set("Content-Type", "application/protobuf") + resp.Header().Set("Content-Length", strconv.Itoa(len(respBytes))) + resp.WriteHeader(http.StatusOK) + if n, err := resp.Write(respBytes); err != nil { + msg := fmt.Sprintf("failed to write response, %d of %d bytes written: %s", n, len(respBytes), err.Error()) + twerr := twirp.NewError(twirp.Unknown, msg) + ctx = callError(ctx, s.hooks, twerr) + } + callResponseSent(ctx, s.hooks) +} + +func (s *applicationsServiceServer) serveListApplications(ctx context.Context, resp http.ResponseWriter, req *http.Request) { + header := req.Header.Get("Content-Type") + i := strings.Index(header, ";") + if i == -1 { + i = len(header) + } + switch strings.TrimSpace(strings.ToLower(header[:i])) { + case "application/json": + s.serveListApplicationsJSON(ctx, resp, req) + case "application/protobuf": + s.serveListApplicationsProtobuf(ctx, resp, req) + default: + msg := fmt.Sprintf("unexpected Content-Type: %q", req.Header.Get("Content-Type")) + twerr := badRouteError(msg, req.Method, req.URL.Path) + s.writeError(ctx, resp, twerr) + } +} + +func (s *applicationsServiceServer) serveListApplicationsJSON(ctx context.Context, resp http.ResponseWriter, req *http.Request) { + var err error + ctx = ctxsetters.WithMethodName(ctx, "ListApplications") + ctx, err = callRequestRouted(ctx, s.hooks) + if err != nil { + s.writeError(ctx, resp, err) + return + } + + d := json.NewDecoder(req.Body) + rawReqBody := json.RawMessage{} + if err := d.Decode(&rawReqBody); err != nil { + s.handleRequestBodyError(ctx, resp, "the json request could not be decoded", err) + return + } + reqContent := new(ListApplicationsRequest) + unmarshaler := protojson.UnmarshalOptions{DiscardUnknown: true} + if err = unmarshaler.Unmarshal(rawReqBody, reqContent); err != nil { + s.handleRequestBodyError(ctx, resp, "the json request could not be decoded", err) + return + } + + handler := s.ApplicationsService.ListApplications + if s.interceptor != nil { + handler = func(ctx context.Context, req *ListApplicationsRequest) (*ListApplicationsResponse, error) { + resp, err := s.interceptor( + func(ctx context.Context, req interface{}) (interface{}, error) { + typedReq, ok := req.(*ListApplicationsRequest) + if !ok { + return nil, twirp.InternalError("failed type assertion req.(*ListApplicationsRequest) when calling interceptor") + } + return s.ApplicationsService.ListApplications(ctx, typedReq) + }, + )(ctx, req) + if resp != nil { + typedResp, ok := resp.(*ListApplicationsResponse) + if !ok { + return nil, twirp.InternalError("failed type assertion resp.(*ListApplicationsResponse) when calling interceptor") + } + return typedResp, err + } + return nil, err + } + } + + // Call service method + var respContent *ListApplicationsResponse + func() { + defer ensurePanicResponses(ctx, resp, s.hooks) + respContent, err = handler(ctx, reqContent) + }() + + if err != nil { + s.writeError(ctx, resp, err) + return + } + if respContent == nil { + s.writeError(ctx, resp, twirp.InternalError("received a nil *ListApplicationsResponse and nil error while calling ListApplications. nil responses are not supported")) + return + } + + ctx = callResponsePrepared(ctx, s.hooks) + + marshaler := &protojson.MarshalOptions{UseProtoNames: !s.jsonCamelCase, EmitUnpopulated: !s.jsonSkipDefaults} + respBytes, err := marshaler.Marshal(respContent) + if err != nil { + s.writeError(ctx, resp, wrapInternal(err, "failed to marshal json response")) + return + } + + ctx = ctxsetters.WithStatusCode(ctx, http.StatusOK) + resp.Header().Set("Content-Type", "application/json") + resp.Header().Set("Content-Length", strconv.Itoa(len(respBytes))) + resp.WriteHeader(http.StatusOK) + + if n, err := resp.Write(respBytes); err != nil { + msg := fmt.Sprintf("failed to write response, %d of %d bytes written: %s", n, len(respBytes), err.Error()) + twerr := twirp.NewError(twirp.Unknown, msg) + ctx = callError(ctx, s.hooks, twerr) + } + callResponseSent(ctx, s.hooks) +} + +func (s *applicationsServiceServer) serveListApplicationsProtobuf(ctx context.Context, resp http.ResponseWriter, req *http.Request) { + var err error + ctx = ctxsetters.WithMethodName(ctx, "ListApplications") + ctx, err = callRequestRouted(ctx, s.hooks) + if err != nil { + s.writeError(ctx, resp, err) + return + } + + buf, err := io.ReadAll(req.Body) + if err != nil { + s.handleRequestBodyError(ctx, resp, "failed to read request body", err) + return + } + reqContent := new(ListApplicationsRequest) + if err = proto.Unmarshal(buf, reqContent); err != nil { + s.writeError(ctx, resp, malformedRequestError("the protobuf request could not be decoded")) + return + } + + handler := s.ApplicationsService.ListApplications + if s.interceptor != nil { + handler = func(ctx context.Context, req *ListApplicationsRequest) (*ListApplicationsResponse, error) { + resp, err := s.interceptor( + func(ctx context.Context, req interface{}) (interface{}, error) { + typedReq, ok := req.(*ListApplicationsRequest) + if !ok { + return nil, twirp.InternalError("failed type assertion req.(*ListApplicationsRequest) when calling interceptor") + } + return s.ApplicationsService.ListApplications(ctx, typedReq) + }, + )(ctx, req) + if resp != nil { + typedResp, ok := resp.(*ListApplicationsResponse) + if !ok { + return nil, twirp.InternalError("failed type assertion resp.(*ListApplicationsResponse) when calling interceptor") + } + return typedResp, err + } + return nil, err + } + } + + // Call service method + var respContent *ListApplicationsResponse + func() { + defer ensurePanicResponses(ctx, resp, s.hooks) + respContent, err = handler(ctx, reqContent) + }() + + if err != nil { + s.writeError(ctx, resp, err) + return + } + if respContent == nil { + s.writeError(ctx, resp, twirp.InternalError("received a nil *ListApplicationsResponse and nil error while calling ListApplications. nil responses are not supported")) + return + } + + ctx = callResponsePrepared(ctx, s.hooks) + + respBytes, err := proto.Marshal(respContent) + if err != nil { + s.writeError(ctx, resp, wrapInternal(err, "failed to marshal proto response")) + return + } + + ctx = ctxsetters.WithStatusCode(ctx, http.StatusOK) + resp.Header().Set("Content-Type", "application/protobuf") + resp.Header().Set("Content-Length", strconv.Itoa(len(respBytes))) + resp.WriteHeader(http.StatusOK) + if n, err := resp.Write(respBytes); err != nil { + msg := fmt.Sprintf("failed to write response, %d of %d bytes written: %s", n, len(respBytes), err.Error()) + twerr := twirp.NewError(twirp.Unknown, msg) + ctx = callError(ctx, s.hooks, twerr) + } + callResponseSent(ctx, s.hooks) +} + +func (s *applicationsServiceServer) serveGetApplication(ctx context.Context, resp http.ResponseWriter, req *http.Request) { + header := req.Header.Get("Content-Type") + i := strings.Index(header, ";") + if i == -1 { + i = len(header) + } + switch strings.TrimSpace(strings.ToLower(header[:i])) { + case "application/json": + s.serveGetApplicationJSON(ctx, resp, req) + case "application/protobuf": + s.serveGetApplicationProtobuf(ctx, resp, req) + default: + msg := fmt.Sprintf("unexpected Content-Type: %q", req.Header.Get("Content-Type")) + twerr := badRouteError(msg, req.Method, req.URL.Path) + s.writeError(ctx, resp, twerr) + } +} + +func (s *applicationsServiceServer) serveGetApplicationJSON(ctx context.Context, resp http.ResponseWriter, req *http.Request) { + var err error + ctx = ctxsetters.WithMethodName(ctx, "GetApplication") + ctx, err = callRequestRouted(ctx, s.hooks) + if err != nil { + s.writeError(ctx, resp, err) + return + } + + d := json.NewDecoder(req.Body) + rawReqBody := json.RawMessage{} + if err := d.Decode(&rawReqBody); err != nil { + s.handleRequestBodyError(ctx, resp, "the json request could not be decoded", err) + return + } + reqContent := new(GetApplicationRequest) + unmarshaler := protojson.UnmarshalOptions{DiscardUnknown: true} + if err = unmarshaler.Unmarshal(rawReqBody, reqContent); err != nil { + s.handleRequestBodyError(ctx, resp, "the json request could not be decoded", err) + return + } + + handler := s.ApplicationsService.GetApplication + if s.interceptor != nil { + handler = func(ctx context.Context, req *GetApplicationRequest) (*GetApplicationResponse, error) { + resp, err := s.interceptor( + func(ctx context.Context, req interface{}) (interface{}, error) { + typedReq, ok := req.(*GetApplicationRequest) + if !ok { + return nil, twirp.InternalError("failed type assertion req.(*GetApplicationRequest) when calling interceptor") + } + return s.ApplicationsService.GetApplication(ctx, typedReq) + }, + )(ctx, req) + if resp != nil { + typedResp, ok := resp.(*GetApplicationResponse) + if !ok { + return nil, twirp.InternalError("failed type assertion resp.(*GetApplicationResponse) when calling interceptor") + } + return typedResp, err + } + return nil, err + } + } + + // Call service method + var respContent *GetApplicationResponse + func() { + defer ensurePanicResponses(ctx, resp, s.hooks) + respContent, err = handler(ctx, reqContent) + }() + + if err != nil { + s.writeError(ctx, resp, err) + return + } + if respContent == nil { + s.writeError(ctx, resp, twirp.InternalError("received a nil *GetApplicationResponse and nil error while calling GetApplication. nil responses are not supported")) + return + } + + ctx = callResponsePrepared(ctx, s.hooks) + + marshaler := &protojson.MarshalOptions{UseProtoNames: !s.jsonCamelCase, EmitUnpopulated: !s.jsonSkipDefaults} + respBytes, err := marshaler.Marshal(respContent) + if err != nil { + s.writeError(ctx, resp, wrapInternal(err, "failed to marshal json response")) + return + } + + ctx = ctxsetters.WithStatusCode(ctx, http.StatusOK) + resp.Header().Set("Content-Type", "application/json") + resp.Header().Set("Content-Length", strconv.Itoa(len(respBytes))) + resp.WriteHeader(http.StatusOK) + + if n, err := resp.Write(respBytes); err != nil { + msg := fmt.Sprintf("failed to write response, %d of %d bytes written: %s", n, len(respBytes), err.Error()) + twerr := twirp.NewError(twirp.Unknown, msg) + ctx = callError(ctx, s.hooks, twerr) + } + callResponseSent(ctx, s.hooks) +} + +func (s *applicationsServiceServer) serveGetApplicationProtobuf(ctx context.Context, resp http.ResponseWriter, req *http.Request) { + var err error + ctx = ctxsetters.WithMethodName(ctx, "GetApplication") + ctx, err = callRequestRouted(ctx, s.hooks) + if err != nil { + s.writeError(ctx, resp, err) + return + } + + buf, err := io.ReadAll(req.Body) + if err != nil { + s.handleRequestBodyError(ctx, resp, "failed to read request body", err) + return + } + reqContent := new(GetApplicationRequest) + if err = proto.Unmarshal(buf, reqContent); err != nil { + s.writeError(ctx, resp, malformedRequestError("the protobuf request could not be decoded")) + return + } + + handler := s.ApplicationsService.GetApplication + if s.interceptor != nil { + handler = func(ctx context.Context, req *GetApplicationRequest) (*GetApplicationResponse, error) { + resp, err := s.interceptor( + func(ctx context.Context, req interface{}) (interface{}, error) { + typedReq, ok := req.(*GetApplicationRequest) + if !ok { + return nil, twirp.InternalError("failed type assertion req.(*GetApplicationRequest) when calling interceptor") + } + return s.ApplicationsService.GetApplication(ctx, typedReq) + }, + )(ctx, req) + if resp != nil { + typedResp, ok := resp.(*GetApplicationResponse) + if !ok { + return nil, twirp.InternalError("failed type assertion resp.(*GetApplicationResponse) when calling interceptor") + } + return typedResp, err + } + return nil, err + } + } + + // Call service method + var respContent *GetApplicationResponse + func() { + defer ensurePanicResponses(ctx, resp, s.hooks) + respContent, err = handler(ctx, reqContent) + }() + + if err != nil { + s.writeError(ctx, resp, err) + return + } + if respContent == nil { + s.writeError(ctx, resp, twirp.InternalError("received a nil *GetApplicationResponse and nil error while calling GetApplication. nil responses are not supported")) + return + } + + ctx = callResponsePrepared(ctx, s.hooks) + + respBytes, err := proto.Marshal(respContent) + if err != nil { + s.writeError(ctx, resp, wrapInternal(err, "failed to marshal proto response")) + return + } + + ctx = ctxsetters.WithStatusCode(ctx, http.StatusOK) + resp.Header().Set("Content-Type", "application/protobuf") + resp.Header().Set("Content-Length", strconv.Itoa(len(respBytes))) + resp.WriteHeader(http.StatusOK) + if n, err := resp.Write(respBytes); err != nil { + msg := fmt.Sprintf("failed to write response, %d of %d bytes written: %s", n, len(respBytes), err.Error()) + twerr := twirp.NewError(twirp.Unknown, msg) + ctx = callError(ctx, s.hooks, twerr) + } + callResponseSent(ctx, s.hooks) +} + +func (s *applicationsServiceServer) serveUpdateApplication(ctx context.Context, resp http.ResponseWriter, req *http.Request) { + header := req.Header.Get("Content-Type") + i := strings.Index(header, ";") + if i == -1 { + i = len(header) + } + switch strings.TrimSpace(strings.ToLower(header[:i])) { + case "application/json": + s.serveUpdateApplicationJSON(ctx, resp, req) + case "application/protobuf": + s.serveUpdateApplicationProtobuf(ctx, resp, req) + default: + msg := fmt.Sprintf("unexpected Content-Type: %q", req.Header.Get("Content-Type")) + twerr := badRouteError(msg, req.Method, req.URL.Path) + s.writeError(ctx, resp, twerr) + } +} + +func (s *applicationsServiceServer) serveUpdateApplicationJSON(ctx context.Context, resp http.ResponseWriter, req *http.Request) { + var err error + ctx = ctxsetters.WithMethodName(ctx, "UpdateApplication") + ctx, err = callRequestRouted(ctx, s.hooks) + if err != nil { + s.writeError(ctx, resp, err) + return + } + + d := json.NewDecoder(req.Body) + rawReqBody := json.RawMessage{} + if err := d.Decode(&rawReqBody); err != nil { + s.handleRequestBodyError(ctx, resp, "the json request could not be decoded", err) + return + } + reqContent := new(UpdateApplicationRequest) + unmarshaler := protojson.UnmarshalOptions{DiscardUnknown: true} + if err = unmarshaler.Unmarshal(rawReqBody, reqContent); err != nil { + s.handleRequestBodyError(ctx, resp, "the json request could not be decoded", err) + return + } + + handler := s.ApplicationsService.UpdateApplication + if s.interceptor != nil { + handler = func(ctx context.Context, req *UpdateApplicationRequest) (*UpdateApplicationResponse, error) { + resp, err := s.interceptor( + func(ctx context.Context, req interface{}) (interface{}, error) { + typedReq, ok := req.(*UpdateApplicationRequest) + if !ok { + return nil, twirp.InternalError("failed type assertion req.(*UpdateApplicationRequest) when calling interceptor") + } + return s.ApplicationsService.UpdateApplication(ctx, typedReq) + }, + )(ctx, req) + if resp != nil { + typedResp, ok := resp.(*UpdateApplicationResponse) + if !ok { + return nil, twirp.InternalError("failed type assertion resp.(*UpdateApplicationResponse) when calling interceptor") + } + return typedResp, err + } + return nil, err + } + } + + // Call service method + var respContent *UpdateApplicationResponse + func() { + defer ensurePanicResponses(ctx, resp, s.hooks) + respContent, err = handler(ctx, reqContent) + }() + + if err != nil { + s.writeError(ctx, resp, err) + return + } + if respContent == nil { + s.writeError(ctx, resp, twirp.InternalError("received a nil *UpdateApplicationResponse and nil error while calling UpdateApplication. nil responses are not supported")) + return + } + + ctx = callResponsePrepared(ctx, s.hooks) + + marshaler := &protojson.MarshalOptions{UseProtoNames: !s.jsonCamelCase, EmitUnpopulated: !s.jsonSkipDefaults} + respBytes, err := marshaler.Marshal(respContent) + if err != nil { + s.writeError(ctx, resp, wrapInternal(err, "failed to marshal json response")) + return + } + + ctx = ctxsetters.WithStatusCode(ctx, http.StatusOK) + resp.Header().Set("Content-Type", "application/json") + resp.Header().Set("Content-Length", strconv.Itoa(len(respBytes))) + resp.WriteHeader(http.StatusOK) + + if n, err := resp.Write(respBytes); err != nil { + msg := fmt.Sprintf("failed to write response, %d of %d bytes written: %s", n, len(respBytes), err.Error()) + twerr := twirp.NewError(twirp.Unknown, msg) + ctx = callError(ctx, s.hooks, twerr) + } + callResponseSent(ctx, s.hooks) +} + +func (s *applicationsServiceServer) serveUpdateApplicationProtobuf(ctx context.Context, resp http.ResponseWriter, req *http.Request) { + var err error + ctx = ctxsetters.WithMethodName(ctx, "UpdateApplication") + ctx, err = callRequestRouted(ctx, s.hooks) + if err != nil { + s.writeError(ctx, resp, err) + return + } + + buf, err := io.ReadAll(req.Body) + if err != nil { + s.handleRequestBodyError(ctx, resp, "failed to read request body", err) + return + } + reqContent := new(UpdateApplicationRequest) + if err = proto.Unmarshal(buf, reqContent); err != nil { + s.writeError(ctx, resp, malformedRequestError("the protobuf request could not be decoded")) + return + } + + handler := s.ApplicationsService.UpdateApplication + if s.interceptor != nil { + handler = func(ctx context.Context, req *UpdateApplicationRequest) (*UpdateApplicationResponse, error) { + resp, err := s.interceptor( + func(ctx context.Context, req interface{}) (interface{}, error) { + typedReq, ok := req.(*UpdateApplicationRequest) + if !ok { + return nil, twirp.InternalError("failed type assertion req.(*UpdateApplicationRequest) when calling interceptor") + } + return s.ApplicationsService.UpdateApplication(ctx, typedReq) + }, + )(ctx, req) + if resp != nil { + typedResp, ok := resp.(*UpdateApplicationResponse) + if !ok { + return nil, twirp.InternalError("failed type assertion resp.(*UpdateApplicationResponse) when calling interceptor") + } + return typedResp, err + } + return nil, err + } + } + + // Call service method + var respContent *UpdateApplicationResponse + func() { + defer ensurePanicResponses(ctx, resp, s.hooks) + respContent, err = handler(ctx, reqContent) + }() + + if err != nil { + s.writeError(ctx, resp, err) + return + } + if respContent == nil { + s.writeError(ctx, resp, twirp.InternalError("received a nil *UpdateApplicationResponse and nil error while calling UpdateApplication. nil responses are not supported")) + return + } + + ctx = callResponsePrepared(ctx, s.hooks) + + respBytes, err := proto.Marshal(respContent) + if err != nil { + s.writeError(ctx, resp, wrapInternal(err, "failed to marshal proto response")) + return + } + + ctx = ctxsetters.WithStatusCode(ctx, http.StatusOK) + resp.Header().Set("Content-Type", "application/protobuf") + resp.Header().Set("Content-Length", strconv.Itoa(len(respBytes))) + resp.WriteHeader(http.StatusOK) + if n, err := resp.Write(respBytes); err != nil { + msg := fmt.Sprintf("failed to write response, %d of %d bytes written: %s", n, len(respBytes), err.Error()) + twerr := twirp.NewError(twirp.Unknown, msg) + ctx = callError(ctx, s.hooks, twerr) + } + callResponseSent(ctx, s.hooks) +} + +func (s *applicationsServiceServer) serveDeleteApplication(ctx context.Context, resp http.ResponseWriter, req *http.Request) { + header := req.Header.Get("Content-Type") + i := strings.Index(header, ";") + if i == -1 { + i = len(header) + } + switch strings.TrimSpace(strings.ToLower(header[:i])) { + case "application/json": + s.serveDeleteApplicationJSON(ctx, resp, req) + case "application/protobuf": + s.serveDeleteApplicationProtobuf(ctx, resp, req) + default: + msg := fmt.Sprintf("unexpected Content-Type: %q", req.Header.Get("Content-Type")) + twerr := badRouteError(msg, req.Method, req.URL.Path) + s.writeError(ctx, resp, twerr) + } +} + +func (s *applicationsServiceServer) serveDeleteApplicationJSON(ctx context.Context, resp http.ResponseWriter, req *http.Request) { + var err error + ctx = ctxsetters.WithMethodName(ctx, "DeleteApplication") + ctx, err = callRequestRouted(ctx, s.hooks) + if err != nil { + s.writeError(ctx, resp, err) + return + } + + d := json.NewDecoder(req.Body) + rawReqBody := json.RawMessage{} + if err := d.Decode(&rawReqBody); err != nil { + s.handleRequestBodyError(ctx, resp, "the json request could not be decoded", err) + return + } + reqContent := new(DeleteApplicationRequest) + unmarshaler := protojson.UnmarshalOptions{DiscardUnknown: true} + if err = unmarshaler.Unmarshal(rawReqBody, reqContent); err != nil { + s.handleRequestBodyError(ctx, resp, "the json request could not be decoded", err) + return + } + + handler := s.ApplicationsService.DeleteApplication + if s.interceptor != nil { + handler = func(ctx context.Context, req *DeleteApplicationRequest) (*DeleteApplicationResponse, error) { + resp, err := s.interceptor( + func(ctx context.Context, req interface{}) (interface{}, error) { + typedReq, ok := req.(*DeleteApplicationRequest) + if !ok { + return nil, twirp.InternalError("failed type assertion req.(*DeleteApplicationRequest) when calling interceptor") + } + return s.ApplicationsService.DeleteApplication(ctx, typedReq) + }, + )(ctx, req) + if resp != nil { + typedResp, ok := resp.(*DeleteApplicationResponse) + if !ok { + return nil, twirp.InternalError("failed type assertion resp.(*DeleteApplicationResponse) when calling interceptor") + } + return typedResp, err + } + return nil, err + } + } + + // Call service method + var respContent *DeleteApplicationResponse + func() { + defer ensurePanicResponses(ctx, resp, s.hooks) + respContent, err = handler(ctx, reqContent) + }() + + if err != nil { + s.writeError(ctx, resp, err) + return + } + if respContent == nil { + s.writeError(ctx, resp, twirp.InternalError("received a nil *DeleteApplicationResponse and nil error while calling DeleteApplication. nil responses are not supported")) + return + } + + ctx = callResponsePrepared(ctx, s.hooks) + + marshaler := &protojson.MarshalOptions{UseProtoNames: !s.jsonCamelCase, EmitUnpopulated: !s.jsonSkipDefaults} + respBytes, err := marshaler.Marshal(respContent) + if err != nil { + s.writeError(ctx, resp, wrapInternal(err, "failed to marshal json response")) + return + } + + ctx = ctxsetters.WithStatusCode(ctx, http.StatusOK) + resp.Header().Set("Content-Type", "application/json") + resp.Header().Set("Content-Length", strconv.Itoa(len(respBytes))) + resp.WriteHeader(http.StatusOK) + + if n, err := resp.Write(respBytes); err != nil { + msg := fmt.Sprintf("failed to write response, %d of %d bytes written: %s", n, len(respBytes), err.Error()) + twerr := twirp.NewError(twirp.Unknown, msg) + ctx = callError(ctx, s.hooks, twerr) + } + callResponseSent(ctx, s.hooks) +} + +func (s *applicationsServiceServer) serveDeleteApplicationProtobuf(ctx context.Context, resp http.ResponseWriter, req *http.Request) { + var err error + ctx = ctxsetters.WithMethodName(ctx, "DeleteApplication") + ctx, err = callRequestRouted(ctx, s.hooks) + if err != nil { + s.writeError(ctx, resp, err) + return + } + + buf, err := io.ReadAll(req.Body) + if err != nil { + s.handleRequestBodyError(ctx, resp, "failed to read request body", err) + return + } + reqContent := new(DeleteApplicationRequest) + if err = proto.Unmarshal(buf, reqContent); err != nil { + s.writeError(ctx, resp, malformedRequestError("the protobuf request could not be decoded")) + return + } + + handler := s.ApplicationsService.DeleteApplication + if s.interceptor != nil { + handler = func(ctx context.Context, req *DeleteApplicationRequest) (*DeleteApplicationResponse, error) { + resp, err := s.interceptor( + func(ctx context.Context, req interface{}) (interface{}, error) { + typedReq, ok := req.(*DeleteApplicationRequest) + if !ok { + return nil, twirp.InternalError("failed type assertion req.(*DeleteApplicationRequest) when calling interceptor") + } + return s.ApplicationsService.DeleteApplication(ctx, typedReq) + }, + )(ctx, req) + if resp != nil { + typedResp, ok := resp.(*DeleteApplicationResponse) + if !ok { + return nil, twirp.InternalError("failed type assertion resp.(*DeleteApplicationResponse) when calling interceptor") + } + return typedResp, err + } + return nil, err + } + } + + // Call service method + var respContent *DeleteApplicationResponse + func() { + defer ensurePanicResponses(ctx, resp, s.hooks) + respContent, err = handler(ctx, reqContent) + }() + + if err != nil { + s.writeError(ctx, resp, err) + return + } + if respContent == nil { + s.writeError(ctx, resp, twirp.InternalError("received a nil *DeleteApplicationResponse and nil error while calling DeleteApplication. nil responses are not supported")) + return + } + + ctx = callResponsePrepared(ctx, s.hooks) + + respBytes, err := proto.Marshal(respContent) + if err != nil { + s.writeError(ctx, resp, wrapInternal(err, "failed to marshal proto response")) + return + } + + ctx = ctxsetters.WithStatusCode(ctx, http.StatusOK) + resp.Header().Set("Content-Type", "application/protobuf") + resp.Header().Set("Content-Length", strconv.Itoa(len(respBytes))) + resp.WriteHeader(http.StatusOK) + if n, err := resp.Write(respBytes); err != nil { + msg := fmt.Sprintf("failed to write response, %d of %d bytes written: %s", n, len(respBytes), err.Error()) + twerr := twirp.NewError(twirp.Unknown, msg) + ctx = callError(ctx, s.hooks, twerr) + } + callResponseSent(ctx, s.hooks) +} + +func (s *applicationsServiceServer) serveRegenerateKey(ctx context.Context, resp http.ResponseWriter, req *http.Request) { + header := req.Header.Get("Content-Type") + i := strings.Index(header, ";") + if i == -1 { + i = len(header) + } + switch strings.TrimSpace(strings.ToLower(header[:i])) { + case "application/json": + s.serveRegenerateKeyJSON(ctx, resp, req) + case "application/protobuf": + s.serveRegenerateKeyProtobuf(ctx, resp, req) + default: + msg := fmt.Sprintf("unexpected Content-Type: %q", req.Header.Get("Content-Type")) + twerr := badRouteError(msg, req.Method, req.URL.Path) + s.writeError(ctx, resp, twerr) + } +} + +func (s *applicationsServiceServer) serveRegenerateKeyJSON(ctx context.Context, resp http.ResponseWriter, req *http.Request) { + var err error + ctx = ctxsetters.WithMethodName(ctx, "RegenerateKey") + ctx, err = callRequestRouted(ctx, s.hooks) + if err != nil { + s.writeError(ctx, resp, err) + return + } + + d := json.NewDecoder(req.Body) + rawReqBody := json.RawMessage{} + if err := d.Decode(&rawReqBody); err != nil { + s.handleRequestBodyError(ctx, resp, "the json request could not be decoded", err) + return + } + reqContent := new(RegenerateKeyRequest) + unmarshaler := protojson.UnmarshalOptions{DiscardUnknown: true} + if err = unmarshaler.Unmarshal(rawReqBody, reqContent); err != nil { + s.handleRequestBodyError(ctx, resp, "the json request could not be decoded", err) + return + } + + handler := s.ApplicationsService.RegenerateKey + if s.interceptor != nil { + handler = func(ctx context.Context, req *RegenerateKeyRequest) (*RegenerateKeyResponse, error) { + resp, err := s.interceptor( + func(ctx context.Context, req interface{}) (interface{}, error) { + typedReq, ok := req.(*RegenerateKeyRequest) + if !ok { + return nil, twirp.InternalError("failed type assertion req.(*RegenerateKeyRequest) when calling interceptor") + } + return s.ApplicationsService.RegenerateKey(ctx, typedReq) + }, + )(ctx, req) + if resp != nil { + typedResp, ok := resp.(*RegenerateKeyResponse) + if !ok { + return nil, twirp.InternalError("failed type assertion resp.(*RegenerateKeyResponse) when calling interceptor") + } + return typedResp, err + } + return nil, err + } + } + + // Call service method + var respContent *RegenerateKeyResponse + func() { + defer ensurePanicResponses(ctx, resp, s.hooks) + respContent, err = handler(ctx, reqContent) + }() + + if err != nil { + s.writeError(ctx, resp, err) + return + } + if respContent == nil { + s.writeError(ctx, resp, twirp.InternalError("received a nil *RegenerateKeyResponse and nil error while calling RegenerateKey. nil responses are not supported")) + return + } + + ctx = callResponsePrepared(ctx, s.hooks) + + marshaler := &protojson.MarshalOptions{UseProtoNames: !s.jsonCamelCase, EmitUnpopulated: !s.jsonSkipDefaults} + respBytes, err := marshaler.Marshal(respContent) + if err != nil { + s.writeError(ctx, resp, wrapInternal(err, "failed to marshal json response")) + return + } + + ctx = ctxsetters.WithStatusCode(ctx, http.StatusOK) + resp.Header().Set("Content-Type", "application/json") + resp.Header().Set("Content-Length", strconv.Itoa(len(respBytes))) + resp.WriteHeader(http.StatusOK) + + if n, err := resp.Write(respBytes); err != nil { + msg := fmt.Sprintf("failed to write response, %d of %d bytes written: %s", n, len(respBytes), err.Error()) + twerr := twirp.NewError(twirp.Unknown, msg) + ctx = callError(ctx, s.hooks, twerr) + } + callResponseSent(ctx, s.hooks) +} + +func (s *applicationsServiceServer) serveRegenerateKeyProtobuf(ctx context.Context, resp http.ResponseWriter, req *http.Request) { + var err error + ctx = ctxsetters.WithMethodName(ctx, "RegenerateKey") + ctx, err = callRequestRouted(ctx, s.hooks) + if err != nil { + s.writeError(ctx, resp, err) + return + } + + buf, err := io.ReadAll(req.Body) + if err != nil { + s.handleRequestBodyError(ctx, resp, "failed to read request body", err) + return + } + reqContent := new(RegenerateKeyRequest) + if err = proto.Unmarshal(buf, reqContent); err != nil { + s.writeError(ctx, resp, malformedRequestError("the protobuf request could not be decoded")) + return + } + + handler := s.ApplicationsService.RegenerateKey + if s.interceptor != nil { + handler = func(ctx context.Context, req *RegenerateKeyRequest) (*RegenerateKeyResponse, error) { + resp, err := s.interceptor( + func(ctx context.Context, req interface{}) (interface{}, error) { + typedReq, ok := req.(*RegenerateKeyRequest) + if !ok { + return nil, twirp.InternalError("failed type assertion req.(*RegenerateKeyRequest) when calling interceptor") + } + return s.ApplicationsService.RegenerateKey(ctx, typedReq) + }, + )(ctx, req) + if resp != nil { + typedResp, ok := resp.(*RegenerateKeyResponse) + if !ok { + return nil, twirp.InternalError("failed type assertion resp.(*RegenerateKeyResponse) when calling interceptor") + } + return typedResp, err + } + return nil, err + } + } + + // Call service method + var respContent *RegenerateKeyResponse + func() { + defer ensurePanicResponses(ctx, resp, s.hooks) + respContent, err = handler(ctx, reqContent) + }() + + if err != nil { + s.writeError(ctx, resp, err) + return + } + if respContent == nil { + s.writeError(ctx, resp, twirp.InternalError("received a nil *RegenerateKeyResponse and nil error while calling RegenerateKey. nil responses are not supported")) + return + } + + ctx = callResponsePrepared(ctx, s.hooks) + + respBytes, err := proto.Marshal(respContent) + if err != nil { + s.writeError(ctx, resp, wrapInternal(err, "failed to marshal proto response")) + return + } + + ctx = ctxsetters.WithStatusCode(ctx, http.StatusOK) + resp.Header().Set("Content-Type", "application/protobuf") + resp.Header().Set("Content-Length", strconv.Itoa(len(respBytes))) + resp.WriteHeader(http.StatusOK) + if n, err := resp.Write(respBytes); err != nil { + msg := fmt.Sprintf("failed to write response, %d of %d bytes written: %s", n, len(respBytes), err.Error()) + twerr := twirp.NewError(twirp.Unknown, msg) + ctx = callError(ctx, s.hooks, twerr) + } + callResponseSent(ctx, s.hooks) +} + +func (s *applicationsServiceServer) ServiceDescriptor() ([]byte, int) { + return twirpFileDescriptor0, 0 +} + +func (s *applicationsServiceServer) ProtocGenTwirpVersion() string { + return "v8.1.3" +} + +// PathPrefix returns the base service path, in the form: "/<prefix>/<package>.<Service>/" +// that is everything in a Twirp route except for the <Method>. This can be used for routing, +// for example to identify the requests that are targeted to this service in a mux. +func (s *applicationsServiceServer) PathPrefix() string { + return baseServicePath(s.pathPrefix, "applications", "ApplicationsService") +} + +// ===== +// Utils +// ===== + +// HTTPClient is the interface used by generated clients to send HTTP requests. +// It is fulfilled by *(net/http).Client, which is sufficient for most users. +// Users can provide their own implementation for special retry policies. +// +// HTTPClient implementations should not follow redirects. Redirects are +// automatically disabled if *(net/http).Client is passed to client +// constructors. See the withoutRedirects function in this file for more +// details. +type HTTPClient interface { + Do(req *http.Request) (*http.Response, error) +} + +// TwirpServer is the interface generated server structs will support: they're +// HTTP handlers with additional methods for accessing metadata about the +// service. Those accessors are a low-level API for building reflection tools. +// Most people can think of TwirpServers as just http.Handlers. +type TwirpServer interface { + http.Handler + + // ServiceDescriptor returns gzipped bytes describing the .proto file that + // this service was generated from. Once unzipped, the bytes can be + // unmarshalled as a + // google.golang.org/protobuf/types/descriptorpb.FileDescriptorProto. + // + // The returned integer is the index of this particular service within that + // FileDescriptorProto's 'Service' slice of ServiceDescriptorProtos. This is a + // low-level field, expected to be used for reflection. + ServiceDescriptor() ([]byte, int) + + // ProtocGenTwirpVersion is the semantic version string of the version of + // twirp used to generate this file. + ProtocGenTwirpVersion() string + + // PathPrefix returns the HTTP URL path prefix for all methods handled by this + // service. This can be used with an HTTP mux to route Twirp requests. + // The path prefix is in the form: "/<prefix>/<package>.<Service>/" + // that is, everything in a Twirp route except for the <Method> at the end. + PathPrefix() string +} + +func newServerOpts(opts []interface{}) *twirp.ServerOptions { + serverOpts := &twirp.ServerOptions{} + for _, opt := range opts { + switch o := opt.(type) { + case twirp.ServerOption: + o(serverOpts) + case *twirp.ServerHooks: // backwards compatibility, allow to specify hooks as an argument + twirp.WithServerHooks(o)(serverOpts) + case nil: // backwards compatibility, allow nil value for the argument + continue + default: + panic(fmt.Sprintf("Invalid option type %T, please use a twirp.ServerOption", o)) + } + } + return serverOpts +} + +// WriteError writes an HTTP response with a valid Twirp error format (code, msg, meta). +// Useful outside of the Twirp server (e.g. http middleware), but does not trigger hooks. +// If err is not a twirp.Error, it will get wrapped with twirp.InternalErrorWith(err) +func WriteError(resp http.ResponseWriter, err error) { + writeError(context.Background(), resp, err, nil) +} + +// writeError writes Twirp errors in the response and triggers hooks. +func writeError(ctx context.Context, resp http.ResponseWriter, err error, hooks *twirp.ServerHooks) { + // Convert to a twirp.Error. Non-twirp errors are converted to internal errors. + var twerr twirp.Error + if !errors.As(err, &twerr) { + twerr = twirp.InternalErrorWith(err) + } + + statusCode := twirp.ServerHTTPStatusFromErrorCode(twerr.Code()) + ctx = ctxsetters.WithStatusCode(ctx, statusCode) + ctx = callError(ctx, hooks, twerr) + + respBody := marshalErrorToJSON(twerr) + + resp.Header().Set("Content-Type", "application/json") // Error responses are always JSON + resp.Header().Set("Content-Length", strconv.Itoa(len(respBody))) + resp.WriteHeader(statusCode) // set HTTP status code and send response + + _, writeErr := resp.Write(respBody) + if writeErr != nil { + // We have three options here. We could log the error, call the Error + // hook, or just silently ignore the error. + // + // Logging is unacceptable because we don't have a user-controlled + // logger; writing out to stderr without permission is too rude. + // + // Calling the Error hook would confuse users: it would mean the Error + // hook got called twice for one request, which is likely to lead to + // duplicated log messages and metrics, no matter how well we document + // the behavior. + // + // Silently ignoring the error is our least-bad option. It's highly + // likely that the connection is broken and the original 'err' says + // so anyway. + _ = writeErr + } + + callResponseSent(ctx, hooks) +} + +// sanitizeBaseURL parses the the baseURL, and adds the "http" scheme if needed. +// If the URL is unparsable, the baseURL is returned unchanged. +func sanitizeBaseURL(baseURL string) string { + u, err := url.Parse(baseURL) + if err != nil { + return baseURL // invalid URL will fail later when making requests + } + if u.Scheme == "" { + u.Scheme = "http" + } + return u.String() +} + +// baseServicePath composes the path prefix for the service (without <Method>). +// e.g.: baseServicePath("/twirp", "my.pkg", "MyService") +// +// returns => "/twirp/my.pkg.MyService/" +// +// e.g.: baseServicePath("", "", "MyService") +// +// returns => "/MyService/" +func baseServicePath(prefix, pkg, service string) string { + fullServiceName := service + if pkg != "" { + fullServiceName = pkg + "." + service + } + return path.Join("/", prefix, fullServiceName) + "/" +} + +// parseTwirpPath extracts path components form a valid Twirp route. +// Expected format: "[<prefix>]/<package>.<Service>/<Method>" +// e.g.: prefix, pkgService, method := parseTwirpPath("/twirp/pkg.Svc/MakeHat") +func parseTwirpPath(path string) (string, string, string) { + parts := strings.Split(path, "/") + if len(parts) < 2 { + return "", "", "" + } + method := parts[len(parts)-1] + pkgService := parts[len(parts)-2] + prefix := strings.Join(parts[0:len(parts)-2], "/") + return prefix, pkgService, method +} + +// getCustomHTTPReqHeaders retrieves a copy of any headers that are set in +// a context through the twirp.WithHTTPRequestHeaders function. +// If there are no headers set, or if they have the wrong type, nil is returned. +func getCustomHTTPReqHeaders(ctx context.Context) http.Header { + header, ok := twirp.HTTPRequestHeaders(ctx) + if !ok || header == nil { + return nil + } + copied := make(http.Header) + for k, vv := range header { + if vv == nil { + copied[k] = nil + continue + } + copied[k] = make([]string, len(vv)) + copy(copied[k], vv) + } + return copied +} + +// newRequest makes an http.Request from a client, adding common headers. +func newRequest(ctx context.Context, url string, reqBody io.Reader, contentType string) (*http.Request, error) { + req, err := http.NewRequest("POST", url, reqBody) + if err != nil { + return nil, err + } + req = req.WithContext(ctx) + if customHeader := getCustomHTTPReqHeaders(ctx); customHeader != nil { + req.Header = customHeader + } + req.Header.Set("Accept", contentType) + req.Header.Set("Content-Type", contentType) + req.Header.Set("Twirp-Version", "v8.1.3") + return req, nil +} + +// JSON serialization for errors +type twerrJSON struct { + Code string `json:"code"` + Msg string `json:"msg"` + Meta map[string]string `json:"meta,omitempty"` +} + +// marshalErrorToJSON returns JSON from a twirp.Error, that can be used as HTTP error response body. +// If serialization fails, it will use a descriptive Internal error instead. +func marshalErrorToJSON(twerr twirp.Error) []byte { + // make sure that msg is not too large + msg := twerr.Msg() + if len(msg) > 1e6 { + msg = msg[:1e6] + } + + tj := twerrJSON{ + Code: string(twerr.Code()), + Msg: msg, + Meta: twerr.MetaMap(), + } + + buf, err := json.Marshal(&tj) + if err != nil { + buf = []byte("{\"type\": \"" + twirp.Internal + "\", \"msg\": \"There was an error but it could not be serialized into JSON\"}") // fallback + } + + return buf +} + +// errorFromResponse builds a twirp.Error from a non-200 HTTP response. +// If the response has a valid serialized Twirp error, then it's returned. +// If not, the response status code is used to generate a similar twirp +// error. See twirpErrorFromIntermediary for more info on intermediary errors. +func errorFromResponse(resp *http.Response) twirp.Error { + statusCode := resp.StatusCode + statusText := http.StatusText(statusCode) + + if isHTTPRedirect(statusCode) { + // Unexpected redirect: it must be an error from an intermediary. + // Twirp clients don't follow redirects automatically, Twirp only handles + // POST requests, redirects should only happen on GET and HEAD requests. + location := resp.Header.Get("Location") + msg := fmt.Sprintf("unexpected HTTP status code %d %q received, Location=%q", statusCode, statusText, location) + return twirpErrorFromIntermediary(statusCode, msg, location) + } + + respBodyBytes, err := io.ReadAll(resp.Body) + if err != nil { + return wrapInternal(err, "failed to read server error response body") + } + + var tj twerrJSON + dec := json.NewDecoder(bytes.NewReader(respBodyBytes)) + dec.DisallowUnknownFields() + if err := dec.Decode(&tj); err != nil || tj.Code == "" { + // Invalid JSON response; it must be an error from an intermediary. + msg := fmt.Sprintf("Error from intermediary with HTTP status code %d %q", statusCode, statusText) + return twirpErrorFromIntermediary(statusCode, msg, string(respBodyBytes)) + } + + errorCode := twirp.ErrorCode(tj.Code) + if !twirp.IsValidErrorCode(errorCode) { + msg := "invalid type returned from server error response: " + tj.Code + return twirp.InternalError(msg).WithMeta("body", string(respBodyBytes)) + } + + twerr := twirp.NewError(errorCode, tj.Msg) + for k, v := range tj.Meta { + twerr = twerr.WithMeta(k, v) + } + return twerr +} + +// twirpErrorFromIntermediary maps HTTP errors from non-twirp sources to twirp errors. +// The mapping is similar to gRPC: https://github.com/grpc/grpc/blob/master/doc/http-grpc-status-mapping.md. +// Returned twirp Errors have some additional metadata for inspection. +func twirpErrorFromIntermediary(status int, msg string, bodyOrLocation string) twirp.Error { + var code twirp.ErrorCode + if isHTTPRedirect(status) { // 3xx + code = twirp.Internal + } else { + switch status { + case 400: // Bad Request + code = twirp.Internal + case 401: // Unauthorized + code = twirp.Unauthenticated + case 403: // Forbidden + code = twirp.PermissionDenied + case 404: // Not Found + code = twirp.BadRoute + case 429: // Too Many Requests + code = twirp.ResourceExhausted + case 502, 503, 504: // Bad Gateway, Service Unavailable, Gateway Timeout + code = twirp.Unavailable + default: // All other codes + code = twirp.Unknown + } + } + + twerr := twirp.NewError(code, msg) + twerr = twerr.WithMeta("http_error_from_intermediary", "true") // to easily know if this error was from intermediary + twerr = twerr.WithMeta("status_code", strconv.Itoa(status)) + if isHTTPRedirect(status) { + twerr = twerr.WithMeta("location", bodyOrLocation) + } else { + twerr = twerr.WithMeta("body", bodyOrLocation) + } + return twerr +} + +func isHTTPRedirect(status int) bool { + return status >= 300 && status <= 399 +} + +// wrapInternal wraps an error with a prefix as an Internal error. +// The original error cause is accessible by github.com/pkg/errors.Cause. +func wrapInternal(err error, prefix string) twirp.Error { + return twirp.InternalErrorWith(&wrappedError{prefix: prefix, cause: err}) +} + +type wrappedError struct { + prefix string + cause error +} + +func (e *wrappedError) Error() string { return e.prefix + ": " + e.cause.Error() } +func (e *wrappedError) Unwrap() error { return e.cause } // for go1.13 + errors.Is/As +func (e *wrappedError) Cause() error { return e.cause } // for github.com/pkg/errors + +// ensurePanicResponses makes sure that rpc methods causing a panic still result in a Twirp Internal +// error response (status 500), and error hooks are properly called with the panic wrapped as an error. +// The panic is re-raised so it can be handled normally with middleware. +func ensurePanicResponses(ctx context.Context, resp http.ResponseWriter, hooks *twirp.ServerHooks) { + if r := recover(); r != nil { + // Wrap the panic as an error so it can be passed to error hooks. + // The original error is accessible from error hooks, but not visible in the response. + err := errFromPanic(r) + twerr := &internalWithCause{msg: "Internal service panic", cause: err} + // Actually write the error + writeError(ctx, resp, twerr, hooks) + // If possible, flush the error to the wire. + f, ok := resp.(http.Flusher) + if ok { + f.Flush() + } + + panic(r) + } +} + +// errFromPanic returns the typed error if the recovered panic is an error, otherwise formats as error. +func errFromPanic(p interface{}) error { + if err, ok := p.(error); ok { + return err + } + return fmt.Errorf("panic: %v", p) +} + +// internalWithCause is a Twirp Internal error wrapping an original error cause, +// but the original error message is not exposed on Msg(). The original error +// can be checked with go1.13+ errors.Is/As, and also by (github.com/pkg/errors).Unwrap +type internalWithCause struct { + msg string + cause error +} + +func (e *internalWithCause) Unwrap() error { return e.cause } // for go1.13 + errors.Is/As +func (e *internalWithCause) Cause() error { return e.cause } // for github.com/pkg/errors +func (e *internalWithCause) Error() string { return e.msg + ": " + e.cause.Error() } +func (e *internalWithCause) Code() twirp.ErrorCode { return twirp.Internal } +func (e *internalWithCause) Msg() string { return e.msg } +func (e *internalWithCause) Meta(key string) string { return "" } +func (e *internalWithCause) MetaMap() map[string]string { return nil } +func (e *internalWithCause) WithMeta(key string, val string) twirp.Error { return e } + +// malformedRequestError is used when the twirp server cannot unmarshal a request +func malformedRequestError(msg string) twirp.Error { + return twirp.NewError(twirp.Malformed, msg) +} + +// badRouteError is used when the twirp server cannot route a request +func badRouteError(msg string, method, url string) twirp.Error { + err := twirp.NewError(twirp.BadRoute, msg) + err = err.WithMeta("twirp_invalid_route", method+" "+url) + return err +} + +// withoutRedirects makes sure that the POST request can not be redirected. +// The standard library will, by default, redirect requests (including POSTs) if it gets a 302 or +// 303 response, and also 301s in go1.8. It redirects by making a second request, changing the +// method to GET and removing the body. This produces very confusing error messages, so instead we +// set a redirect policy that always errors. This stops Go from executing the redirect. +// +// We have to be a little careful in case the user-provided http.Client has its own CheckRedirect +// policy - if so, we'll run through that policy first. +// +// Because this requires modifying the http.Client, we make a new copy of the client and return it. +func withoutRedirects(in *http.Client) *http.Client { + copy := *in + copy.CheckRedirect = func(req *http.Request, via []*http.Request) error { + if in.CheckRedirect != nil { + // Run the input's redirect if it exists, in case it has side effects, but ignore any error it + // returns, since we want to use ErrUseLastResponse. + err := in.CheckRedirect(req, via) + _ = err // Silly, but this makes sure generated code passes errcheck -blank, which some people use. + } + return http.ErrUseLastResponse + } + return © +} + +// doProtobufRequest makes a Protobuf request to the remote Twirp service. +func doProtobufRequest(ctx context.Context, client HTTPClient, hooks *twirp.ClientHooks, url string, in, out proto.Message) (_ context.Context, err error) { + reqBodyBytes, err := proto.Marshal(in) + if err != nil { + return ctx, wrapInternal(err, "failed to marshal proto request") + } + reqBody := bytes.NewBuffer(reqBodyBytes) + if err = ctx.Err(); err != nil { + return ctx, wrapInternal(err, "aborted because context was done") + } + + req, err := newRequest(ctx, url, reqBody, "application/protobuf") + if err != nil { + return ctx, wrapInternal(err, "could not build request") + } + ctx, err = callClientRequestPrepared(ctx, hooks, req) + if err != nil { + return ctx, err + } + + req = req.WithContext(ctx) + resp, err := client.Do(req) + if err != nil { + return ctx, wrapInternal(err, "failed to do request") + } + defer func() { _ = resp.Body.Close() }() + + if err = ctx.Err(); err != nil { + return ctx, wrapInternal(err, "aborted because context was done") + } + + if resp.StatusCode != 200 { + return ctx, errorFromResponse(resp) + } + + respBodyBytes, err := io.ReadAll(resp.Body) + if err != nil { + return ctx, wrapInternal(err, "failed to read response body") + } + if err = ctx.Err(); err != nil { + return ctx, wrapInternal(err, "aborted because context was done") + } + + if err = proto.Unmarshal(respBodyBytes, out); err != nil { + return ctx, wrapInternal(err, "failed to unmarshal proto response") + } + return ctx, nil +} + +// doJSONRequest makes a JSON request to the remote Twirp service. +func doJSONRequest(ctx context.Context, client HTTPClient, hooks *twirp.ClientHooks, url string, in, out proto.Message) (_ context.Context, err error) { + marshaler := &protojson.MarshalOptions{UseProtoNames: true} + reqBytes, err := marshaler.Marshal(in) + if err != nil { + return ctx, wrapInternal(err, "failed to marshal json request") + } + if err = ctx.Err(); err != nil { + return ctx, wrapInternal(err, "aborted because context was done") + } + + req, err := newRequest(ctx, url, bytes.NewReader(reqBytes), "application/json") + if err != nil { + return ctx, wrapInternal(err, "could not build request") + } + ctx, err = callClientRequestPrepared(ctx, hooks, req) + if err != nil { + return ctx, err + } + + req = req.WithContext(ctx) + resp, err := client.Do(req) + if err != nil { + return ctx, wrapInternal(err, "failed to do request") + } + + defer func() { + cerr := resp.Body.Close() + if err == nil && cerr != nil { + err = wrapInternal(cerr, "failed to close response body") + } + }() + + if err = ctx.Err(); err != nil { + return ctx, wrapInternal(err, "aborted because context was done") + } + + if resp.StatusCode != 200 { + return ctx, errorFromResponse(resp) + } + + d := json.NewDecoder(resp.Body) + rawRespBody := json.RawMessage{} + if err := d.Decode(&rawRespBody); err != nil { + return ctx, wrapInternal(err, "failed to unmarshal json response") + } + unmarshaler := protojson.UnmarshalOptions{DiscardUnknown: true} + if err = unmarshaler.Unmarshal(rawRespBody, out); err != nil { + return ctx, wrapInternal(err, "failed to unmarshal json response") + } + if err = ctx.Err(); err != nil { + return ctx, wrapInternal(err, "aborted because context was done") + } + return ctx, nil +} + +// Call twirp.ServerHooks.RequestReceived if the hook is available +func callRequestReceived(ctx context.Context, h *twirp.ServerHooks) (context.Context, error) { + if h == nil || h.RequestReceived == nil { + return ctx, nil + } + return h.RequestReceived(ctx) +} + +// Call twirp.ServerHooks.RequestRouted if the hook is available +func callRequestRouted(ctx context.Context, h *twirp.ServerHooks) (context.Context, error) { + if h == nil || h.RequestRouted == nil { + return ctx, nil + } + return h.RequestRouted(ctx) +} + +// Call twirp.ServerHooks.ResponsePrepared if the hook is available +func callResponsePrepared(ctx context.Context, h *twirp.ServerHooks) context.Context { + if h == nil || h.ResponsePrepared == nil { + return ctx + } + return h.ResponsePrepared(ctx) +} + +// Call twirp.ServerHooks.ResponseSent if the hook is available +func callResponseSent(ctx context.Context, h *twirp.ServerHooks) { + if h == nil || h.ResponseSent == nil { + return + } + h.ResponseSent(ctx) +} + +// Call twirp.ServerHooks.Error if the hook is available +func callError(ctx context.Context, h *twirp.ServerHooks, err twirp.Error) context.Context { + if h == nil || h.Error == nil { + return ctx + } + return h.Error(ctx, err) +} + +func callClientResponseReceived(ctx context.Context, h *twirp.ClientHooks) { + if h == nil || h.ResponseReceived == nil { + return + } + h.ResponseReceived(ctx) +} + +func callClientRequestPrepared(ctx context.Context, h *twirp.ClientHooks, req *http.Request) (context.Context, error) { + if h == nil || h.RequestPrepared == nil { + return ctx, nil + } + return h.RequestPrepared(ctx, req) +} + +func callClientError(ctx context.Context, h *twirp.ClientHooks, err twirp.Error) { + if h == nil || h.Error == nil { + return + } + h.Error(ctx, err) +} + +var twirpFileDescriptor0 = []byte{ + // 512 bytes of a gzipped FileDescriptorProto + 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xac, 0x55, 0xdd, 0x4e, 0x13, 0x41, + 0x14, 0xce, 0xb6, 0xa5, 0x86, 0x53, 0x69, 0xe8, 0x11, 0x64, 0x5a, 0x82, 0x69, 0x06, 0x41, 0xbd, + 0xb0, 0x4d, 0xf0, 0xd2, 0x78, 0x51, 0x35, 0x31, 0x44, 0xaf, 0x8a, 0x44, 0xd4, 0x0b, 0xb2, 0xee, + 0x1c, 0xc9, 0x0a, 0xee, 0xae, 0x33, 0x53, 0x13, 0x1e, 0xc2, 0x17, 0xf1, 0xad, 0x7c, 0x13, 0xd3, + 0xd9, 0x11, 0x66, 0x7f, 0x31, 0x64, 0xef, 0x76, 0xcf, 0xef, 0x37, 0xdf, 0x7e, 0xdf, 0x0e, 0x3c, + 0x90, 0x49, 0x30, 0xf5, 0x93, 0xe4, 0x22, 0x0c, 0x7c, 0x1d, 0xc6, 0x91, 0x9a, 0x2a, 0x92, 0x3f, + 0xc3, 0x80, 0x26, 0x89, 0x8c, 0x75, 0x8c, 0x77, 0xdd, 0x1c, 0xff, 0xed, 0x41, 0x6f, 0x76, 0x1d, + 0xc0, 0x3e, 0xb4, 0x42, 0xc1, 0xbc, 0xb1, 0xf7, 0x78, 0x75, 0xde, 0x0a, 0x05, 0x6e, 0xc1, 0x9d, + 0x85, 0x22, 0x79, 0x1a, 0x0a, 0xd6, 0x32, 0xc1, 0xee, 0xf2, 0xf5, 0x50, 0x20, 0x42, 0x27, 0xf2, + 0xbf, 0x13, 0x6b, 0x9b, 0xa8, 0x79, 0xc6, 0x31, 0xf4, 0x04, 0xa9, 0x40, 0x86, 0xc9, 0x72, 0x16, + 0xeb, 0x98, 0x94, 0x1b, 0xc2, 0x1d, 0x80, 0x40, 0x92, 0xaf, 0x49, 0x9c, 0xfa, 0x9a, 0xad, 0x98, + 0x82, 0x55, 0x1b, 0x99, 0xe9, 0x65, 0x7a, 0x91, 0x88, 0x7f, 0xe9, 0x6e, 0x9a, 0xb6, 0x91, 0x99, + 0xe6, 0x5f, 0x81, 0xbd, 0x32, 0xb5, 0x0e, 0xe2, 0x39, 0xfd, 0x58, 0x90, 0xd2, 0xb8, 0x01, 0x2b, + 0x3a, 0x3e, 0xa7, 0xc8, 0x62, 0x4f, 0x5f, 0xae, 0x50, 0xb6, 0xaa, 0x51, 0xb6, 0x0b, 0x28, 0xf9, + 0x37, 0x18, 0x96, 0xec, 0x51, 0x49, 0x1c, 0x29, 0xc2, 0xe7, 0xd0, 0x73, 0x18, 0x34, 0xeb, 0x7a, + 0x07, 0xc3, 0x89, 0xcb, 0xea, 0xc4, 0xed, 0x73, 0xab, 0x71, 0x1d, 0xda, 0xe7, 0x74, 0x69, 0xe1, + 0x2c, 0x1f, 0xf9, 0x14, 0xb6, 0xde, 0x85, 0x4a, 0x3b, 0x1d, 0xaa, 0xf6, 0x48, 0xfc, 0x23, 0xb0, + 0x62, 0x83, 0xc5, 0xf6, 0x02, 0x32, 0x5f, 0x97, 0x79, 0xe3, 0x76, 0x3d, 0xb8, 0xac, 0x18, 0xde, + 0xc3, 0xe6, 0x1b, 0xd2, 0xff, 0x4d, 0xee, 0x1e, 0xf4, 0x9d, 0xf6, 0x6b, 0x89, 0xac, 0x39, 0xd1, + 0x43, 0xc1, 0x8f, 0xe1, 0x7e, 0x7e, 0x6a, 0x03, 0x54, 0xf2, 0x5f, 0x1e, 0xb0, 0x63, 0x23, 0x8d, + 0x86, 0x01, 0xdf, 0x4e, 0xda, 0xfc, 0x04, 0x86, 0x25, 0x70, 0x9a, 0x38, 0xe9, 0x07, 0x60, 0xaf, + 0xe9, 0x82, 0x1a, 0x3f, 0x28, 0xdf, 0x86, 0x61, 0xc9, 0xe0, 0x14, 0x32, 0x3f, 0x82, 0x8d, 0x39, + 0x9d, 0x51, 0x44, 0xd2, 0xd7, 0xf4, 0x96, 0x2e, 0x1b, 0xd9, 0xf8, 0x04, 0x36, 0x73, 0x43, 0x2d, + 0x41, 0xd6, 0x18, 0xde, 0x95, 0x31, 0x0e, 0xfe, 0x74, 0xe0, 0x9e, 0x2b, 0xf2, 0xa3, 0xf4, 0x2f, + 0x86, 0x02, 0x06, 0x05, 0x73, 0xe2, 0x7e, 0x96, 0xca, 0xaa, 0xbf, 0xc4, 0xe8, 0xd1, 0x8d, 0x75, + 0x16, 0x8f, 0x0f, 0xeb, 0x79, 0x97, 0xe1, 0x5e, 0xb6, 0xb9, 0xc2, 0xb6, 0xa3, 0xfd, 0x9b, 0xca, + 0xec, 0x8a, 0xcf, 0xd0, 0xcf, 0xfa, 0x02, 0x77, 0xb3, 0x9d, 0xa5, 0x5e, 0x1c, 0x3d, 0xac, 0x2f, + 0xb2, 0xc3, 0x05, 0x0c, 0x0a, 0x6a, 0xcc, 0xb3, 0x54, 0xe5, 0x9e, 0x3c, 0x4b, 0xd5, 0xb2, 0x16, + 0x30, 0x28, 0x08, 0x28, 0xbf, 0xa5, 0x4a, 0xba, 0xf9, 0x2d, 0x95, 0x4a, 0xc4, 0x13, 0x58, 0xcb, + 0x88, 0x06, 0x79, 0xb6, 0xb3, 0x4c, 0xa6, 0xa3, 0xdd, 0xda, 0x9a, 0x74, 0xf2, 0xcb, 0x9d, 0x4f, + 0xdb, 0xbe, 0x3c, 0x5b, 0xa8, 0xa7, 0x41, 0x2c, 0x69, 0x9a, 0xbf, 0x38, 0xbf, 0x74, 0xcd, 0x8d, + 0xf9, 0xec, 0x6f, 0x00, 0x00, 0x00, 0xff, 0xff, 0x88, 0xdd, 0x06, 0xcd, 0x53, 0x07, 0x00, 0x00, +}