Annotation of parser3/src/classes/amqp.C, revision 1.28

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.28    ! moko       18: volatile const char * IDENT_AMQP_C="$Id: amqp.C,v 1.27 2026/10/09 18:32:15 moko Exp $" IDENT_PA_VAMQP_H;
1.1       moko       19: 
                     20: class MAmqp: public Methoded {
                     21: public: // VStateless_class
1.28    ! moko       22:        Value* create_new_value(Pool& apool) { return new VAmqp(apool); }
1.1       moko       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&) {
1.28    ! moko      446:        GET_SELF(r, VAmqp).release();
1.1       moko      447: }
                    448: 
1.15      moko      449: // to allow both [] and () call syntax
                    450: static uint64_t as_delivery_tag(MethodParams& params, int index=0) {
                    451:        const String &tag_s=params.as_string(index, "delivery tag must not be code");
                    452:        return pa_atoul(tag_s.cstr());
                    453: }
                    454: 
1.1       moko      455: static void _ack(Request& r, MethodParams& params) {
                    456:        VAmqp& self=GET_SELF(r, VAmqp);
1.15      moko      457:        int ret = amqp_basic_ack(self.connection(), self.channel(), as_delivery_tag(params), 0);
1.16      moko      458:        status_check(self, ret, "ack ");
1.1       moko      459: }
                    460: 
                    461: static void _nack(Request& r, MethodParams& params) {
                    462:        VAmqp& self=GET_SELF(r, VAmqp);
1.15      moko      463:        uint64_t tag=as_delivery_tag(params);
1.1       moko      464:        bool requeue=false;
                    465:        if(params.count()>1){
                    466:                if(HashStringValue* options=params.as_hash(1)){
                    467:                        for(HashStringValue::Iterator i(*options); i; i.next()){
                    468:                                if(i.key()=="requeue"){
                    469:                                        requeue=r.process(*i.value()).as_bool();
                    470:                                } else
                    471:                                        throw Exception(PARSER_RUNTIME, 0, CALLED_WITH_INVALID_OPTION);
                    472:                        }
                    473:                }
                    474:        }
1.15      moko      475:        int ret = amqp_basic_nack(self.connection(), self.channel(), tag, 0, requeue);
1.16      moko      476:        status_check(self, ret, "nack ");
1.1       moko      477: }
                    478: 
                    479: static void _qos(Request& r, MethodParams& params) {
                    480:        VAmqp& self=GET_SELF(r, VAmqp);
                    481:        uint16_t prefetch_count=0;
                    482:        if(params.count()>0){
                    483:                if(HashStringValue* options=params.as_hash(0)){
                    484:                        for(HashStringValue::Iterator i(*options); i; i.next()){
                    485:                                if(i.key()=="prefetch_count"){
                    486:                                        int pc=r.process(*i.value()).as_int();
                    487:                                        prefetch_count= pc<0 ? 0 : (pc>65535 ? 65535 : (uint16_t)pc);
                    488:                                } else
                    489:                                        throw Exception(PARSER_RUNTIME, 0, CALLED_WITH_INVALID_OPTION);
                    490:                        }
                    491:                }
                    492:        }
1.16      moko      493:        amqp_basic_qos(self.connection(), self.channel(), 0, prefetch_count, 0);
                    494:        check(self, amqp_get_rpc_reply(self.connection()), "qos ");
1.1       moko      495: }
                    496: 
                    497: static void _reject(Request& r, MethodParams& params) {
                    498:        VAmqp& self=GET_SELF(r, VAmqp);
1.15      moko      499:        uint64_t tag=as_delivery_tag(params);
1.1       moko      500:        bool requeue=true; // by default return to queue
                    501:        if(params.count()>1){
                    502:                if(HashStringValue* options = params.as_hash(1)){
                    503:                        for(HashStringValue::Iterator i(*options); i; i.next()){
                    504:                                if(i.key() == "requeue"){
                    505:                                        requeue=r.process(*i.value()).as_bool();
                    506:                                } else
                    507:                                        throw Exception(PARSER_RUNTIME, 0, CALLED_WITH_INVALID_OPTION);
                    508:                        }
                    509:                }
                    510:        }
1.15      moko      511:        int ret = amqp_basic_reject(self.connection(), self.channel(), tag, requeue);
1.16      moko      512:        status_check(self, ret, "reject ");
1.1       moko      513: }
                    514: 
