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

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

E-mail: