-
Notifications
You must be signed in to change notification settings - Fork 22
/
api.go
84 lines (68 loc) 路 2.17 KB
/
api.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
package http
import (
"fmt"
"time"
goHttp "net/http"
iface "github.com/taubyte/go-interfaces/services/substrate/components/http"
http "github.com/taubyte/http"
"github.com/taubyte/tau/protocols/substrate/components/http/common"
"github.com/taubyte/tau/vm/counter"
"github.com/taubyte/tau/vm/helpers"
"github.com/taubyte/tau/vm/lookup"
)
func (s *Service) Lookup(matcher *common.MatchDefinition) (iface.Serviceable, error) {
// TODO: Lookup should not be in vm/
servs, err := lookup.Lookup(s, matcher)
if err != nil {
return nil, fmt.Errorf("http serviceable lookup failed with: %w", err)
}
if len(servs) != 1 {
// probably we got old entries in cache. let's purge them and try again
for _, srv := range servs {
s.Cache().Remove(srv)
}
servs, err = lookup.Lookup(s, matcher)
if err != nil {
return nil, fmt.Errorf("http serviceable lookup failed with: %w", err)
} else if len(servs) != 1 {
return nil, fmt.Errorf("lookup returned %d serviceables, expected 1", len(servs))
}
}
pick, ok := servs[0].(iface.Serviceable)
if !ok {
return nil, fmt.Errorf("matched serviceable is not a http serviceable")
}
return pick, nil
}
func (s *Service) handle(w goHttp.ResponseWriter, r *goHttp.Request) error {
startTime := time.Now()
matcher := common.New(helpers.ExtractHost(r.Host), r.URL.Path, r.Method)
pick, err := s.Lookup(matcher)
if err != nil {
return fmt.Errorf("looking up serviceable failed with: %w", err)
}
if !pick.IsProvisioned() {
pick, err = pick.Provision()
if err != nil {
return fmt.Errorf("provisioning serviceable failed with: %w", err)
}
}
if err := pick.Ready(); err != nil {
return counter.ErrorWrapper(pick, startTime, time.Time{}, fmt.Errorf("HTTP serviceable is not ready with: %s", err))
}
coldStartDoneTime, err := pick.Handle(w, r, matcher)
return counter.ErrorWrapper(pick, startTime, coldStartDoneTime, err)
}
func (s *Service) Handler(w goHttp.ResponseWriter, r *goHttp.Request) {
if err := s.handle(w, r); err != nil {
w.Write([]byte(err.Error()))
w.WriteHeader(500)
}
}
func (s *Service) attach() error {
s.Http().LowLevel(&http.LowLevelDefinition{
PathPrefix: "/",
Handler: s.Handler,
})
return nil
}