| 1 |
// Copyright 2012-2023 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 |
package nats |
| 15 |
|
| 16 |
import ( |
| 17 |
"errors" |
| 18 |
"fmt" |
| 19 |
"reflect" |
| 20 |
"sync" |
| 21 |
"time" |
| 22 |
|
| 23 |
// Default Encoders |
| 24 |
"github.com/nats-io/nats.go/encoders/builtin" |
| 25 |
) |
| 26 |
|
| 27 |
//lint:file-ignore SA1019 Ignore deprecation warnings for EncodedConn |
| 28 |
|
| 29 |
// Encoder interface is for all register encoders |
| 30 |
// |
| 31 |
// Deprecated: Encoded connections are no longer supported. |
| 32 |
type Encoder interface { |
| 33 |
Encode(subject string, v any) ([]byte, error) |
| 34 |
Decode(subject string, data []byte, vPtr any) error |
| 35 |
} |
| 36 |
|
| 37 |
var encMap map[string]Encoder |
| 38 |
var encLock sync.Mutex |
| 39 |
|
| 40 |
// Indexed names into the Registered Encoders. |
| 41 |
const ( |
| 42 |
JSON_ENCODER = "json" |
| 43 |
GOB_ENCODER = "gob" |
| 44 |
DEFAULT_ENCODER = "default" |
| 45 |
) |
| 46 |
|
| 47 |
func init() { |
| 48 |
encMap = make(map[string]Encoder) |
| 49 |
// Register json, gob and default encoder |
| 50 |
RegisterEncoder(JSON_ENCODER, &builtin.JsonEncoder{}) |
| 51 |
RegisterEncoder(GOB_ENCODER, &builtin.GobEncoder{}) |
| 52 |
RegisterEncoder(DEFAULT_ENCODER, &builtin.DefaultEncoder{}) |
| 53 |
} |
| 54 |
|
| 55 |
// EncodedConn are the preferred way to interface with NATS. They wrap a bare connection to |
| 56 |
// a nats server and have an extendable encoder system that will encode and decode messages |
| 57 |
// from raw Go types. |
| 58 |
// |
| 59 |
// Deprecated: Encoded connections are no longer supported. |
| 60 |
type EncodedConn struct { |
| 61 |
Conn *Conn |
| 62 |
Enc Encoder |
| 63 |
} |
| 64 |
|
| 65 |
// NewEncodedConn will wrap an existing Connection and utilize the appropriate registered |
| 66 |
// encoder. |
| 67 |
// |
| 68 |
// Deprecated: Encoded connections are no longer supported. |
| 69 |
func NewEncodedConn(c *Conn, encType string) (*EncodedConn, error) { |
| 70 |
if c == nil { |
| 71 |
return nil, errors.New("nats: Nil Connection") |
| 72 |
} |
| 73 |
if c.IsClosed() { |
| 74 |
return nil, ErrConnectionClosed |
| 75 |
} |
| 76 |
ec := &EncodedConn{Conn: c, Enc: EncoderForType(encType)} |
| 77 |
if ec.Enc == nil { |
| 78 |
return nil, fmt.Errorf("no encoder registered for '%s'", encType) |
| 79 |
} |
| 80 |
return ec, nil |
| 81 |
} |
| 82 |
|
| 83 |
// RegisterEncoder will register the encType with the given Encoder. Useful for customization. |
| 84 |
// |
| 85 |
// Deprecated: Encoded connections are no longer supported. |
| 86 |
func RegisterEncoder(encType string, enc Encoder) { |
| 87 |
encLock.Lock() |
| 88 |
defer encLock.Unlock() |
| 89 |
encMap[encType] = enc |
| 90 |
} |
| 91 |
|
| 92 |
// EncoderForType will return the registered Encoder for the encType. |
| 93 |
// |
| 94 |
// Deprecated: Encoded connections are no longer supported. |
| 95 |
func EncoderForType(encType string) Encoder { |
| 96 |
encLock.Lock() |
| 97 |
defer encLock.Unlock() |
| 98 |
return encMap[encType] |
| 99 |
} |
| 100 |
|
| 101 |
// Publish publishes the data argument to the given subject. The data argument |
| 102 |
// will be encoded using the associated encoder. |
| 103 |
// |
| 104 |
// Deprecated: Encoded connections are no longer supported. |
| 105 |
func (c *EncodedConn) Publish(subject string, v any) error { |
| 106 |
b, err := c.Enc.Encode(subject, v) |
| 107 |
if err != nil { |
| 108 |
return err |
| 109 |
} |
| 110 |
return c.Conn.publish(subject, _EMPTY_, false, nil, b) |
| 111 |
} |
| 112 |
|
| 113 |
// PublishRequest will perform a Publish() expecting a response on the |
| 114 |
// reply subject. Use Request() for automatically waiting for a response |
| 115 |
// inline. |
| 116 |
// |
| 117 |
// Deprecated: Encoded connections are no longer supported. |
| 118 |
func (c *EncodedConn) PublishRequest(subject, reply string, v any) error { |
| 119 |
b, err := c.Enc.Encode(subject, v) |
| 120 |
if err != nil { |
| 121 |
return err |
| 122 |
} |
| 123 |
return c.Conn.publish(subject, reply, true, nil, b) |
| 124 |
} |
| 125 |
|
| 126 |
// Request will create an Inbox and perform a Request() call |
| 127 |
// with the Inbox reply for the data v. A response will be |
| 128 |
// decoded into the vPtr Response. |
| 129 |
// |
| 130 |
// Deprecated: Encoded connections are no longer supported. |
| 131 |
func (c *EncodedConn) Request(subject string, v any, vPtr any, timeout time.Duration) error { |
| 132 |
b, err := c.Enc.Encode(subject, v) |
| 133 |
if err != nil { |
| 134 |
return err |
| 135 |
} |
| 136 |
m, err := c.Conn.Request(subject, b, timeout) |
| 137 |
if err != nil { |
| 138 |
return err |
| 139 |
} |
| 140 |
if reflect.TypeOf(vPtr) == emptyMsgType { |
| 141 |
mPtr := vPtr.(*Msg) |
| 142 |
*mPtr = *m |
| 143 |
} else { |
| 144 |
err = c.Enc.Decode(m.Subject, m.Data, vPtr) |
| 145 |
} |
| 146 |
return err |
| 147 |
} |
| 148 |
|
| 149 |
// Handler is a specific callback used for Subscribe. It is generalized to |
| 150 |
// an any, but we will discover its format and arguments at runtime |
| 151 |
// and perform the correct callback, including demarshaling encoded data |
| 152 |
// back into the appropriate struct based on the signature of the Handler. |
| 153 |
// |
| 154 |
// Handlers are expected to have one of four signatures. |
| 155 |
// |
| 156 |
// type person struct { |
| 157 |
// Name string `json:"name,omitempty"` |
| 158 |
// Age uint `json:"age,omitempty"` |
| 159 |
// } |
| 160 |
// |
| 161 |
// handler := func(m *Msg) |
| 162 |
// handler := func(p *person) |
| 163 |
// handler := func(subject string, o *obj) |
| 164 |
// handler := func(subject, reply string, o *obj) |
| 165 |
// |
| 166 |
// These forms allow a callback to request a raw Msg ptr, where the processing |
| 167 |
// of the message from the wire is untouched. Process a JSON representation |
| 168 |
// and demarshal it into the given struct, e.g. person. |
| 169 |
// There are also variants where the callback wants either the subject, or the |
| 170 |
// subject and the reply subject. |
| 171 |
// |
| 172 |
// Deprecated: Encoded connections are no longer supported. |
| 173 |
type Handler any |
| 174 |
|
| 175 |
// Dissect the cb Handler's signature |
| 176 |
func argInfo(cb Handler) (reflect.Type, int) { |
| 177 |
cbType := reflect.TypeOf(cb) |
| 178 |
if cbType.Kind() != reflect.Func { |
| 179 |
panic("nats: Handler needs to be a func") |
| 180 |
} |
| 181 |
numArgs := cbType.NumIn() |
| 182 |
if numArgs == 0 { |
| 183 |
return nil, numArgs |
| 184 |
} |
| 185 |
return cbType.In(numArgs - 1), numArgs |
| 186 |
} |
| 187 |
|
| 188 |
var emptyMsgType = reflect.TypeOf(&Msg{}) |
| 189 |
|
| 190 |
// Subscribe will create a subscription on the given subject and process incoming |
| 191 |
// messages using the specified Handler. The Handler should be a func that matches |
| 192 |
// a signature from the description of Handler from above. |
| 193 |
// |
| 194 |
// Deprecated: Encoded connections are no longer supported. |
| 195 |
func (c *EncodedConn) Subscribe(subject string, cb Handler) (*Subscription, error) { |
| 196 |
return c.subscribe(subject, _EMPTY_, cb) |
| 197 |
} |
| 198 |
|
| 199 |
// QueueSubscribe will create a queue subscription on the given subject and process |
| 200 |
// incoming messages using the specified Handler. The Handler should be a func that |
| 201 |
// matches a signature from the description of Handler from above. |
| 202 |
// |
| 203 |
// Deprecated: Encoded connections are no longer supported. |
| 204 |
func (c *EncodedConn) QueueSubscribe(subject, queue string, cb Handler) (*Subscription, error) { |
| 205 |
return c.subscribe(subject, queue, cb) |
| 206 |
} |
| 207 |
|
| 208 |
// Internal implementation that all public functions will use. |
| 209 |
func (c *EncodedConn) subscribe(subject, queue string, cb Handler) (*Subscription, error) { |
| 210 |
if cb == nil { |
| 211 |
return nil, errors.New("nats: Handler required for EncodedConn Subscription") |
| 212 |
} |
| 213 |
argType, numArgs := argInfo(cb) |
| 214 |
if argType == nil { |
| 215 |
return nil, errors.New("nats: Handler requires at least one argument") |
| 216 |
} |
| 217 |
|
| 218 |
cbValue := reflect.ValueOf(cb) |
| 219 |
wantsRaw := (argType == emptyMsgType) |
| 220 |
|
| 221 |
natsCB := func(m *Msg) { |
| 222 |
var oV []reflect.Value |
| 223 |
if wantsRaw { |
| 224 |
oV = []reflect.Value{reflect.ValueOf(m)} |
| 225 |
} else { |
| 226 |
var oPtr reflect.Value |
| 227 |
if argType.Kind() != reflect.Ptr { |
| 228 |
oPtr = reflect.New(argType) |
| 229 |
} else { |
| 230 |
oPtr = reflect.New(argType.Elem()) |
| 231 |
} |
| 232 |
if err := c.Enc.Decode(m.Subject, m.Data, oPtr.Interface()); err != nil { |
| 233 |
if c.Conn.Opts.AsyncErrorCB != nil { |
| 234 |
c.Conn.ach.push(func() { |
| 235 |
c.Conn.Opts.AsyncErrorCB(c.Conn, m.Sub, errors.New("nats: Got an error trying to unmarshal: "+err.Error())) |
| 236 |
}) |
| 237 |
} |
| 238 |
return |
| 239 |
} |
| 240 |
if argType.Kind() != reflect.Ptr { |
| 241 |
oPtr = reflect.Indirect(oPtr) |
| 242 |
} |
| 243 |
|
| 244 |
// Callback Arity |
| 245 |
switch numArgs { |
| 246 |
case 1: |
| 247 |
oV = []reflect.Value{oPtr} |
| 248 |
case 2: |
| 249 |
subV := reflect.ValueOf(m.Subject) |
| 250 |
oV = []reflect.Value{subV, oPtr} |
| 251 |
case 3: |
| 252 |
subV := reflect.ValueOf(m.Subject) |
| 253 |
replyV := reflect.ValueOf(m.Reply) |
| 254 |
oV = []reflect.Value{subV, replyV, oPtr} |
| 255 |
} |
| 256 |
|
| 257 |
} |
| 258 |
cbValue.Call(oV) |
| 259 |
} |
| 260 |
|
| 261 |
return c.Conn.subscribe(subject, queue, natsCB, nil, nil, false, nil) |
| 262 |
} |
| 263 |
|
| 264 |
// FlushTimeout allows a Flush operation to have an associated timeout. |
| 265 |
// |
| 266 |
// Deprecated: Encoded connections are no longer supported. |
| 267 |
func (c *EncodedConn) FlushTimeout(timeout time.Duration) (err error) { |
| 268 |
return c.Conn.FlushTimeout(timeout) |
| 269 |
} |
| 270 |
|
| 271 |
// Flush will perform a round trip to the server and return when it |
| 272 |
// receives the internal reply. |
| 273 |
// |
| 274 |
// Deprecated: Encoded connections are no longer supported. |
| 275 |
func (c *EncodedConn) Flush() error { |
| 276 |
return c.Conn.Flush() |
| 277 |
} |
| 278 |
|
| 279 |
// Close will close the connection to the server. This call will release |
| 280 |
// all blocking calls, such as Flush(), etc. |
| 281 |
// |
| 282 |
// Deprecated: Encoded connections are no longer supported. |
| 283 |
func (c *EncodedConn) Close() { |
| 284 |
c.Conn.Close() |
| 285 |
} |
| 286 |
|
| 287 |
// Drain will put a connection into a drain state. All subscriptions will |
| 288 |
// immediately be put into a drain state. Upon completion, the publishers |
| 289 |
// will be drained and can not publish any additional messages. Upon draining |
| 290 |
// of the publishers, the connection will be closed. Use the ClosedCB() |
| 291 |
// option to know when the connection has moved from draining to closed. |
| 292 |
// |
| 293 |
// Deprecated: Encoded connections are no longer supported. |
| 294 |
func (c *EncodedConn) Drain() error { |
| 295 |
return c.Conn.Drain() |
| 296 |
} |
| 297 |
|
| 298 |
// LastError reports the last error encountered via the Connection. |
| 299 |
// |
| 300 |
// Deprecated: Encoded connections are no longer supported. |
| 301 |
func (c *EncodedConn) LastError() error { |
| 302 |
return c.Conn.LastError() |
| 303 |
} |