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

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

E-mail: