forked from fiatjaf/etleneum
-
Notifications
You must be signed in to change notification settings - Fork 1
/
stream.go
81 lines (69 loc) · 1.85 KB
/
stream.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
package main
import (
"encoding/json"
"net/http"
"time"
"github.com/gorilla/mux"
"gopkg.in/antage/eventsource.v1"
)
type ctevent struct {
Id string `json:"id"`
ContractId string `json:"contract_id,omitempty"`
Method string `json:"method,omitempty"`
Msatoshi int64 `json:"msatoshi,omitempty"`
Message string `json:"message,omitempty"`
Kind string `json:"kind,omitempty"`
}
func dispatchContractEvent(contractId string, ev ctevent, typ string) {
jpayload, _ := json.Marshal(ev)
payload := string(jpayload)
if ies, ok := contractstreams.Get(contractId); ok {
ies.(eventsource.EventSource).SendEventMessage(payload, typ, "")
}
}
func contractStream(w http.ResponseWriter, r *http.Request) {
ctid := mux.Vars(r)["ctid"]
var es eventsource.EventSource
ies, ok := contractstreams.Get(ctid)
if !ok {
es = eventsource.New(
&eventsource.Settings{
Timeout: 5 * time.Second,
CloseOnTimeout: true,
IdleTimeout: 1 * time.Minute,
},
func(r *http.Request) [][]byte {
return [][]byte{
[]byte("X-Accel-Buffering: no"),
[]byte("Cache-Control: no-cache"),
[]byte("Content-Type: text/event-stream"),
[]byte("Connection: keep-alive"),
[]byte("Access-Control-Allow-Origin: *"),
}
},
)
go func() {
for {
time.Sleep(25 * time.Second)
es.SendEventMessage("", "keepalive", "")
}
}()
contractstreams.Set(ctid, es)
} else {
es = ies.(eventsource.EventSource)
}
go func() {
time.Sleep(1 * time.Second)
es.SendRetryMessage(3 * time.Second)
}()
es.ServeHTTP(w, r)
}
type callPrinter struct {
ContractId string
CallId string
Method string
}
func (cp *callPrinter) Write(data []byte) (n int, err error) {
dispatchContractEvent(cp.ContractId, ctevent{cp.CallId, cp.ContractId, cp.Method, 0, string(data), "print"}, "call-run-event")
return len(data), nil
}