Changeset 0.11.0 (#62)
This commit is contained in:
@@ -3,6 +3,7 @@ package events
|
||||
import (
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
// Bus is a labeled publish/subscribe event bus.
|
||||
@@ -114,3 +115,28 @@ func match(label, pattern string) bool {
|
||||
prefix := pattern[:len(pattern)-1] // "chat.message." from "chat.message.*"
|
||||
return strings.HasPrefix(label, prefix)
|
||||
}
|
||||
|
||||
// WaitFor subscribes to an exact label and blocks until an event arrives
|
||||
// or the timeout elapses. Returns the event and true, or a zero Event and
|
||||
// false on timeout. The subscription is automatically removed after.
|
||||
//
|
||||
// Used by the browser tool bridge: the server publishes tool.call.{id}
|
||||
// to the client and then calls WaitFor("tool.result.{id}", 30s) to block
|
||||
// until the browser returns the result.
|
||||
func (b *Bus) WaitFor(label string, timeout time.Duration) (Event, bool) {
|
||||
ch := make(chan Event, 1)
|
||||
unsub := b.Subscribe(label, func(e Event) {
|
||||
select {
|
||||
case ch <- e:
|
||||
default:
|
||||
}
|
||||
})
|
||||
defer unsub()
|
||||
|
||||
select {
|
||||
case e := <-ch:
|
||||
return e, true
|
||||
case <-time.After(timeout):
|
||||
return Event{}, false
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user