1.8       moko      515: static void _declare(Request& r, MethodParams& params) {
1.1       moko      516:        VAmqp& self=GET_SELF(r, VAmqp);
1.8       moko      517:        const char* exchange_c = 0;
                    518:        const char* queue_c = 0;
1.1       moko      519:        const char* type_c = "direct";
1.12      moko      520:        bool passive=false, durable=false, auto_delete=false, internal=false, exclusive=false;
1.17      moko      521:        amqp_table_t arguments=amqp_empty_table;
1.8       moko      522:        if(HashStringValue* options=params.as_hash(0)){
                    523:                for(HashStringValue::Iterator i(*options); i; i.next()){
                    524:                        String::Body key=i.key();
                    525:                        Value* value=i.value();
                    526:                        if(key=="exchange"){
                    527:                                exchange_c=value->as_string().cstr();
                    528:                        } else if(key=="queue"){
                    529:                                queue_c=value->as_string().cstr();
                    530:                        } else if(key=="type"){
                    531:                                type_c=value->as_string().cstr();
                    532:                        } else if(key=="passive"){
                    533:                                passive=r.process(*value).as_bool();
                    534:                        } else if(key=="durable"){
                    535:                                durable=r.process(*value).as_bool();
                    536:                        } else if(key=="auto_delete"){
                    537:                                auto_delete=r.process(*value).as_bool();
1.11      moko      538:                        } else if(key=="internal"){
                    539:                                internal=r.process(*value).as_bool();
                    540:                        } else if(key=="exclusive"){
                    541:                                exclusive=r.process(*value).as_bool();
1.17      moko      542:                        } else if(key=="arguments"){
                    543:                                arguments=amqp_build_arguments_table(r, value->get_hash());
1.8       moko      544:                        } else
                    545:                                throw Exception(PARSER_RUNTIME, 0, CALLED_WITH_INVALID_OPTION);
1.1       moko      546:                }
                    547:        }
1.8       moko      548:        if(!exchange_c && !queue_c)
                    549:                throw Exception("amqp", 0, "exchange or queue must be specified");
                    550: 
                    551:        if(exchange_c){
1.17      moko      552:                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      553:                check(self, amqp_get_rpc_reply(self.connection()));
1.8       moko      554:        }
1.1       moko      555: 
1.8       moko      556:        if(queue_c){
1.17      moko      557:                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      558:                check(self, amqp_get_rpc_reply(self.connection()));
1.8       moko      559:                if(!*queue_c && ok){
                    560:                        r.write(*AMQP_STRING(ok->queue.bytes, ok->queue.len));
1.1       moko      561:                }
                    562:        }
                    563: }
                    564: 
1.8       moko      565: static void _delete(Request& r, MethodParams& params) {
1.1       moko      566:        VAmqp& self=GET_SELF(r, VAmqp);
1.8       moko      567:        const char* exchange_c = 0;
                    568:        const char* queue_c = 0;
1.11      moko      569:        bool if_unused=false, if_empty=false;
1.8       moko      570:        if(HashStringValue* options=params.as_hash(0)){
                    571:                for(HashStringValue::Iterator i(*options); i; i.next()){
                    572:                        String::Body key=i.key();
                    573:                        Value* value=i.value();
                    574:                        if(key=="exchange"){
                    575:                                exchange_c=value->as_string().cstr();
                    576:                        } else if(key=="queue"){
                    577:                                queue_c=value->as_string().cstr();
                    578:                        } else if(key=="if_unused"){
                    579:                                if_unused=r.process(*value).as_bool();
                    580:                        } else if(key=="if_empty"){
                    581:                                if_empty=r.process(*value).as_bool();
                    582:                        } else
                    583:                                throw Exception(PARSER_RUNTIME, 0, CALLED_WITH_INVALID_OPTION);
1.1       moko      584:                }
                    585:        }
1.8       moko      586:        if(!exchange_c && !queue_c)
                    587:                throw Exception("amqp", 0, "exchange or queue must be specified");
                    588: 
                    589:        if(exchange_c){
                    590:                amqp_exchange_delete(self.connection(), self.channel(), amqp_cstring_bytes(exchange_c), if_unused);
1.16      moko      591:                check(self, amqp_get_rpc_reply(self.connection()));
1.1       moko      592:        }
                    593: 
1.8       moko      594:        if(queue_c){
                    595:                amqp_queue_delete(self.connection(), self.channel(), amqp_cstring_bytes(queue_c), if_unused, if_empty);
1.16      moko      596:                check(self, amqp_get_rpc_reply(self.connection()));
1.1       moko      597:        }
                    598: }
                    599: 
