@@ -7,14 +7,18 @@ package contentservice
7
7
import (
8
8
"context"
9
9
"fmt"
10
+ "net/http"
11
+ "os"
12
+ "path/filepath"
10
13
14
+ "github.com/gitpod-io/gitpod/common-go/log"
11
15
"github.com/gitpod-io/gitpod/content-service/api"
12
16
"google.golang.org/grpc"
13
17
"google.golang.org/grpc/credentials/insecure"
14
18
)
15
19
16
20
type Interface interface {
17
- GetSignedUploadUrl (ctx context.Context ) ( string , error )
21
+ UploadFile (ctx context.Context , filePath string ) error
18
22
}
19
23
20
24
type Client struct {
@@ -25,7 +29,42 @@ func New(url string) *Client {
25
29
return & Client {url : url }
26
30
}
27
31
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 ) {
29
68
conn , err := grpc .Dial (c .url , grpc .WithTransportCredentials (insecure .NewCredentials ()))
30
69
if err != nil {
31
70
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) {
34
73
35
74
uc := api .NewUsageReportServiceClient (conn )
36
75
37
- resp , err := uc .UploadURL (ctx , & api.UsageReportUploadURLRequest {Name : "some-name" })
76
+ resp , err := uc .UploadURL (ctx , & api.UsageReportUploadURLRequest {Name : key })
38
77
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 )
40
79
}
41
80
42
81
return resp .Url , nil
0 commit comments