-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathengine.go
More file actions
292 lines (253 loc) · 6.38 KB
/
engine.go
File metadata and controls
292 lines (253 loc) · 6.38 KB
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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
package godvm
import (
"context"
"errors"
"log"
"os"
"sync"
goNostr "github.com/nbd-wtf/go-nostr"
"github.com/sebdeveloper6952/godvm/lightning"
)
type Engine struct {
dvmsByKind map[int][]Dvmer
nostrSvc NostrService
lnSvc lightning.Service
log *log.Logger
waitingForEvent map[string][]chan *goNostr.Event
}
func NewEngine() (*Engine, error) {
logger := log.New(os.Stderr, "[godvm] ", log.LstdFlags)
nostrSvc, err := NewNostrService(
logger,
)
if err != nil {
return nil, err
}
e := &Engine{
dvmsByKind: make(map[int][]Dvmer),
waitingForEvent: make(map[string][]chan *goNostr.Event),
nostrSvc: nostrSvc,
log: logger,
}
return e, nil
}
func (e *Engine) RegisterDVM(dvm Dvmer) {
kindSupported := dvm.KindSupported()
if _, ok := e.dvmsByKind[kindSupported]; !ok {
e.dvmsByKind[kindSupported] = make([]Dvmer, 0, 2)
}
e.dvmsByKind[kindSupported] = append(e.dvmsByKind[kindSupported], dvm)
}
func (e *Engine) SetLnService(ln lightning.Service) {
e.lnSvc = ln
}
func (e *Engine) Run(
ctx context.Context,
initialRelays []string,
) error {
if initialRelays == nil || len(initialRelays) == 0 {
return errors.New("must provide at least one relay")
}
kindsSupported := e.getKindsSupported()
go func() {
if err := e.nostrSvc.Run(ctx, kindsSupported, initialRelays); err != nil {
e.log.Printf("run nostr service %+v", err)
}
e.advertiseDvms(ctx)
}()
go func() {
for {
select {
case event := <-e.nostrSvc.JobRequestEvents():
dvmsForKind, ok := e.dvmsByKind[event.Kind]
if !ok {
e.log.Printf("no dvms for kind %d\n", event.Kind)
continue
}
nip90Input, err := Nip90InputFromJobRequestEvent(event)
if err != nil {
e.log.Printf("nip90Input from event %+v\n", err)
continue
}
// if the inputs are asking for events/jobs, we fetch them here before proceeding
var wg sync.WaitGroup
for inputIdx := range nip90Input.Inputs {
if nip90Input.Inputs[inputIdx].Type == InputTypeEvent ||
nip90Input.Inputs[inputIdx].Type == InputTypeJob {
wg.Add(1)
go func(input *Input) {
defer wg.Done()
// TODO: must handle when the event is not found, only when the input type is "event".
// When input type is "job", we have to wait no matter what, because it could
// be a job that is completed in the future.
waitCh, err := e.nostrSvc.FetchEvent(ctx, input.Value)
if err != nil {
e.log.Printf("fetch event for job input %+v", err)
return
}
input.Event = <-waitCh
e.log.Printf("fetched event for job input")
}(nip90Input.Inputs[inputIdx])
}
}
wg.Wait()
e.log.Printf("finished waiting for input events")
for i := range dvmsForKind {
go func(dvm Dvmer, input *Nip90Input) {
if err := e.runDvm(ctx, dvm, input); err != nil {
e.log.Println(err)
}
}(dvmsForKind[i], nip90Input)
}
case <-ctx.Done():
return
}
}
}()
return nil
}
func (e *Engine) runDvm(ctx context.Context, dvm Dvmer, input *Nip90Input) error {
chanToDvm := make(chan *JobUpdate)
chanToEngine := make(chan *JobUpdate)
defer func() {
close(chanToDvm)
}()
if !dvm.Run(ctx, input, chanToDvm, chanToEngine) {
return errors.New("job not accepted by DVM")
}
for {
select {
case update := <-chanToEngine:
if update.Status == StatusPaymentRequired || update.Status == StatusSuccessWithPayment {
invoice, err := e.addInvoiceAndTrack(ctx, chanToDvm, int64(update.AmountSats))
if err != nil {
return err
}
update.PaymentRequest = invoice.PayReq
}
if err := e.sendFeedbackEvent(
ctx,
dvm,
input,
update,
); err != nil {
return err
}
if update.Status == StatusSuccess || update.Status == StatusSuccessWithPayment {
if err := e.sendJobResultEvent(
ctx,
dvm,
input,
update,
); err != nil {
return err
}
// if success status, exit this goroutine to free resources
return nil
}
case <-ctx.Done():
e.log.Printf("job context canceled")
return nil
}
}
}
// advertiseDvms publishes two events:
// - kind 31990 for nip-89 handler information
// - kind 0 for nip-01 profile metadata
func (e *Engine) advertiseDvms(ctx context.Context) {
for kind, dvms := range e.dvmsByKind {
for i := range dvms {
ev := NewHandlerInformationEvent(
dvms[i].PublicKeyHex(),
dvms[i].Profile(),
[]int{kind},
dvms[i].Version(),
)
dvms[i].Sign(ev)
if err := e.nostrSvc.PublishEvent(ctx, *ev); err != nil {
e.log.Printf("publish nip-89 %s %+v", dvms[i].PublicKeyHex(), err)
}
profileEv := NewProfileMetadataEvent(
dvms[i].PublicKeyHex(),
dvms[i].Profile(),
)
dvms[i].Sign(profileEv)
if err := e.nostrSvc.PublishEvent(ctx, *profileEv); err != nil {
e.log.Printf("publish profile %s %+v", dvms[i].PublicKeyHex(), err)
}
}
}
}
func (e *Engine) addInvoiceAndTrack(
ctx context.Context,
chanToDvm chan<- *JobUpdate,
amountSats int64,
) (*lightning.Invoice, error) {
invoice, err := e.lnSvc.AddInvoice(ctx, amountSats)
if err != nil {
chanToDvm <- &JobUpdate{
Status: StatusError,
}
return nil, err
}
go func() {
u, e := e.lnSvc.TrackInvoice(ctx, invoice)
trackInvoiceLoop:
for {
select {
case invoiceUpdate := <-u:
if invoiceUpdate.Settled {
chanToDvm <- &JobUpdate{
Status: StatusPaymentCompleted,
}
break trackInvoiceLoop
}
case <-e:
chanToDvm <- &JobUpdate{
Status: StatusError,
}
return
}
}
}()
return invoice, nil
}
func (e *Engine) sendFeedbackEvent(
ctx context.Context,
dvm Dvmer,
input *Nip90Input,
update *JobUpdate,
) error {
feedbackEvent := Nip90JobFeedbackFromEngineUpdate(input, update)
if err := dvm.Sign(feedbackEvent); err != nil {
return err
}
return e.nostrSvc.PublishEvent(
ctx,
*feedbackEvent,
input.Relays...,
)
}
func (e *Engine) sendJobResultEvent(
ctx context.Context,
dvm Dvmer,
input *Nip90Input,
update *JobUpdate,
) error {
jobResultEvent := Nip90JobResultFromEngineUpdate(input, update)
if err := dvm.Sign(jobResultEvent); err != nil {
return err
}
return e.nostrSvc.PublishEvent(
ctx,
*jobResultEvent,
input.Relays...,
)
}
func (e *Engine) getKindsSupported() []int {
kinds := make([]int, 0, len(e.dvmsByKind))
for kindKey := range e.dvmsByKind {
kinds = append(kinds, kindKey)
}
return kinds
}