1.8       moko      600: static void _bind(Request& r, MethodParams& params) {
1.1       moko      601:        VAmqp& self=GET_SELF(r, VAmqp);
                    602:        const char* exchange_c=0;
                    603:        const char* queue_c=0;
                    604:        const char* routing_key_c="";
1.8       moko      605:        if(HashStringValue* options=params.as_hash(0)){
                    606:                for(HashStringValue::Iterator i(*options); i; i.next()){
                    607:                        String::Body key=i.key();
                    608:                        Value* value=i.value();
                    609:                        if(key=="exchange"){
                    610:                                exchange_c=value->as_string().cstr();
                    611:                        } else if(key=="queue"){
                    612:                                queue_c=value->as_string().cstr();
                    613:                        } else if(key=="routing_key"){
                    614:                                routing_key_c=value->as_string().cstr();
                    615:                        } else
                    616:                                throw Exception(PARSER_RUNTIME, 0, CALLED_WITH_INVALID_OPTION);
1.1       moko      617:                }
                    618:        }
                    619:        if(!exchange_c || !queue_c) throw Exception("amqp", 0, "exchange and queue are required");
                    620:        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      621:        check(self, amqp_get_rpc_reply(self.connection()));
1.1       moko      622: }
                    623: 
1.8       moko      624: static void _unbind(Request& r, MethodParams& params) {
1.1       moko      625:        VAmqp& self=GET_SELF(r, VAmqp);
                    626:        const char* exchange_c=0;
                    627:        const char* queue_c=0;
                    628:        const char* routing_key_c="";
1.8       moko      629:        if(HashStringValue* options=params.as_hash(0)){
                    630:                for(HashStringValue::Iterator i(*options); i; i.next()){
                    631:                        String::Body key=i.key();
                    632:                        Value* value=i.value();
                    633:                        if(key=="exchange"){
                    634:                                exchange_c=value->as_string().cstr();
                    635:                        } else if(key=="queue"){
                    636:                                queue_c=value->as_string().cstr();
                    637:                        } else if(key=="routing_key"){
                    638:                                routing_key_c=value->as_string().cstr();
                    639:                        } else
                    640:                                throw Exception(PARSER_RUNTIME, 0, CALLED_WITH_INVALID_OPTION);
1.1       moko      641:                }
                    642:        }
                    643:        if(!exchange_c || !queue_c) throw Exception("amqp", 0, "exchange and queue are required");
                    644:        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      645:        check(self, amqp_get_rpc_reply(self.connection()));
1.1       moko      646: }
                    647: 
