Annotation of parser3/src/classes/amqp.C, revision 1.27
1.1 moko 1: /** @file
2: Parser: @b amqp parser class.
3:
1.13 moko 4: Copyright (c) 2001-2026 Art. Lebedev Studio (https://www.artlebedev.com)
1.1 moko 5: Authors: Konstantin Morshnev <moko@design.ru>
6: */
7:
1.25 moko 8:
9: #include "classes.h"
1.1 moko 10: #include "pa_vmethod_frame.h"
11:
1.25 moko 12: #include "pa_vamqp.h"
1.1 moko 13: #include "pa_request.h"
1.8 moko 14: #include "pa_varray.h"
1.1 moko 15: #include "pa_vbool.h"
1.16 moko 16: #include "pa_os.h"
1.1 moko 17:
1.27 ! moko 18: volatile const char * IDENT_AMQP_C="$Id: amqp.C,v 1.26 2026/10/08 18:56:00 moko Exp $" IDENT_PA_VAMQP_H;
1.1 moko 19:
20: class MAmqp: public Methoded {
21: public: // VStateless_class
22: Value* create_new_value(Pool&) { return new VAmqp(); }
23: public:
24: MAmqp();
25: };
26:
27: DECLARE_CLASS_VAR(amqp, new MAmqp);
28:
1.6 moko 29: #ifdef WITH_AMQP
30:
1.16 moko 31: static void status_check(VAmqp& self, int ret, const char *detail=""){
1.6 moko 32: if(ret == AMQP_STATUS_OK)
33: return;
34:
1.16 moko 35: self.fstate = VAmqp::CONNECTION_DEAD;
36:
1.6 moko 37: const char* error_str = amqp_error_string2(ret);
38: if(error_str) {
39: throw Exception("amqp", 0, "%sfailed: %s", detail, error_str);
40: } else {
41: throw Exception("amqp", 0, "%sfailed: error %d", detail, ret);
42: }
43: }
44:
1.16 moko 45: static void check(VAmqp& self, amqp_rpc_reply_t rr, const char *detail=""){
1.6 moko 46: if(rr.reply_type == AMQP_RESPONSE_NORMAL)
47: return;
48:
1.16 moko 49: self.fstate = (rr.reply_type == AMQP_RESPONSE_SERVER_EXCEPTION && rr.reply.id == AMQP_CHANNEL_CLOSE_METHOD) ? VAmqp::CHANNEL_DEAD : VAmqp::CONNECTION_DEAD;
50:
1.6 moko 51: // Extract error message from reply
52: const char* error_msg = 0;
53: size_t error_len = 0;
54: if(rr.reply_type == AMQP_RESPONSE_SERVER_EXCEPTION) {
55: if(rr.reply.id == AMQP_CHANNEL_CLOSE_METHOD) {
56: amqp_channel_close_t *m = (amqp_channel_close_t *)rr.reply.decoded;
57: if(m->reply_text.len > 0 && m->reply_text.bytes) {
58: error_msg = (const char*)m->reply_text.bytes;
59: error_len = m->reply_text.len;
60: }
61: } else if(rr.reply.id == AMQP_CONNECTION_CLOSE_METHOD) {
62: amqp_connection_close_t *m = (amqp_connection_close_t *)rr.reply.decoded;
63: if(m->reply_text.len > 0 && m->reply_text.bytes) {
64: error_msg = (const char*)m->reply_text.bytes;
65: error_len = m->reply_text.len;
66: }
67: }
68: }
1.16 moko 69:
1.6 moko 70: if(error_msg) {
71: throw Exception("amqp", 0, "%sfailed: %.*s", detail, (int)error_len, error_msg);
72: } else if(rr.reply_type == AMQP_RESPONSE_LIBRARY_EXCEPTION) {
1.16 moko 73: status_check(self, rr.library_error, detail);
1.6 moko 74: }
75:
76: throw Exception("amqp", 0, "%sfailed", detail);
77: }
78:
1.16 moko 79: static void amqp_connect(VAmqp& self, Request& r, HashStringValue* options) {
1.1 moko 80: const char* host_c = "localhost";
81: int port = 5672;
82: const char* user_c = "guest";
83: const char* pass_c = "guest";
84: const char* vhost_c = "/";
85: const char* locale_c = "en_US";
1.22 moko 86: int heartbeat_sec = 30;
87: int reconnect_interval_sec = 0;
88: bool tls_specified = false;
1.26 moko 89: #ifdef WITH_AMQP_SSL
1.5 moko 90: const char* tls_ca = 0;
91: const char* tls_cert = 0;
92: const char* tls_key = 0;
93: bool tls_verify = true;
1.22 moko 94: #endif
1.1 moko 95:
1.16 moko 96: if(options){
97: for(HashStringValue::Iterator i(*options); i; i.next()){
98: String::Body key=i.key();
99: Value* value=i.value();
100: if(key=="host"){
101: host_c=value->as_string().cstr();
102: } else if(key=="port"){
103: port=r.process(*value).as_int();
104: } else if(key=="user"){
105: user_c=value->as_string().cstr();
106: } else if(key=="password"){
107: pass_c=value->as_string().cstr();
108: } else if(key=="vhost"){
109: vhost_c=value->as_string().cstr();
110: } else if(key=="locale"){
111: locale_c=value->as_string().cstr();
112: } else if(key=="heartbeat"){
1.22 moko 113: heartbeat_sec=r.process(*value).as_int();
1.16 moko 114: } else if(key=="auto_reconnect"){
115: reconnect_interval_sec=r.process(*value).as_int();
116: } else if(key=="tls"){
1.26 moko 117: #ifdef WITH_AMQP_SSL
1.16 moko 118: tls_specified = true;
119: if(HashStringValue* tls_options=value->get_hash()){
120: for(HashStringValue::Iterator t(*tls_options); t; t.next()){
121: String::Body tkey=t.key();
122: Value* tval=t.value();
123: if(tkey=="ca"){
124: tls_ca=tval->as_string().cstr();
125: } else if(tkey=="cert"){
126: tls_cert=tval->as_string().cstr();
127: } else if(tkey=="key"){
128: tls_key=tval->as_string().cstr();
129: } else if(tkey=="verify"){
130: tls_verify=r.process(*tval).as_bool();
131: } else
132: throw Exception(PARSER_RUNTIME, 0, CALLED_WITH_INVALID_OPTION);
1.5 moko 133: }
1.16 moko 134: }
1.22 moko 135: #else
136: throw Exception("amqp", 0, "AMQP SSL support is disabled");
137: #endif
1.16 moko 138: } else
139: throw Exception(PARSER_RUNTIME, 0, CALLED_WITH_INVALID_OPTION);
1.1 moko 140: }
141: }
142:
143: amqp_connection_state_t conn = amqp_new_connection();
1.5 moko 144: amqp_socket_t* socket = 0;
1.16 moko 145:
1.26 moko 146: #ifdef WITH_AMQP_SSL
1.5 moko 147: if(tls_specified) {
148: socket = amqp_ssl_socket_new(conn);
149: if(!socket)
150: throw Exception("amqp", 0, "failed to create SSL socket");
1.16 moko 151:
1.5 moko 152: // Set CA certificate if provided
153: if(tls_ca)
154: if(amqp_ssl_socket_set_cacert(socket, tls_ca))
155: throw Exception("amqp", 0, "failed to set CA certificate");
1.6 moko 156:
1.5 moko 157: // Set client certificate and key if provided
158: if(tls_cert && tls_key) {
159: if(amqp_ssl_socket_set_key(socket, tls_cert, tls_key))
160: throw Exception("amqp", 0, "failed to set client certificate/key");
161: } else if(tls_cert || tls_key) {
162: throw Exception("amqp", 0, "both cert and key must be specified for TLS");
163: }
1.6 moko 164:
1.5 moko 165: // If CA is provided, peer verification will use it
166: amqp_ssl_socket_set_verify_peer(socket, tls_verify && tls_ca);
167: // If verify=true, enable hostname verification
168: amqp_ssl_socket_set_verify_hostname(socket, tls_verify);
1.22 moko 169: } else
170: #endif
171: {
1.5 moko 172: socket = amqp_tcp_socket_new(conn);
173: if(!socket)
174: throw Exception("amqp", 0, "failed to create TCP socket");
175: }
1.16 moko 176:
177: status_check(self, amqp_socket_open(socket, host_c, port), tls_specified ? "open SSL socket " : "open TCP socket ");
1.1 moko 178:
1.22 moko 179: amqp_rpc_reply_t rlogin = amqp_login(conn, vhost_c, 0, 131072, heartbeat_sec, AMQP_SASL_METHOD_PLAIN, user_c, pass_c);
1.1 moko 180: if(rlogin.reply_type != AMQP_RESPONSE_NORMAL){
181: amqp_destroy_connection(conn);
1.16 moko 182: check(self, rlogin, "login ");
1.1 moko 183: }
184:
1.23 moko 185: amqp_channel_t channel = 1;
1.1 moko 186: amqp_channel_open(conn, channel);
187: amqp_rpc_reply_t ropen = amqp_get_rpc_reply(conn);
188: if(ropen.reply_type != AMQP_RESPONSE_NORMAL){
189: amqp_connection_close(conn, AMQP_REPLY_SUCCESS);
190: amqp_destroy_connection(conn);
1.16 moko 191: check(self, ropen, "open channel ");
1.1 moko 192: }
193:
1.16 moko 194: if(self.fconnection)
195: amqp_destroy_connection(self.fconnection);
196:
1.1 moko 197: self.fconnection = conn;
198: self.fchannel = channel;
1.16 moko 199: self.fstate = VAmqp::ALIVE;
200: self.freconnect_interval = reconnect_interval_sec;
201: }
202:
1.19 moko 203: // repairs a channel-level error cheaply: reopen on the same connection. Only valid when the server has
204: // already sent (or is about to send) channel.close - we're completing that handshake with close-ok, not
205: // initiating our own.
1.16 moko 206: static void amqp_repair_channel(VAmqp& self) {
207: amqp_channel_close_ok_t close_ok;
208: amqp_send_method(self.fconnection, self.fchannel, AMQP_CHANNEL_CLOSE_OK_METHOD, &close_ok);
209: amqp_channel_open(self.fconnection, self.fchannel);
210: check(self, amqp_get_rpc_reply(self.fconnection), "channel repair ");
211: self.fstate = VAmqp::ALIVE;
212: }
213:
1.19 moko 214: // voluntarily closes and reopens an otherwise-healthy channel
215: static void amqp_reset_channel(VAmqp& self) {
216: amqp_channel_close(self.fconnection, self.fchannel, AMQP_REPLY_SUCCESS);
217: amqp_channel_open(self.fconnection, self.fchannel);
218: amqp_get_rpc_reply(self.fconnection);
219: }
220:
1.16 moko 221: void VAmqp::ensure_connected() {
222: if(fstate == ALIVE)
223: return;
224:
225: if(fstate == CHANNEL_DEAD){
226: amqp_repair_channel(*this);
227: return;
228: }
229:
230: // CONNECTION_DEAD
231: if(freconnect_interval <= 0)
232: throw Exception("amqp", 0, "connection is dead (auto_reconnect is not enabled)");
233:
234: pa_sleep(freconnect_interval, 0);
235:
236: amqp_connect(*this, pa_thread_request(), fcreate_options);
237: }
238:
239: #endif // WITH_AMQP
240:
241: static void _create(Request& r, MethodParams& params) {
242: VAmqp& self=GET_SELF(r, VAmqp);
243:
244: #ifdef WITH_AMQP
245: self.fcreate_options = params.count()>0 ? params.as_hash(0) : 0;
246: amqp_connect(self, r, self.fcreate_options);
1.1 moko 247: #else
248: (void)params; (void)self;
249: throw Exception("amqp", 0, "compiled without amqp support");
1.6 moko 250: #endif // WITH_AMQP
1.1 moko 251: }
252:
253: #ifdef WITH_AMQP
254:
1.2 moko 255: #define AMQP_STRING(s,l) new String(String::C(pa_strdup((const char*)(s), (l)), (l)))
256: #define AMQP_VSTRING(s,l) new VString(*AMQP_STRING(s,l))
257:
1.17 moko 258: // broker-defined arguments/headers (x-message-ttl, x-dead-letter-exchange, ...)
259: // Type is taken from how the value was assigned: [] -> string, () -> number, (true|false) -> bool
260: static amqp_table_t amqp_build_arguments_table(Request& r, HashStringValue* arguments) {
261: amqp_table_t table = amqp_empty_table;
262: size_t count = arguments ? arguments->count() : 0;
263: if(!count)
264: return table;
265:
266: amqp_table_entry_t* entries = (amqp_table_entry_t*)pa_malloc(count * sizeof(amqp_table_entry_t));
267: size_t i = 0;
268: for(HashStringValue::Iterator it(*arguments); it; it.next()){
269: entries[i].key = amqp_cstring_bytes(it.key().cstr());
270:
271: Value& value = r.process(*it.value());
272: if(value.is_string() || value.is_void()){
273: entries[i].value.kind = AMQP_FIELD_KIND_UTF8;
274: entries[i].value.value.bytes = amqp_cstring_bytes(value.as_string().cstr());
275: } else if(value.is_bool()){
276: entries[i].value.kind = AMQP_FIELD_KIND_BOOLEAN;
277: entries[i].value.value.boolean = value.as_bool();
278: } else {
1.18 moko 279: double d = value.as_double();
280: double rounded = round(d);
281: if(ulp_eq_double(d, rounded)){
282: entries[i].value.kind = AMQP_FIELD_KIND_I64;
283: entries[i].value.value.i64 = (int64_t)rounded;
284: } else {
285: entries[i].value.kind = AMQP_FIELD_KIND_F64;
286: entries[i].value.value.f64 = d;
287: }
1.17 moko 288: }
289: i++;
290: }
291:
292: table.num_entries = (int)count;
293: table.entries = entries;
294: return table;
295: }
296:
297: // reverse of amqp_build_arguments_table - decodes a broker-provided field table (e.g. message headers) back into a hash.
298: static VHash* amqp_table_to_hash(amqp_table_t& table);
299:
300: static Value* amqp_field_to_value(amqp_field_value_t& f) {
301: switch(f.kind){
302: case AMQP_FIELD_KIND_UTF8:
303: case AMQP_FIELD_KIND_BYTES:
304: return AMQP_VSTRING(f.value.bytes.bytes, f.value.bytes.len);
305: case AMQP_FIELD_KIND_BOOLEAN:
306: return &VBool::get(f.value.boolean);
307: case AMQP_FIELD_KIND_I8: return new VInt((pa_wint)f.value.i8);
308: case AMQP_FIELD_KIND_U8: return new VInt((pa_wint)f.value.u8);
309: case AMQP_FIELD_KIND_I16: return new VInt((pa_wint)f.value.i16);
310: case AMQP_FIELD_KIND_U16: return new VInt((pa_wint)f.value.u16);
311: case AMQP_FIELD_KIND_I32: return new VInt((pa_wint)f.value.i32);
312: case AMQP_FIELD_KIND_U32: return new VInt((pa_wint)f.value.u32);
313: case AMQP_FIELD_KIND_I64: return new VInt((pa_wint)f.value.i64);
314: case AMQP_FIELD_KIND_U64: return new VInt((pa_wint)f.value.u64);
315: case AMQP_FIELD_KIND_TIMESTAMP: return new VInt((pa_wint)f.value.u64);
316: case AMQP_FIELD_KIND_F32: return new VDouble((double)f.value.f32);
317: case AMQP_FIELD_KIND_F64: return new VDouble(f.value.f64);
318: case AMQP_FIELD_KIND_DECIMAL: {
319: double divisor=1;
320: for(uint8_t i=0; i<f.value.decimal.decimals; i++) divisor*=10;
321: return new VDouble(f.value.decimal.value/divisor);
322: }
323: case AMQP_FIELD_KIND_TABLE:
324: return amqp_table_to_hash(f.value.table);
325: case AMQP_FIELD_KIND_ARRAY: {
326: VArray* result=new VArray();
327: ArrayValue& av=result->array();
328: for(int i=0; i<f.value.array.num_entries; i++)
329: av+=amqp_field_to_value(f.value.array.entries[i]);
330: return result;
331: }
332: case AMQP_FIELD_KIND_VOID:
333: return VVoid::get();
334: default:
335: return VString::empty();
336: }
337: }
338:
339: static VHash* amqp_table_to_hash(amqp_table_t& table) {
340: VHash* result=new VHash;
341: HashStringValue* h=result->get_hash();
342: for(int i=0; i<table.num_entries; i++){
343: amqp_table_entry_t& e=table.entries[i];
344: h->put(*AMQP_STRING(e.key.bytes, e.key.len), amqp_field_to_value(e.value));
345: }
346: return result;
347: }
348:
1.1 moko 349: static void _publish(Request& r, MethodParams& params) {
350: VAmqp& self=GET_SELF(r, VAmqp);
351: const String &msg=params.as_string(0, "msg must be string");
352: const char* exchange_c = ""; // default exchange
353: const char* routing_key_c = 0;
354: bool mandatory=false;
355:
356: amqp_basic_properties_t props;
357: props._flags = 0;
358:
359: if(params.count()>1){
360: if(HashStringValue* options=params.as_hash(1)){
361: for(HashStringValue::Iterator i(*options); i; i.next()){
362: String::Body key=i.key();
363: Value* value=i.value();
364: if(key=="exchange"){
365: exchange_c=value->as_string().cstr();
366: } else if(key=="routing_key"){
367: routing_key_c=value->as_string().cstr();
368: } else if(key=="queue"){
1.3 moko 369: routing_key_c=value->as_string().cstr();
1.1 moko 370: } else if(key=="mandatory"){
371: mandatory=r.process(*value).as_bool();
1.3 moko 372: } else if(key=="content_type"){
373: const char* v=value->as_string().cstr();
374: props.content_type=amqp_cstring_bytes(v);
375: props._flags|=AMQP_BASIC_CONTENT_TYPE_FLAG;
376: } else if(key=="content_encoding"){
377: const char* v=value->as_string().cstr();
378: props.content_encoding=amqp_cstring_bytes(v);
379: props._flags|=AMQP_BASIC_CONTENT_ENCODING_FLAG;
380: } else if(key=="delivery_mode"){
381: uint8_t dm=(uint8_t)value->as_int();
382: props.delivery_mode=dm;
383: props._flags|=AMQP_BASIC_DELIVERY_MODE_FLAG;
384: } else if(key=="priority"){
385: uint8_t pr=(uint8_t)value->as_int();
386: props.priority=pr;
387: props._flags|=AMQP_BASIC_PRIORITY_FLAG;
388: } else if(key=="correlation_id"){
389: const char* v=value->as_string().cstr();
390: props.correlation_id=amqp_cstring_bytes(v);
391: props._flags|=AMQP_BASIC_CORRELATION_ID_FLAG;
392: } else if(key=="reply_to"){
393: const char* v=value->as_string().cstr();
394: props.reply_to=amqp_cstring_bytes(v);
395: props._flags|=AMQP_BASIC_REPLY_TO_FLAG;
396: } else if(key=="expiration"){
397: const char* v=value->as_string().cstr();
398: props.expiration=amqp_cstring_bytes(v);
399: props._flags|=AMQP_BASIC_EXPIRATION_FLAG;
400: } else if(key=="message_id"){
401: const char* v=value->as_string().cstr();
402: props.message_id=amqp_cstring_bytes(v);
403: props._flags|=AMQP_BASIC_MESSAGE_ID_FLAG;
404: } else if(key=="timestamp"){
405: uint64_t ts=(uint64_t)value->as_double();
406: props.timestamp=ts;
407: props._flags|=AMQP_BASIC_TIMESTAMP_FLAG;
408: } else if(key=="type"){
409: const char* v=value->as_string().cstr();
410: props.type=amqp_cstring_bytes(v);
411: props._flags|=AMQP_BASIC_TYPE_FLAG;
412: } else if(key=="user_id"){
413: const char* v=value->as_string().cstr();
414: props.user_id=amqp_cstring_bytes(v);
415: props._flags|=AMQP_BASIC_USER_ID_FLAG;
416: } else if(key=="app_id"){
417: const char* v=value->as_string().cstr();
418: props.app_id=amqp_cstring_bytes(v);
419: props._flags|=AMQP_BASIC_APP_ID_FLAG;
1.18 moko 420: } else if(key=="cluster_id"){
421: const char* v=value->as_string().cstr();
422: props.cluster_id=amqp_cstring_bytes(v);
423: props._flags|=AMQP_BASIC_CLUSTER_ID_FLAG;
1.3 moko 424: } else if(key=="headers"){
1.17 moko 425: props.headers=amqp_build_arguments_table(r, value->get_hash());
426: props._flags|=AMQP_BASIC_HEADERS_FLAG;
427: } else
1.1 moko 428: throw Exception(PARSER_RUNTIME, 0, CALLED_WITH_INVALID_OPTION);
429: }
430: }
431: }
432:
433: if(!routing_key_c)
434: throw Exception("amqp", 0, "routing_key or queue must be specified");
435:
436: amqp_bytes_t body;
437: body.len = msg.length();
438: body.bytes=(void*)msg.cstr();
439:
1.3 moko 440: int ret = amqp_basic_publish(self.connection(), self.channel(), amqp_cstring_bytes(exchange_c), amqp_cstring_bytes(routing_key_c), mandatory, 0, &props, body);
1.1 moko 441:
1.16 moko 442: status_check(self, ret, "publish ");
1.1 moko 443: }
444:
445: static void _release(Request& r, MethodParams&) {
446: VAmqp& self=GET_SELF(r, VAmqp);
447: if(self.fconnection){
448: amqp_connection_state_t conn=self.fconnection;
449: amqp_channel_close(conn, self.fchannel, AMQP_REPLY_SUCCESS);
450: amqp_connection_close(conn, AMQP_REPLY_SUCCESS);
451: amqp_destroy_connection(conn);
452: self.fconnection=0;
453: self.fchannel=0;
1.16 moko 454: self.fstate=VAmqp::CONNECTION_DEAD;
1.1 moko 455: }
456: }
457:
1.15 moko 458: // to allow both [] and () call syntax
459: static uint64_t as_delivery_tag(MethodParams& params, int index=0) {
460: const String &tag_s=params.as_string(index, "delivery tag must not be code");
461: return pa_atoul(tag_s.cstr());
462: }
463:
1.1 moko 464: static void _ack(Request& r, MethodParams& params) {
465: VAmqp& self=GET_SELF(r, VAmqp);
1.15 moko 466: int ret = amqp_basic_ack(self.connection(), self.channel(), as_delivery_tag(params), 0);
1.16 moko 467: status_check(self, ret, "ack ");
1.1 moko 468: }
469:
470: static void _nack(Request& r, MethodParams& params) {
471: VAmqp& self=GET_SELF(r, VAmqp);
1.15 moko 472: uint64_t tag=as_delivery_tag(params);
1.1 moko 473: bool requeue=false;
474: if(params.count()>1){
475: if(HashStringValue* options=params.as_hash(1)){
476: for(HashStringValue::Iterator i(*options); i; i.next()){
477: if(i.key()=="requeue"){
478: requeue=r.process(*i.value()).as_bool();
479: } else
480: throw Exception(PARSER_RUNTIME, 0, CALLED_WITH_INVALID_OPTION);
481: }
482: }
483: }
1.15 moko 484: int ret = amqp_basic_nack(self.connection(), self.channel(), tag, 0, requeue);
1.16 moko 485: status_check(self, ret, "nack ");
1.1 moko 486: }
487:
488: static void _qos(Request& r, MethodParams& params) {
489: VAmqp& self=GET_SELF(r, VAmqp);
490: uint16_t prefetch_count=0;
491: if(params.count()>0){
492: if(HashStringValue* options=params.as_hash(0)){
493: for(HashStringValue::Iterator i(*options); i; i.next()){
494: if(i.key()=="prefetch_count"){
495: int pc=r.process(*i.value()).as_int();
496: prefetch_count= pc<0 ? 0 : (pc>65535 ? 65535 : (uint16_t)pc);
497: } else
498: throw Exception(PARSER_RUNTIME, 0, CALLED_WITH_INVALID_OPTION);
499: }
500: }
501: }
1.16 moko 502: amqp_basic_qos(self.connection(), self.channel(), 0, prefetch_count, 0);
503: check(self, amqp_get_rpc_reply(self.connection()), "qos ");
1.1 moko 504: }
505:
506: static void _reject(Request& r, MethodParams& params) {
507: VAmqp& self=GET_SELF(r, VAmqp);
1.15 moko 508: uint64_t tag=as_delivery_tag(params);
1.1 moko 509: bool requeue=true; // by default return to queue
510: if(params.count()>1){
511: if(HashStringValue* options = params.as_hash(1)){
512: for(HashStringValue::Iterator i(*options); i; i.next()){
513: if(i.key() == "requeue"){
514: requeue=r.process(*i.value()).as_bool();
515: } else
516: throw Exception(PARSER_RUNTIME, 0, CALLED_WITH_INVALID_OPTION);
517: }
518: }
519: }
1.15 moko 520: int ret = amqp_basic_reject(self.connection(), self.channel(), tag, requeue);
1.16 moko 521: status_check(self, ret, "reject ");
1.1 moko 522: }
523:
1.8 moko 524: static void _declare(Request& r, MethodParams& params) {
1.1 moko 525: VAmqp& self=GET_SELF(r, VAmqp);
1.8 moko 526: const char* exchange_c = 0;
527: const char* queue_c = 0;
1.1 moko 528: const char* type_c = "direct";
1.12 moko 529: bool passive=false, durable=false, auto_delete=false, internal=false, exclusive=false;
1.17 moko 530: amqp_table_t arguments=amqp_empty_table;
1.8 moko 531: if(HashStringValue* options=params.as_hash(0)){
532: for(HashStringValue::Iterator i(*options); i; i.next()){
533: String::Body key=i.key();
534: Value* value=i.value();
535: if(key=="exchange"){
536: exchange_c=value->as_string().cstr();
537: } else if(key=="queue"){
538: queue_c=value->as_string().cstr();
539: } else if(key=="type"){
540: type_c=value->as_string().cstr();
541: } else if(key=="passive"){
542: passive=r.process(*value).as_bool();
543: } else if(key=="durable"){
544: durable=r.process(*value).as_bool();
545: } else if(key=="auto_delete"){
546: auto_delete=r.process(*value).as_bool();
1.11 moko 547: } else if(key=="internal"){
548: internal=r.process(*value).as_bool();
549: } else if(key=="exclusive"){
550: exclusive=r.process(*value).as_bool();
1.17 moko 551: } else if(key=="arguments"){
552: arguments=amqp_build_arguments_table(r, value->get_hash());
1.8 moko 553: } else
554: throw Exception(PARSER_RUNTIME, 0, CALLED_WITH_INVALID_OPTION);
1.1 moko 555: }
556: }
1.8 moko 557: if(!exchange_c && !queue_c)
558: throw Exception("amqp", 0, "exchange or queue must be specified");
559:
560: if(exchange_c){
1.17 moko 561: amqp_exchange_declare(self.connection(), self.channel(), amqp_cstring_bytes(exchange_c), amqp_cstring_bytes(type_c), passive, durable, auto_delete, internal, arguments);
1.16 moko 562: check(self, amqp_get_rpc_reply(self.connection()));
1.8 moko 563: }
1.1 moko 564:
1.8 moko 565: if(queue_c){
1.17 moko 566: amqp_queue_declare_ok_t *ok = amqp_queue_declare(self.connection(), self.channel(), *queue_c ? amqp_cstring_bytes(queue_c) : amqp_empty_bytes, passive, durable, exclusive, auto_delete, arguments);
1.16 moko 567: check(self, amqp_get_rpc_reply(self.connection()));
1.8 moko 568: if(!*queue_c && ok){
569: r.write(*AMQP_STRING(ok->queue.bytes, ok->queue.len));
1.1 moko 570: }
571: }
572: }
573:
1.8 moko 574: static void _delete(Request& r, MethodParams& params) {
1.1 moko 575: VAmqp& self=GET_SELF(r, VAmqp);
1.8 moko 576: const char* exchange_c = 0;
577: const char* queue_c = 0;
1.11 moko 578: bool if_unused=false, if_empty=false;
1.8 moko 579: if(HashStringValue* options=params.as_hash(0)){
580: for(HashStringValue::Iterator i(*options); i; i.next()){
581: String::Body key=i.key();
582: Value* value=i.value();
583: if(key=="exchange"){
584: exchange_c=value->as_string().cstr();
585: } else if(key=="queue"){
586: queue_c=value->as_string().cstr();
587: } else if(key=="if_unused"){
588: if_unused=r.process(*value).as_bool();
589: } else if(key=="if_empty"){
590: if_empty=r.process(*value).as_bool();
591: } else
592: throw Exception(PARSER_RUNTIME, 0, CALLED_WITH_INVALID_OPTION);
1.1 moko 593: }
594: }
1.8 moko 595: if(!exchange_c && !queue_c)
596: throw Exception("amqp", 0, "exchange or queue must be specified");
597:
598: if(exchange_c){
599: amqp_exchange_delete(self.connection(), self.channel(), amqp_cstring_bytes(exchange_c), if_unused);
1.16 moko 600: check(self, amqp_get_rpc_reply(self.connection()));
1.1 moko 601: }
602:
1.8 moko 603: if(queue_c){
604: amqp_queue_delete(self.connection(), self.channel(), amqp_cstring_bytes(queue_c), if_unused, if_empty);
1.16 moko 605: check(self, amqp_get_rpc_reply(self.connection()));
1.1 moko 606: }
607: }
608:
1.8 moko 609: static void _bind(Request& r, MethodParams& params) {
1.1 moko 610: VAmqp& self=GET_SELF(r, VAmqp);
611: const char* exchange_c=0;
612: const char* queue_c=0;
613: const char* routing_key_c="";
1.8 moko 614: if(HashStringValue* options=params.as_hash(0)){
615: for(HashStringValue::Iterator i(*options); i; i.next()){
616: String::Body key=i.key();
617: Value* value=i.value();
618: if(key=="exchange"){
619: exchange_c=value->as_string().cstr();
620: } else if(key=="queue"){
621: queue_c=value->as_string().cstr();
622: } else if(key=="routing_key"){
623: routing_key_c=value->as_string().cstr();
624: } else
625: throw Exception(PARSER_RUNTIME, 0, CALLED_WITH_INVALID_OPTION);
1.1 moko 626: }
627: }
628: if(!exchange_c || !queue_c) throw Exception("amqp", 0, "exchange and queue are required");
629: amqp_queue_bind(self.connection(), self.channel(), amqp_cstring_bytes(queue_c), amqp_cstring_bytes(exchange_c), amqp_cstring_bytes(routing_key_c), amqp_empty_table);
1.16 moko 630: check(self, amqp_get_rpc_reply(self.connection()));
1.1 moko 631: }
632:
1.8 moko 633: static void _unbind(Request& r, MethodParams& params) {
1.1 moko 634: VAmqp& self=GET_SELF(r, VAmqp);
635: const char* exchange_c=0;
636: const char* queue_c=0;
637: const char* routing_key_c="";
1.8 moko 638: if(HashStringValue* options=params.as_hash(0)){
639: for(HashStringValue::Iterator i(*options); i; i.next()){
640: String::Body key=i.key();
641: Value* value=i.value();
642: if(key=="exchange"){
643: exchange_c=value->as_string().cstr();
644: } else if(key=="queue"){
645: queue_c=value->as_string().cstr();
646: } else if(key=="routing_key"){
647: routing_key_c=value->as_string().cstr();
648: } else
649: throw Exception(PARSER_RUNTIME, 0, CALLED_WITH_INVALID_OPTION);
1.1 moko 650: }
651: }
652: if(!exchange_c || !queue_c) throw Exception("amqp", 0, "exchange and queue are required");
653: amqp_queue_unbind(self.connection(), self.channel(), amqp_cstring_bytes(queue_c), amqp_cstring_bytes(exchange_c), amqp_cstring_bytes(routing_key_c), amqp_empty_table);
1.16 moko 654: check(self, amqp_get_rpc_reply(self.connection()));
1.1 moko 655: }
656:
1.8 moko 657: static void _purge(Request& r, MethodParams& params) {
658: VAmqp& self=GET_SELF(r, VAmqp);
659: const char* queue_c = 0;
660: if(HashStringValue* options=params.as_hash(0)){
661: for(HashStringValue::Iterator i(*options); i; i.next()){
662: String::Body key=i.key();
663: Value* value=i.value();
664: if(key=="queue"){
665: queue_c=value->as_string().cstr();
666: } else
667: throw Exception(PARSER_RUNTIME, 0, CALLED_WITH_INVALID_OPTION);
668: }
669: }
670: if(!queue_c)
671: throw Exception("amqp", 0, "queue must be specified");
672:
1.9 moko 673: amqp_queue_purge_ok_t *ok = amqp_queue_purge(self.connection(), self.channel(), amqp_cstring_bytes(queue_c));
1.16 moko 674: check(self, amqp_get_rpc_reply(self.connection()));
1.9 moko 675: r.write(*new VInt(ok ? ok->message_count : 0));
1.8 moko 676: }
677:
678: static void _info(Request& r, MethodParams& params) {
679: VAmqp& self = GET_SELF(r, VAmqp);
680: const char* queue_c = 0;
681:
682: if (HashStringValue* options=params.as_hash(0)) {
683: for (HashStringValue::Iterator i(*options); i; i.next()) {
684: String::Body key=i.key();
685: Value* value=i.value();
686: if(key=="queue"){
687: queue_c=value->as_string().cstr();
688: } else {
689: throw Exception(PARSER_RUNTIME, 0, CALLED_WITH_INVALID_OPTION);
690: }
691: }
692: }
693:
694: if (!queue_c)
695: throw Exception("amqp", 0, "queue must be specified");
696:
697: amqp_queue_declare_ok_t* ok = amqp_queue_declare(self.connection(), self.channel(), amqp_cstring_bytes(queue_c), /*passive*/ 1, 0, 0, 0, amqp_empty_table);
1.16 moko 698: check(self, amqp_get_rpc_reply(self.connection()));
1.8 moko 699:
700: Value& result=*new VHash;
1.9 moko 701: if(ok){
702: result.put_element(*new String("queue"), AMQP_VSTRING(ok->queue.bytes, ok->queue.len));
703: result.put_element(*new String("messages"), new VInt(ok->message_count));
704: result.put_element(*new String("consumers"), new VInt(ok->consumer_count));
705: }
1.8 moko 706: r.write(result);
707: }
708:
709: static VHash *amqp_message_hash(amqp_envelope_t &envelope) {
710: VHash *result=new VHash;
711: HashStringValue* h=result->get_hash();
712: h->put("msg", AMQP_VSTRING(envelope.message.body.bytes, envelope.message.body.len));
713: h->put("delivery_tag", new VInt(envelope.delivery_tag));
714: h->put("consumer_tag", AMQP_VSTRING(envelope.consumer_tag.bytes, envelope.consumer_tag.len));
715: h->put("exchange", AMQP_VSTRING(envelope.exchange.bytes, envelope.exchange.len));
1.17 moko 716: h->put("routing_key", AMQP_VSTRING(envelope.routing_key.bytes, envelope.routing_key.len));
717: h->put("redelivered", &VBool::get(envelope.redelivered));
718:
719: // properties are only put when the publisher actually set them (per the wire's own _flags bitmask) -
720: // same handful of allocations as the fields above, just conditional on what's actually present
721: amqp_basic_properties_t& props=envelope.message.properties;
722: if(props._flags & AMQP_BASIC_CONTENT_TYPE_FLAG)
723: h->put("content_type", AMQP_VSTRING(props.content_type.bytes, props.content_type.len));
724: if(props._flags & AMQP_BASIC_CONTENT_ENCODING_FLAG)
725: h->put("content_encoding", AMQP_VSTRING(props.content_encoding.bytes, props.content_encoding.len));
726: if(props._flags & AMQP_BASIC_HEADERS_FLAG)
727: h->put("headers", amqp_table_to_hash(props.headers));
728: if(props._flags & AMQP_BASIC_DELIVERY_MODE_FLAG)
729: h->put("delivery_mode", new VInt(props.delivery_mode));
730: if(props._flags & AMQP_BASIC_PRIORITY_FLAG)
731: h->put("priority", new VInt(props.priority));
732: if(props._flags & AMQP_BASIC_CORRELATION_ID_FLAG)
733: h->put("correlation_id", AMQP_VSTRING(props.correlation_id.bytes, props.correlation_id.len));
734: if(props._flags & AMQP_BASIC_REPLY_TO_FLAG)
735: h->put("reply_to", AMQP_VSTRING(props.reply_to.bytes, props.reply_to.len));
736: if(props._flags & AMQP_BASIC_EXPIRATION_FLAG)
737: h->put("expiration", AMQP_VSTRING(props.expiration.bytes, props.expiration.len));
738: if(props._flags & AMQP_BASIC_MESSAGE_ID_FLAG)
739: h->put("message_id", AMQP_VSTRING(props.message_id.bytes, props.message_id.len));
740: if(props._flags & AMQP_BASIC_TIMESTAMP_FLAG)
741: h->put("timestamp", new VInt((pa_wint)props.timestamp));
742: if(props._flags & AMQP_BASIC_TYPE_FLAG)
743: h->put("type", AMQP_VSTRING(props.type.bytes, props.type.len));
744: if(props._flags & AMQP_BASIC_USER_ID_FLAG)
745: h->put("user_id", AMQP_VSTRING(props.user_id.bytes, props.user_id.len));
746: if(props._flags & AMQP_BASIC_APP_ID_FLAG)
747: h->put("app_id", AMQP_VSTRING(props.app_id.bytes, props.app_id.len));
748: if(props._flags & AMQP_BASIC_CLUSTER_ID_FLAG)
749: h->put("cluster_id", AMQP_VSTRING(props.cluster_id.bytes, props.cluster_id.len));
750:
1.8 moko 751: return result;
752: }
753:
1.14 moko 754: // timeout<0 - wait forever (NULL), timeout==0 - don't wait (poll), timeout>0 - wait up to timeout seconds
755: static struct timeval* amqp_wait_tv(struct timeval& tv, int timeout){
756: if(timeout<0)
757: return NULL;
758: tv.tv_sec=timeout;
759: tv.tv_usec=0;
760: return &tv;
761: }
762:
1.17 moko 763: // amqp_consume_message() returns AMQP_STATUS_UNEXPECTED_STATE when it read a frame other than a deliver while polling.
764: // Per its own documented contract, read that pending frame to find out what it actually was:
765: // - a basic.return for an earlier mandatory publish that found no route: benign, doesn't close anything;
766: // drain the returned message (header+body, still pending right behind it) and retry - the real
767: // message (if any) is still coming
768: // - anything else: a genuine channel/connection close (typically after a protocol violation) - build a
769: // reply so check() can classify it correctly (cheap channel repair vs full reconnect)
1.23 moko 770: static amqp_rpc_reply_t amqp_consume_message_checked(amqp_connection_state_t conn, amqp_channel_t channel, amqp_envelope_t* envelope, struct timeval* tv) {
1.17 moko 771: for(;;) {
772: amqp_rpc_reply_t res = amqp_consume_message(conn, envelope, tv, 0);
773: if(res.reply_type != AMQP_RESPONSE_LIBRARY_EXCEPTION || res.library_error != AMQP_STATUS_UNEXPECTED_STATE)
774: return res;
775:
776: amqp_frame_t frame;
777: if(amqp_simple_wait_frame(conn, &frame) != AMQP_STATUS_OK || frame.frame_type != AMQP_FRAME_METHOD)
778: return res; // give up, let the original UNEXPECTED_STATE be treated as fatal
779:
780: if(frame.payload.method.id == AMQP_BASIC_RETURN_METHOD) {
781: amqp_message_t message;
782: if(amqp_read_message(conn, channel, &message, 0).reply_type == AMQP_RESPONSE_NORMAL)
783: amqp_destroy_message(&message);
784: continue;
785: }
786:
787: res.reply_type = AMQP_RESPONSE_SERVER_EXCEPTION;
788: res.reply.id = frame.payload.method.id;
789: res.reply.decoded = frame.payload.method.decoded;
790: return res;
791: }
1.16 moko 792: }
793:
1.18 moko 794: // Auto-object used for cancelling the consumer when the enclosing scope exits. A cancel failure here must
795: // never mask whatever error is already propagating, so its result is discarded rather than check()ed.
796: class Temp_amqp_consumer {
797: public:
1.19 moko 798: Temp_amqp_consumer(VAmqp& aself, const char* aconsumer_tag, bool adrain): self(aself), consumer_tag(aconsumer_tag), drain(adrain) {}
1.18 moko 799: ~Temp_amqp_consumer() {
800: if(!consumer_tag || self.fstate != VAmqp::ALIVE) return;
801: amqp_basic_cancel(self.fconnection, self.fchannel, amqp_cstring_bytes(consumer_tag));
802: amqp_get_rpc_reply(self.fconnection);
1.19 moko 803: if(drain){
804: // The broker may have already sent a deliver frame for this (now cancelled) consumer before it even saw our cancel,
805: // so it can still be sitting in the library's own buffer. Its delivery tag belongs to the pre-reset channel and
806: // won't exist anymore afterward, so drain anything already in flight - otherwise it would surface later, misattributed.
807: amqp_envelope_t envelope;
808: struct timeval no_wait = {0,0};
809: while(amqp_consume_message(self.fconnection, &envelope, &no_wait, 0).reply_type == AMQP_RESPONSE_NORMAL)
810: amqp_destroy_envelope(&envelope);
811: amqp_reset_channel(self);
812: }
1.18 moko 813: }
814: private:
815: VAmqp& self;
816: const char* consumer_tag;
1.19 moko 817: bool drain;
1.18 moko 818: };
819:
1.1 moko 820: static void _consume(Request& r, MethodParams& params) {
821: VAmqp& self=GET_SELF(r, VAmqp);
822: const char* queue_c=0;
823: const char* consumer_tag_c=0;
1.17 moko 824: bool ack=true, exclusive=false;
1.14 moko 825: int count=1; bool count_specified=false;
826: int timeout=0; bool timeout_specified=false;
1.1 moko 827: Junction* callback=0;
828:
1.2 moko 829: if(HashStringValue* options=params.as_hash(0)){
830: for(HashStringValue::Iterator i(*options); i; i.next()){
831: String::Body key=i.key();
832: Value* value=i.value();
1.3 moko 833: if(key=="callback"){
834: callback=value->get_junction();
835: } else if(key=="queue"){
1.2 moko 836: queue_c=value->as_string().cstr();
837: } else if(key=="consumer_tag"){
838: consumer_tag_c=value->as_string().cstr();
1.17 moko 839: } else if(key=="ack"){
840: ack=r.process(*value).as_bool();
1.10 moko 841: } else if(key=="exclusive"){
842: exclusive=r.process(*value).as_bool();
1.8 moko 843: } else if(key=="count"){
844: count=r.process(*value).as_int();
1.14 moko 845: count_specified=true;
846: } else if(key=="timeout"){
847: timeout=r.process(*value).as_int();
848: timeout_specified=true;
1.2 moko 849: } else
850: throw Exception(PARSER_RUNTIME, 0, CALLED_WITH_INVALID_OPTION);
1.1 moko 851: }
852: }
853:
1.8 moko 854: if(!queue_c) throw Exception("amqp", 0, "queue must be specified");
1.14 moko 855: if(count==0) throw Exception("amqp", 0, "count must not be zero");
856:
857: // listen mode (callback): count/timeout unlimited by default - runs until stop_consume/timeout/error
858: // pull mode (no callback): count(1)/timeout(0) by default - returns whatever is ready right now
859: if(!count_specified)
860: count = callback ? -1 : 1;
861: if(!timeout_specified)
862: timeout = callback ? -1 : 0;
1.1 moko 863:
1.9 moko 864: amqp_basic_consume_ok_t *ok = amqp_basic_consume(self.connection(), self.channel(), amqp_cstring_bytes(queue_c),
1.1 moko 865: consumer_tag_c ? amqp_cstring_bytes(consumer_tag_c) : amqp_empty_bytes,
1.17 moko 866: 0 /*no_local*/, !ack, exclusive, amqp_empty_table);
1.16 moko 867: check(self, amqp_get_rpc_reply(self.connection()));
1.1 moko 868:
1.15 moko 869: // amqp_maybe_release_buffers() recycles ok->consumer_tag
870: const char* consumer_tag_copy = ok ? pa_strdup((const char*)ok->consumer_tag.bytes, ok->consumer_tag.len) : 0;
1.19 moko 871: Temp_amqp_consumer cancel_consumer(self, consumer_tag_copy, ack && callback);
1.15 moko 872:
1.14 moko 873: struct timeval tv;
874:
1.8 moko 875: if(callback){
876: self.fstop=false;
1.14 moko 877: for(int received=0; !self.fstop && (count<0 || received<count); received++){
1.8 moko 878: amqp_envelope_t envelope;
879: memset(&envelope, 0, sizeof(envelope));
880: amqp_maybe_release_buffers(self.connection());
1.14 moko 881: // timeout is the max idle gap between messages, re-armed on every wait
1.17 moko 882: amqp_rpc_reply_t res = amqp_consume_message_checked(self.connection(), self.channel(), &envelope, amqp_wait_tv(tv, timeout));
1.8 moko 883: if(res.reply_type == AMQP_RESPONSE_NORMAL){
884: VHash *vh=amqp_message_hash(envelope);
885: Value *params_cb[]={vh};
886: METHOD_FRAME_ACTION(*callback->method, r.method_frame, callback->self, {
887: frame.store_params(params_cb, 1);
888: r.call(frame);
889: });
890: amqp_destroy_envelope(&envelope);
891: } else if(res.reply_type == AMQP_RESPONSE_LIBRARY_EXCEPTION && res.library_error == AMQP_STATUS_TIMEOUT) {
1.14 moko 892: break; // idle too long - stop cleanly
1.8 moko 893: } else {
1.17 moko 894: check(self, res, "consume ");
1.8 moko 895: }
896: }
897: } else {
898: VArray& result=*new VArray();
899: ArrayValue& result_array=result.array();
900:
1.14 moko 901: for(int received=0; count<0 || received<count; received++){
1.8 moko 902: amqp_envelope_t envelope;
903: memset(&envelope, 0, sizeof(envelope));
904: amqp_maybe_release_buffers(self.connection());
1.14 moko 905: // timeout applies only to the first message of the batch;
906: // the rest is drained with a non-blocking poll until nothing more is ready
1.17 moko 907: amqp_rpc_reply_t res = amqp_consume_message_checked(self.connection(), self.channel(), &envelope, amqp_wait_tv(tv, received==0 ? timeout : 0));
1.8 moko 908: if(res.reply_type == AMQP_RESPONSE_NORMAL){
909: result_array+=amqp_message_hash(envelope);
910: amqp_destroy_envelope(&envelope);
1.14 moko 911: } else if(res.reply_type == AMQP_RESPONSE_LIBRARY_EXCEPTION && res.library_error == AMQP_STATUS_TIMEOUT) {
912: break; // nothing (more) ready - return what we have
1.8 moko 913: } else {
1.17 moko 914: check(self, res, "consume ");
1.8 moko 915: }
1.1 moko 916: }
1.8 moko 917: r.write(result);
1.1 moko 918: }
919: }
920:
921: static void _stop_consume(Request& r, MethodParams&) {
922: VAmqp& self=GET_SELF(r, VAmqp);
923: self.fstop=true;
924: }
925:
1.6 moko 926: #endif // WITH_AMQP
1.1 moko 927:
928: // constructor
929: MAmqp::MAmqp(): Methoded("amqp") {
930: add_native_method("create", Method::CT_DYNAMIC, _create, 0, 1);
931: #ifdef WITH_AMQP
932: add_native_method("publish", Method::CT_DYNAMIC, _publish, 1, 2);
933: add_native_method("release", Method::CT_DYNAMIC, _release, 0, 0);
934: add_native_method("ack", Method::CT_DYNAMIC, _ack, 1, 1);
935: add_native_method("nack", Method::CT_DYNAMIC, _nack, 1, 2);
936: add_native_method("reject", Method::CT_DYNAMIC, _reject, 1, 2);
937: add_native_method("qos", Method::CT_DYNAMIC, _qos, 0, 1);
1.8 moko 938: add_native_method("declare", Method::CT_DYNAMIC, _declare, 1, 1);
939: add_native_method("delete", Method::CT_DYNAMIC, _delete, 1, 1);
940: add_native_method("bind", Method::CT_DYNAMIC, _bind, 1, 1);
941: add_native_method("unbind", Method::CT_DYNAMIC, _unbind, 1, 1);
942: add_native_method("purge", Method::CT_DYNAMIC, _purge, 1, 1);
943: add_native_method("info", Method::CT_DYNAMIC, _info, 1, 1);
1.2 moko 944: add_native_method("consume", Method::CT_DYNAMIC, _consume, 1, 1);
1.1 moko 945: add_native_method("stop_consume", Method::CT_DYNAMIC, _stop_consume, 0, 0);
1.6 moko 946: #endif // WITH_AMQP
1.1 moko 947: }
E-mail: