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

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

E-mail: