|
| 1 | +package controller |
| 2 | + |
| 3 | +import ( |
| 4 | + "fmt" |
| 5 | + "io" |
| 6 | + "lambda-runtime-simulator/pkg/config" |
| 7 | + "lambda-runtime-simulator/pkg/event" |
| 8 | + "lambda-runtime-simulator/pkg/lambda" |
| 9 | + "net/http" |
| 10 | + |
| 11 | + "github.com/labstack/echo/v4" |
| 12 | +) |
| 13 | + |
| 14 | +type RuntimeController struct { |
| 15 | + config config.Runtime |
| 16 | + service *event.Service |
| 17 | +} |
| 18 | + |
| 19 | +var _ Controller = &RuntimeController{} |
| 20 | + |
| 21 | +func NewRuntimeController(cfg config.Runtime, service *event.Service) *RuntimeController { |
| 22 | + return &RuntimeController{ |
| 23 | + config: cfg, |
| 24 | + service: service, |
| 25 | + } |
| 26 | +} |
| 27 | + |
| 28 | +func (r RuntimeController) RegisterRoutes(e *echo.Echo) error { |
| 29 | + e.GET("/2018-06-01/runtime/invocation/next", r.NextInvocation) |
| 30 | + e.POST("/2018-06-01/runtime/invocation/:requestId/response", r.SendResponse) |
| 31 | + e.POST("/2018-06-01/runtime/invocation/:requestId/error", r.SendError) |
| 32 | + |
| 33 | + return nil |
| 34 | +} |
| 35 | + |
| 36 | +func (r RuntimeController) NextInvocation(c echo.Context) error { |
| 37 | + next, err := r.service.GetNextInvocation() |
| 38 | + if err != nil { |
| 39 | + return err |
| 40 | + } |
| 41 | + |
| 42 | + c.Response().Header().Set(lambda.HeaderLambdaRuntimeAwsRequestId, next.Id) |
| 43 | + c.Response().Header().Set(lambda.HeaderLambdaRuntimeInvokedFunctionArn, r.config.Arn) |
| 44 | + c.Response().Header().Set(lambda.HeaderLambdaRuntimeDeadlineMs, fmt.Sprint(next.Timeout.Unix())) |
| 45 | + // TODO: Implement Tracing Part |
| 46 | + return c.JSON(http.StatusOK, next.Body) |
| 47 | +} |
| 48 | + |
| 49 | +func (r RuntimeController) SendResponse(c echo.Context) error { |
| 50 | + requestId := c.Param("requestId") |
| 51 | + |
| 52 | + body, err := io.ReadAll(c.Request().Body) |
| 53 | + if err != nil { |
| 54 | + return err |
| 55 | + } |
| 56 | + |
| 57 | + err = r.service.SendResponse(requestId, body) |
| 58 | + if err != nil { |
| 59 | + return echo.NewHTTPError(http.StatusBadRequest, err.Error()) |
| 60 | + } |
| 61 | + |
| 62 | + return nil |
| 63 | +} |
| 64 | + |
| 65 | +func (r RuntimeController) SendError(c echo.Context) error { |
| 66 | + errorType := c.Request().Header.Get(lambda.HeaderLambdaRuntimeFunctionErrorType) |
| 67 | + requestId := c.Param("requestId") |
| 68 | + |
| 69 | + var body event.RuntimeError |
| 70 | + err := c.Bind(&body) |
| 71 | + if err != nil { |
| 72 | + return c.String(http.StatusBadRequest, "invalid body") |
| 73 | + } |
| 74 | + |
| 75 | + err = r.service.SendError(requestId, &body, errorType) |
| 76 | + if err != nil { |
| 77 | + return echo.NewHTTPError(http.StatusBadRequest, err.Error()) |
| 78 | + } |
| 79 | + |
| 80 | + return err |
| 81 | +} |
0 commit comments