3 * A NetworkPackage class. This class implements Deliverable and Receivable
4 * because all network packages should be deliverable to other nodes and
5 * receivable from other nodes. It further provides methods for reading raw
6 * content from template engines and feeding it to the stacker for undeclared
9 * The factory method requires you to provide a compressor class (which must
10 * implement the Compressor interface). If you don't want any compression (not
11 * adviceable due to increased network load), please use the NullCompressor
12 * class and encode it with BASE64 for a more error-free transfer over the
15 * For performance reasons, this class should only be instanciated once and then
16 * used as a "pipe-through" class.
18 * @author Roland Haeder <webmaster@ship-simu.org>
20 * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2011 Hub Developer Team
21 * @license GNU GPL 3.0 or any newer version
22 * @link http://www.ship-simu.org
23 * @todo Needs to add functionality for handling the object's type
25 * This program is free software: you can redistribute it and/or modify
26 * it under the terms of the GNU General Public License as published by
27 * the Free Software Foundation, either version 3 of the License, or
28 * (at your option) any later version.
30 * This program is distributed in the hope that it will be useful,
31 * but WITHOUT ANY WARRANTY; without even the implied warranty of
32 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
33 * GNU General Public License for more details.
35 * You should have received a copy of the GNU General Public License
36 * along with this program. If not, see <http://www.gnu.org/licenses/>.
38 class NetworkPackage extends BaseHubSystem implements Deliverable, Receivable, Registerable, Visitable {
40 * Package mask for compressing package data:
41 * 0: Compressor extension
43 * 2: Tags, seperated by semicolons, no semicolon is required if only one tag is needed
47 const PACKAGE_MASK = '%s%s%s%s%s%s%s';
50 * Separator for the above mask
52 const PACKAGE_MASK_SEPARATOR = '^';
55 * SEPARATOR for checksum
57 const PACKAGE_CHECKSUM_SEPARATOR = '_';
60 * Array indexes for above mask, start with zero
62 const INDEX_COMPRESSOR_EXTENSION = 0;
63 const INDEX_PACKAGE_DATA = 1;
65 const INDEX_CHECKSUM = 3;
68 * Array indexes for raw package array
70 const INDEX_PACKAGE_SENDER = 0;
71 const INDEX_PACKAGE_RECIPIENT = 1;
72 const INDEX_PACKAGE_CONTENT = 2;
73 const INDEX_PACKAGE_STATUS = 3;
74 const INDEX_PACKAGE_SIGNATURE = 4;
77 * Named array elements for package data
79 const PACKAGE_DATA_SENDER = 'sender';
80 const PACKAGE_DATA_RECIPIENT = 'recipient';
81 const PACKAGE_DATA_CONTENT = 'content';
82 const PACKAGE_DATA_STATUS = 'status';
83 const PACKAGE_DATA_SIGNATURE = 'signature';
88 const PACKAGE_STATUS_NEW = 'new';
89 const PACKAGE_STATUS_FAILED = 'failed';
90 const PACKAGE_STATUS_DECODED = 'decoded';
95 const PACKAGE_TAGS_SEPARATOR = ';';
98 * Raw package data separator
100 const PACKAGE_DATA_SEPARATOR = '#';
103 * Network target (alias): 'upper hubs'
105 const NETWORK_TARGET_UPPER_HUBS = 'upper';
108 * Network target (alias): 'self'
110 const NETWORK_TARGET_SELF = 'self';
113 * TCP package size in bytes
115 const TCP_PACKAGE_SIZE = 512;
118 * Size of the decoded data array
120 const DECODED_DATA_ARRAY_SIZE = 4;
122 /**************************************************************************
123 * Stacker for out-going packages *
124 **************************************************************************/
127 * Stacker name for "undeclared" packages
129 const STACKER_NAME_UNDECLARED = 'package_undeclared';
132 * Stacker name for "declared" packages (which are ready to send out)
134 const STACKER_NAME_DECLARED = 'package_declared';
137 * Stacker name for "out-going" packages
139 const STACKER_NAME_OUTGOING = 'package_outgoing';
141 /**************************************************************************
142 * Stacker for incoming packages *
143 **************************************************************************/
146 * Stacker name for "incoming" decoded raw data
148 const STACKER_NAME_DECODED_INCOMING = 'package_decoded_data';
151 * Stacker name for handled decoded raw data
153 const STACKER_NAME_DECODED_HANDLED = 'package_handled_decoded';
156 * Stacker name for "chunked" decoded raw data
158 const STACKER_NAME_DECODED_CHUNKED = 'package_chunked_decoded';
160 /**************************************************************************
161 * Stacker for other/internal purposes *
162 **************************************************************************/
165 * Stacker name for "back-buffered" packages
167 const STACKER_NAME_BACK_BUFFER = 'package_backbuffer';
170 * Protected constructor
174 protected function __construct () {
175 // Call parent constructor
176 parent::__construct(__CLASS__);
180 * Creates an instance of this class
182 * @param $compressorInstance A Compressor instance for compressing the content
183 * @return $packageInstance An instance of a Deliverable class
185 public static final function createNetworkPackage (Compressor $compressorInstance) {
187 $packageInstance = new NetworkPackage();
189 // Now set the compressor instance
190 $packageInstance->setCompressorInstance($compressorInstance);
193 * We need to initialize a stack here for our packages even for those
194 * which have no recipient address and stamp... ;-) This stacker will
195 * also be used for incoming raw data to handle it.
197 $stackerInstance = ObjectFactory::createObjectByConfiguredName('network_package_stacker_class');
199 // At last, set it in this class
200 $packageInstance->setStackerInstance($stackerInstance);
203 $packageInstance->initStackers();
205 // Get a visitor instance for speeding up things
206 $visitorInstance = ObjectFactory::createObjectByConfiguredName('node_raw_data_monitor_visitor_class', array($packageInstance));
208 // Set it in this package
209 $packageInstance->setVisitorInstance($visitorInstance);
211 // Get crypto instance and set it in this package
212 $cryptoInstance = ObjectFactory::createObjectByConfiguredName('crypto_class');
213 $packageInstance->setCryptoInstance($cryptoInstance);
215 // Get a singleton package assembler instance from factory and set it here
216 $assemblerInstance = PackageAssemblerFactory::createAssemblerInstance($packageInstance);
217 $packageInstance->setAssemblerInstance($assemblerInstance);
219 // Return the prepared instance
220 return $packageInstance;
224 * Initialize all stackers
226 * @param $forceReInit Whether to force reinitialization of all stacks
229 protected function initStackers ($forceReInit = false) {
233 self::STACKER_NAME_UNDECLARED,
234 self::STACKER_NAME_DECLARED,
235 self::STACKER_NAME_OUTGOING,
236 self::STACKER_NAME_DECODED_INCOMING,
237 self::STACKER_NAME_DECODED_HANDLED,
238 self::STACKER_NAME_DECODED_CHUNKED,
239 self::STACKER_NAME_BACK_BUFFER
242 $this->getStackerInstance()->initStacker($stackerName, $forceReInit);
247 * "Getter" for hash from given content and helper instance
249 * @param $content Raw package content
250 * @param $helperInstance An instance of a HelpableHub class
251 * @param $nodeInstance An instance of a NodeHelper class
252 * @return $hash Hash for given package content
254 private function getHashFromContent ($content) {
256 //* NOISY-DEBUG: */ $this->debugOutput('NETWORK-PACKAGE: content[md5]=' . md5($content) . ',sender=' . $this->getSessionId() . ',compressor=' . $this->getCompressorInstance()->getCompressorExtension());
259 // @TODO crc32() is very weak, but it needs to be fast
262 self::PACKAGE_CHECKSUM_SEPARATOR .
263 $this->getSessionId() .
264 self::PACKAGE_CHECKSUM_SEPARATOR .
265 $this->getCompressorInstance()->getCompressorExtension()
273 * Change the package with given status in given stack
275 * @param $packageData Raw package data in an array
276 * @param $stackerName Name of the stacker
277 * @param $newStatus New status to set
280 private function changePackageStatus (array $packageData, $stackerName, $newStatus) {
281 // Skip this for empty stacks
282 if ($this->getStackerInstance()->isStackEmpty($stackerName)) {
283 // This avoids an exception after all packages has failed
287 // Pop the entry (it should be it)
288 $nextData = $this->getStackerInstance()->popNamed($stackerName);
290 // Compare both arrays
291 assert($nextData[self::PACKAGE_DATA_SIGNATURE] == $packageData[self::PACKAGE_DATA_SIGNATURE]);
293 // Temporary set the new status
294 $packageData[self::PACKAGE_DATA_STATUS] = $newStatus;
297 $this->getStackerInstance()->pushNamed($stackerName, $packageData);
300 ///////////////////////////////////////////////////////////////////////////
301 // Delivering packages / raw data
302 ///////////////////////////////////////////////////////////////////////////
305 * Delivers the given raw package data.
307 * @param $packageData Raw package data in an array
310 private function declareRawPackageData (array $packageData) {
312 * We need to disover every recipient, just in case we have a
313 * multi-recipient entry like 'upper' is. 'all' may be a not so good
314 * target because it causes an overload on the network and may be
315 * abused for attacking the network with large packages.
317 $discoveryInstance = PackageDiscoveryFactory::createPackageDiscoveryInstance();
319 // Discover all recipients, this may throw an exception
320 $discoveryInstance->discoverRecipients($packageData);
322 // Now get an iterator
323 $iteratorInstance = $discoveryInstance->getIterator();
325 // Rewind back to the beginning
326 $iteratorInstance->rewind();
328 // ... and begin iteration
329 while ($iteratorInstance->valid()) {
331 $currentRecipient = $iteratorInstance->current();
334 $packageData[self::PACKAGE_DATA_RECIPIENT] = $currentRecipient;
336 // And enqueue it to the writer class
337 $this->getStackerInstance()->pushNamed(self::STACKER_NAME_DECLARED, $packageData);
340 $this->debugOutput('PACKAGE: Package declared for recipient ' . $currentRecipient);
342 // Skip to next entry
343 $iteratorInstance->next();
347 * The recipient list can be cleaned up here because the package which
348 * shall be delivered has already been added for all entries from the
351 $discoveryInstance->clearRecipients();
355 * Delivers raw package data. In short, this will discover the raw socket
356 * resource through a discovery class (which will analyse the receipient of
357 * the package), register the socket with the connection (handler/helper?)
358 * instance and finally push the raw data on our outgoing queue.
360 * @param $packageData Raw package data in an array
363 private function deliverRawPackageData (array $packageData) {
365 * This package may become big, depending on the shared object size or
366 * delivered message size which shouldn't be so long (to save
367 * bandwidth). Because of the nature of the used protocol (TCP) we need
368 * to split it up into smaller pieces to fit it into a TCP frame.
370 * So first we need (again) a discovery class but now a protocol
371 * discovery to choose the right socket resource. The discovery class
372 * should take a look at the raw package data itself and then decide
373 * which (configurable!) protocol should be used for that type of
376 $discoveryInstance = SocketDiscoveryFactory::createSocketDiscoveryInstance();
378 // Now discover the right protocol
379 $socketResource = $discoveryInstance->discoverSocket($packageData);
382 //* NOISY-DEBUG: */ $this->debugOutput('PACKAGE: Reached line ' . __LINE__ . ' after discoverSocket() has been called.');
384 // We have to put this socket in our registry, so get an instance
385 $registryInstance = SocketRegistry::createSocketRegistry();
387 // Get the listener from registry
388 $helperInstance = Registry::getRegistry()->getInstance('connection');
391 //* NOISY-DEBUG: */ $this->debugOutput('PACKAGE: stateInstance=' . $helperInstance->getStateInstance());
392 //* NOISY-DEBUG: */ $this->debugOutput('PACKAGE: Reached line ' . __LINE__ . ' before isSocketRegistered() has been called.');
395 if ((is_resource($socketResource)) && (!$registryInstance->isSocketRegistered($helperInstance, $socketResource))) {
397 $this->debugOutput('PACKAGE: Registering socket ' . $socketResource . ' ...');
400 $registryInstance->registerSocket($helperInstance, $socketResource, $packageData);
401 } elseif (!$helperInstance->getStateInstance()->isPeerStateConnected()) {
402 // Is not connected, then we cannot send
403 $this->debugOutput('PACKAGE: Unexpected peer state ' . $helperInstance->getStateInstance()->__toString() . ' detected.');
405 // Shutdown the socket
406 $this->shutdownSocket($socketResource);
410 //* NOISY-DEBUG: */ $this->debugOutput('PACKAGE: Reached line ' . __LINE__ . ' after isSocketRegistered() has been called.');
412 // Make sure the connection is up
413 $helperInstance->getStateInstance()->validatePeerStateConnected();
416 //* NOISY-DEBUG: */ $this->debugOutput('PACKAGE: Reached line ' . __LINE__ . ' after validatePeerStateConnected() has been called.');
418 // Enqueue it again on the out-going queue, the connection is up and working at this point
419 $this->getStackerInstance()->pushNamed(self::STACKER_NAME_OUTGOING, $packageData);
422 //* NOISY-DEBUG: */ $this->debugOutput('PACKAGE: Reached line ' . __LINE__ . ' after pushNamed() has been called.');
426 * Sends waiting packages
428 * @param $packageData Raw package data
431 private function sendOutgoingRawPackageData (array $packageData) {
435 // Get the right connection instance
436 $helperInstance = SocketRegistry::createSocketRegistry()->getHandlerInstanceFromPackageData($packageData);
438 // Is this connection still alive?
439 if ($helperInstance->isShuttedDown()) {
440 // This connection is shutting down
441 // @TODO We may want to do somthing more here?
445 // Sent out package data
446 $sentBytes = $helperInstance->sendRawPackageData($packageData);
448 // Remember unsent raw bytes in back-buffer, if any
449 $this->storeUnsentBytesInBackBuffer($packageData, $sentBytes);
453 * Generates a signature for given raw package content and sender id
455 * @param $content Raw package data
456 * @param $senderId Sender id to generate a signature for
457 * @return $signature Signature as BASE64-encoded string
459 private function generatePackageSignature ($content, $senderId) {
460 // ash content and sender id together, use md5() as last algo
461 $hash = md5($this->getCryptoInstance()->hashString($senderId . $content, $this->getNodeId(), false));
463 // Encrypt the content again with the hash as a key
464 $encryptedContent = $this->getCryptoInstance()->encryptString($content, $hash);
466 // Encode it with BASE64
467 $signature = base64_encode($encryptedContent);
474 * "Enqueues" raw content into this delivery class by reading the raw content
475 * from given template instance and pushing it on the 'undeclared' stack.
477 * @param $helperInstance An instance of a HelpableHub class
480 public function enqueueRawDataFromTemplate (HelpableHub $helperInstance) {
481 // Get the raw content ...
482 $content = $helperInstance->getTemplateInstance()->getRawTemplateData();
484 // ... and compress it
485 $content = $this->getCompressorInstance()->compressStream($content);
487 // Add magic in front of it and hash behind it, including BASE64 encoding
488 $content = sprintf(self::PACKAGE_MASK,
489 // 1.) Compressor's extension
490 $this->getCompressorInstance()->getCompressorExtension(),
492 self::PACKAGE_MASK_SEPARATOR,
493 // 2.) Raw package content, encoded with BASE64
494 base64_encode($content),
496 self::PACKAGE_MASK_SEPARATOR,
498 implode(self::PACKAGE_TAGS_SEPARATOR, $helperInstance->getPackageTags()),
500 self::PACKAGE_MASK_SEPARATOR,
502 $this->getHashFromContent($content)
505 // Now prepare the temporary array and push it on the 'undeclared' stack
506 $this->getStackerInstance()->pushNamed(self::STACKER_NAME_UNDECLARED, array(
507 self::PACKAGE_DATA_SENDER => $this->getSessionId(),
508 self::PACKAGE_DATA_RECIPIENT => $helperInstance->getRecipientType(),
509 self::PACKAGE_DATA_CONTENT => $content,
510 self::PACKAGE_DATA_STATUS => self::PACKAGE_STATUS_NEW,
511 self::PACKAGE_DATA_SIGNATURE => $this->generatePackageSignature($content, $this->getSessionId())
516 * Checks whether a package has been enqueued for delivery.
518 * @return $isEnqueued Whether a package is enqueued
520 public function isPackageEnqueued () {
521 // Check whether the stacker is not empty
522 $isEnqueued = (($this->getStackerInstance()->isStackInitialized(self::STACKER_NAME_UNDECLARED)) && (!$this->getStackerInstance()->isStackEmpty(self::STACKER_NAME_UNDECLARED)));
529 * Checks whether a package has been declared
531 * @return $isDeclared Whether a package is declared
533 public function isPackageDeclared () {
534 // Check whether the stacker is not empty
535 $isDeclared = (($this->getStackerInstance()->isStackInitialized(self::STACKER_NAME_DECLARED)) && (!$this->getStackerInstance()->isStackEmpty(self::STACKER_NAME_DECLARED)));
542 * Checks whether a package should be sent out
544 * @return $isWaitingDelivery Whether a package is waiting for delivery
546 public function isPackageWaitingForDelivery () {
547 // Check whether the stacker is not empty
548 $isWaitingDelivery = (($this->getStackerInstance()->isStackInitialized(self::STACKER_NAME_OUTGOING)) && (!$this->getStackerInstance()->isStackEmpty(self::STACKER_NAME_OUTGOING)));
551 return $isWaitingDelivery;
555 * Delivers an enqueued package to the stated destination. If a non-session
556 * id is provided, recipient resolver is being asked (and instanced once).
557 * This allows that a single package is being delivered to multiple targets
558 * without enqueueing it for every target. If no target is provided or it
559 * can't be determined a NoTargetException is being thrown.
562 * @throws NoTargetException If no target can't be determined
564 public function declareEnqueuedPackage () {
565 // Make sure this method isn't working if there is no package enqueued
566 if (!$this->isPackageEnqueued()) {
567 // This is not fatal but should be avoided
568 // @TODO Add some logging here
572 // Now we know for sure there are packages to deliver, we can start
573 // with the first one.
574 $packageData = $this->getStackerInstance()->getNamed(self::STACKER_NAME_UNDECLARED);
576 // Declare the raw package data for delivery
577 $this->declareRawPackageData($packageData);
579 // And remove it finally
580 $this->getStackerInstance()->popNamed(self::STACKER_NAME_UNDECLARED);
584 * Delivers the next declared package. Only one package per time will be sent
585 * because this may take time and slows down the whole delivery
590 public function deliverDeclaredPackage () {
591 // Sanity check if we have packages declared
592 if (!$this->isPackageDeclared()) {
593 // This is not fatal but should be avoided
594 $this->debugOutput('PACKAGE: No package has been declared, but ' . __METHOD__ . ' has been called!');
599 $packageData = $this->getStackerInstance()->getNamed(self::STACKER_NAME_DECLARED);
602 // And try to send it
603 $this->deliverRawPackageData($packageData);
605 // And remove it finally
606 $this->getStackerInstance()->popNamed(self::STACKER_NAME_DECLARED);
607 } catch (InvalidStateException $e) {
608 // The state is not excepected (shall be 'connected')
609 $this->debugOutput('PACKAGE: Caught ' . $e->__toString() . ',message=' . $e->getMessage());
611 // Mark the package with status failed
612 $this->changePackageStatus($packageData, self::STACKER_NAME_DECLARED, self::PACKAGE_STATUS_FAILED);
617 * Sends waiting packages out for delivery
621 public function sendWaitingPackage () {
622 // Send any waiting bytes in the back-buffer before sending a new package
623 $this->sendBackBufferBytes();
625 // Sanity check if we have packages waiting for delivery
626 if (!$this->isPackageWaitingForDelivery()) {
627 // This is not fatal but should be avoided
628 $this->debugOutput('PACKAGE: No package is waiting for delivery, but ' . __METHOD__ . ' was called.');
633 $packageData = $this->getStackerInstance()->getNamed(self::STACKER_NAME_OUTGOING);
636 // Now try to send it
637 $this->sendOutgoingRawPackageData($packageData);
639 // And remove it finally
640 $this->getStackerInstance()->popNamed(self::STACKER_NAME_OUTGOING);
641 } catch (InvalidSocketException $e) {
642 // Output exception message
643 $this->debugOutput('PACKAGE: Package was not delivered: ' . $e->getMessage());
645 // Mark package as failed
646 $this->changePackageStatus($packageData, self::STACKER_NAME_OUTGOING, self::PACKAGE_STATUS_FAILED);
650 ///////////////////////////////////////////////////////////////////////////
651 // Receiving packages / raw data
652 ///////////////////////////////////////////////////////////////////////////
655 * Checks whether decoded raw data is pending
657 * @return $isPending Whether decoded raw data is pending
659 private function isDecodedDataPending () {
660 // Just return whether the stack is not empty
661 $isPending = (!$this->getStackerInstance()->isStackEmpty(self::STACKER_NAME_DECODED_INCOMING));
668 * Checks whether new raw package data has arrived at a socket
670 * @param $poolInstance An instance of a PoolableListener class
671 * @return $hasArrived Whether new raw package data has arrived for processing
673 public function isNewRawDataPending (PoolableListener $poolInstance) {
674 // Visit the pool. This monitors the pool for incoming raw data.
675 $poolInstance->accept($this->getVisitorInstance());
677 // Check for new data arrival
678 $hasArrived = $this->isDecodedDataPending();
685 * Handles the incoming decoded raw data. This method does not "convert" the
686 * decoded data back into a package array, it just "handles" it and pushs it
691 public function handleIncomingDecodedData () {
693 * This method should only be called if decoded raw data is pending,
696 if (!$this->isDecodedDataPending()) {
697 // This is not fatal but should be avoided
698 // @TODO Add some logging here
702 // Very noisy debug message:
703 /* NOISY-DEBUG: */ $this->debugOutput('PACKAGE: Stacker size is ' . $this->getStackerInstance()->getStackCount(self::STACKER_NAME_DECODED_INCOMING) . ' entries.');
705 // "Pop" the next entry (the same array again) from the stack
706 $decodedData = $this->getStackerInstance()->popNamed(self::STACKER_NAME_DECODED_INCOMING);
708 // Make sure both array elements are there
710 (is_array($decodedData)) &&
711 (isset($decodedData[BaseRawDataHandler::PACKAGE_DECODED_DATA])) &&
712 (isset($decodedData[BaseRawDataHandler::PACKAGE_ERROR_CODE]))
716 * Also make sure the error code is SOCKET_ERROR_UNHANDLED because we
717 * only want to handle unhandled packages here.
719 /* NOISY-DEBUG: */ $this->debugOutput('NETWORK-PACKAGE: errorCode=' . $decodedData[BaseRawDataHandler::PACKAGE_ERROR_CODE]);
720 assert($decodedData[BaseRawDataHandler::PACKAGE_ERROR_CODE] == BaseRawDataHandler::SOCKET_ERROR_UNHANDLED);
722 // Remove the last chunk SEPARATOR (because it is being added and we don't need it)
723 if (substr($decodedData[BaseRawDataHandler::PACKAGE_DECODED_DATA], -1, 1) == PackageFragmenter::CHUNK_SEPARATOR) {
724 // It is there and should be removed
725 $decodedData[BaseRawDataHandler::PACKAGE_DECODED_DATA] = substr($decodedData[BaseRawDataHandler::PACKAGE_DECODED_DATA], 0, -1);
728 // This package is "handled" and can be pushed on the next stack
729 $this->getStackerInstance()->pushNamed(self::STACKER_NAME_DECODED_HANDLED, $decodedData);
733 * Adds raw decoded data from the given handler instance to this receiver
735 * @param $handlerInstance An instance of a Networkable class
738 public function addDecodedDataToIncomingStack (Networkable $handlerInstance) {
740 * Get the decoded data from the handler, this is an array with
741 * 'decoded_data' and 'error_code' as elements.
743 $decodedData = $handlerInstance->getNextDecodedData();
745 // Very noisy debug message:
746 //* NOISY-DEBUG: */ $this->debugOutput('PACKAGE: decodedData[' . gettype($decodedData) . ']=' . print_r($decodedData, true));
748 // And push it on our stack
749 $this->getStackerInstance()->pushNamed(self::STACKER_NAME_DECODED_INCOMING, $decodedData);
753 * Checks whether incoming decoded data is handled.
755 * @return $isHandled Whether incoming decoded data is handled
757 public function isIncomingDecodedDataHandled () {
758 // Determine if the stack is not empty
759 $isHandled = (!$this->getStackerInstance()->isStackEmpty(self::STACKER_NAME_DECODED_HANDLED));
766 * Checks whether the assembler has pending data left
768 * @return $isHandled Whether the assembler has pending data left
770 public function ifAssemblerHasPendingDataLeft () {
771 // Determine if the stack is not empty
772 $isHandled = (!$this->getAssemblerInstance()->isPendingDataEmpty());
779 * Handles the attached assemler's pending data queue to be finally
780 * assembled to the raw package data back.
784 public function handleAssemblerPendingData () {
786 $this->getAssemblerInstance()->handlePendingData();
790 * Assembles incoming decoded data so it will become an abstract network
791 * package again. The assembler does later do it's job by an other task,
792 * not this one to keep best speed possible.
796 public function assembleDecodedDataToPackage () {
797 // Make sure the raw decoded package data is handled
798 assert($this->isIncomingDecodedDataHandled());
800 // Get current package content (an array with two elements; see handleIncomingDecodedData() for details)
801 $packageContent = $this->getStackerInstance()->getNamed(self::STACKER_NAME_DECODED_HANDLED);
803 // Start assembling the raw package data array by chunking it
804 $this->getAssemblerInstance()->chunkPackageContent($packageContent);
806 // Remove the package from 'handled_decoded' stack ...
807 $this->getStackerInstance()->popNamed(self::STACKER_NAME_DECODED_HANDLED);
809 // ... and push it on the 'chunked' stacker
810 $this->getStackerInstance()->pushNamed(self::STACKER_NAME_DECODED_CHUNKED, $packageContent);
814 * Checks whether a new package has arrived
816 * @return $hasArrived Whether a new package has arrived for processing
818 public function isNewPackageArrived () {
819 // @TODO Add some content here
823 * Accepts the visitor to process the visit "request"
825 * @param $visitorInstance An instance of a Visitor class
828 public function accept (Visitor $visitorInstance) {
830 //* NOISY-DEBUG: */ $this->debugOutput('PACKAGE: ' . $visitorInstance->__toString() . ' has visited - START');
833 $visitorInstance->visitNetworkPackage($this);
836 //* NOISY-DEBUG: */ $this->debugOutput('PACKAGE: ' . $visitorInstance->__toString() . ' has visited - FINISHED');
844 public function clearAllStacker () {
845 // Call the init method to force re-initialization
846 $this->initStackers(true);
849 /* DEBUG: */ $this->debugOutput('PACKAGE: All stacker have been re-initialized.');
853 * Removes the first failed outoging package from the stack to continue
854 * with next one (it will never work until the issue is fixed by you).
857 * @throws UnexpectedPackageStatusException If the package status is not 'failed'
858 * @todo This may be enchanced for outgoing packages?
860 public function removeFirstFailedPackage () {
861 // Get the package again
862 $packageData = $this->getStackerInstance()->getNamed(self::STACKER_NAME_DECLARED);
864 // Is the package status 'failed'?
865 if ($packageData[self::PACKAGE_DATA_STATUS] != self::PACKAGE_STATUS_FAILED) {
867 throw new UnexpectedPackageStatusException(array($this, $packageData, self::PACKAGE_STATUS_FAILED), BaseListener::EXCEPTION_UNEXPECTED_PACKAGE_STATUS);
871 $this->getStackerInstance()->popNamed(self::STACKER_NAME_DECLARED);
875 * "Decode" the package content into the same array when it was sent.
877 * @param $rawPackageContent The raw package content to be "decoded"
878 * @return $decodedData An array with 'sender', 'recipient', 'content' and 'status' elements
880 public function decodeRawContent ($rawPackageContent) {
881 // Use the separator '#' to "decode" it
882 $decodedArray = explode(self::PACKAGE_DATA_SEPARATOR, $rawPackageContent);
884 // Assert on count (should be always 3)
885 assert(count($decodedArray) == self::DECODED_DATA_ARRAY_SIZE);
887 // Create 'decodedData' array with all assoziative array elements
888 $decodedData = array(
889 self::PACKAGE_DATA_SENDER => $decodedArray[self::INDEX_PACKAGE_SENDER],
890 self::PACKAGE_DATA_RECIPIENT => $decodedArray[self::INDEX_PACKAGE_RECIPIENT],
891 self::PACKAGE_DATA_CONTENT => $decodedArray[self::INDEX_PACKAGE_CONTENT],
892 self::PACKAGE_DATA_STATUS => self::PACKAGE_STATUS_DECODED,
893 self::PACKAGE_DATA_SIGNATURE => $this->generatePackageSignature($decodedArray[self::INDEX_PACKAGE_CONTENT], $decodedArray[self::INDEX_PACKAGE_SENDER])