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
14 BodySink(const BodyPipe::Pointer
&bp
): AsyncJob("BodySink"), body_pipe(bp
) {}
15 virtual ~BodySink() { assert(!body_pipe
); }
17 virtual void noteMoreBodyDataAvailable(BodyPipe::Pointer bp
) {
18 size_t contentSize
= bp
->buf().contentSize();
19 bp
->consume(contentSize
);
21 virtual void noteBodyProductionEnded(BodyPipe::Pointer bp
) {
22 stopConsumingFrom(body_pipe
);
24 virtual void noteBodyProducerAborted(BodyPipe::Pointer bp
) {
25 stopConsumingFrom(body_pipe
);
27 bool doneAll() const {return !body_pipe
&& AsyncJob::doneAll();}
30 BodyPipe::Pointer body_pipe
; ///< the pipe we are consuming from
32 CBDATA_CLASS2(BodySink
);
35 CBDATA_CLASS_INIT(BodySink
);
37 // The BodyProducerDialer is an AsyncCall class which used to schedule BodyProducer calls.
38 // In addition to a normal AsyncCall checks if the BodyProducer is still the producer of
39 // the BodyPipe passed as argument
40 class BodyProducerDialer
: public UnaryMemFunT
<BodyProducer
, BodyPipe::Pointer
>
43 typedef UnaryMemFunT
<BodyProducer
, BodyPipe::Pointer
> Parent
;
45 BodyProducerDialer(const BodyProducer::Pointer
&aProducer
,
46 Parent::Method aHandler
, BodyPipe::Pointer bp
):
47 Parent(aProducer
, aHandler
, bp
) {}
49 virtual bool canDial(AsyncCall
&call
);
52 // The BodyConsumerDialer is an AsyncCall class which used to schedule BodyConsumer calls.
53 // In addition to a normal AsyncCall checks if the BodyConsumer is still the reciptient
54 // of the BodyPipe passed as argument
55 class BodyConsumerDialer
: public UnaryMemFunT
<BodyConsumer
, BodyPipe::Pointer
>
58 typedef UnaryMemFunT
<BodyConsumer
, BodyPipe::Pointer
> Parent
;
60 BodyConsumerDialer(const BodyConsumer::Pointer
&aConsumer
,
61 Parent::Method aHandler
, BodyPipe::Pointer bp
):
62 Parent(aConsumer
, aHandler
, bp
) {}
64 virtual bool canDial(AsyncCall
&call
);
68 BodyProducerDialer::canDial(AsyncCall
&call
)
70 if (!Parent::canDial(call
))
73 const BodyProducer::Pointer
&producer
= job
;
74 BodyPipe::Pointer pipe
= arg1
;
75 if (!pipe
->stillProducing(producer
)) {
76 debugs(call
.debugSection
, call
.debugLevel
, HERE
<< producer
<<
77 " no longer producing for " << pipe
->status());
78 return call
.cancel("no longer producing");
85 BodyConsumerDialer::canDial(AsyncCall
&call
)
87 if (!Parent::canDial(call
))
90 const BodyConsumer::Pointer
&consumer
= job
;
91 BodyPipe::Pointer pipe
= arg1
;
92 if (!pipe
->stillConsuming(consumer
)) {
93 debugs(call
.debugSection
, call
.debugLevel
, HERE
<< consumer
<<
94 " no longer consuming from " << pipe
->status());
95 return call
.cancel("no longer consuming");
104 // inform the pipe that we are done and clear the Pointer
105 void BodyProducer::stopProducingFor(RefCount
<BodyPipe
> &pipe
, bool atEof
)
107 debugs(91,7, HERE
<< this << " will not produce for " << pipe
<<
108 "; atEof: " << atEof
);
109 assert(pipe
!= NULL
); // be strict: the caller state may depend on this
110 pipe
->clearProducer(atEof
);
118 // inform the pipe that we are done and clear the Pointer
119 void BodyConsumer::stopConsumingFrom(RefCount
<BodyPipe
> &pipe
)
121 debugs(91,7, HERE
<< this << " will not consume from " << pipe
);
122 assert(pipe
!= NULL
); // be strict: the caller state may depend on this
123 pipe
->clearConsumer();
130 BodyPipe::BodyPipe(Producer
*aProducer
): theBodySize(-1),
131 theProducer(aProducer
), theConsumer(0),
132 thePutSize(0), theGetSize(0),
133 mustAutoConsume(false), abortedConsumption(false), isCheckedOut(false)
135 // TODO: teach MemBuf to start with zero minSize
136 // TODO: limit maxSize by theBodySize, when known?
137 theBuf
.init(2*1024, MaxCapacity
);
138 debugs(91,7, HERE
<< "created BodyPipe" << status());
141 BodyPipe::~BodyPipe()
143 debugs(91,7, HERE
<< "destroying BodyPipe" << status());
144 assert(!theProducer
);
145 assert(!theConsumer
);
149 void BodyPipe::setBodySize(uint64_t aBodySize
)
151 assert(!bodySizeKnown());
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 Must(!abortedConsumption
); // did not promise to never consume
245 theConsumer
= aConsumer
;
246 debugs(91,7, HERE
<< "set consumer" << status());
247 if (theBuf
.hasContent())
248 scheduleBodyDataNotification();
250 scheduleBodyEndNotification();
256 BodyPipe::clearConsumer()
258 if (theConsumer
.set()) {
259 debugs(91,7, HERE
<< "clearing consumer" << status());
261 // do not abort if we have not consumed so that HTTP or ICAP can retry
262 // benign xaction failures due to persistent connection race conditions
264 expectNoConsumption();
269 BodyPipe::expectNoConsumption()
271 // We may be called multiple times because multiple jobs on the consumption
272 // chain may realize that there will be no more setConsumer() calls (e.g.,
273 // consuming code and retrying code). It is both difficult and not really
274 // necessary for them to coordinate their expectNoConsumption() calls.
276 // As a consequence, we may be called when we are auto-consuming already.
278 if (!abortedConsumption
&& !exhausted()) {
279 // Before we abort, any regular consumption should be over and auto
280 // consumption must not be started.
283 AsyncCall::Pointer call
= asyncCall(91, 7,
284 "BodyProducer::noteBodyConsumerAborted",
285 BodyProducerDialer(theProducer
,
286 &BodyProducer::noteBodyConsumerAborted
, this));
287 ScheduleCallHere(call
);
288 abortedConsumption
= true;
290 // in case somebody enabled auto-consumption before regular one aborted
292 startAutoConsumption();
297 BodyPipe::getMoreData(MemBuf
&aMemBuffer
)
299 if (!theBuf
.hasContent())
300 return 0; // did not touch the possibly uninitialized buf
302 if (aMemBuffer
.isNull())
304 const size_t size
= min(theBuf
.contentSize(), aMemBuffer
.potentialSpaceSize());
305 aMemBuffer
.append(theBuf
.content(), size
);
306 theBuf
.consume(size
);
308 return size
; // cannot be zero if we called buf.init above
312 BodyPipe::consume(size_t size
)
314 theBuf
.consume(size
);
318 // In the AutoConsumption mode the consumer has gone but the producer continues
319 // producing data. We are using a BodySink BodyConsumer which just discards the produced data.
321 BodyPipe::enableAutoConsumption()
323 mustAutoConsume
= true;
324 debugs(91,5, HERE
<< "enabled auto consumption" << status());
325 if (!theConsumer
&& theBuf
.hasContent())
326 startAutoConsumption();
329 // start auto consumption by creating body sink
331 BodyPipe::startAutoConsumption()
333 Must(mustAutoConsume
);
335 theConsumer
= new BodySink(this);
336 debugs(91,7, HERE
<< "starting auto consumption" << status());
337 scheduleBodyDataNotification();
343 assert(!isCheckedOut
);
349 BodyPipe::checkIn(Checkout
&checkout
)
351 assert(isCheckedOut
);
352 isCheckedOut
= false;
353 const size_t currentSize
= theBuf
.contentSize();
354 if (checkout
.checkedOutSize
> currentSize
)
355 postConsume(checkout
.checkedOutSize
- currentSize
);
356 else if (checkout
.checkedOutSize
< currentSize
)
357 postAppend(currentSize
- checkout
.checkedOutSize
);
361 BodyPipe::undoCheckOut(Checkout
&checkout
)
363 assert(isCheckedOut
);
364 const size_t currentSize
= theBuf
.contentSize();
365 // We can only undo if size did not change, and even that carries
366 // some risk. If this becomes a problem, the code checking out
367 // raw buffers should always check them in (possibly unchanged)
368 // instead of relying on the automated undo mechanism of Checkout.
369 // The code can always use a temporary buffer to accomplish that.
370 Must(checkout
.checkedOutSize
== currentSize
);
373 // TODO: Optimize: inform consumer/producer about more data/space only if
374 // they used the data/space since we notified them last time.
377 BodyPipe::postConsume(size_t size
)
379 assert(!isCheckedOut
);
381 debugs(91,7, HERE
<< "consumed " << size
<< " bytes" << status());
382 if (mayNeedMoreData()) {
383 AsyncCall::Pointer call
= asyncCall(91, 7,
384 "BodyProducer::noteMoreBodySpaceAvailable",
385 BodyProducerDialer(theProducer
,
386 &BodyProducer::noteMoreBodySpaceAvailable
, this));
387 ScheduleCallHere(call
);
392 BodyPipe::postAppend(size_t size
)
394 assert(!isCheckedOut
);
396 debugs(91,7, HERE
<< "added " << size
<< " bytes" << status());
398 if (mustAutoConsume
&& !theConsumer
&& size
> 0)
399 startAutoConsumption();
401 // We should not consume here even if mustAutoConsume because the
402 // caller may not be ready for the data to be consumed during this call.
403 scheduleBodyDataNotification();
405 if (!mayNeedMoreData())
406 clearProducer(true); // reached end-of-body
411 BodyPipe::scheduleBodyDataNotification()
413 if (theConsumer
.valid()) { // TODO: allow asyncCall() to check this instead
414 AsyncCall::Pointer call
= asyncCall(91, 7,
415 "BodyConsumer::noteMoreBodyDataAvailable",
416 BodyConsumerDialer(theConsumer
,
417 &BodyConsumer::noteMoreBodyDataAvailable
, this));
418 ScheduleCallHere(call
);
423 BodyPipe::scheduleBodyEndNotification()
425 if (theConsumer
.valid()) { // TODO: allow asyncCall() to check this instead
426 if (bodySizeKnown() && bodySize() == thePutSize
) {
427 AsyncCall::Pointer call
= asyncCall(91, 7,
428 "BodyConsumer::noteBodyProductionEnded",
429 BodyConsumerDialer(theConsumer
,
430 &BodyConsumer::noteBodyProductionEnded
, this));
431 ScheduleCallHere(call
);
433 AsyncCall::Pointer call
= asyncCall(91, 7,
434 "BodyConsumer::noteBodyProducerAborted",
435 BodyConsumerDialer(theConsumer
,
436 &BodyConsumer::noteBodyProducerAborted
, this));
437 ScheduleCallHere(call
);
442 // a short temporary string describing buffer status for debugging
443 const char *BodyPipe::status() const
445 static MemBuf outputBuffer
;
446 outputBuffer
.reset();
448 outputBuffer
.append(" [", 2);
450 outputBuffer
.Printf("%" PRIu64
"<=%" PRIu64
, theGetSize
, thePutSize
);
451 if (theBodySize
>= 0)
452 outputBuffer
.Printf("<=%" PRId64
, theBodySize
);
454 outputBuffer
.append("<=?", 3);
456 outputBuffer
.Printf(" %d+%d", (int)theBuf
.contentSize(), (int)theBuf
.spaceSize());
458 outputBuffer
.Printf(" pipe%p", this);
459 if (theProducer
.set())
460 outputBuffer
.Printf(" prod%p", theProducer
.get());
461 if (theConsumer
.set())
462 outputBuffer
.Printf(" cons%p", theConsumer
.get());
465 outputBuffer
.append(" A", 2);
466 if (abortedConsumption
)
467 outputBuffer
.append(" !C", 3);
469 outputBuffer
.append(" L", 2); // Locked
471 outputBuffer
.append("]", 1);
473 outputBuffer
.terminate();
475 return outputBuffer
.content();
479 /* BodyPipeCheckout */
481 BodyPipeCheckout::BodyPipeCheckout(BodyPipe
&aPipe
): pipe(aPipe
),
482 buf(aPipe
.checkOut()), offset(aPipe
.consumedSize()),
483 checkedOutSize(buf
.contentSize()), checkedIn(false)
487 BodyPipeCheckout::~BodyPipeCheckout()
490 // Do not pipe.undoCheckOut(*this) because it asserts or throws
491 // TODO: consider implementing the long-term solution discussed at
492 // http://www.mail-archive.com/squid-dev@squid-cache.org/msg07910.html
493 debugs(91,2, HERE
<< "Warning: cannot undo BodyPipeCheckout");
499 BodyPipeCheckout::checkIn()
507 BodyPipeCheckout::BodyPipeCheckout(const BodyPipeCheckout
&c
): pipe(c
.pipe
),
508 buf(c
.buf
), offset(c
.offset
), checkedOutSize(c
.checkedOutSize
),
509 checkedIn(c
.checkedIn
)
511 assert(false); // prevent copying
515 BodyPipeCheckout::operator =(const BodyPipeCheckout
&)
517 assert(false); // prevent assignment