1.8       moko      648: static void _purge(Request& r, MethodParams& params) {
                    649:        VAmqp& self=GET_SELF(r, VAmqp);
                    650:        const char* queue_c = 0;
                    651:        if(HashStringValue* options=params.as_hash(0)){
                    652:                for(HashStringValue::Iterator i(*options); i; i.next()){
                    653:                        String::Body key=i.key();
                    654:                        Value* value=i.value();
                    655:                        if(key=="queue"){
                    656:                                queue_c=value->as_string().cstr();
                    657:                        } else
                    658:                                throw Exception(PARSER_RUNTIME, 0, CALLED_WITH_INVALID_OPTION);
                    659:                }
                    660:        }
                    661:        if(!queue_c)
                    662:                throw Exception("amqp", 0, "queue must be specified");
                    663: 
1.9       moko      664:        amqp_queue_purge_ok_t *ok = amqp_queue_purge(self.connection(), self.channel(), amqp_cstring_bytes(queue_c));
1.16      moko      665:        check(self, amqp_get_rpc_reply(self.connection()));
1.9       moko      666:        r.write(*new VInt(ok ? ok->message_count : 0));
1.8       moko      667: }
                    668: 
                    669: static void _info(Request& r, MethodParams& params) {
                    670:        VAmqp& self = GET_SELF(r, VAmqp);
                    671:        const char* queue_c = 0;
                    672: 
                    673:        if (HashStringValue* options=params.as_hash(0)) {
                    674:                for (HashStringValue::Iterator i(*options); i; i.next()) {
                    675:                        String::Body key=i.key();
                    676:                        Value* value=i.value();
                    677:                        if(key=="queue"){
                    678:                                queue_c=value->as_string().cstr();
                    679:                        } else {
                    680:                                throw Exception(PARSER_RUNTIME, 0, CALLED_WITH_INVALID_OPTION);
                    681:                        }
                    682:                }
                    683:        }
                    684: 
                    685:        if (!queue_c)
                    686:                throw Exception("amqp", 0, "queue must be specified");
                    687: 
                    688:        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      689:        check(self, amqp_get_rpc_reply(self.connection()));
1.8       moko      690: 
                    691:        Value& result=*new VHash;
1.9       moko      692:        if(ok){
                    693:                result.put_element(*new String("queue"), AMQP_VSTRING(ok->queue.bytes, ok->queue.len));
                    694:                result.put_element(*new String("messages"), new VInt(ok->message_count));
                    695:                result.put_element(*new String("consumers"), new VInt(ok->consumer_count));
                    696:        }
1.8       moko      697:        r.write(result);
                    698: }
                    699: 
                    700: static VHash *amqp_message_hash(amqp_envelope_t &envelope) {
                    701:        VHash *result=new VHash;
                    702:        HashStringValue* h=result->get_hash();
                    703:        h->put("msg", AMQP_VSTRING(envelope.message.body.bytes, envelope.message.body.len));
                    704:        h->put("delivery_tag", new VInt(envelope.delivery_tag));
                    705:        h->put("consumer_tag", AMQP_VSTRING(envelope.consumer_tag.bytes, envelope.consumer_tag.len));
                    706:        h->put("exchange", AMQP_VSTRING(envelope.exchange.bytes, envelope.exchange.len));
1.17      moko      707:        h->put("routing_key", AMQP_VSTRING(envelope.routing_key.bytes, envelope.routing_key.len));
                    708:        h->put("redelivered", &VBool::get(envelope.redelivered));
                    709: 
                    710:        // properties are only put when the publisher actually set them (per the wire's own _flags bitmask) -
                    711:        // same handful of allocations as the fields above, just conditional on what's actually present
                    712:        amqp_basic_properties_t& props=envelope.message.properties;
                    713:        if(props._flags & AMQP_BASIC_CONTENT_TYPE_FLAG)
                    714:                h->put("content_type", AMQP_VSTRING(props.content_type.bytes, props.content_type.len));
                    715:        if(props._flags & AMQP_BASIC_CONTENT_ENCODING_FLAG)
                    716:                h->put("content_encoding", AMQP_VSTRING(props.content_encoding.bytes, props.content_encoding.len));
                    717:        if(props._flags & AMQP_BASIC_HEADERS_FLAG)
                    718:                h->put("headers", amqp_table_to_hash(props.headers));
                    719:        if(props._flags & AMQP_BASIC_DELIVERY_MODE_FLAG)
                    720:                h->put("delivery_mode", new VInt(props.delivery_mode));
                    721:        if(props._flags & AMQP_BASIC_PRIORITY_FLAG)
                    722:                h->put("priority", new VInt(props.priority));
                    723:        if(props._flags & AMQP_BASIC_CORRELATION_ID_FLAG)
                    724:                h->put("correlation_id", AMQP_VSTRING(props.correlation_id.bytes, props.correlation_id.len));
                    725:        if(props._flags & AMQP_BASIC_REPLY_TO_FLAG)
                    726:                h->put("reply_to", AMQP_VSTRING(props.reply_to.bytes, props.reply_to.len));
                    727:        if(props._flags & AMQP_BASIC_EXPIRATION_FLAG)
                    728:                h->put("expiration", AMQP_VSTRING(props.expiration.bytes, props.expiration.len));
                    729:        if(props._flags & AMQP_BASIC_MESSAGE_ID_FLAG)
                    730:                h->put("message_id", AMQP_VSTRING(props.message_id.bytes, props.message_id.len));
                    731:        if(props._flags & AMQP_BASIC_TIMESTAMP_FLAG)
                    732:                h->put("timestamp", new VInt((pa_wint)props.timestamp));
                    733:        if(props._flags & AMQP_BASIC_TYPE_FLAG)
                    734:                h->put("type", AMQP_VSTRING(props.type.bytes, props.type.len));
                    735:        if(props._flags & AMQP_BASIC_USER_ID_FLAG)
                    736:                h->put("user_id", AMQP_VSTRING(props.user_id.bytes, props.user_id.len));
                    737:        if(props._flags & AMQP_BASIC_APP_ID_FLAG)
                    738:                h->put("app_id", AMQP_VSTRING(props.app_id.bytes, props.app_id.len));
                    739:        if(props._flags & AMQP_BASIC_CLUSTER_ID_FLAG)
                    740:                h->put("cluster_id", AMQP_VSTRING(props.cluster_id.bytes, props.cluster_id.len));
                    741: 
1.8       moko      742:        return result;
                    743: }
                    744: 
