forked from blessnetwork/b7s
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathinstall.go
82 lines (63 loc) · 1.76 KB
/
install.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
package api
import (
"context"
"errors"
"fmt"
"net/http"
"strconv"
"time"
"github.com/labstack/echo/v4"
)
const (
functionInstallTimeout = 10 * time.Second
)
func (r FunctionInstallRequest) Valid() error {
if r.Cid == "" {
return errors.New("function CID is required")
}
return nil
}
func (a *API) InstallFunction(ctx echo.Context) error {
// Unpack the API request.
var req FunctionInstallRequest
err := ctx.Bind(&req)
if err != nil {
return echo.NewHTTPError(http.StatusBadRequest, fmt.Errorf("could not unpack request: %w", err))
}
err = req.Valid()
if err != nil {
return echo.NewHTTPError(http.StatusBadRequest, fmt.Errorf("invalid request: %w", err))
}
// Add a deadline to the context.
reqCtx, cancel := context.WithTimeout(ctx.Request().Context(), functionInstallTimeout)
defer cancel()
// Start function install in a separate goroutine and signal when it's done.
fnErr := make(chan error)
go func() {
err = a.Node.PublishFunctionInstall(reqCtx, req.Uri, req.Cid, req.Topic)
fnErr <- err
}()
// Wait until either function install finishes, or request times out.
select {
// Context timed out.
case <-reqCtx.Done():
status := http.StatusRequestTimeout
if !errors.Is(reqCtx.Err(), context.DeadlineExceeded) {
status = http.StatusInternalServerError
}
// return inner code as body
return ctx.JSON(200, map[string]interface{}{
"code": strconv.Itoa(status),
})
// Work done.
case err = <-fnErr:
break
}
// Check if function install succeeded and handle error or return response.
if err != nil {
return echo.NewHTTPError(http.StatusInternalServerError, fmt.Errorf("function installation failed: %w", err))
}
return ctx.JSON(http.StatusOK, map[string]interface{}{
"code": strconv.Itoa(http.StatusOK),
})
}