-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgrpc.go
77 lines (72 loc) · 2 KB
/
grpc.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
72
73
74
75
76
77
package main
import (
"io"
"math"
"net"
v5 "github.com/iver-wharf/wharf-api/v5/api/wharfapi/v5"
"github.com/iver-wharf/wharf-api/v5/pkg/model/response"
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
"gorm.io/gorm"
)
type grpcWharfServer struct {
v5.UnimplementedBuildsServer
db *gorm.DB
}
func serveGRPC(listener net.Listener, db *gorm.DB) {
grpcServer := grpc.NewServer()
grpcWharf := &grpcWharfServer{db: db}
v5.RegisterBuildsServer(grpcServer, grpcWharf)
grpcServer.Serve(listener)
}
func (s *grpcWharfServer) CreateLogStream(stream v5.Builds_CreateLogStreamServer) error {
var logsInserted uint64
for {
line, err := stream.Recv()
if err == io.EOF {
break
} else if err != nil {
return err
} else if line == nil {
log.Warn().Message("Received nil message, skipping.")
continue
}
if err := line.Timestamp.CheckValid(); err != nil {
log.Warn().WithError(err).
Message("Received invalid log timestamp, skipping.")
continue
}
if line.BuildID == 0 {
log.Warn().Message("Received log with build ID: 0, skipping.")
continue
}
if line.BuildID > math.MaxUint {
log.Warn().WithUint64("buildId", line.BuildID).
Message("Received too big log build ID, skipping.")
return status.Errorf(codes.InvalidArgument,
"received build ID is too big: %d (build ID) > %d (max)",
line.BuildID, uint(math.MaxUint))
}
createdLog, err := saveLog(s.db.WithContext(stream.Context()),
uint(line.BuildID),
line.Message,
line.Timestamp.AsTime(),
)
if err != nil {
return status.Errorf(codes.Internal, "insert logs: %v", err)
}
log.Debug().WithUint("logId", createdLog.LogID).
Message("Inserted log into database.")
build(createdLog.BuildID).Submit(response.Log{
LogID: createdLog.LogID,
BuildID: createdLog.BuildID,
Message: createdLog.Message,
Timestamp: createdLog.Timestamp,
})
logsInserted++
}
return stream.SendAndClose(&v5.CreateLogStreamResponse{
LinesInserted: logsInserted,
})
}