-
Notifications
You must be signed in to change notification settings - Fork 115
Expand file tree
/
Copy pathinvoke_router.go
More file actions
201 lines (156 loc) · 6.17 KB
/
invoke_router.go
File metadata and controls
201 lines (156 loc) · 6.17 KB
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
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package invoke
import (
"context"
"encoding/json"
"errors"
"io"
"log/slog"
"net/http"
"sync"
cmap "github.com/orcaman/concurrent-map"
"github.com/aws/aws-lambda-runtime-interface-emulator/internal/lambda-managed-instances/interop"
"github.com/aws/aws-lambda-runtime-interface-emulator/internal/lambda-managed-instances/logging"
"github.com/aws/aws-lambda-runtime-interface-emulator/internal/lambda-managed-instances/rapid/model"
)
var (
ErrInvokeIdAlreadyExists = errors.New("invoke ID already exists")
ErrInvokeNoReadyRuntime = errors.New("no idle runtimes")
)
type RuntimeResponseRequest interface {
ParsingError() model.AppError
InvokeID() interop.InvokeID
ContentType() string
ResponseMode() string
BodyReader() io.Reader
TrailerError() ErrorForInvoker
}
type RuntimeErrorRequest interface {
InvokeID() interop.InvokeID
ContentType() string
ErrorType() model.ErrorType
ErrorCategory() model.ErrorCategory
GetError() model.AppError
IsRuntimeError(model.AppError) bool
ReturnCode() int
ErrorDetails() string
GetXrayErrorCause() json.RawMessage
}
type runningInvoke interface {
RunInvokeAndSendResult(context.Context, interop.InitStaticDataProvider, interop.InvokeRequest, interop.InvokeMetrics) model.AppError
RuntimeNextWait(context.Context) model.AppError
RuntimeResponse(context.Context, RuntimeResponseRequest) model.AppError
RuntimeError(context.Context, RuntimeErrorRequest) model.AppError
CancelAsync(model.AppError)
}
type timeoutCache interface {
Register(invokeID interop.InvokeID)
Consume(invokeID interop.InvokeID) (consumed bool)
}
type InvokeRouter struct {
eventsApi interop.EventsAPI
idleRuntimes chan runningInvoke
runningInvokes cmap.ConcurrentMap
wg sync.WaitGroup
createRunningInvoke func(http.ResponseWriter) runningInvoke
timeoutCache timeoutCache
}
func NewInvokeRouter(
maxIdleRuntimesQueueSize int,
telemetryEventsApi interop.EventsAPI,
responderFactoryFunc ResponderFactoryFunc,
timeoutCache timeoutCache,
) *InvokeRouter {
return &InvokeRouter{
idleRuntimes: make(chan runningInvoke, maxIdleRuntimesQueueSize),
runningInvokes: cmap.New(),
eventsApi: telemetryEventsApi,
timeoutCache: timeoutCache,
createRunningInvoke: func(runtimeNext http.ResponseWriter) runningInvoke {
r := newRunningInvoke(runtimeNext, responderFactoryFunc, timeoutCache)
return &r
},
}
}
func (ir *InvokeRouter) Invoke(ctx context.Context, initData interop.InitStaticDataProvider, invokeReq interop.InvokeRequest, metrics interop.InvokeMetrics) (err model.AppError, wasResponseSent bool) {
logging.Debug(ctx, "InvokeRouter: received Invoke")
ir.wg.Add(1)
defer ir.wg.Done()
var idleRuntime runningInvoke
metrics.UpdateConcurrencyMetrics(ir.runningInvokes.Count(), len(ir.idleRuntimes))
if !ir.runningInvokes.SetIfAbsent(invokeReq.InvokeID(), idleRuntime) {
logging.Warn(ctx, "InvokeRouter error: duplicated invokeId")
return model.NewClientError(ErrInvokeIdAlreadyExists, model.ErrorSeverityError, model.ErrorDuplicatedInvokeId), false
}
defer ir.runningInvokes.Remove(invokeReq.InvokeID())
select {
case idleRuntime = <-ir.idleRuntimes:
ir.runningInvokes.Set(invokeReq.InvokeID(), idleRuntime)
default:
logging.Warn(ctx, "InvokeRouter: no ready runtimes")
return model.NewClientError(ErrInvokeNoReadyRuntime, model.ErrorSeverityError, model.ErrorRuntimeUnavailable), false
}
return idleRuntime.RunInvokeAndSendResult(ctx, initData, invokeReq, metrics), true
}
func (ir *InvokeRouter) RuntimeNext(ctx context.Context, runtimeReq http.ResponseWriter) (model.RuntimeNextWaiter, model.AppError) {
logging.Debug(ctx, "InvokeRouter: received runtime /next")
newRunningInvoke := ir.createRunningInvoke(runtimeReq)
if err := ir.addIdleRuntimeToQueue(newRunningInvoke); err != nil {
logging.Error(ctx, "InvokeRouter: failed to add idle runtime to the queue", "err", err)
return nil, err
}
return newRunningInvoke, nil
}
func (ir *InvokeRouter) RuntimeResponse(ctx context.Context, runtimeRespReq RuntimeResponseRequest) model.AppError {
logging.Debug(ctx, "InvokeRouter: received runtime response")
invoke, ok := ir.runningInvokes.Get(runtimeRespReq.InvokeID())
if !ok {
if ir.timeoutCache.Consume(runtimeRespReq.InvokeID()) {
logging.Warn(ctx, "InvokeRouter: response is too late for timed out invoke")
return model.NewCustomerError(model.ErrorRuntimeInvokeTimeout)
}
logging.Warn(ctx, "InvokeRouter: invoke id not found")
return model.NewCustomerError(model.ErrorRuntimeInvalidInvokeId)
}
return invoke.(runningInvoke).RuntimeResponse(ctx, runtimeRespReq)
}
func (ir *InvokeRouter) RuntimeError(ctx context.Context, runtimeErrReq RuntimeErrorRequest) model.AppError {
invoke, ok := ir.runningInvokes.Get(runtimeErrReq.InvokeID())
if !ok {
if ir.timeoutCache.Consume(runtimeErrReq.InvokeID()) {
logging.Warn(ctx, "InvokeRouter: error is too late for timed out invoke")
return model.NewCustomerError(model.ErrorRuntimeInvokeTimeout)
}
logging.Warn(ctx, "InvokeRouter: invoke id not found")
return model.NewCustomerError(model.ErrorRuntimeInvalidInvokeId)
}
logging.Warn(ctx, "InvokeRouter: received Runtime error", "err", runtimeErrReq.GetError())
return invoke.(runningInvoke).RuntimeError(ctx, runtimeErrReq)
}
func (ir *InvokeRouter) AbortRunningInvokes(metrics interop.ShutdownMetrics, err model.AppError) {
duration := metrics.CreateDurationMetric(interop.ShutdownAbortInvokesDurationMetric)
defer duration.Done()
slog.Info("InvokeRouter: Aborting running invokes", "reason", err)
ir.runningInvokes.IterCb(func(key string, v interface{}) {
if runningInvoke, ok := v.(runningInvoke); ok {
runningInvoke.CancelAsync(err)
}
})
slog.Debug("InvokeRouter: Waiting for invokes to be aborted")
ir.wg.Wait()
}
func (ir *InvokeRouter) addIdleRuntimeToQueue(invoke runningInvoke) model.AppError {
select {
case ir.idleRuntimes <- invoke:
return nil
default:
return model.NewCustomerError(model.ErrorRuntimeTooManyIdleRuntimes)
}
}
func (ir *InvokeRouter) GetRunningInvokesCount() int {
return ir.runningInvokes.Count()
}
func (ir *InvokeRouter) GetIdleRuntimesCount() int {
return len(ir.idleRuntimes)
}