Debian Codegraph @

go/pkg/amqp/message.go

raw
1 /*
2 Licensed to the Apache Software Foundation (ASF) under one
3 or more contributor license agreements. See the NOTICE file
4 distributed with this work for additional information
5 regarding copyright ownership. The ASF licenses this file
6 to you under the Apache License, Version 2.0 (the
7 "License"); you may not use this file except in compliance
8 with the License. You may obtain a copy of the License at
9
10 http://www.apache.org/licenses/LICENSE-2.0
11
12 Unless required by applicable law or agreed to in writing,
13 software distributed under the License is distributed on an
14 "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15 KIND, either express or implied. See the License for the
16 specific language governing permissions and limitations
17 under the License.
18 */
19
20 package amqp
21
22 // #include <proton/codec.h>
23 // #include <proton/types.h>
24 // #include <proton/message.h>
25 // #include <stdlib.h>
26 //
27 // /* Helper for setting message string fields */
28 // typedef int (*set_fn)(pn_message_t*, const char*);
29 // int msg_set_str(pn_message_t* m, char* s, set_fn set) {
30 // int result = set(m, s);
31 // free(s);
32 // return result;
33 // }
34 //
35 import "C"
36
37 import (
38 "bytes"
39 "fmt"
40 "reflect"
41 "time"
42 )
43
44 // Message is the interface to an AMQP message.
45 type Message interface {
46 // Durable indicates that any parties taking responsibility
47 // for the message must durably store the content.
48 Durable() bool
49 SetDurable(bool)
50
51 // Priority impacts ordering guarantees. Within a
52 // given ordered context, higher priority messages may jump ahead of
53 // lower priority messages.
54 Priority() uint8
55 SetPriority(uint8)
56
57 // TTL or Time To Live, a message it may be dropped after this duration
58 TTL() time.Duration
59 SetTTL(time.Duration)
60
61 // FirstAcquirer indicates
62 // that the recipient of the message is the first recipient to acquire
63 // the message, i.e. there have been no failed delivery attempts to
64 // other acquirers. Note that this does not mean the message has not
65 // been delivered to, but not acquired, by other recipients.
66 FirstAcquirer() bool
67 SetFirstAcquirer(bool)
68
69 // DeliveryCount tracks how many attempts have been made to
70 // delivery a message.
71 DeliveryCount() uint32
72 SetDeliveryCount(uint32)
73
74 // MessageId provides a unique identifier for a message.
75 // it can be an a string, an unsigned long, a uuid or a
76 // binary value.
77 MessageId() interface{}
78 SetMessageId(interface{})
79
80 UserId() string
81 SetUserId(string)
82
83 Address() string
84 SetAddress(string)
85
86 Subject() string
87 SetSubject(string)
88
89 ReplyTo() string
90 SetReplyTo(string)
91
92 // CorrelationId is set on correlated request and response messages. It can be
93 // an a string, an unsigned long, a uuid or a binary value.
94 CorrelationId() interface{}
95 SetCorrelationId(interface{})
96
97 ContentType() string
98 SetContentType(string)
99
100 ContentEncoding() string
101 SetContentEncoding(string)
102
103 // ExpiryTime indicates an absolute time when the message may be dropped.
104 // A Zero time (i.e. t.isZero() == true) indicates a message never expires.
105 ExpiryTime() time.Time
106 SetExpiryTime(time.Time)
107
108 CreationTime() time.Time
109 SetCreationTime(time.Time)
110
111 GroupId() string
112 SetGroupId(string)
113
114 GroupSequence() int32
115 SetGroupSequence(int32)
116
117 ReplyToGroupId() string
118 SetReplyToGroupId(string)
119
120 // Properties set by the application to be carried with the message.
121 // Values must be simple types (not maps, lists or sequences)
122 ApplicationProperties() map[string]interface{}
123 SetApplicationProperties(map[string]interface{})
124
125 // Per-delivery annotations to provide delivery instructions.
126 // May be added or removed by intermediaries during delivery.
127 // See ApplicationProperties() for properties set by the application.
128 DeliveryAnnotations() map[AnnotationKey]interface{}
129 SetDeliveryAnnotations(map[AnnotationKey]interface{})
130
131 // Message annotations added as part of the bare message at creation, usually
132 // by an AMQP library. See ApplicationProperties() for properties set by the application.
133 MessageAnnotations() map[AnnotationKey]interface{}
134 SetMessageAnnotations(map[AnnotationKey]interface{})
135
136 // Inferred indicates how the message content
137 // is encoded into AMQP sections. If inferred is true then binary and
138 // list values in the body of the message will be encoded as AMQP DATA
139 // and AMQP SEQUENCE sections, respectively. If inferred is false,
140 // then all values in the body of the message will be encoded as AMQP
141 // VALUE sections regardless of their type.
142 Inferred() bool
143 SetInferred(bool)
144
145 // Get the message body, using the amqp.Unmarshal() rules for interface{}
146 Body() interface{}
147
148 // Set the body using amqp.Marshal()
149 SetBody(interface{})
150
151 // Marshal a Go value into the message body, synonym for SetBody()
152 Marshal(interface{})
153
154 // Unmarshal the message body, using amqp.Unmarshal()
155 Unmarshal(interface{})
156
157 // Encode encodes the message as AMQP data. If buffer is non-nil and is large enough
158 // the message is encoded into it, otherwise a new buffer is created.
159 // Returns the buffer containing the message.
160 Encode(buffer []byte) ([]byte, error)
161
162 // Decode data into this message. Overwrites an existing message content.
163 Decode(buffer []byte) error
164
165 // Clear the message contents, set all fields to the default value.
166 Clear()
167
168 // Copy the contents of another message to this one.
169 Copy(m Message) error
170
171 // Deprecated: use DeliveryAnnotations() for a more type-safe interface
172 Instructions() map[string]interface{}
173 SetInstructions(v map[string]interface{})
174
175 // Deprecated: use MessageAnnotations() for a more type-safe interface
176 Annotations() map[string]interface{}
177 SetAnnotations(v map[string]interface{})
178
179 // Deprecated: use ApplicationProperties() for a more type-safe interface
180 Properties() map[string]interface{}
181 SetProperties(v map[string]interface{})
182
183 // Human-readable string showing message contents and properties
184 String() string
185 }
186
187 // NewMessage creates a new message instance.
188 func NewMessage() Message {
189 m := &message{}
190 m.Clear()
191 return m
192 }
193
194 // NewMessageWith creates a message with value as the body.
195 func NewMessageWith(value interface{}) Message {
196 m := NewMessage()
197 m.SetBody(value)
198 return m
199 }
200
201 // NewMessageCopy creates a copy of an existing message.
202 func NewMessageCopy(m Message) Message {
203 m2 := NewMessage()
204 m2.Copy(m)
205 return m2
206 }
207
208 // Reset message to all default values
209 func (m *message) Clear() { *m = message{priority: 4} }
210
211 // Copy makes a deep copy of message x
212 func (m *message) Copy(x Message) error {
213 var mc MessageCodec
214 bytes, err := mc.Encode(x, nil)
215 if err == nil {
216 err = mc.Decode(m, bytes)
217 }
218 return err
219 }
220
221 type message struct {
222 address string
223 applicationProperties map[string]interface{}
224 contentEncoding string
225 contentType string
226 correlationId interface{}
227 creationTime time.Time
228 deliveryAnnotations map[AnnotationKey]interface{}
229 deliveryCount uint32
230 durable bool
231 expiryTime time.Time
232 firstAcquirer bool
233 groupId string
234 groupSequence int32
235 inferred bool
236 messageAnnotations map[AnnotationKey]interface{}
237 messageId interface{}
238 priority uint8
239 replyTo string
240 replyToGroupId string
241 subject string
242 ttl time.Duration
243 userId string
244 body interface{}
245 // Keep the original data to support Unmarshal to a non-interface{} type
246 // Waste of memory, consider deprecating or making it optional.
247 pnBody *C.pn_data_t
248 }
249
250 // ==== message get methods
251 func (m *message) Body() interface{} { return m.body }
252 func (m *message) Inferred() bool { return m.inferred }
253 func (m *message) Durable() bool { return m.durable }
254 func (m *message) Priority() uint8 { return m.priority }
255 func (m *message) TTL() time.Duration { return m.ttl }
256 func (m *message) FirstAcquirer() bool { return m.firstAcquirer }
257 func (m *message) DeliveryCount() uint32 { return m.deliveryCount }
258 func (m *message) MessageId() interface{} { return m.messageId }
259 func (m *message) UserId() string { return m.userId }
260 func (m *message) Address() string { return m.address }
261 func (m *message) Subject() string { return m.subject }
262 func (m *message) ReplyTo() string { return m.replyTo }
263 func (m *message) CorrelationId() interface{} { return m.correlationId }
264 func (m *message) ContentType() string { return m.contentType }
265 func (m *message) ContentEncoding() string { return m.contentEncoding }
266 func (m *message) ExpiryTime() time.Time { return m.expiryTime }
267 func (m *message) CreationTime() time.Time { return m.creationTime }
268 func (m *message) GroupId() string { return m.groupId }
269 func (m *message) GroupSequence() int32 { return m.groupSequence }
270 func (m *message) ReplyToGroupId() string { return m.replyToGroupId }
271
272 func (m *message) DeliveryAnnotations() map[AnnotationKey]interface{} {
273 if m.deliveryAnnotations == nil {
274 m.deliveryAnnotations = make(map[AnnotationKey]interface{})
275 }
276 return m.deliveryAnnotations
277 }
278 func (m *message) MessageAnnotations() map[AnnotationKey]interface{} {
279 if m.messageAnnotations == nil {
280 m.messageAnnotations = make(map[AnnotationKey]interface{})
281 }
282 return m.messageAnnotations
283 }
284 func (m *message) ApplicationProperties() map[string]interface{} {
285 if m.applicationProperties == nil {
286 m.applicationProperties = make(map[string]interface{})
287 }
288 return m.applicationProperties
289 }
290
291 // ==== message set methods
292
293 func (m *message) SetBody(v interface{}) { m.body = v }
294 func (m *message) SetInferred(x bool) { m.inferred = x }
295 func (m *message) SetDurable(x bool) { m.durable = x }
296 func (m *message) SetPriority(x uint8) { m.priority = x }
297 func (m *message) SetTTL(x time.Duration) { m.ttl = x }
298 func (m *message) SetFirstAcquirer(x bool) { m.firstAcquirer = x }
299 func (m *message) SetDeliveryCount(x uint32) { m.deliveryCount = x }
300 func (m *message) SetMessageId(x interface{}) { m.messageId = x }
301 func (m *message) SetUserId(x string) { m.userId = x }
302 func (m *message) SetAddress(x string) { m.address = x }
303 func (m *message) SetSubject(x string) { m.subject = x }
304 func (m *message) SetReplyTo(x string) { m.replyTo = x }
305 func (m *message) SetCorrelationId(x interface{}) { m.correlationId = x }
306 func (m *message) SetContentType(x string) { m.contentType = x }
307 func (m *message) SetContentEncoding(x string) { m.contentEncoding = x }
308 func (m *message) SetExpiryTime(x time.Time) { m.expiryTime = x }
309 func (m *message) SetCreationTime(x time.Time) { m.creationTime = x }
310 func (m *message) SetGroupId(x string) { m.groupId = x }
311 func (m *message) SetGroupSequence(x int32) { m.groupSequence = x }
312 func (m *message) SetReplyToGroupId(x string) { m.replyToGroupId = x }
313
314 func (m *message) SetDeliveryAnnotations(x map[AnnotationKey]interface{}) {
315 m.deliveryAnnotations = x
316 }
317 func (m *message) SetMessageAnnotations(x map[AnnotationKey]interface{}) {
318 m.messageAnnotations = x
319 }
320 func (m *message) SetApplicationProperties(x map[string]interface{}) {
321 m.applicationProperties = x
322 }
323
324 // Marshal body from v, same as SetBody(v). See amqp.Marshal.
325 func (m *message) Marshal(v interface{}) { m.body = v }
326
327 func (m *message) Unmarshal(v interface{}) {
328 pnData := C.pn_data(2)
329 defer C.pn_data_free(pnData)
330 marshal(m.body, pnData)
331 unmarshal(v, pnData)
332 }
333
334 // Internal use only
335 type MessageCodec struct {
336 pn *C.pn_message_t // Cache a pn_message_t to speed up encode/decode
337 // Optionally remember a byte buffer to use with MessageCodec methods.
338 Buffer []byte
339 }
340
341 func (mc *MessageCodec) pnMessage() *C.pn_message_t {
342 if mc.pn == nil {
343 mc.pn = C.pn_message()
344 }
345 return mc.pn
346 }
347
348 func (mc *MessageCodec) Close() {
349 if mc.pn != nil {
350 C.pn_message_free(mc.pn)
351 mc.pn = nil
352 }
353 }
354
355 func (mc *MessageCodec) Decode(m Message, data []byte) error {
356 pn := mc.pnMessage()
357 if C.pn_message_decode(pn, cPtr(data), cLen(data)) < 0 {
358 return fmt.Errorf("decoding message: %s", PnError(C.pn_message_error(pn)))
359 }
360 m.(*message).get(pn)
361 return nil
362 }
363
364 func (m *message) Decode(data []byte) error {
365 var mc MessageCodec
366 defer mc.Close()
367 return mc.Decode(m, data)
368 }
369
370 func DecodeMessage(data []byte) (m Message, err error) {
371 m = NewMessage()
372 err = m.Decode(data)
373 return
374 }
375
376 // Encode m using buffer. Return the final buffer used to hold m,
377 // may be different if the initial buffer was not large enough.
378 func (mc *MessageCodec) Encode(m Message, buffer []byte) ([]byte, error) {
379 pn := mc.pnMessage()
380 m.(*message).put(pn)
381 encode := func(buf []byte) ([]byte, error) {
382 len := cLen(buf)
383 result := C.pn_message_encode(pn, cPtr(buf), &len)
384 switch {
385 case result == C.PN_OVERFLOW:
386 return buf, overflow
387 case result < 0:
388 return buf, fmt.Errorf("cannot encode message: %s", PnErrorCode(result))
389 default:
390 return buf[:len], nil
391 }
392 }
393 return encodeGrow(buffer, encode)
394 }
395
396 func (m *message) Encode(buffer []byte) ([]byte, error) {
397 var mc MessageCodec
398 defer mc.Close()
399 return mc.Encode(m, buffer)
400 }
401
402 // TODO aconway 2015-09-14: Multi-section messages.
403
404 type ignoreFunc func(v interface{}) bool
405
406 func isNil(v interface{}) bool { return v == nil }
407 func isZero(v interface{}) bool { return v == reflect.Zero(reflect.TypeOf(v)).Interface() }
408 func isEmpty(v interface{}) bool { return reflect.ValueOf(v).Len() == 0 }
409
410 type stringBuilder struct {
411 bytes.Buffer
412 separator string
413 }
414
415 func (b *stringBuilder) field(name string, value interface{}, ignore ignoreFunc) {
416 if !ignore(value) {
417 b.WriteString(b.separator)
418 b.separator = ", "
419 b.WriteString(name)
420 b.WriteString(": ")
421 fmt.Fprintf(&b.Buffer, "%v", value)
422 }
423 }
424
425 // Human-readable string describing message.
426 // Includes only message fields with non-default values.
427 func (m *message) String() string {
428 var b stringBuilder
429 b.WriteString("Message{")
430 b.field("address", m.address, isEmpty)
431 b.field("durable", m.durable, isZero)
432 // Priority has weird default
433 b.field("priority", m.priority, func(v interface{}) bool { return v.(uint8) == 4 })
434 b.field("ttl", m.ttl, isZero)
435 b.field("first-acquirer", m.firstAcquirer, isZero)
436 b.field("delivery-count", m.deliveryCount, isZero)
437 b.field("message-id", m.messageId, isNil)
438 b.field("user-id", m.userId, isEmpty)
439 b.field("subject", m.subject, isEmpty)
440 b.field("reply-to", m.replyTo, isEmpty)
441 b.field("correlation-id", m.correlationId, isNil)
442 b.field("content-type", m.contentType, isEmpty)
443 b.field("content-encoding", m.contentEncoding, isEmpty)
444 b.field("expiry-time", m.expiryTime, isZero)
445 b.field("creation-time", m.creationTime, isZero)
446 b.field("group-id", m.groupId, isEmpty)
447 b.field("group-sequence", m.groupSequence, isZero)
448 b.field("reply-to-group-id", m.replyToGroupId, isEmpty)
449 b.field("inferred", m.inferred, isZero)
450 b.field("delivery-annotations", m.deliveryAnnotations, isEmpty)
451 b.field("message-annotations", m.messageAnnotations, isEmpty)
452 b.field("application-properties", m.applicationProperties, isEmpty)
453 b.field("body", m.body, isNil)
454 b.WriteString("}")
455 return b.String()
456 }
457
458 // ==== get message from pn_message_t
459
460 func getData(v interface{}, data *C.pn_data_t) {
461 if data != nil && C.pn_data_size(data) > 0 {
462 C.pn_data_rewind(data)
463 C.pn_data_next(data)
464 unmarshal(v, data)
465 }
466 return
467 }
468
469 func getString(c *C.char) string {
470 if c == nil {
471 return ""
472 }
473 return C.GoString(c)
474 }
475
476 func (m *message) get(pn *C.pn_message_t) {
477 m.Clear()
478 m.inferred = bool(C.pn_message_is_inferred(pn))
479 m.durable = bool(C.pn_message_is_durable(pn))
480 m.priority = uint8(C.pn_message_get_priority(pn))
481 m.ttl = goDuration(C.pn_message_get_ttl(pn))
482 m.firstAcquirer = bool(C.pn_message_is_first_acquirer(pn))
483 m.deliveryCount = uint32(C.pn_message_get_delivery_count(pn))
484 getData(&m.messageId, C.pn_message_id(pn))
485 m.userId = string(goBytes(C.pn_message_get_user_id(pn)))
486 m.address = getString(C.pn_message_get_address(pn))
487 m.subject = getString(C.pn_message_get_subject(pn))
488 m.replyTo = getString(C.pn_message_get_reply_to(pn))
489 getData(&m.correlationId, C.pn_message_correlation_id(pn))
490 m.contentType = getString(C.pn_message_get_content_type(pn))
491 m.contentEncoding = getString(C.pn_message_get_content_encoding(pn))
492 m.expiryTime = goTime(C.pn_message_get_expiry_time(pn))
493 m.creationTime = goTime(C.pn_message_get_creation_time(pn))
494 m.groupId = getString(C.pn_message_get_group_id(pn))
495 m.groupSequence = int32(C.pn_message_get_group_sequence(pn))
496 m.replyToGroupId = getString(C.pn_message_get_reply_to_group_id(pn))
497 getData(&m.deliveryAnnotations, C.pn_message_instructions(pn))
498 getData(&m.messageAnnotations, C.pn_message_annotations(pn))
499 getData(&m.applicationProperties, C.pn_message_properties(pn))
500 getData(&m.body, C.pn_message_body(pn))
501 }
502
503 // ==== put message to pn_message_t
504
505 func putData(v interface{}, pn *C.pn_data_t) {
506 if v != nil {
507 C.pn_data_clear(pn)
508 marshal(v, pn)
509 }
510 }
511
512 // For pointer-based fields (pn_data_t, strings, bytes) only
513 // put a field if it has a non-empty value
514 func (m *message) put(pn *C.pn_message_t) {
515 C.pn_message_clear(pn)
516 C.pn_message_set_inferred(pn, C.bool(m.inferred))
517 C.pn_message_set_durable(pn, C.bool(m.durable))
518 C.pn_message_set_priority(pn, C.uint8_t(m.priority))
519 C.pn_message_set_ttl(pn, pnDuration(m.ttl))
520 C.pn_message_set_first_acquirer(pn, C.bool(m.firstAcquirer))
521 C.pn_message_set_delivery_count(pn, C.uint32_t(m.deliveryCount))
522 putData(m.messageId, C.pn_message_id(pn))
523 if m.userId != "" {
524 C.pn_message_set_user_id(pn, pnBytes(([]byte)(m.userId)))
525 }
526 if m.address != "" {
527 C.pn_message_set_address(pn, C.CString(m.address))
528 }
529 if m.subject != "" {
530 C.pn_message_set_subject(pn, C.CString(m.subject))
531 }
532 if m.replyTo != "" {
533 C.pn_message_set_reply_to(pn, C.CString(m.replyTo))
534 }
535 putData(m.correlationId, C.pn_message_correlation_id(pn))
536 if m.contentType != "" {
537 C.pn_message_set_content_type(pn, C.CString(m.contentType))
538 }
539 if m.contentEncoding != "" {
540 C.pn_message_set_content_encoding(pn, C.CString(m.contentEncoding))
541 }
542 C.pn_message_set_expiry_time(pn, pnTime(m.expiryTime))
543 C.pn_message_set_creation_time(pn, pnTime(m.creationTime))
544 if m.groupId != "" {
545 C.pn_message_set_group_id(pn, C.CString(m.groupId))
546 }
547 C.pn_message_set_group_sequence(pn, C.pn_sequence_t(m.groupSequence))
548 if m.replyToGroupId != "" {
549 C.pn_message_set_reply_to_group_id(pn, C.CString(m.replyToGroupId))
550 }
551 if len(m.deliveryAnnotations) != 0 {
552 putData(m.deliveryAnnotations, C.pn_message_instructions(pn))
553 }
554 if len(m.messageAnnotations) != 0 {
555 putData(m.messageAnnotations, C.pn_message_annotations(pn))
556 }
557 if len(m.applicationProperties) != 0 {
558 putData(m.applicationProperties, C.pn_message_properties(pn))
559 }
560 putData(m.body, C.pn_message_body(pn))
561 }
562
563 // ==== Deprecated functions
564
565 func oldAnnotations(in map[AnnotationKey]interface{}) (out map[string]interface{}) {
566 if len(in) == 0 {
567 return nil
568 }
569 out = make(map[string]interface{})
570 for k, v := range in {
571 out[k.String()] = v
572 }
573 return
574 }
575
576 func (m *message) Instructions() map[string]interface{} {
577 return oldAnnotations(m.deliveryAnnotations)
578 }
579 func (m *message) Annotations() map[string]interface{} {
580 return oldAnnotations(m.messageAnnotations)
581 }
582 func (m *message) Properties() map[string]interface{} {
583 return m.applicationProperties
584 }
585
586 // Convert old string-keyed annotations to an AnnotationKey map
587 func newAnnotations(in map[string]interface{}) (out map[AnnotationKey]interface{}) {
588 if len(in) == 0 {
589 return nil
590 }
591 out = make(map[AnnotationKey]interface{})
592 for k, v := range in {
593 out[AnnotationKeyString(k)] = v
594 }
595 return
596 }
597
598 func (m *message) SetInstructions(v map[string]interface{}) {
599 m.deliveryAnnotations = newAnnotations(v)
600 }
601 func (m *message) SetAnnotations(v map[string]interface{}) {
602 m.messageAnnotations = newAnnotations(v)
603 }
604 func (m *message) SetProperties(v map[string]interface{}) {
605 m.applicationProperties = v
606 }