1.14      moko      745: // timeout<0 - wait forever (NULL), timeout==0 - don't wait (poll), timeout>0 - wait up to timeout seconds
                    746: static struct timeval* amqp_wait_tv(struct timeval& tv, int timeout){
                    747:        if(timeout<0)
                    748:                return NULL;
                    749:        tv.tv_sec=timeout;
                    750:        tv.tv_usec=0;
                    751:        return &tv;
                    752: }
                    753: 
1.17      moko      754: // amqp_consume_message() returns AMQP_STATUS_UNEXPECTED_STATE when it read a frame other than a deliver while polling.
                    755: // Per its own documented contract, read that pending frame to find out what it actually was:
                    756: //  - a basic.return for an earlier mandatory publish that found no route: benign, doesn't close anything;
                    757: //    drain the returned message (header+body, still pending right behind it) and retry - the real
                    758: //    message (if any) is still coming
                    759: //  - anything else: a genuine channel/connection close (typically after a protocol violation) - build a
                    760: //    reply so check() can classify it correctly (cheap channel repair vs full reconnect)
1.23      moko      761: 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      762:        for(;;) {
                    763:                amqp_rpc_reply_t res = amqp_consume_message(conn, envelope, tv, 0);
                    764:                if(res.reply_type != AMQP_RESPONSE_LIBRARY_EXCEPTION || res.library_error != AMQP_STATUS_UNEXPECTED_STATE)
                    765:                        return res;
                    766: 
                    767:                amqp_frame_t frame;
                    768:                if(amqp_simple_wait_frame(conn, &frame) != AMQP_STATUS_OK || frame.frame_type != AMQP_FRAME_METHOD)
                    769:                        return res; // give up, let the original UNEXPECTED_STATE be treated as fatal
                    770: 
                    771:                if(frame.payload.method.id == AMQP_BASIC_RETURN_METHOD) {
                    772:                        amqp_message_t message;
                    773:                        if(amqp_read_message(conn, channel, &message, 0).reply_type == AMQP_RESPONSE_NORMAL)
                    774:                                amqp_destroy_message(&message);
                    775:                        continue;
                    776:                }
                    777: 
                    778:                res.reply_type = AMQP_RESPONSE_SERVER_EXCEPTION;
                    779:                res.reply.id = frame.payload.method.id;
                    780:                res.reply.decoded = frame.payload.method.decoded;
                    781:                return res;
                    782:        }
1.16      moko      783: }
                    784: 
1.18      moko      785: // Auto-object used for cancelling the consumer when the enclosing scope exits. A cancel failure here must
                    786: // never mask whatever error is already propagating, so its result is discarded rather than check()ed.
                    787: class Temp_amqp_consumer {
                    788: public:
1.19      moko      789:        Temp_amqp_consumer(VAmqp& aself, const char* aconsumer_tag, bool adrain): self(aself), consumer_tag(aconsumer_tag), drain(adrain) {}
1.18      moko      790:        ~Temp_amqp_consumer() {
                    791:                if(!consumer_tag || self.fstate != VAmqp::ALIVE) return;
                    792:                amqp_basic_cancel(self.fconnection, self.fchannel, amqp_cstring_bytes(consumer_tag));
                    793:                amqp_get_rpc_reply(self.fconnection);
1.19      moko      794:                if(drain){
                    795:                        // The broker may have already sent a deliver frame for this (now cancelled) consumer before it even saw our cancel,
                    796:                        // so it can still be sitting in the library's own buffer. Its delivery tag belongs to the pre-reset channel and
                    797:                        // won't exist anymore afterward, so drain anything already in flight  - otherwise it would surface later, misattributed.
                    798:                        amqp_envelope_t envelope;
                    799:                        struct timeval no_wait = {0,0};
                    800:                        while(amqp_consume_message(self.fconnection, &envelope, &no_wait, 0).reply_type == AMQP_RESPONSE_NORMAL)
                    801:                                amqp_destroy_envelope(&envelope);
                    802:                        amqp_reset_channel(self);
                    803:                }
1.18      moko      804:        }
                    805: private:
                    806:        VAmqp& self;
                    807:        const char* consumer_tag;
1.19      moko      808:        bool drain;
1.18      moko      809: };
                    810: 
