-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathlambda.go
265 lines (237 loc) · 6.6 KB
/
lambda.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
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
package lambda
import (
"bufio"
"bytes"
"encoding/json"
"fmt"
"io"
"log"
"os"
"strings"
"github.com/golang/protobuf/jsonpb"
"github.com/golang/protobuf/proto"
"golang.org/x/net/context"
"google.golang.org/grpc"
)
type Payload struct {
Event *PayloadEvent `json:"event"`
Context *PayloadContext `json:"context"`
}
func (p *Payload) String() string {
var id, ev string
if p.Context != nil {
id = p.Context.AWSRequestID
}
if p.Event != nil {
ev = p.Event.String()
}
return fmt.Sprintf("[Payload %s] %s", id, ev)
}
type PayloadEvent struct {
Package *string `json:"package"`
Service *string `json:"service"`
Method *string `json:"method"`
Data *json.RawMessage `json:"data"`
}
func (e *PayloadEvent) String() string {
var p, s, m, d string
if e.Package != nil {
p = *e.Package
}
if e.Service != nil {
s = *e.Service
}
if e.Method != nil {
m = *e.Method
}
if e.Data != nil {
d = string(*e.Data)
}
return fmt.Sprintf("[%s] %s", NewMethodID(p, s, m), d)
}
type PayloadContext struct {
FunctionName string `json:"functionName"`
FunctionVersion string `json:"functionVersion"`
InvokedFunctionARN string `json:"invokedFunctionArn"`
MemoryLimitInMB string `json:"memoryLimitInMB"`
AWSRequestID string `json:"awsRequestId"`
LogGroupName string `json:"logGroupName"`
LogStreamName string `json:"logStreamName"`
Identity *PayloadContextIdentity `json:"identity"`
ClientContext *PayloadContextClientContext `json:"clientContext"`
}
type PayloadContextClientContext struct {
Client *PayloadContextClientContextClient `json:"client"`
Custom interface{}
Env *PayloadContextClientContextEnv `json:"env"`
}
type PayloadContextClientContextClient struct {
InstallationID string `json:"installation_id"`
AppTitle string `json:"app_title"`
AppVersionName string `json:"app_version_name"`
AppVersionCode string `json:"app_version_code"`
AppPackageName string `json:"app_package_name"`
}
type PayloadContextClientContextEnv struct {
PlatformVersion string `json:"platform_version"`
Platform string `json:"platform"`
Make string `json:"make"`
Model string `json:"model"`
Locale string `json:"locale"`
}
type PayloadContextIdentity struct {
CognitoIdentityID string `json:"cognito_identity_id"`
CognitoIdentityPoolID string `json:"cognito_identity_pool_id"`
}
type Response struct {
Context *PayloadContext
Reply *proto.Message
Error error
}
func (r *Response) String() string {
id := ""
if r.Context != nil {
id = r.Context.AWSRequestID
}
if r.Error != nil {
return fmt.Sprintf("[Response %s] Error: %s", id, r.Error.Error())
}
return fmt.Sprintf("[Response %s] %s", id, (*r.Reply).String())
}
var replyMarshaler = &jsonpb.Marshaler{}
func NewResponse(c *PayloadContext, reply *proto.Message, err error) *Response {
return &Response{
Context: c,
Reply: reply,
Error: err,
}
}
func (r *Response) EncodeToJSON() string {
id := "null"
if r.Context != nil {
id = fmt.Sprintf(`"%s"`, r.Context.AWSRequestID)
}
if r.Error != nil {
return fmt.Sprintf(`{"id":%s,"error":"%s"}`, id, strings.Replace(r.Error.Error(), `"`, `\"`, -1))
}
reply, err := replyMarshaler.MarshalToString(*r.Reply)
if err != nil {
log.Fatalf("Failed to encode response to JSON: %s", err.Error())
}
return fmt.Sprintf(`{"id":%s,"reply":%s}`, id, reply)
}
type Service struct {
ServiceDesc *grpc.ServiceDesc
Server interface{}
}
type MethodID string
func NewMethodID(pkg string, svc string, mtd string) MethodID {
var id string
if pkg == "" {
id = fmt.Sprintf("%s/%s", svc, mtd)
} else {
id = fmt.Sprintf("%s.%s/%s", pkg, svc, mtd)
}
return MethodID(id)
}
func (id MethodID) String() string {
return string(id)
}
type handler struct {
srv interface{}
md *grpc.MethodDesc
}
type Server struct {
handlers map[MethodID]handler
}
func NewServer() *Server {
return &Server{
handlers: map[MethodID]handler{},
}
}
func (s *Server) Register(svcs []Service) {
for _, svc := range svcs {
for _, md := range svc.ServiceDesc.Methods {
uid := NewMethodID("", svc.ServiceDesc.ServiceName, md.MethodName)
s.handlers[uid] = handler{svc.Server, &md}
}
}
}
func (s *Server) Run() {
payloadCh := make(chan *Payload)
resCh := make(chan *Response)
errCh := make(chan error)
go s.listenStdin(payloadCh, resCh, errCh)
for {
select {
case payload := <-payloadCh:
log.Printf("go-lambda RCVD %s\n", payload.String())
go s.processPayload(payload, resCh)
case res := <-resCh:
fmt.Println(res.EncodeToJSON())
log.Printf("go-lambda SENT %s\n", res.String())
case err := <-errCh:
log.Fatal(err)
}
}
}
func (s *Server) listenStdin(payloadCh chan *Payload, resCh chan *Response, errCh chan error) {
log.Println("go-lambda listening stdin...")
scanner := bufio.NewScanner(os.Stdin)
for scanner.Scan() {
var payload Payload
if err := json.Unmarshal(scanner.Bytes(), &payload); err != nil {
resCh <- NewResponse(payload.Context, nil, fmt.Errorf("invalid payload"))
continue
}
payloadCh <- &payload
}
if err := scanner.Err(); err != nil {
errCh <- err
}
}
func (s *Server) processPayload(payload *Payload, resCh chan *Response) {
if payload.Event == nil {
resCh <- NewResponse(nil, nil, fmt.Errorf("payload missing event"))
return
}
if payload.Event.Package == nil {
var p string
payload.Event.Package = &p
}
if payload.Event.Service == nil {
resCh <- NewResponse(nil, nil, fmt.Errorf("payload missing event.service"))
return
}
if payload.Event.Method == nil {
resCh <- NewResponse(nil, nil, fmt.Errorf("payload missing event.method"))
return
}
var data io.Reader
if payload.Event.Data == nil {
data = strings.NewReader("{}")
} else {
data = bytes.NewReader(*payload.Event.Data)
}
methodID := NewMethodID(*payload.Event.Package, *payload.Event.Service, *payload.Event.Method)
reply, err := s.callGRPCMethod(methodID, data)
resCh <- NewResponse(payload.Context, reply, err)
}
func (s *Server) callGRPCMethod(id MethodID, data io.Reader) (*proto.Message, error) {
decode := func(v interface{}) error {
if err := jsonpb.Unmarshal(data, v.(proto.Message)); err != nil {
return fmt.Errorf("invalid method (%s) data", id)
}
return nil
}
h, ok := s.handlers[id]
if !ok {
return nil, fmt.Errorf("method handler not found - %s", id)
}
reply, err := h.md.Handler(h.srv, context.Background(), decode)
if err != nil {
return nil, err
}
replyMsg := reply.(proto.Message)
return &replyMsg, nil
}