-
Notifications
You must be signed in to change notification settings - Fork 3
/
main.go
86 lines (72 loc) · 1.89 KB
/
main.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
package main
import (
"context"
"log"
wasm "github.com/wasmerio/go-ext-wasm/wasmer"
y3 "github.com/yomorun/y3-codec-golang"
"github.com/yomorun/yomo/pkg/quic"
)
var (
addr = "0.0.0.0:4141"
)
func main() {
go serveSinkServer(addr)
select {}
}
// serveSinkServer serves the Sink server over QUIC.
func serveSinkServer(addr string) {
log.Print("Starting sink server...")
quicServer := quic.NewServer(&quicServerHandler{})
err := quicServer.ListenAndServe(context.Background(), addr)
if err != nil {
log.Printf("❌ Serve the yomo-ssvm-example on %s failure with err: %v", addr, err)
}
}
type quicServerHandler struct {
}
func (s *quicServerHandler) Listen() error {
return nil
}
func (s *quicServerHandler) Read(st quic.Stream) error {
// decode the data via Y3 Codec.
ch := y3.
FromStream(st).
Subscribe(0x10).
OnObserve(onObserve)
go func() {
for item := range ch {
// Invoke wasm
val := triple(item.(noiseData).Noise)
println(val)
}
}()
return nil
}
type noiseData struct {
Noise float64 `yomo:"0x11" fauna:"noise"` // Noise value
Time int64 `yomo:"0x12" fauna:"time"` // Timestamp (ms)
From string `yomo:"0x13" fauna:"from"` // Source IP
}
func onObserve(v []byte) (interface{}, error) {
// decode the data via Y3 Codec.
data := noiseData{}
err := y3.ToObject(v, &data)
if err != nil {
log.Print(err)
return nil, err
}
return data, nil
}
func triple(i float64) float64 {
// Reads the WebAssembly module as bytes.
bytes, _ := wasm.ReadBytes("triple/pkg/triple_lib_bg.wasm")
// Instantiates the WebAssembly module.
instance, _ := wasm.NewInstance(bytes)
defer instance.Close()
// Gets the `sum` exported function from the WebAssembly instance.
sum := instance.Exports["triple"]
// Calls that exported function with Go standard values. The WebAssembly
// types are inferred and values are casted automatically.
result, _ := sum(i)
return result.ToF64()
}