1.1       moko      811: static void _consume(Request& r, MethodParams& params) {
                    812:        VAmqp& self=GET_SELF(r, VAmqp);
                    813:        const char* queue_c=0;
                    814:        const char* consumer_tag_c=0;
1.17      moko      815:        bool ack=true, exclusive=false;
1.14      moko      816:        int count=1; bool count_specified=false;
                    817:        int timeout=0; bool timeout_specified=false;
1.1       moko      818:        Junction* callback=0;
                    819: 
1.2       moko      820:        if(HashStringValue* options=params.as_hash(0)){
                    821:                for(HashStringValue::Iterator i(*options); i; i.next()){
                    822:                        String::Body key=i.key();
                    823:                        Value* value=i.value();
1.3       moko      824:                        if(key=="callback"){
                    825:                                callback=value->get_junction();
                    826:                        } else if(key=="queue"){
1.2       moko      827:                                queue_c=value->as_string().cstr();
                    828:                        } else if(key=="consumer_tag"){
                    829:                                consumer_tag_c=value->as_string().cstr();
1.17      moko      830:                        } else if(key=="ack"){
                    831:                                ack=r.process(*value).as_bool();
1.10      moko      832:                        } else if(key=="exclusive"){
                    833:                                exclusive=r.process(*value).as_bool();
1.8       moko      834:                        } else if(key=="count"){
                    835:                                count=r.process(*value).as_int();
1.14      moko      836:                                count_specified=true;
                    837:                        } else if(key=="timeout"){
                    838:                                timeout=r.process(*value).as_int();
                    839:                                timeout_specified=true;
1.2       moko      840:                        } else
                    841:                                throw Exception(PARSER_RUNTIME, 0, CALLED_WITH_INVALID_OPTION);
1.1       moko      842:                }
                    843:        }
                    844: 
1.8       moko      845:        if(!queue_c) throw Exception("amqp", 0, "queue must be specified");
1.14      moko      846:        if(count==0) throw Exception("amqp", 0, "count must not be zero");
                    847: 
                    848:        // listen mode (callback): count/timeout unlimited by default - runs until stop_consume/timeout/error
                    849:        // pull mode (no callback): count(1)/timeout(0) by default - returns whatever is ready right now
                    850:        if(!count_specified)
                    851:                count = callback ? -1 : 1;
                    852:        if(!timeout_specified)
                    853:                timeout = callback ? -1 : 0;
1.1       moko      854: 
1.9       moko      855:        amqp_basic_consume_ok_t *ok = amqp_basic_consume(self.connection(), self.channel(), amqp_cstring_bytes(queue_c),
1.1       moko      856:                consumer_tag_c ? amqp_cstring_bytes(consumer_tag_c) : amqp_empty_bytes,
1.17      moko      857:                0 /*no_local*/, !ack, exclusive, amqp_empty_table);
1.16      moko      858:        check(self, amqp_get_rpc_reply(self.connection()));
1.1       moko      859: 
1.15      moko      860:        // amqp_maybe_release_buffers() recycles ok->consumer_tag
                    861:        const char* consumer_tag_copy = ok ? pa_strdup((const char*)ok->consumer_tag.bytes, ok->consumer_tag.len) : 0;
1.19      moko      862:        Temp_amqp_consumer cancel_consumer(self, consumer_tag_copy, ack && callback);
1.15      moko      863: 
1.14      moko      864:        struct timeval tv;
                    865: 
1.8       moko      866:        if(callback){
                    867:                self.fstop=false;
1.14      moko      868:                for(int received=0; !self.fstop && (count<0 || received<count); received++){
1.8       moko      869:                        amqp_envelope_t envelope;
                    870:                        memset(&envelope, 0, sizeof(envelope));
                    871:                        amqp_maybe_release_buffers(self.connection());
1.14      moko      872:                        // timeout is the max idle gap between messages, re-armed on every wait
1.17      moko      873:                        amqp_rpc_reply_t res = amqp_consume_message_checked(self.connection(), self.channel(), &envelope, amqp_wait_tv(tv, timeout));
1.8       moko      874:                        if(res.reply_type == AMQP_RESPONSE_NORMAL){
                    875:                                VHash *vh=amqp_message_hash(envelope);
                    876:                                Value *params_cb[]={vh};
                    877:                                METHOD_FRAME_ACTION(*callback->method, r.method_frame, callback->self, {
                    878:                                        frame.store_params(params_cb, 1);
                    879:                                        r.call(frame);
                    880:                                });
                    881:                                amqp_destroy_envelope(&envelope);
                    882:                        } else if(res.reply_type == AMQP_RESPONSE_LIBRARY_EXCEPTION && res.library_error == AMQP_STATUS_TIMEOUT) {
1.14      moko      883:                                break; // idle too long - stop cleanly
1.8       moko      884:                        } else {
1.17      moko      885:                                check(self, res, "consume ");
1.8       moko      886:                        }
                    887:                }
                    888:        } else {
                    889:                VArray& result=*new VArray();
                    890:                ArrayValue& result_array=result.array();
                    891: 
1.14      moko      892:                for(int received=0; count<0 || received<count; received++){
1.8       moko      893:                        amqp_envelope_t envelope;
                    894:                        memset(&envelope, 0, sizeof(envelope));
                    895:                        amqp_maybe_release_buffers(self.connection());
1.14      moko      896:                        // timeout applies only to the first message of the batch;
                    897:                        // the rest is drained with a non-blocking poll until nothing more is ready
1.17      moko      898:                        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      899:                        if(res.reply_type == AMQP_RESPONSE_NORMAL){
                    900:                                result_array+=amqp_message_hash(envelope);
                    901:                                amqp_destroy_envelope(&envelope);
1.14      moko      902:                        } else if(res.reply_type == AMQP_RESPONSE_LIBRARY_EXCEPTION && res.library_error == AMQP_STATUS_TIMEOUT) {
                    903:                                break; // nothing (more) ready - return what we have
1.8       moko      904:                        } else {
1.17      moko      905:                                check(self, res, "consume ");
1.8       moko      906:                        }
1.1       moko      907:                }
1.8       moko      908:                r.write(result);
1.1       moko      909:        }
                    910: }
                    911: 
                    912: static void _stop_consume(Request& r, MethodParams&) {
                    913:        VAmqp& self=GET_SELF(r, VAmqp);
                    914:        self.fstop=true;
                    915: }
                    916: 
