-
-
Notifications
You must be signed in to change notification settings - Fork 106
/
definitions.go
69 lines (60 loc) · 1.45 KB
/
definitions.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
// Copyright © 2023 Ory Corp
// SPDX-License-Identifier: Apache-2.0
package watcherx
import (
"context"
"fmt"
"net/url"
)
type (
errSchemeUnknown struct {
scheme string
}
EventChannel chan Event
Watcher interface {
// DispatchNow fires the watcher and causes an event.
//
// WARNING: The returned channel must be read or no further events will
// be propagated due to a deadlock.
DispatchNow() (<-chan int, error)
}
dispatcher struct {
trigger chan struct{}
done chan int
}
)
var (
// ErrSchemeUnknown is just for checking with errors.Is()
ErrSchemeUnknown = &errSchemeUnknown{}
ErrWatcherNotRunning = fmt.Errorf("watcher is not running")
)
func (e *errSchemeUnknown) Is(other error) bool {
_, ok := other.(*errSchemeUnknown)
return ok
}
func (e *errSchemeUnknown) Error() string {
return fmt.Sprintf("unknown scheme '%s' to watch", e.scheme)
}
func newDispatcher() *dispatcher {
return &dispatcher{
trigger: make(chan struct{}),
done: make(chan int),
}
}
func (d *dispatcher) DispatchNow() (<-chan int, error) {
if d.trigger == nil {
return nil, ErrWatcherNotRunning
}
d.trigger <- struct{}{}
return d.done, nil
}
func Watch(ctx context.Context, u *url.URL, c EventChannel) (Watcher, error) {
switch u.Scheme {
// see urlx.Parse for why the empty string is also file
case "file", "":
return WatchFile(ctx, u.Path, c)
case "ws":
return WatchWebsocket(ctx, u, c)
}
return nil, &errSchemeUnknown{u.Scheme}
}