summaryrefslogtreecommitdiff
path: root/wcf/src/Apache/Qpid/Interop/InputLink.cpp
blob: 2b0119e338a9a7a44c6a1819fbfcbd6af4197ecc (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements.  See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership.  The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License.  You may obtain a copy of the License at
*
*   http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied.  See the License for the
* specific language governing permissions and limitations
* under the License.
*/

#include <windows.h>
#include <msclr\lock.h>

#include "qpid/client/AsyncSession.h"
#include "qpid/framing/FrameSet.h"
#include "qpid/client/SubscriptionManager.h"
#include "qpid/client/Connection.h"
#include "qpid/client/Message.h"
#include "qpid/client/MessageListener.h"
#include "qpid/client/Demux.h"
#include "qpid/client/SessionImpl.h"
#include "qpid/client/SessionBase_0_10Access.h"

#include "MessageBodyStream.h"
#include "AmqpMessage.h"
#include "AmqpSession.h"
#include "InputLink.h"
#include "QpidMarshal.h"
#include "QpidException.h"

namespace Apache {
namespace Qpid {
namespace Interop {


using namespace System;
using namespace System::Runtime::InteropServices;
using namespace System::Threading;
using namespace msclr;

using namespace qpid::client;
using namespace qpid::framing;

using namespace std;

using namespace Apache::Qpid::AmqpTypes;

// Scalability note: When using async methods, an async helper thread is created
// to block on the Demux BlockingQueue.  This design should be revised in line
// with proposed changes to the native library to reduce the number of servicing
// threads for large numbers of subscriptions.

// synchronization is accomplished with locks, but also by ensuring that only one
// MessageWaiter (the one at the front of the line) is ever active.  
// async threads to watch for: Close/finalizer, Timers, SyncCredit and the native Dispatch
// thread (who deposits FrameSets into the local queue and is oblivious to the
// managed space locks).


// The folowing def must match the "Frames" private typedef.
// TODO, make Qpid-cpp "Frames" definition visible.
typedef qpid::InlineVector<AMQFrame, 4> FrameSetFrames;

InputLink::InputLink(AmqpSession^ session, System::String^ sourceQueue,
		     qpid::client::AsyncSession *qpidSessionp, qpid::client::SubscriptionManager *qpidSubsMgrp,
		     bool exclusive,
		     bool temporary, System::String^ filterKey, System::String^ exchange) :
    amqpSession(session),
    subscriptionp(NULL),
    localQueuep(NULL),
    queuePtrp(NULL),
    dequeuedFrameSetpp(NULL),
    disposed(false),
    finalizing(false)
{
    bool success = false;
    System::Exception^ linkException = nullptr;

    waiters = gcnew Collections::Generic::List<MessageWaiter^>();
    linkLock = waiters;  // private and available
    subscriptionLock = gcnew Object();
    qpidAddress = QpidAddress::CreateAddress(sourceQueue, true);
    qpidAddress->ResolveLink(session);
    browsing = qpidAddress->Browsing;

    try {
	std::string qname = QpidMarshal::ToNative(qpidAddress->LinkName);

	if (temporary) {
	    qpidSessionp->queueDeclare(arg::queue=qname, arg::durable=false, arg::autoDelete=true, arg::exclusive=true);
	    qpidSessionp->exchangeBind(arg::exchange=QpidMarshal::ToNative(exchange),
				       arg::queue=qname, arg::bindingKey=QpidMarshal::ToNative(filterKey));
	    qpidSessionp->sync();
	}

	localQueuep = new LocalQueue;
	SubscriptionSettings settings;
	settings.flowControl = FlowControl::messageCredit(0);
	settings.completionMode = CompletionMode::MANUAL_COMPLETION;

	if (browsing) {
	    settings.acquireMode = AcquireMode::ACQUIRE_MODE_NOT_ACQUIRED;
	    settings.acceptMode = AcceptMode::ACCEPT_MODE_NONE;
	}
	else {
	    settings.acquireMode = AcquireMode::ACQUIRE_MODE_PRE_ACQUIRED;
	    settings.acceptMode = AcceptMode::ACCEPT_MODE_EXPLICIT;
	}

	Subscription sub = qpidSubsMgrp->subscribe(*localQueuep, qname, settings);
	subscriptionp = new Subscription (sub); // copy smart pointer for later IDisposable cleanup

	// the roundabout way to obtain localQueuep->queue
	SessionBase_0_10Access sa(*qpidSessionp);
	boost::shared_ptr<SessionImpl> simpl = sa.get();
	queuePtrp = new Demux::QueuePtr(simpl->getDemux().get(sub.getName()));

	success = true;
    } finally {
        if (!success) {
 	    Cleanup();
	    linkException = gcnew QpidException ("InputLink creation failure");
	    throw linkException;
	}
    }
}

// called with lock held
void InputLink::ReleaseNative()
{
    // involves talking to the Broker unless the connection is broken

    if ((subscriptionp != NULL) && !finalizing) {
	// TODO: find boost time error on cleanup when in finalizer thread
        try {
	    subscriptionp->cancel();
	}
	catch (const std::exception& error) {
	    // TODO: log this properly
	    std::cout << "shutdown error " << error.what() << std::endl;
	}
    }

    // free native mem (or smart pointers) that we own
    if (subscriptionp != NULL) {
	delete subscriptionp;
	subscriptionp = NULL;
    }
    if (queuePtrp != NULL) {
	delete queuePtrp;
	queuePtrp = NULL;
    }
    if (localQueuep != NULL) {
	if (!finalizing) {
	    // TODO: find boost time error on cleanup when in finalizer thread
	    delete localQueuep;
	    localQueuep = NULL;
	}
    }
    if (dequeuedFrameSetpp != NULL) {
	delete dequeuedFrameSetpp;
	dequeuedFrameSetpp = NULL;
    }
}

void InputLink::Cleanup()
{
    {
        lock l(linkLock);
        if (disposed)
	    return;

	disposed = true;

	// if the asyncHelper exists and is idle, unblock it
	if (asyncHelperWaitHandle != nullptr) {
	    asyncHelperWaitHandle->Set();
	}

	// wakeup anyone waiting for messages
	if (queuePtrp != NULL)
	    (*queuePtrp)->close();
  
	// wait for any sync operations on the subscription to complete before ReleaseNative
	lock l2(subscriptionLock);

	try {}
	finally
	{
	    ReleaseNative();
	}
    }

    // Now that subscription is torn down, we can execute pending delete on remote node
    qpidAddress->CleanupLink(amqpSession);
    amqpSession->NotifyClosed();
}

InputLink::~InputLink()
{
    Cleanup();
}

InputLink::!InputLink()
{
    finalizing = true;
    Cleanup();
}

void InputLink::Close()
{
    // Simulate Dispose()...
    Cleanup();
    GC::SuppressFinalize(this);
}

// call with lock held
bool InputLink::haveMessage()
{
    if (dequeuedFrameSetpp != NULL)
	return true;

    if (queuePtrp != NULL) {
	if ((*queuePtrp)->size() > 0)
	    return true;
    }
    return false;
}
	
IntPtr InputLink::nextLocalMessage()
{
    lock l(linkLock);

    if (disposed)
	return (IntPtr) NULL;

    // A message already pulled off BlockingQueue?
    if (dequeuedFrameSetpp != NULL) {
	QpidFrameSetPtr* rv = dequeuedFrameSetpp;
	dequeuedFrameSetpp = NULL;
	return (IntPtr) rv;
    }

    if ((*queuePtrp)->empty())
	return (IntPtr) NULL;

    bool received = false;
    QpidFrameSetPtr* frameSetpp = new QpidFrameSetPtr;

    try {
	received = (*queuePtrp)->pop(*frameSetpp, qpid::sys::TIME_INFINITE);
	if (received) {
	    QpidFrameSetPtr* rv = frameSetpp;
	    // no need to free native in finally block
	    frameSetpp = NULL;
	    return (IntPtr) rv;
	}
    } catch(const std::exception& error) {
	// should be no async tampering with queue since we hold the lock and have a
	// smart pointer ref to the native LocalQueue, even if the network connection fails...
	cout << "unknown exception in InputLink.nextLocalMessage() " << error.what() <<endl;
	// TODO: log this
    }
    finally {
	if (frameSetpp != NULL) {
	    delete frameSetpp;
	}
    }

    return (IntPtr) NULL;
}

    

void InputLink::unblockWaiter()
{
    // to be followed by resetQueue() below
    lock l(linkLock);
    if (disposed)
	return;
    (*queuePtrp)->close();
}



// Set things right after unblockWaiter(). Closing and opening a Qpid BlockingQueue unsticks 
// a blocking thread without interefering with queue contents or the ability to push
// new incoming messages.

void InputLink::resetQueue()
{
    lock l(linkLock);
    if (disposed)
	return;
    if ((*queuePtrp)->isClosed()) {
	(*queuePtrp)->open();
    }
}


// returns true if there is a message to consume, i.e. nextLocalMessage() won't block

bool InputLink::internalWaitForMessage()
{
    Demux::QueuePtr demuxQueuePtr;

    bool received = false;
    QpidFrameSetPtr* frameSetpp = NULL;
    try	{
	lock l(linkLock);
	if (disposed)
	    return false;
	if (haveMessage())
	    return true;

	AdjustCredit();

	// get a scoped smart ptr ref to guard against async close or hangup
	demuxQueuePtr = *queuePtrp;
	frameSetpp = new QpidFrameSetPtr;

	l.release();
	// Async cleanup is now possible.  Only use demuxQueuePtr until lock reacquired.
	received = demuxQueuePtr->pop(*frameSetpp, qpid::sys::TIME_INFINITE);
	l.acquire();

	if (received) {
	    dequeuedFrameSetpp = frameSetpp;
	    frameSetpp = NULL;	// native will eventually be freed in Cleanup or MessageBodyStream
	}

	return true;
    } catch(const std::exception& ) {
	// timeout or connection closed
	return false;
    }
    finally {
	if (frameSetpp != NULL) {
	    delete frameSetpp;
	}
    }

    return false;
}


// call with lock held
void InputLink::addWaiter(MessageWaiter^ waiter)
{
    waiters->Add(waiter);
    if (waiters->Count == 1) {
	// mark this waiter as ready to run
	// Only the waiter at the head of the queue is active.
	waiter->Activate();
    }
    
    if (waiter->Assigned)
	return;

    if (asyncHelperWaitHandle == nullptr) {
	asyncHelperWaitHandle = gcnew ManualResetEvent(false);
	ThreadStart^ threadDelegate = gcnew ThreadStart(this, &InputLink::asyncHelper);
	(gcnew Thread(threadDelegate))->Start();
    }

    if (waiters->Count == 1) {
	// wake up the asyncHelper
	asyncHelperWaitHandle->Set();
    }
}


void InputLink::removeWaiter(MessageWaiter^ waiter) {
    // a waiter can be removed from anywhere in the list if timed out

    lock l(linkLock);
    int idx = waiters->IndexOf(waiter);
    if (idx == -1) {
	// TODO: assert or log
	if (asyncHelperWaitHandle != nullptr) {
	    // just in case.
	    asyncHelperWaitHandle->Set();
	}
	return;
    }

    waiters->RemoveAt(idx);
    if (waiter->TimedOut) {
	// may have to give back message if it arrives momentarily
	AdjustCredit();
    }

    // let the next waiter know it's his turn. 
    if (waiters->Count > 0) {
	MessageWaiter^ nextWaiter = waiters[0];

	// wakeup the asyncHelper thread to help out if necessary.
	if (!nextWaiter->Assigned) {
	    asyncHelperWaitHandle->Set();
	}

	l.release();
	nextWaiter->Activate();
	return;
    }
    else {
	if (disposed && (asyncHelperWaitHandle != nullptr)) {
	    asyncHelperWaitHandle->Set();
	}
    }
}


void InputLink::asyncHelper()
{
    lock l(linkLock);

    while (true) {
	if (disposed && (waiters->Count == 0)) {
	    asyncHelperWaitHandle = nullptr;
	    return;
	}

	if (waiters->Count > 0) {
	    MessageWaiter^ waiter = waiters[0];

	    l.release();
	    if (waiter->AcceptForWork()) {
		waiter->Run();
	    }
	    l.acquire();
	}

	// sleep if more work may be coming or it is currently someone else's turn
	if (((waiters->Count == 0) && !disposed) || ((waiters->Count != 0) && waiters[0]->Assigned)) {
	    // wait for something to do
	    asyncHelperWaitHandle->Reset();
	    l.release();
	    asyncHelperWaitHandle->WaitOne();
	    l.acquire();
	}
    }
}

void InputLink::sync()
{
    // used by the MessageWaiter timeout thread to not run before fully initialized
    lock l(linkLock);
}


void InputLink::PrefetchLimit::set(int value)
{
    lock l(linkLock);
    prefetchLimit = value;

    int delta = 0;

    // rough rule of thumb to keep the flow, but reduce chatter.
    // for small messages, the credit request is almost as expensive as the transfer itself.
    // experience may suggest a better heuristic or require a property for the low water mark
    if (prefetchLimit >= 3) {
	delta = prefetchLimit / 3;
    }
    minWorkingCredit = prefetchLimit - delta;
    AdjustCredit();
}


// call with lock held
void InputLink::AdjustCredit()
{
    if (creditSyncPending || disposed)
	return;

    // low watermark check
    if ((prefetchLimit != 0) &&
	(workingCredit >= minWorkingCredit) &&
	(workingCredit >= waiters->Count))
	return;

    // should have enough for all waiters or to satisfy the prefetch window
    int targetCredit = waiters->Count;
    if (targetCredit < prefetchLimit)
	targetCredit = prefetchLimit;

    if (targetCredit > workingCredit) {
	subscriptionp->grantMessageCredit(targetCredit - workingCredit);
	workingCredit = targetCredit;
	return;
    }
    if (targetCredit < workingCredit) {
	if ((targetCredit == 0) && (prefetchLimit == 0)) {
	    creditSyncPending = true;
	    ThreadPool::QueueUserWorkItem(gcnew WaitCallback(this, &InputLink::SyncCredit));
	}
	// TODO: also shrink credit when prefetchLimit != 0
    }
}

void InputLink::SyncCredit(Object ^unused)
{
    lock l(linkLock);

    try {
	if (disposed)
	    return;

	if (!amqpSession->MessageStop(subscriptionp->getName())) {
	    // connection closed
	    return;
	}

	l.release();
	// use setFlowControl to re-enable credit flow on the broker.
	// setFlowControl is a sync operation
	{
	    lock l2(subscriptionLock);
	    if (subscriptionp != NULL) {
		subscriptionp->setFlowControl(subscriptionp->getSettings().flowControl);
	    }
	}
	l.acquire();

	if (disposed)
	    return;

	// let existing waiters use up any messages that arrived.
	// local queue size can only decrease until more credit is issued
	while (true) {
	    if ((waiters->Count > 0) && ((*queuePtrp)->size() > 0)) {
		l.release();
		// a rare use case and not used in performance oriented code.
		// optimization can wait until the qpid/messaging api is used
		Thread::Sleep(10);
		l.acquire();
		if (disposed)
		    return;
	    }
	    else {
		break;
	    }
	}

	// At this point, the lock is held and we are fully synced with the broker
	// so we have a valid snapshot 

	if ((prefetchLimit == 0) && ((*queuePtrp)->size() > 0)) {
	    // can't be sure application will request a message again any time soon
	    QpidFrameSetPtr frameSetp;
	    while (!(*queuePtrp)->empty()) {
		(*queuePtrp)->pop(frameSetp);
		SequenceSet frameSetID(frameSetp->getId());
		subscriptionp->release(frameSetID);
	    }

	    // don't touch dequeuedFrameSetpp.  It is spoken for: explicitely from a
	    // MessageWaiter about to to get the nextLocalMessage(), or implicitely
	    // from a WaitForMessage().
	}
	// TODO: if prefetchLimit != 0, release messages from back of the queue that exceed targetCredit

	workingCredit = (*queuePtrp)->size();
	if (dequeuedFrameSetpp != NULL) {
	    workingCredit++;
	}
    }
    finally {
	creditSyncPending = false;
    }

    AdjustCredit();
}


AmqpMessage^ InputLink::createAmqpMessage(IntPtr msgp)
{
    QpidFrameSetPtr* fspp = (QpidFrameSetPtr*) msgp.ToPointer();
    bool ownFrameSet = true;
    bool haveProperties = false;

    try {
	MessageBodyStream^  mstream = gcnew MessageBodyStream(fspp);
	ownFrameSet = false;	// stream releases on close/dispose

	AmqpMessage^ amqpMessage = gcnew AmqpMessage(mstream);

	AMQHeaderBody* headerBodyp = (*fspp)->getHeaders();
	uint64_t contentSize = (*fspp)->getContentSize();
	SequenceSet frameSetID((*fspp)->getId());

	// target managed representation
	AmqpProperties^ amqpProperties = gcnew AmqpProperties();

	// source native representation
	const DeliveryProperties* deliveryProperties = headerBodyp->get<DeliveryProperties>();
	const qpid::framing::MessageProperties* messageProperties = headerBodyp->get<qpid::framing::MessageProperties>();

	if (deliveryProperties) {
	    if (deliveryProperties->hasRoutingKey()) {
		haveProperties = true;

		amqpProperties->RoutingKey = gcnew String(deliveryProperties->getRoutingKey().c_str());
	    }

	    if (deliveryProperties->hasDeliveryMode()) {
		if (deliveryProperties->getDeliveryMode() == qpid::framing::PERSISTENT)
		    amqpProperties->Durable = true;
	    }

	    if (deliveryProperties->hasTtl()) {
		long long ticks = deliveryProperties->getTtl() * TimeSpan::TicksPerMillisecond;
		amqpProperties->TimeToLive = Nullable<TimeSpan>(TimeSpan::FromTicks(ticks));
	    }
	}

	if (messageProperties) {

	    if (messageProperties->hasReplyTo()) {
		haveProperties = true;
		const ReplyTo& rpto = messageProperties->getReplyTo();
		String^ rk = nullptr;
		String^ ex = nullptr;
		if (rpto.hasRoutingKey()) {
		    rk = gcnew String(rpto.getRoutingKey().c_str());
		}
		if (rpto.hasExchange()) {
		    ex = gcnew String(rpto.getExchange().c_str());
		}
		amqpProperties->SetReplyTo(ex,rk);
	    }
	    
	    if (messageProperties->hasContentType()) {
		haveProperties = true;
		amqpProperties->ContentType = gcnew String(messageProperties->getContentType().c_str());

		if (messageProperties->hasContentEncoding()) {
		    String^ enc = gcnew String(messageProperties->getContentEncoding().c_str());
		    if (!String::IsNullOrEmpty(enc)) {
			// TODO: properly assemble 1.0 style to 0-10 for all cases
			amqpProperties->ContentType += "; charset=" + enc;
		    }
		}
	    }

	    if (messageProperties->hasCorrelationId()) {
		haveProperties = true;
		const std::string& ncid = messageProperties->getCorrelationId();
		int len = ncid.size();
		array<unsigned char>^ mcid = gcnew array<unsigned char>(len);
		Marshal::Copy ((IntPtr) (void *) ncid.data(), mcid, 0, len);
		amqpProperties->CorrelationId = mcid;
	    }

	    if (messageProperties->hasUserId()) {
		haveProperties = true;
		const std::string& nuid = messageProperties->getUserId();
		int len = nuid.size();
		array<unsigned char>^ muid = gcnew array<unsigned char>(len);
		Marshal::Copy ((IntPtr) (void *) nuid.data(), muid, 0, len);
		amqpProperties->UserId = muid;
	    }

	    if (messageProperties->hasApplicationHeaders()) {
		haveProperties = true;
		const qpid::framing::FieldTable& fieldTable = messageProperties->getApplicationHeaders();
		int count = fieldTable.count();

		if (count > 0) {
		    haveProperties = true;
		    Collections::Generic::Dictionary<System::String^, AmqpType^>^ mmap = 
			gcnew Collections::Generic::Dictionary<System::String^, AmqpType^>(count);

		    for(qpid::framing::FieldTable::ValueMap::const_iterator i = fieldTable.begin(); i != fieldTable.end(); i++) {

			qpid::framing::FieldValue::Data &data = i->second->getData();
			
			// TODO: replace these generic int/string conversions with handler for each AMQP specific type:
			// uint8_t dataType = i->second->getType();
			// switch (dataType) { case TYPE_CODE_STR8: ... }

			if (data.convertsToInt()) {
			    mmap->Add (gcnew String(i->first.data()), gcnew AmqpInt((int) i->second->getData().getInt()));
			}
			if (data.convertsToString()) {
			    std::string ns = data.getString();
			    String^ ms = gcnew String(ns.data(), 0, ns.size());
			    mmap->Add (gcnew String(i->first.data()), gcnew AmqpString(ms));
			}
		    }
		
		    amqpProperties->PropertyMap = mmap;
		}

	    }
	}

	if (haveProperties) {
	    amqpMessage->Properties = amqpProperties;
	}

	// We have a message we can return to the caller.
	// Tell the broker we got it.
	
	// subscriptionp->accept(frameSetID) is a slow sync operation in the native API
	// so do it within the AsyncSession directly
	amqpSession->AcceptAndComplete(frameSetID, browsing);

	workingCredit--;
	// check if more messages need to be requested from broker
	AdjustCredit();

	return amqpMessage;
    }
    finally {
	if (ownFrameSet)
	    delete (fspp);
    }
}

    // As for IInputChannel:
    //   if success, return true + amqpMessage
    //   elseif timeout, return false
    //   elseif closed/EOF, return true and amqpMessage = null
    //   else throw an Exception

bool InputLink::TryReceive(TimeSpan timeout, [Out] AmqpMessage^% amqpMessage)
{
    lock l(linkLock);

    if (waiters->Count == 0) {
	// see if there is a message already available without blocking
	IntPtr fspp = nextLocalMessage();
	if (fspp.ToPointer() != NULL) {
	    amqpMessage = createAmqpMessage(fspp);
	    return true;
	}
    }

    MessageWaiter^ waiter = gcnew MessageWaiter(this, timeout, true, false, nullptr, nullptr);
    addWaiter(waiter);

    l.release();
    waiter->Run();
    l.acquire();
    
    if (waiter->TimedOut) {
	return false;
    }

    IntPtr waiterMsg = waiter->Message;
    if (waiterMsg.ToPointer() == NULL) {
	if (disposed) {
	    // indicate normal EOF on channel
	    amqpMessage = nullptr;
	    return true;
	}
    }

    amqpMessage = createAmqpMessage(waiterMsg);
    return true;
}

IAsyncResult^ InputLink::BeginTryReceive(TimeSpan timeout, AsyncCallback^ callback, Object^ state)
{

    //TODO: if haveMessage() complete synchronously

    lock l(linkLock);
    MessageWaiter^ waiter = gcnew MessageWaiter(this, timeout, true, true, callback, state);
    addWaiter(waiter);
    return waiter;
}

bool InputLink::EndTryReceive(IAsyncResult^ result, [Out] AmqpMessage^% amqpMessage)
{

    // TODO: validate result

    MessageWaiter^ waiter = (MessageWaiter ^) result;

    waiter->WaitForCompletion();

    if (waiter->RunException != nullptr)
	throw waiter->RunException;

    if (waiter->TimedOut) {
	amqpMessage = nullptr;
	return false;
    }

    IntPtr waiterMsg = waiter->Message;
    if (waiterMsg.ToPointer() == NULL) {
	if (disposed) {
	    // indicate normal EOF on channel
	    amqpMessage = nullptr;
	    return true;
	}
    }

    amqpMessage = createAmqpMessage(waiterMsg);
    return true;
}


bool InputLink::WaitForMessage(TimeSpan timeout)
{
    lock l(linkLock);

    if (disposed)
	return false;

    if (waiters->Count == 0) {
	// see if there is a message already available without blocking
	if (haveMessage())
	    return true;
    }

    // Same as for TryReceive, except consuming = false
    MessageWaiter^ waiter = gcnew MessageWaiter(this, timeout, false, false, nullptr, nullptr);
    addWaiter(waiter);

    l.release();
    waiter->Run();
    l.acquire();
    
    if (waiter->TimedOut) {
	return false;
    }

    return haveMessage();
}

IAsyncResult^ InputLink::BeginWaitForMessage(TimeSpan timeout, AsyncCallback^ callback, Object^ state)
{
    lock l(linkLock);

    // Same as for BeginTryReceive, except consuming = false
    MessageWaiter^ waiter = gcnew MessageWaiter(this, timeout, false, true, callback, state);
    addWaiter(waiter);
    return waiter;
}

bool InputLink::EndWaitForMessage(IAsyncResult^ result)
{
    MessageWaiter^ waiter = (MessageWaiter ^) result;

    waiter->WaitForCompletion();

    if (waiter->TimedOut) {
	return false;
    }

    return haveMessage();
}


}}} // namespace Apache::Qpid::Interop