-
-
Notifications
You must be signed in to change notification settings - Fork 24
Expand file tree
/
Copy pathsubscriber.go
More file actions
292 lines (248 loc) · 8.44 KB
/
Copy pathsubscriber.go
File metadata and controls
292 lines (248 loc) · 8.44 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
// Copyright 2025 samber.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://github.com/samber/ro/blob/main/licenses/LICENSE.apache.md
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package ro
import (
"context"
"sync"
"sync/atomic"
)
// Subscriber implements the Observer and Subscription interfaces. While the Observer is
// the public API for consuming the values of an Observable, all Observers get
// converted to a Subscriber, in order to provide Subscription-like capabilities
// such as `Unsubscribe()`. Subscriber is a common type in samber/ro, and crucial for
// implementing operators, but it is rarely used as a public API.
type Subscriber[T any] interface {
Subscription
Observer[T]
}
var _ Subscriber[int] = (*subscriberImpl[int])(nil)
// NewSubscriber creates a new Subscriber from an Observer. If the Observer
// is already a Subscriber, it is returned as is. Otherwise, a new Subscriber
// is created that wraps the Observer.
//
// The returned Subscriber will unsubscribe from the destination Observer when
// Unsubscribe() is called.
//
// This method is safe for concurrent use.
//
// It is rarely used as a public API.
func NewSubscriber[T any](destination Observer[T]) Subscriber[T] {
return NewSafeSubscriber(destination)
}
// NewSafeSubscriber creates a new Subscriber from an Observer. If the Observer
// is already a Subscriber, it is returned as is. Otherwise, a new Subscriber
// is created that wraps the Observer.
//
// The returned Subscriber will unsubscribe from the destination Observer when
// Unsubscribe() is called.
//
// This method is safe for concurrent use.
//
// It is rarely used as a public API.
func NewSafeSubscriber[T any](destination Observer[T]) Subscriber[T] {
return NewSubscriberWithConcurrencyMode(destination, ConcurrencyModeSafe)
}
// NewUnsafeSubscriber creates a new Subscriber from an Observer. If the Observer
// is already a Subscriber, it is returned as is. Otherwise, a new Subscriber
// is created that wraps the Observer.
//
// The returned Subscriber will unsubscribe from the destination Observer when
// Unsubscribe() is called.
//
// This method is not safe for concurrent use.
//
// It is rarely used as a public API.
func NewUnsafeSubscriber[T any](destination Observer[T]) Subscriber[T] {
return NewSubscriberWithConcurrencyMode(destination, ConcurrencyModeUnsafe)
}
// NewEventuallySafeSubscriber creates a new Subscriber from an Observer. If the Observer
// is already a Subscriber, it is returned as is. Otherwise, a new Subscriber
// is created that wraps the Observer.
//
// The returned Subscriber will unsubscribe from the destination Observer when
// Unsubscribe() is called.
//
// This method is safe for concurrent use, but concurrent messages are dropped.
//
// It is rarely used as a public API.
func NewEventuallySafeSubscriber[T any](destination Observer[T]) Subscriber[T] {
return NewSubscriberWithConcurrencyMode(destination, ConcurrencyModeEventuallySafe)
}
// NewSubscriberWithConcurrencyMode creates a new Subscriber from an Observer. If the Observer
// is already a Subscriber, it is returned as is. Otherwise, a new Subscriber
// is created that wraps the Observer.
//
// The returned Subscriber will unsubscribe from the destination Observer when
// Unsubscribe() is called.
//
// It is rarely used as a public API.
func NewSubscriberWithConcurrencyMode[T any](destination Observer[T], mode ConcurrencyMode) Subscriber[T] {
// Spinlock is ignored because it is too slow when chaining operators. Spinlock should be used
// only for short-lived local locks.
switch mode {
case ConcurrencyModeSafe:
return newSubscriberImpl(mode, false, BackpressureBlock, destination)
case ConcurrencyModeUnsafe:
return newSubscriberImpl(mode, true, BackpressureBlock, destination)
case ConcurrencyModeEventuallySafe:
return newSubscriberImpl(mode, false, BackpressureDrop, destination)
default:
panic("invalid concurrency mode")
}
}
// newSubscriberImpl creates a new subscriber implementation with the specified
// synchronization behavior and destination observer.
func newSubscriberImpl[T any](mode ConcurrencyMode, noLock bool, backpressure Backpressure, destination Observer[T]) Subscriber[T] {
// Protect against multiple encapsulation layers.
if subscriber, ok := destination.(Subscriber[T]); ok {
return subscriber
}
subscriber := &subscriberImpl[T]{
status: 0, // KindNext
backpressure: backpressure,
noLock: noLock,
destination: destination,
Subscription: NewSubscription(nil),
mode: mode,
}
if subscription, ok := destination.(Subscription); ok {
subscription.Add(subscriber.Unsubscribe)
}
return subscriber
}
type subscriberImpl[T any] struct {
// While mutex is used for synchronization of producer, status is used for storing state of
// the subscriber. Using the mutex for reading the status would have create a dead lock if
// an Observer calls Unsubscribe(), IsClosed(), HasThrown(), IsCompleted() synchronously.
//
// 0 - KindNext
// 1 - KindError
// 2 - KindComplete
status int32
backpressure Backpressure
_ [59]byte // padding to prevent false sharing
// Mutexes are much faster than channels.
//
// A concrete sync.Mutex (instead of an xsync.Mutex interface) keeps the
// lock fast path inlinable: interface dispatch on every Next is measurably
// slower. ConcurrencyModeUnsafe skips the lock via the noLock flag.
//
// Also, generators has been added in go1.23. A different implem of Observable/Observer
// might reduce latency induced by mutexes.
//
// It could be interesting to implement a lock-free version of this,
// with message drop instead of backpressure, and when SLO must be kept under
// control (real-time streams?).
mu sync.Mutex
noLock bool
destination Observer[T]
Subscription
mode ConcurrencyMode
}
func (s *subscriberImpl[T]) lock() {
if !s.noLock {
s.mu.Lock()
}
}
func (s *subscriberImpl[T]) unlock() {
if !s.noLock {
s.mu.Unlock()
}
}
func (s *subscriberImpl[T]) tryLock() bool {
if s.noLock {
return true
}
return s.mu.TryLock()
}
// Implements Observer.
func (s *subscriberImpl[T]) Next(v T) {
s.NextWithContext(context.Background(), v)
}
// Implements Observer.
func (s *subscriberImpl[T]) NextWithContext(ctx context.Context, v T) {
if s.destination == nil {
return
}
if s.backpressure == BackpressureDrop {
if !s.tryLock() {
OnDroppedNotification(ctx, NewNotificationNext(v))
return
}
} else {
s.lock()
}
if atomic.LoadInt32(&s.status) == 0 {
s.destination.NextWithContext(ctx, v)
} else {
OnDroppedNotification(ctx, NewNotificationNext(v))
}
s.unlock()
}
// Implements Observer.
func (s *subscriberImpl[T]) Error(err error) {
s.ErrorWithContext(context.Background(), err)
}
// Implements Observer.
func (s *subscriberImpl[T]) ErrorWithContext(ctx context.Context, err error) {
s.lock()
if atomic.CompareAndSwapInt32(&s.status, 0, 1) {
if s.destination != nil {
s.destination.ErrorWithContext(ctx, err)
}
} else {
OnDroppedNotification(ctx, NewNotificationError[T](err))
}
s.unlock()
s.unsubscribe()
}
// Implements Observer.
func (s *subscriberImpl[T]) Complete() {
s.CompleteWithContext(context.Background())
}
// Implements Observer.
func (s *subscriberImpl[T]) CompleteWithContext(ctx context.Context) {
s.lock()
if atomic.CompareAndSwapInt32(&s.status, 0, 2) {
if s.destination != nil {
s.destination.CompleteWithContext(ctx)
}
} else {
OnDroppedNotification(ctx, NewNotificationComplete[T]())
}
s.unlock()
s.unsubscribe()
}
// Implements Observer.
func (s *subscriberImpl[T]) IsClosed() bool {
return atomic.LoadInt32(&s.status) != 0
}
// Implements Observer.
func (s *subscriberImpl[T]) HasThrown() bool {
return atomic.LoadInt32(&s.status) == 1
}
// Implements Observer.
func (s *subscriberImpl[T]) IsCompleted() bool {
return atomic.LoadInt32(&s.status) == 2
}
// Implements Observer.
func (s *subscriberImpl[T]) Unsubscribe() {
if atomic.CompareAndSwapInt32(&s.status, 0, 2) {
s.unsubscribe()
}
}
func (s *subscriberImpl[T]) unsubscribe() {
// s.Subscription.Unsubscribe() is protected against concurrent calls.
s.Subscription.Unsubscribe()
}