/
operation.go
191 lines (167 loc) · 5.29 KB
/
operation.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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
package operations
import (
"context"
"database/sql"
"errors"
"fmt"
"strings"
"github.com/golang/protobuf/ptypes/any"
"github.com/golang/protobuf/ptypes/empty"
"github.com/ngalaiko/miniboard/server/actor"
"github.com/ngalaiko/miniboard/server/api/operations/db"
longrunning "github.com/ngalaiko/miniboard/server/genproto/google/longrunning"
"github.com/segmentio/ksuid"
rpcstatus "google.golang.org/genproto/googleapis/rpc/status"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
)
type operationTask struct {
UserID string
Operation *longrunning.Operation
Func Operation
}
type logger interface {
Error(string, ...interface{})
}
// Service manages longrunning api operations.
type Service struct {
db *db.DB
logger logger
processQueue chan *operationTask
}
// New returns new service.
func New(ctx context.Context, logger logger, sqldb *sql.DB) *Service {
s := &Service{
db: db.New(sqldb),
processQueue: make(chan *operationTask),
logger: logger,
}
for i := 0; i < 10; i++ {
go s.runWorker(ctx)
}
return s
}
// Operation is a single long running operation.
type Operation func(context.Context, *longrunning.Operation, chan<- *longrunning.Operation) error
// CreateOperation creates an operation, and runs it.
func (s *Service) CreateOperation(ctx context.Context, metadata *any.Any, operationFunc Operation) (*longrunning.Operation, error) {
a, _ := actor.FromContext(ctx)
operation := &longrunning.Operation{
Name: fmt.Sprintf("operations/%s", ksuid.New().String()),
Metadata: metadata,
}
if err := s.db.Create(ctx, a.ID, operation); err != nil {
return nil, fmt.Errorf("failed to create operation: %w", err)
}
s.processQueue <- &operationTask{
UserID: a.ID,
Operation: &longrunning.Operation{
Name: operation.Name,
Metadata: operation.Metadata,
},
Func: operationFunc,
}
return operation, nil
}
func (s *Service) runWorker(ctx context.Context) {
for {
select {
case <-ctx.Done():
return
case task := <-s.processQueue:
backgroundCtx := actor.NewContext(ctx, task.UserID)
s.runOperation(backgroundCtx, task.UserID, task.Operation, task.Func)
}
}
}
func (s *Service) runOperation(ctx context.Context, userID string, operation *longrunning.Operation, operationFunc Operation) {
statusChan := make(chan *longrunning.Operation, 10)
errChan := make(chan error)
go func() {
defer func() {
if r := recover(); r != nil {
s.logger.Error("panic: %s", r)
operation.Result = &longrunning.Operation_Error{
Error: &rpcstatus.Status{
Code: int32(codes.Internal),
Message: "Internal Error",
},
}
operation.Done = true
if err := s.db.Update(ctx, userID, operation); err != nil {
s.logger.Error("failed to update operation: %s", err)
}
}
}()
if err := operationFunc(ctx, &longrunning.Operation{
Name: operation.Name,
Metadata: operation.Metadata,
}, statusChan); err != nil {
errChan <- err
}
close(errChan)
}()
var lastStatus *longrunning.Operation
for {
select {
case status := <-statusChan:
lastStatus = status
if err := s.db.Update(ctx, userID, status); err != nil {
s.logger.Error("failed to update operation: %s", err)
}
case err := <-errChan:
switch {
case lastStatus == nil:
operation.Done = true
operation.Result = &longrunning.Operation_Error{
Error: &rpcstatus.Status{
Code: int32(codes.Internal),
Message: "Internal Error",
},
}
case err != nil:
operation.Done = true
operation.Result = &longrunning.Operation_Error{
Error: &rpcstatus.Status{
Code: int32(codes.Internal),
Message: err.Error(),
},
}
default:
return
}
if err := s.db.Update(ctx, userID, operation); err != nil {
s.logger.Error("failed to update operation: %s", err)
}
}
}
}
// GetOperation returns a single operation.
func (s *Service) GetOperation(ctx context.Context, in *longrunning.GetOperationRequest) (*longrunning.Operation, error) {
a, _ := actor.FromContext(ctx)
operation, err := s.db.Get(ctx, strings.Replace(in.Name, "operations/", "", -1), a.ID)
switch {
case err == nil:
return operation, nil
case errors.Is(err, sql.ErrNoRows):
return nil, status.Errorf(codes.NotFound, "not found")
default:
return nil, status.Errorf(codes.Internal, "failed to load operation")
}
}
// ListOperations returns list of operations.
func (s *Service) ListOperations(ctx context.Context, in *longrunning.ListOperationsRequest) (*longrunning.ListOperationsResponse, error) {
return nil, status.Errorf(codes.Unimplemented, "not implemented")
}
// DeleteOperation deletes an operation.
func (s *Service) DeleteOperation(ctx context.Context, in *longrunning.DeleteOperationRequest) (*empty.Empty, error) {
return nil, status.Errorf(codes.Unimplemented, "not implemented")
}
// CancelOperation cancels a running operation.
func (s *Service) CancelOperation(ctx context.Context, in *longrunning.CancelOperationRequest) (*empty.Empty, error) {
return nil, status.Errorf(codes.Unimplemented, "not implemented")
}
// WaitOperation waits until operations is done, and then returns an operation.
func (s *Service) WaitOperation(ctx context.Context, in *longrunning.WaitOperationRequest) (*longrunning.Operation, error) {
return nil, status.Errorf(codes.Unimplemented, "not implemented")
}