3 #include "base/AsyncJobCalls.h"
4 #include "base/TextException.h"
7 CBDATA_CLASS_INIT(BodyPipe
);
9 // BodySink is a BodyConsumer class which just consume and drops
10 // data from a BodyPipe
11 class BodySink
: public BodyConsumer
15 BodySink():AsyncJob("BodySink"), done(false) {}
16 virtual ~BodySink() {}
18 virtual void noteMoreBodyDataAvailable(BodyPipe::Pointer bp
) {
19 size_t contentSize
= bp
->buf().contentSize();
20 bp
->consume(contentSize
);
22 virtual void noteBodyProductionEnded(BodyPipe::Pointer bp
) {
23 stopConsumingFrom(bp
);
26 virtual void noteBodyProducerAborted(BodyPipe::Pointer bp
) {
27 stopConsumingFrom(bp
);
30 bool doneAll() const {return done
&& AsyncJob::doneAll();}
31 CBDATA_CLASS2(BodySink
);
34 CBDATA_CLASS_INIT(BodySink
);
36 // The BodyProducerDialer is an AsyncCall class which used to schedule BodyProducer calls.
37 // In addition to a normal AsyncCall checks if the BodyProducer is still the producer of
38 // the BodyPipe passed as argument
39 class BodyProducerDialer
: public UnaryMemFunT
<BodyProducer
, BodyPipe::Pointer
>
42 typedef UnaryMemFunT
<BodyProducer
, BodyPipe::Pointer
> Parent
;
44 BodyProducerDialer(const BodyProducer::Pointer
&aProducer
,
45 Parent::Method aHandler
, BodyPipe::Pointer bp
):
46 Parent(aProducer
, aHandler
, bp
) {}
48 virtual bool canDial(AsyncCall
&call
);
51 // The BodyConsumerDialer is an AsyncCall class which used to schedule BodyConsumer calls.
52 // In addition to a normal AsyncCall checks if the BodyConsumer is still the reciptient
53 // of the BodyPipe passed as argument
54 class BodyConsumerDialer
: public UnaryMemFunT
<BodyConsumer
, BodyPipe::Pointer
>
57 typedef UnaryMemFunT
<BodyConsumer
, BodyPipe::Pointer
> Parent
;
59 BodyConsumerDialer(const BodyConsumer::Pointer
&aConsumer
,
60 Parent::Method aHandler
, BodyPipe::Pointer bp
):
61 Parent(aConsumer
, aHandler
, bp
) {}
63 virtual bool canDial(AsyncCall
&call
);
67 BodyProducerDialer::canDial(AsyncCall
&call
)
69 if (!Parent::canDial(call
))
72 const BodyProducer::Pointer
&producer
= job
;
73 BodyPipe::Pointer pipe
= arg1
;
74 if (!pipe
->stillProducing(producer
)) {
75 debugs(call
.debugSection
, call
.debugLevel
, HERE
<< producer
<<
76 " no longer producing for " << pipe
->status());
77 return call
.cancel("no longer producing");
84 BodyConsumerDialer::canDial(AsyncCall
&call
)
86 if (!Parent::canDial(call
))
89 const BodyConsumer::Pointer
&consumer
= job
;
90 BodyPipe::Pointer pipe
= arg1
;
91 if (!pipe
->stillConsuming(consumer
)) {
92 debugs(call
.debugSection
, call
.debugLevel
, HERE
<< consumer
<<
93 " no longer consuming from " << pipe
->status());
94 return call
.cancel("no longer consuming");
103 // inform the pipe that we are done and clear the Pointer
104 void BodyProducer::stopProducingFor(RefCount
<BodyPipe
> &pipe
, bool atEof
)
106 debugs(91,7, HERE
<< this << " will not produce for " << pipe
<<
107 "; atEof: " << atEof
);
108 assert(pipe
!= NULL
); // be strict: the caller state may depend on this
109 pipe
->clearProducer(atEof
);
117 // inform the pipe that we are done and clear the Pointer
118 void BodyConsumer::stopConsumingFrom(RefCount
<BodyPipe
> &pipe
)
120 debugs(91,7, HERE
<< this << " will not consume from " << pipe
);
121 assert(pipe
!= NULL
); // be strict: the caller state may depend on this
122 pipe
->clearConsumer();
129 BodyPipe::BodyPipe(Producer
*aProducer
): theBodySize(-1),
130 theProducer(aProducer
), theConsumer(0),
131 thePutSize(0), theGetSize(0),
132 mustAutoConsume(false), isCheckedOut(false)
134 // TODO: teach MemBuf to start with zero minSize
135 // TODO: limit maxSize by theBodySize, when known?
136 theBuf
.init(2*1024, MaxCapacity
);
137 debugs(91,7, HERE
<< "created BodyPipe" << status());
140 BodyPipe::~BodyPipe()
142 debugs(91,7, HERE
<< "destroying BodyPipe" << status());
143 assert(!theProducer
);
144 assert(!theConsumer
);
148 void BodyPipe::setBodySize(uint64_t aBodySize
)
150 assert(!bodySizeKnown());
151 assert(aBodySize
>= 0);
152 assert(thePutSize
<= aBodySize
);
154 // If this assert fails, we need to add code to check for eof and inform
155 // the consumer about the eof condition via scheduleBodyEndNotification,
156 // because just setting a body size limit may trigger the eof condition.
157 assert(!theConsumer
);
159 theBodySize
= aBodySize
;
160 debugs(91,7, HERE
<< "set body size" << status());
163 uint64_t BodyPipe::bodySize() const
165 assert(bodySizeKnown());
166 return static_cast<uint64_t>(theBodySize
);
169 bool BodyPipe::expectMoreAfter(uint64_t offset
) const
171 assert(theGetSize
<= offset
);
172 return offset
< thePutSize
|| // buffer has more now or
173 (!productionEnded() && mayNeedMoreData()); // buffer will have more
176 bool BodyPipe::exhausted() const
178 return !expectMoreAfter(theGetSize
);
181 uint64_t BodyPipe::unproducedSize() const
183 return bodySize() - thePutSize
; // bodySize() asserts that size is known
186 void BodyPipe::expectProductionEndAfter(uint64_t size
)
188 const uint64_t expectedSize
= thePutSize
+ size
;
190 Must(bodySize() == expectedSize
);
192 theBodySize
= expectedSize
;
196 BodyPipe::clearProducer(bool atEof
)
198 if (theProducer
.set()) {
199 debugs(91,7, HERE
<< "clearing BodyPipe producer" << status());
202 if (!bodySizeKnown())
203 theBodySize
= thePutSize
;
204 else if (bodySize() != thePutSize
)
205 debugs(91,3, HERE
<< "aborting on premature eof" << status());
207 // asserta that we can detect the abort if the consumer joins later
208 assert(!bodySizeKnown() || bodySize() != thePutSize
);
210 scheduleBodyEndNotification();
215 BodyPipe::putMoreData(const char *aBuffer
, size_t size
)
218 size
= min((uint64_t)size
, unproducedSize());
220 const size_t spaceSize
= static_cast<size_t>(theBuf
.potentialSpaceSize());
221 if ((size
= min(size
, spaceSize
))) {
222 theBuf
.append(aBuffer
, size
);
230 BodyPipe::setConsumerIfNotLate(const Consumer::Pointer
&aConsumer
)
232 assert(!theConsumer
);
233 assert(aConsumer
.set()); // but might be invalid
235 // TODO: convert this into an exception and remove IfNotLate suffix
236 // If there is something consumed already, we are in an auto-consuming mode
237 // and it is too late to attach a real consumer to the pipe.
238 if (theGetSize
> 0) {
239 assert(mustAutoConsume
);
243 theConsumer
= aConsumer
;
244 debugs(91,7, HERE
<< "set consumer" << status());
245 if (theBuf
.hasContent())
246 scheduleBodyDataNotification();
248 scheduleBodyEndNotification();
253 // When BodyPipe consumer is gone, all events for that consumer must not
254 // reach the new consumer (if any). Otherwise, the calls may go out of order
255 // (if _some_ calls are dropped due to the ultimate destination being
256 // temporary NULL). The code keeps track of the number of outstanding
257 // events and skips that number if consumer leaves. TODO: when AscyncCall
258 // support is improved, should we just schedule calls directly to consumer?
260 BodyPipe::clearConsumer()
262 if (theConsumer
.set()) {
263 debugs(91,7, HERE
<< "clearing consumer" << status());
265 if (consumedSize() && !exhausted()) {
266 AsyncCall::Pointer call
= asyncCall(91, 7,
267 "BodyProducer::noteBodyConsumerAborted",
268 BodyProducerDialer(theProducer
,
269 &BodyProducer::noteBodyConsumerAborted
, this));
270 ScheduleCallHere(call
);
276 BodyPipe::getMoreData(MemBuf
&aMemBuffer
)
278 if (!theBuf
.hasContent())
279 return 0; // did not touch the possibly uninitialized buf
281 if (aMemBuffer
.isNull())
283 const size_t size
= min(theBuf
.contentSize(), aMemBuffer
.potentialSpaceSize());
284 aMemBuffer
.append(theBuf
.content(), size
);
285 theBuf
.consume(size
);
287 return size
; // cannot be zero if we called buf.init above
291 BodyPipe::consume(size_t size
)
293 theBuf
.consume(size
);
297 // In the AutoConsumption mode the consumer has gone but the producer continues
298 // producing data. We are using a BodySink BodyConsumer which just discards the produced data.
300 BodyPipe::enableAutoConsumption()
302 mustAutoConsume
= true;
303 debugs(91,5, HERE
<< "enabled auto consumption" << status());
304 if (!theConsumer
&& theBuf
.hasContent())
305 startAutoConsumption();
308 // start auto consumption by creating body sink
310 BodyPipe::startAutoConsumption()
312 Must(mustAutoConsume
);
314 theConsumer
= new BodySink
;
315 debugs(91,7, HERE
<< "starting auto consumption" << status());
316 scheduleBodyDataNotification();
322 assert(!isCheckedOut
);
328 BodyPipe::checkIn(Checkout
&checkout
)
330 assert(isCheckedOut
);
331 isCheckedOut
= false;
332 const size_t currentSize
= theBuf
.contentSize();
333 if (checkout
.checkedOutSize
> currentSize
)
334 postConsume(checkout
.checkedOutSize
- currentSize
);
335 else if (checkout
.checkedOutSize
< currentSize
)
336 postAppend(currentSize
- checkout
.checkedOutSize
);
340 BodyPipe::undoCheckOut(Checkout
&checkout
)
342 assert(isCheckedOut
);
343 const size_t currentSize
= theBuf
.contentSize();
344 // We can only undo if size did not change, and even that carries
345 // some risk. If this becomes a problem, the code checking out
346 // raw buffers should always check them in (possibly unchanged)
347 // instead of relying on the automated undo mechanism of Checkout.
348 // The code can always use a temporary buffer to accomplish that.
349 assert(checkout
.checkedOutSize
== currentSize
);
352 // TODO: Optimize: inform consumer/producer about more data/space only if
353 // they used the data/space since we notified them last time.
356 BodyPipe::postConsume(size_t size
)
358 assert(!isCheckedOut
);
360 debugs(91,7, HERE
<< "consumed " << size
<< " bytes" << status());
361 if (mayNeedMoreData()) {
362 AsyncCall::Pointer call
= asyncCall(91, 7,
363 "BodyProducer::noteMoreBodySpaceAvailable",
364 BodyProducerDialer(theProducer
,
365 &BodyProducer::noteMoreBodySpaceAvailable
, this));
366 ScheduleCallHere(call
);
371 BodyPipe::postAppend(size_t size
)
373 assert(!isCheckedOut
);
375 debugs(91,7, HERE
<< "added " << size
<< " bytes" << status());
377 if (mustAutoConsume
&& !theConsumer
&& size
> 0)
378 startAutoConsumption();
380 // We should not consume here even if mustAutoConsume because the
381 // caller may not be ready for the data to be consumed during this call.
382 scheduleBodyDataNotification();
384 if (!mayNeedMoreData())
385 clearProducer(true); // reached end-of-body
390 BodyPipe::scheduleBodyDataNotification()
392 if (theConsumer
.valid()) { // TODO: allow asyncCall() to check this instead
393 AsyncCall::Pointer call
= asyncCall(91, 7,
394 "BodyConsumer::noteMoreBodyDataAvailable",
395 BodyConsumerDialer(theConsumer
,
396 &BodyConsumer::noteMoreBodyDataAvailable
, this));
397 ScheduleCallHere(call
);
402 BodyPipe::scheduleBodyEndNotification()
404 if (theConsumer
.valid()) { // TODO: allow asyncCall() to check this instead
405 if (bodySizeKnown() && bodySize() == thePutSize
) {
406 AsyncCall::Pointer call
= asyncCall(91, 7,
407 "BodyConsumer::noteBodyProductionEnded",
408 BodyConsumerDialer(theConsumer
,
409 &BodyConsumer::noteBodyProductionEnded
, this));
410 ScheduleCallHere(call
);
412 AsyncCall::Pointer call
= asyncCall(91, 7,
413 "BodyConsumer::noteBodyProducerAborted",
414 BodyConsumerDialer(theConsumer
,
415 &BodyConsumer::noteBodyProducerAborted
, this));
416 ScheduleCallHere(call
);
421 // a short temporary string describing buffer status for debugging
422 const char *BodyPipe::status() const
424 static MemBuf outputBuffer
;
425 outputBuffer
.reset();
427 outputBuffer
.append(" [", 2);
429 outputBuffer
.Printf("%"PRIu64
"<=%"PRIu64
, theGetSize
, thePutSize
);
430 if (theBodySize
>= 0)
431 outputBuffer
.Printf("<=%"PRId64
, theBodySize
);
433 outputBuffer
.append("<=?", 3);
435 outputBuffer
.Printf(" %d+%d", (int)theBuf
.contentSize(), (int)theBuf
.spaceSize());
437 outputBuffer
.Printf(" pipe%p", this);
438 if (theProducer
.set())
439 outputBuffer
.Printf(" prod%p", theProducer
.get());
440 if (theConsumer
.set())
441 outputBuffer
.Printf(" cons%p", theConsumer
.get());
444 outputBuffer
.append(" A", 2);
446 outputBuffer
.append(" L", 2); // Locked
448 outputBuffer
.append("]", 1);
450 outputBuffer
.terminate();
452 return outputBuffer
.content();
456 /* BodyPipeCheckout */
458 BodyPipeCheckout::BodyPipeCheckout(BodyPipe
&aPipe
): pipe(aPipe
),
459 buf(aPipe
.checkOut()), offset(aPipe
.consumedSize()),
460 checkedOutSize(buf
.contentSize()), checkedIn(false)
464 BodyPipeCheckout::~BodyPipeCheckout()
467 pipe
.undoCheckOut(*this);
471 BodyPipeCheckout::checkIn()
479 BodyPipeCheckout::BodyPipeCheckout(const BodyPipeCheckout
&c
): pipe(c
.pipe
),
480 buf(c
.buf
), offset(c
.offset
), checkedOutSize(c
.checkedOutSize
),
481 checkedIn(c
.checkedIn
)
483 assert(false); // prevent copying
487 BodyPipeCheckout::operator =(const BodyPipeCheckout
&)
489 assert(false); // prevent assignment