/
source.go
71 lines (60 loc) · 1.77 KB
/
source.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
package handler
import (
"bytes"
"context"
"fmt"
"io"
pb "github.com/micro/micro/v3/proto/runtime"
"github.com/micro/micro/v3/service/auth"
"github.com/micro/micro/v3/service/errors"
"github.com/micro/micro/v3/service/store"
)
const (
sourcePrefix = "source://"
blobNamespacePrefix = "micro/runtime"
)
// Source implements the proto source service interface
type Source struct{}
// Upload source to the server
func (s *Source) Upload(ctx context.Context, stream pb.Source_UploadStream) error {
// authorize the request
acc, ok := auth.AccountFromContext(ctx)
if !ok {
return errors.Unauthorized("runtime.Source.Upload", "An account is required to upload source")
}
namespace := acc.Issuer
// recieve the source from the client
buf := bytes.NewBuffer(nil)
var srv *pb.Service
for {
req, err := stream.Recv()
if err == io.EOF {
break
} else if err != nil {
return errors.InternalServerError("runtime.Source.Upload", err.Error())
}
// get the service from the request, this should be sent on the first message
if req.Service != nil {
srv = req.Service
}
// write the bytes to the buffer
if _, err := buf.Write(req.Data); err != nil {
return err
}
}
// ensure the blob and a service was sent over the stream
if buf == nil {
return errors.BadRequest("runtime.Source.Upload", "No blob was sent")
}
if srv == nil {
return errors.BadRequest("runtime.Source.Upload", "No service was sent")
}
// write the source to the store
key := fmt.Sprintf("source://%v:%v", srv.Name, srv.Version)
opt := store.BlobNamespace(namespace)
if err := store.DefaultBlobStore.Write(key, buf, opt); err != nil {
return fmt.Errorf("Error writing source to blob store: %v", err)
}
// close the stream
return stream.SendAndClose(&pb.UploadResponse{Id: key})
}