-
-
Notifications
You must be signed in to change notification settings - Fork 106
/
question.go
378 lines (341 loc) · 7.68 KB
/
question.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
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
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
package rpc
import (
"sync"
"golang.org/x/net/context"
"zombiezen.com/go/capnproto2"
"zombiezen.com/go/capnproto2/internal/fulfiller"
"zombiezen.com/go/capnproto2/internal/queue"
"zombiezen.com/go/capnproto2/rpc/rpccapnp"
)
type questionTable struct {
tab []*question
gen idgen
manager *manager
calls chan<- *appCall
cancels chan<- *question
}
// new creates a new question with an unassigned ID.
func (qt *questionTable) new(ctx context.Context, method *capnp.Method) *question {
id := questionID(qt.gen.next())
q := &question{
ctx: ctx,
method: method,
manager: qt.manager,
calls: qt.calls,
cancels: qt.cancels,
resolved: make(chan struct{}),
id: id,
}
// TODO(light): populate paramCaps
if int(id) == len(qt.tab) {
qt.tab = append(qt.tab, q)
} else {
qt.tab[id] = q
}
return q
}
func (qt *questionTable) get(id questionID) *question {
var q *question
if int(id) < len(qt.tab) {
q = qt.tab[id]
}
return q
}
func (qt *questionTable) pop(id questionID) *question {
var q *question
if int(id) < len(qt.tab) {
q = qt.tab[id]
qt.tab[id] = nil
qt.gen.remove(uint32(id))
}
return q
}
type question struct {
ctx context.Context
method *capnp.Method // nil if this is bootstrap
paramCaps []exportID
calls chan<- *appCall
cancels chan<- *question
manager *manager
resolved chan struct{}
// Fields below are protected by mu.
mu sync.RWMutex
id questionID
obj capnp.Ptr
err error
state questionState
derived [][]capnp.PipelineOp
}
type questionState uint8
// Question states
const (
questionInProgress questionState = iota
questionResolved
questionCanceled
)
// start signals that the question has been sent.
func (q *question) start() {
go func() {
select {
case <-q.resolved:
case <-q.ctx.Done():
select {
case q.cancels <- q:
case <-q.resolved:
case <-q.manager.finish:
}
case <-q.manager.finish:
// TODO(light): connection should reject all questions on shutdown.
}
}()
}
// fulfill is called to resolve a question successfully and returns the disembargoes.
// It must be called from the coordinate goroutine.
func (q *question) fulfill(obj capnp.Ptr, makeDisembargo func() (embargoID, embargo)) []rpccapnp.Message {
q.mu.Lock()
if q.state != questionInProgress {
q.mu.Unlock()
panic("question.fulfill called more than once")
}
ctab := obj.Segment().Message().CapTable
visited := make([]bool, len(ctab))
msgs := make([]rpccapnp.Message, 0, len(q.derived))
for _, d := range q.derived {
tgt, err := capnp.TransformPtr(obj, d)
if err != nil {
continue
}
in := tgt.Interface()
if !in.IsValid() {
continue
}
client := extractRPCClient(in.Client())
if ic, ok := client.(*importClient); ok && ic.manager == q.manager {
// Imported from remote vat. Don't need to disembargo.
continue
}
if cn := in.Capability(); !visited[cn] {
id, e := makeDisembargo()
ctab[cn] = newEmbargoClient(q.manager, ctab[cn], e)
m := newDisembargoMessage(nil, rpccapnp.Disembargo_context_Which_senderLoopback, id)
dis, _ := m.Disembargo()
mt, _ := dis.NewTarget()
pa, _ := mt.NewPromisedAnswer()
pa.SetQuestionId(uint32(q.id))
transformToPromisedAnswer(m.Segment(), pa, d)
mt.SetPromisedAnswer(pa)
msgs = append(msgs, m)
visited[cn] = true
}
}
q.obj, q.state = obj, questionResolved
close(q.resolved)
q.mu.Unlock()
return msgs
}
// reject is called to resolve a question with failure.
// It must be called from the coordinate goroutine.
func (q *question) reject(state questionState, err error) {
if err == nil {
panic("question.reject called with nil")
}
q.mu.Lock()
if q.state != questionInProgress {
q.mu.Unlock()
panic("question.reject called more than once")
}
q.err, q.state = err, state
close(q.resolved)
q.mu.Unlock()
}
func (q *question) peek() (id questionID, obj capnp.Ptr, err error, ok bool) {
q.mu.RLock()
id, obj, err, ok = q.id, q.obj, q.err, q.state != questionInProgress
q.mu.RUnlock()
return
}
func (q *question) addPromise(transform []capnp.PipelineOp) {
q.mu.Lock()
defer q.mu.Unlock()
for _, d := range q.derived {
if transformsEqual(transform, d) {
return
}
}
q.derived = append(q.derived, transform)
}
func transformsEqual(t, u []capnp.PipelineOp) bool {
if len(t) != len(u) {
return false
}
for i := range t {
if t[i].Field != u[i].Field {
return false
}
}
return true
}
func (q *question) Struct() (capnp.Struct, error) {
<-q.resolved
_, obj, err, _ := q.peek()
return obj.Struct(), err
}
func (q *question) PipelineCall(transform []capnp.PipelineOp, ccall *capnp.Call) capnp.Answer {
ac, achan := newAppPipelineCall(q, transform, ccall)
select {
case q.calls <- ac:
case <-ccall.Ctx.Done():
return capnp.ErrorAnswer(ccall.Ctx.Err())
case <-q.manager.finish:
return capnp.ErrorAnswer(q.manager.err())
}
select {
case a := <-achan:
return a
case <-ccall.Ctx.Done():
return capnp.ErrorAnswer(ccall.Ctx.Err())
case <-q.manager.finish:
return capnp.ErrorAnswer(q.manager.err())
}
}
func (q *question) PipelineClose(transform []capnp.PipelineOp) error {
<-q.resolved
_, obj, err, _ := q.peek()
if err != nil {
return err
}
x, err := capnp.TransformPtr(obj, transform)
if err != nil {
return err
}
c := x.Interface().Client()
if c == nil {
return capnp.ErrNullClient
}
return c.Close()
}
// embargoClient is a client that waits until an embargo signal is
// received to deliver calls.
type embargoClient struct {
manager *manager
client capnp.Client
embargo embargo
mu sync.RWMutex
q queue.Queue
}
func newEmbargoClient(manager *manager, client capnp.Client, e embargo) *embargoClient {
ec := &embargoClient{
manager: manager,
client: client,
embargo: e,
}
ec.q.Init(make(ecallList, callQueueSize), 0)
go ec.flushQueue()
return ec
}
func (ec *embargoClient) push(cl *capnp.Call) capnp.Answer {
f := new(fulfiller.Fulfiller)
cl, err := cl.Copy(nil)
if err != nil {
return capnp.ErrorAnswer(err)
}
if ok := ec.q.Push(ecall{cl, f}); !ok {
return capnp.ErrorAnswer(errQueueFull)
}
return f
}
func (ec *embargoClient) peek() ecall {
if ec.q.Len() == 0 {
return ecall{}
}
return ec.q.Peek().(ecall)
}
func (ec *embargoClient) pop() ecall {
if ec.q.Len() == 0 {
return ecall{}
}
return ec.q.Pop().(ecall)
}
func (ec *embargoClient) Call(cl *capnp.Call) capnp.Answer {
// Fast path: queue is flushed.
ec.mu.RLock()
ok := ec.isPassthrough()
ec.mu.RUnlock()
if ok {
return ec.client.Call(cl)
}
ec.mu.Lock()
if ec.isPassthrough() {
ec.mu.Unlock()
return ec.client.Call(cl)
}
ans := ec.push(cl)
ec.mu.Unlock()
return ans
}
func (ec *embargoClient) WrappedClient() capnp.Client {
ec.mu.RLock()
ok := ec.isPassthrough()
ec.mu.RUnlock()
if !ok {
return nil
}
return ec.client
}
func (ec *embargoClient) isPassthrough() bool {
select {
case <-ec.embargo:
default:
return false
}
return ec.q.Len() == 0
}
func (ec *embargoClient) Close() error {
ec.mu.Lock()
for {
c := ec.pop()
if c.call == nil {
break
}
c.f.Reject(errQueueCallCancel)
}
ec.mu.Unlock()
return ec.client.Close()
}
// flushQueue is run in its own goroutine.
func (ec *embargoClient) flushQueue() {
select {
case <-ec.embargo:
case <-ec.manager.finish:
return
}
ec.mu.RLock()
c := ec.peek()
ec.mu.RUnlock()
for c.call != nil {
ans := ec.client.Call(c.call)
go joinFulfiller(c.f, ans)
ec.mu.Lock()
ec.pop()
c = ec.peek()
ec.mu.Unlock()
}
}
type ecall struct {
call *capnp.Call
f *fulfiller.Fulfiller
}
type ecallList []ecall
func (el ecallList) Len() int {
return len(el)
}
func (el ecallList) At(i int) interface{} {
return el[i]
}
func (el ecallList) Set(i int, x interface{}) {
if x == nil {
el[i] = ecall{}
} else {
el[i] = x.(ecall)
}
}