1.6       moko      917: #endif // WITH_AMQP
1.1       moko      918: 
                    919: // constructor
                    920: MAmqp::MAmqp(): Methoded("amqp") {
                    921:        add_native_method("create", Method::CT_DYNAMIC, _create, 0, 1);
                    922: #ifdef WITH_AMQP
                    923:        add_native_method("publish", Method::CT_DYNAMIC, _publish, 1, 2);
                    924:        add_native_method("release", Method::CT_DYNAMIC, _release, 0, 0);
                    925:        add_native_method("ack", Method::CT_DYNAMIC, _ack, 1, 1);
                    926:        add_native_method("nack", Method::CT_DYNAMIC, _nack, 1, 2);
                    927:        add_native_method("reject", Method::CT_DYNAMIC, _reject, 1, 2);
                    928:        add_native_method("qos", Method::CT_DYNAMIC, _qos, 0, 1);
1.8       moko      929:        add_native_method("declare", Method::CT_DYNAMIC, _declare, 1, 1);
                    930:        add_native_method("delete", Method::CT_DYNAMIC, _delete, 1, 1);
                    931:        add_native_method("bind", Method::CT_DYNAMIC, _bind, 1, 1);
                    932:        add_native_method("unbind", Method::CT_DYNAMIC, _unbind, 1, 1);
                    933:        add_native_method("purge", Method::CT_DYNAMIC, _purge, 1, 1);
                    934:        add_native_method("info", Method::CT_DYNAMIC, _info, 1, 1);
1.2       moko      935:        add_native_method("consume", Method::CT_DYNAMIC, _consume, 1, 1);
1.1       moko      936:        add_native_method("stop_consume", Method::CT_DYNAMIC, _stop_consume, 0, 0);
1.6       moko      937: #endif // WITH_AMQP
1.1       moko      938: }

E-mail: