| 1 |
// Copyright 2012-2024 The NATS Authors |
| 2 |
// Licensed under the Apache License, Version 2.0 (the "License"); |
| 3 |
// you may not use this file except in compliance with the License. |
| 4 |
// You may obtain a copy of the License at |
| 5 |
// |
| 6 |
// http://www.apache.org/licenses/LICENSE-2.0 |
| 7 |
// |
| 8 |
// Unless required by applicable law or agreed to in writing, software |
| 9 |
// distributed under the License is distributed on an "AS IS" BASIS, |
| 10 |
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 11 |
// See the License for the specific language governing permissions and |
| 12 |
// limitations under the License. |
| 13 |
|
| 14 |
//go:build go1.23 |
| 15 |
|
| 16 |
package nats |
| 17 |
|
| 18 |
import ( |
| 19 |
"errors" |
| 20 |
"iter" |
| 21 |
"time" |
| 22 |
) |
| 23 |
|
| 24 |
// Msgs returns an iter.Seq2[*Msg, error] that can be used to iterate over |
| 25 |
// messages. It can only be used with a subscription that has been created with |
| 26 |
// SubscribeSync or QueueSubscribeSync, otherwise it will return an error on the |
| 27 |
// first iteration. |
| 28 |
// |
| 29 |
// The iterator will block until a message is available. The |
| 30 |
// subscription will not be closed when the iterator is done. |
| 31 |
func (sub *Subscription) Msgs() iter.Seq2[*Msg, error] { |
| 32 |
return func(yield func(*Msg, error) bool) { |
| 33 |
for { |
| 34 |
msg, err := sub.nextMsgNoTimeout() |
| 35 |
if err != nil { |
| 36 |
yield(nil, err) |
| 37 |
return |
| 38 |
} |
| 39 |
if !yield(msg, nil) { |
| 40 |
return |
| 41 |
} |
| 42 |
|
| 43 |
} |
| 44 |
} |
| 45 |
} |
| 46 |
|
| 47 |
// MsgsTimeout returns an iter.Seq2[*Msg, error] that can be used to iterate |
| 48 |
// over messages. It can only be used with a subscription that has been created |
| 49 |
// with SubscribeSync or QueueSubscribeSync, otherwise it will return an error |
| 50 |
// on the first iteration. |
| 51 |
// |
| 52 |
// The iterator will block until a message is available or the timeout is |
| 53 |
// reached. If the timeout is reached, the iterator will return nats.ErrTimeout |
| 54 |
// but it will not be closed. |
| 55 |
func (sub *Subscription) MsgsTimeout(timeout time.Duration) iter.Seq2[*Msg, error] { |
| 56 |
return func(yield func(*Msg, error) bool) { |
| 57 |
for { |
| 58 |
msg, err := sub.NextMsg(timeout) |
| 59 |
if err != nil { |
| 60 |
if !yield(nil, err) { |
| 61 |
return |
| 62 |
} |
| 63 |
if !errors.Is(err, ErrTimeout) { |
| 64 |
return |
| 65 |
} |
| 66 |
continue |
| 67 |
} |
| 68 |
if !yield(msg, nil) { |
| 69 |
return |
| 70 |
} |
| 71 |
} |
| 72 |
} |
| 73 |
} |