@@ -7,14 +7,18 @@ package contentservice
77import (
88 "context"
99 "fmt"
10+ "net/http"
11+ "os"
12+ "path/filepath"
1013
14+ "github.com/gitpod-io/gitpod/common-go/log"
1115 "github.com/gitpod-io/gitpod/content-service/api"
1216 "google.golang.org/grpc"
1317 "google.golang.org/grpc/credentials/insecure"
1418)
1519
1620type Interface interface {
17- GetSignedUploadUrl (ctx context.Context ) ( string , error )
21+ UploadFile (ctx context.Context , filePath string ) error
1822}
1923
2024type Client struct {
@@ -25,7 +29,42 @@ func New(url string) *Client {
2529 return & Client {url : url }
2630}
2731
28- func (c * Client ) GetSignedUploadUrl (ctx context.Context ) (string , error ) {
32+ func (c * Client ) UploadFile (ctx context.Context , filePath string ) error {
33+ url , err := c .getSignedUploadUrl (ctx , filepath .Base (filePath ))
34+ if err != nil {
35+ return fmt .Errorf ("failed to obtain signed upload URL: %w" , err )
36+ }
37+
38+ file , err := os .Open (filePath )
39+ if err != nil {
40+ return fmt .Errorf ("failed to open file: %w" , err )
41+ }
42+
43+ req , err := http .NewRequest (http .MethodPut , url , file )
44+ if err != nil {
45+ return fmt .Errorf ("failed to construct http request: %w" , err )
46+ }
47+
48+ fileInfo , err := os .Stat (filePath )
49+ if err != nil {
50+ return fmt .Errorf ("failed to stat file: %w" , err )
51+ }
52+
53+ log .Infof ("Uploading %q to cloud storage..." , filePath )
54+ req .ContentLength = fileInfo .Size ()
55+ resp , err := http .DefaultClient .Do (req )
56+ if err != nil {
57+ return fmt .Errorf ("failed to make http request: %w" , err )
58+ }
59+ if resp .StatusCode != http .StatusOK {
60+ return fmt .Errorf ("unexpected http response code: %s" , resp .Status )
61+ }
62+ log .Info ("Upload complete" )
63+
64+ return nil
65+ }
66+
67+ func (c * Client ) getSignedUploadUrl (ctx context.Context , key string ) (string , error ) {
2968 conn , err := grpc .Dial (c .url , grpc .WithTransportCredentials (insecure .NewCredentials ()))
3069 if err != nil {
3170 return "" , fmt .Errorf ("failed to dial content-service gRPC server: %w" , err )
@@ -34,9 +73,9 @@ func (c *Client) GetSignedUploadUrl(ctx context.Context) (string, error) {
3473
3574 uc := api .NewUsageReportServiceClient (conn )
3675
37- resp , err := uc .UploadURL (ctx , & api.UsageReportUploadURLRequest {Name : "some-name" })
76+ resp , err := uc .UploadURL (ctx , & api.UsageReportUploadURLRequest {Name : key })
3877 if err != nil {
39- return "" , fmt .Errorf ("failed to obtain signed upload URL : %w" , err )
78+ return "" , fmt .Errorf ("failed RPC to content service : %w" , err )
4079 }
4180
4281 return resp .Url , nil
0 commit comments