]> git.mxchange.org Git - hub.git/blobdiff - application/hub/main/package/class_NetworkPackage.php
Corrected assert, added debug line
[hub.git] / application / hub / main / package / class_NetworkPackage.php
index e060c32f9238c09f7145a067fb9d75f5e0c4ed19..ba893bd89869f120708c79d1d332b42208568940 100644 (file)
@@ -116,6 +116,10 @@ class NetworkPackage extends BaseHubSystem implements Deliverable, Receivable, R
        const MESSAGE_ARRAY_DATA = 'message_data';
        const MESSAGE_ARRAY_TYPE = 'message_type';
 
+       /**
+        * Generic answer status field
+        */
+
        /**
         * Tags separator
         */
@@ -134,13 +138,18 @@ class NetworkPackage extends BaseHubSystem implements Deliverable, Receivable, R
        /**
         * Network target (alias): 'upper nodes'
         */
-       const NETWORK_TARGET_UPPER_NODES = 'upper';
+       const NETWORK_TARGET_UPPER = 'upper';
 
        /**
         * Network target (alias): 'self'
         */
        const NETWORK_TARGET_SELF = 'self';
 
+       /**
+        * Network target (alias): 'dht'
+        */
+       const NETWORK_TARGET_DHT = 'dht';
+
        /**
         * TCP package size in bytes
         */
@@ -271,7 +280,7 @@ class NetworkPackage extends BaseHubSystem implements Deliverable, Receivable, R
         * @param       $forceReInit    Whether to force reinitialization of all stacks
         * @return      void
         */
-       protected function initStackers ($forceReInit = false) {
+       protected function initStackers ($forceReInit = FALSE) {
                // Initialize all
                foreach (
                        array(
@@ -286,6 +295,7 @@ class NetworkPackage extends BaseHubSystem implements Deliverable, Receivable, R
                                self::STACKER_NAME_BACK_BUFFER
                        ) as $stackerName) {
                                // Init this stacker
+                               //* DEBUG: */ print(__METHOD__ . ': stackerName=' . $stackerName . ',forceReInit=' . intval($forceReInit) . PHP_EOL);
                                $this->getStackerInstance()->initStacker($stackerName, $forceReInit);
                } // END - foreach
        }
@@ -298,7 +308,7 @@ class NetworkPackage extends BaseHubSystem implements Deliverable, Receivable, R
         */
        private function getHashFromContent ($content) {
                // Debug message
-               //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('NETWORK-PACKAGE: content[md5]=' . md5($content) . ',sender=' . $this->getSessionId() . ',compressor=' . $this->getCompressorInstance()->getCompressorExtension());
+               //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('NETWORK-PACKAGE[' . __LINE__ . ']: content[md5]=' . md5($content) . ',sender=' . $this->getSessionId() . ',compressor=' . $this->getCompressorInstance()->getCompressorExtension());
 
                // Create the hash
                // @TODO crc32() is very weak, but it needs to be fast
@@ -310,6 +320,9 @@ class NetworkPackage extends BaseHubSystem implements Deliverable, Receivable, R
                        $this->getCompressorInstance()->getCompressorExtension()
                );
 
+               // Debug message
+               //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('NETWORK-PACKAGE[' . __LINE__ . ']: content[md5]=' . md5($content) . ',sender=' . $this->getSessionId() . ',hash=' . $hash . ',compressor=' . $this->getCompressorInstance()->getCompressorExtension());
+
                // And return it
                return $hash;
        }
@@ -369,7 +382,7 @@ class NetworkPackage extends BaseHubSystem implements Deliverable, Receivable, R
         */
        public function getHashFromContentSessionId (array $decodedContent, $sessionId) {
                // Debug message
-               //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('NETWORK-PACKAGE: content[md5]=' . md5($decodedContent[self::PACKAGE_CONTENT_MESSAGE]) . ',sender=' . $sessionId . ',compressor=' . $decodedContent[self::PACKAGE_CONTENT_EXTENSION]);
+               //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('NETWORK-PACKAGE[' . __LINE__ . ']: content[md5]=' . md5($decodedContent[self::PACKAGE_CONTENT_MESSAGE]) . ',sender=' . $sessionId . ',compressor=' . $decodedContent[self::PACKAGE_CONTENT_EXTENSION]);
 
                // Create the hash
                // @TODO crc32() is very weak, but it needs to be fast
@@ -396,6 +409,9 @@ class NetworkPackage extends BaseHubSystem implements Deliverable, Receivable, R
         * @return      void
         */
        private function declareRawPackageData (array $packageData) {
+               // Make sure the required field is there
+               assert(isset($packageData[self::PACKAGE_DATA_RECIPIENT]));
+
                /*
                 * We need to disover every recipient, just in case we have a
                 * multi-recipient entry like 'upper' is. 'all' may be a not so good
@@ -419,7 +435,7 @@ class NetworkPackage extends BaseHubSystem implements Deliverable, Receivable, R
                        $currentRecipient = $iteratorInstance->current();
 
                        // Debug message
-                       self::createDebugInstance(__CLASS__)->debugOutput('NETWORK-PACKAGE: Setting recipient to ' . $currentRecipient . ',previous=' . $packageData[self::PACKAGE_DATA_RECIPIENT]);
+                       //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('NETWORK-PACKAGE[' . __LINE__ . ']: Setting recipient to ' . $currentRecipient . ',previous=' . $packageData[self::PACKAGE_DATA_RECIPIENT]);
 
                        // Set the recipient
                        $packageData[self::PACKAGE_DATA_RECIPIENT] = $currentRecipient;
@@ -428,7 +444,7 @@ class NetworkPackage extends BaseHubSystem implements Deliverable, Receivable, R
                        $this->getStackerInstance()->pushNamed(self::STACKER_NAME_DECLARED, $packageData);
 
                        // Debug message
-                       self::createDebugInstance(__CLASS__)->debugOutput('NETWORK-PACKAGE: Package declared for recipient ' . $currentRecipient);
+                       //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('NETWORK-PACKAGE[' . __LINE__ . ']: Package declared for recipient ' . $currentRecipient);
 
                        // Skip to next entry
                        $iteratorInstance->next();
@@ -470,7 +486,7 @@ class NetworkPackage extends BaseHubSystem implements Deliverable, Receivable, R
                $socketResource = $discoveryInstance->discoverSocket($packageData, BaseConnectionHelper::CONNECTION_TYPE_OUTGOING);
 
                // Debug message
-               //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('NETWORK-PACKAGE: Reached line ' . __LINE__ . ' after discoverSocket() has been called.');
+               //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('NETWORK-PACKAGE[' . __LINE__ . ']: Reached line ' . __LINE__ . ' after discoverSocket() has been called.');
 
                // We have to put this socket in our registry, so get an instance
                $registryInstance = SocketRegistryFactory::createSocketRegistryInstance();
@@ -479,38 +495,38 @@ class NetworkPackage extends BaseHubSystem implements Deliverable, Receivable, R
                $helperInstance = Registry::getRegistry()->getInstance('connection');
 
                // Debug message
-               //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('NETWORK-PACKAGE: stateInstance=' . $helperInstance->getStateInstance());
-               //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('NETWORK-PACKAGE: Reached line ' . __LINE__ . ' before isSocketRegistered() has been called.');
+               //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('NETWORK-PACKAGE[' . __LINE__ . ']: stateInstance=' . $helperInstance->getStateInstance());
+               //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('NETWORK-PACKAGE[' . __LINE__ . ']: Reached line ' . __LINE__ . ' before isSocketRegistered() has been called.');
 
                // Is it not there?
                if ((is_resource($socketResource)) && (!$registryInstance->isSocketRegistered($helperInstance, $socketResource))) {
                        // Debug message
-                       self::createDebugInstance(__CLASS__)->debugOutput('NETWORK-PACKAGE: Registering socket ' . $socketResource . ' ...');
+                       //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('NETWORK-PACKAGE[' . __LINE__ . ']: Registering socket ' . $socketResource . ' ...');
 
                        // Then register it
                        $registryInstance->registerSocket($helperInstance, $socketResource, $packageData);
                } elseif (!$helperInstance->getStateInstance()->isPeerStateConnected()) {
                        // Is not connected, then we cannot send
-                       self::createDebugInstance(__CLASS__)->debugOutput('NETWORK-PACKAGE: Unexpected peer state ' . $helperInstance->getStateInstance()->__toString() . ' detected.');
+                       self::createDebugInstance(__CLASS__)->debugOutput('NETWORK-PACKAGE[' . __LINE__ . ']: Unexpected peer state ' . $helperInstance->getStateInstance()->__toString() . ' detected.');
 
                        // Shutdown the socket
                        $this->shutdownSocket($socketResource);
                }
 
                // Debug message
-               //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('NETWORK-PACKAGE: Reached line ' . __LINE__ . ' after isSocketRegistered() has been called.');
+               //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('NETWORK-PACKAGE[' . __LINE__ . ']: Reached line ' . __LINE__ . ' after isSocketRegistered() has been called.');
 
                // Make sure the connection is up
                $helperInstance->getStateInstance()->validatePeerStateConnected();
 
                // Debug message
-               //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('NETWORK-PACKAGE: Reached line ' . __LINE__ . ' after validatePeerStateConnected() has been called.');
+               //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('NETWORK-PACKAGE[' . __LINE__ . ']: Reached line ' . __LINE__ . ' after validatePeerStateConnected() has been called.');
 
                // Enqueue it again on the out-going queue, the connection is up and working at this point
                $this->getStackerInstance()->pushNamed(self::STACKER_NAME_OUTGOING, $packageData);
 
                // Debug message
-               //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('NETWORK-PACKAGE: Reached line ' . __LINE__ . ' after pushNamed() has been called.');
+               //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('NETWORK-PACKAGE[' . __LINE__ . ']: Reached line ' . __LINE__ . ' after pushNamed() has been called.');
        }
 
        /**
@@ -583,11 +599,11 @@ class NetworkPackage extends BaseHubSystem implements Deliverable, Receivable, R
         * from given helper's template instance and pushing it on the 'undeclared'
         * stack.
         *
-        * @param       $helperInstance         An instance of a HelpableHub class
+        * @param       $helperInstance         An instance of a Helper class
         * @param       $protocol                       Name of used protocol (TCP/UDP)
         * @return      void
         */
-       public function enqueueRawDataFromTemplate (HelpableHub $helperInstance, $protocolName) {
+       public function enqueueRawDataFromTemplate (Helper $helperInstance, $protocolName) {
                // Get the raw content ...
                $content = $helperInstance->getTemplateInstance()->getRawTemplateData();
                //* DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('content(' . strlen($content) . ')=' . $content);
@@ -596,7 +612,7 @@ class NetworkPackage extends BaseHubSystem implements Deliverable, Receivable, R
                $content = $this->getCompressorInstance()->compressStream($content);
 
                // Add magic in front of it and hash behind it, including BASE64 encoding
-               $content = sprintf(self::PACKAGE_MASK,
+               $packageContent = sprintf(self::PACKAGE_MASK,
                        // 1.) Compressor's extension
                        $this->getCompressorInstance()->getCompressorExtension(),
                        // - separator
@@ -618,9 +634,9 @@ class NetworkPackage extends BaseHubSystem implements Deliverable, Receivable, R
                        self::PACKAGE_DATA_SENDER    => $this->getSessionId(),
                        self::PACKAGE_DATA_RECIPIENT => $helperInstance->getRecipientType(),
                        self::PACKAGE_DATA_PROTOCOL  => $protocolName,
-                       self::PACKAGE_DATA_CONTENT   => $content,
+                       self::PACKAGE_DATA_CONTENT   => $packageContent,
                        self::PACKAGE_DATA_STATUS    => self::PACKAGE_STATUS_NEW,
-                       self::PACKAGE_DATA_SIGNATURE => $this->generatePackageSignature($content, $this->getSessionId())
+                       self::PACKAGE_DATA_SIGNATURE => $this->generatePackageSignature($packageContent, $this->getSessionId())
                ));
        }
 
@@ -685,13 +701,10 @@ class NetworkPackage extends BaseHubSystem implements Deliverable, Receivable, R
                 * Now there are for sure packages to deliver, so start with the first
                 * one.
                 */
-               $packageData = $this->getStackerInstance()->getNamed(self::STACKER_NAME_UNDECLARED);
+               $packageData = $this->getStackerInstance()->popNamed(self::STACKER_NAME_UNDECLARED);
 
                // Declare the raw package data for delivery
                $this->declareRawPackageData($packageData);
-
-               // And remove it finally
-               $this->getStackerInstance()->popNamed(self::STACKER_NAME_UNDECLARED);
        }
 
        /**
@@ -705,13 +718,17 @@ class NetworkPackage extends BaseHubSystem implements Deliverable, Receivable, R
                // Sanity check if we have packages declared
                if (!$this->isPackageDeclared()) {
                        // This is not fatal but should be avoided
-                       self::createDebugInstance(__CLASS__)->debugOutput('NETWORK-PACKAGE: No package has been declared, but ' . __METHOD__ . ' has been called!');
+                       self::createDebugInstance(__CLASS__)->debugOutput('NETWORK-PACKAGE[' . __LINE__ . ']: No package has been declared, but ' . __METHOD__ . ' has been called!');
                        return;
                } // END - if
 
                // Get the package
                $packageData = $this->getStackerInstance()->getNamed(self::STACKER_NAME_DECLARED);
 
+               // Assert on it
+               assert(isset($packageData[self::PACKAGE_DATA_RECIPIENT]));
+
+               // Try to deliver the package
                try {
                        // And try to send it
                        $this->deliverRawPackageData($packageData);
@@ -720,7 +737,7 @@ class NetworkPackage extends BaseHubSystem implements Deliverable, Receivable, R
                        $this->getStackerInstance()->popNamed(self::STACKER_NAME_DECLARED);
                } catch (InvalidStateException $e) {
                        // The state is not excepected (shall be 'connected')
-                       self::createDebugInstance(__CLASS__)->debugOutput('NETWORK-PACKAGE: Caught ' . $e->__toString() . ',message=' . $e->getMessage());
+                       self::createDebugInstance(__CLASS__)->debugOutput('NETWORK-PACKAGE[' . __LINE__ . ']: Caught ' . $e->__toString() . ',message=' . $e->getMessage());
 
                        // Mark the package with status failed
                        $this->changePackageStatus($packageData, self::STACKER_NAME_DECLARED, self::PACKAGE_STATUS_FAILED);
@@ -739,7 +756,7 @@ class NetworkPackage extends BaseHubSystem implements Deliverable, Receivable, R
                // Sanity check if we have packages waiting for delivery
                if (!$this->isPackageWaitingForDelivery()) {
                        // This is not fatal but should be avoided
-                       self::createDebugInstance(__CLASS__)->debugOutput('NETWORK-PACKAGE: No package is waiting for delivery, but ' . __METHOD__ . ' was called.');
+                       self::createDebugInstance(__CLASS__)->debugOutput('NETWORK-PACKAGE[' . __LINE__ . ']: No package is waiting for delivery, but ' . __METHOD__ . ' was called.');
                        return;
                } // END - if
 
@@ -754,7 +771,7 @@ class NetworkPackage extends BaseHubSystem implements Deliverable, Receivable, R
                        $this->getStackerInstance()->popNamed(self::STACKER_NAME_OUTGOING);
                } catch (InvalidSocketException $e) {
                        // Output exception message
-                       self::createDebugInstance(__CLASS__)->debugOutput('NETWORK-PACKAGE: Package was not delivered: ' . $e->getMessage());
+                       self::createDebugInstance(__CLASS__)->debugOutput('NETWORK-PACKAGE[' . __LINE__ . ']: Package was not delivered: ' . $e->getMessage());
 
                        // Mark package as failed
                        $this->changePackageStatus($packageData, self::STACKER_NAME_OUTGOING, self::PACKAGE_STATUS_FAILED);
@@ -814,7 +831,7 @@ class NetworkPackage extends BaseHubSystem implements Deliverable, Receivable, R
                } // END - if
 
                // Very noisy debug message:
-               /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('NETWORK-PACKAGE: Stacker size is ' . $this->getStackerInstance()->getStackCount(self::STACKER_NAME_DECODED_INCOMING) . ' entries.');
+               //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('NETWORK-PACKAGE[' . __LINE__ . ']: Stacker size is ' . $this->getStackerInstance()->getStackCount(self::STACKER_NAME_DECODED_INCOMING) . ' entries.');
 
                // "Pop" the next entry (the same array again) from the stack
                $decodedData = $this->getStackerInstance()->popNamed(self::STACKER_NAME_DECODED_INCOMING);
@@ -830,7 +847,7 @@ class NetworkPackage extends BaseHubSystem implements Deliverable, Receivable, R
                 * Also make sure the error code is SOCKET_ERROR_UNHANDLED because we
                 * only want to handle unhandled packages here.
                 */
-               /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('NETWORK-PACKAGE: errorCode=' . $decodedData[BaseRawDataHandler::PACKAGE_ERROR_CODE] . '(' . BaseRawDataHandler::SOCKET_ERROR_UNHANDLED . ')');
+               //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('NETWORK-PACKAGE[' . __LINE__ . ']: errorCode=' . $decodedData[BaseRawDataHandler::PACKAGE_ERROR_CODE] . '(' . BaseRawDataHandler::SOCKET_ERROR_UNHANDLED . ')');
                assert($decodedData[BaseRawDataHandler::PACKAGE_ERROR_CODE] == BaseRawDataHandler::SOCKET_ERROR_UNHANDLED);
 
                // Remove the last chunk SEPARATOR (because it is being added and we don't need it)
@@ -857,7 +874,7 @@ class NetworkPackage extends BaseHubSystem implements Deliverable, Receivable, R
                $decodedData = $handlerInstance->getNextRawData();
 
                // Very noisy debug message:
-               //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('NETWORK-PACKAGE: decodedData[' . gettype($decodedData) . ']=' . print_r($decodedData, true));
+               //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('NETWORK-PACKAGE[' . __LINE__ . ']: decodedData[' . gettype($decodedData) . ']=' . print_r($decodedData, true));
 
                // And push it on our stack
                $this->getStackerInstance()->pushNamed(self::STACKER_NAME_DECODED_INCOMING, $decodedData);
@@ -932,13 +949,13 @@ class NetworkPackage extends BaseHubSystem implements Deliverable, Receivable, R
         */
        public function accept (Visitor $visitorInstance) {
                // Debug message
-               //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('NETWORK-PACKAGE: ' . $visitorInstance->__toString() . ' has visited - START');
+               //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('NETWORK-PACKAGE[' . __LINE__ . ']: ' . $visitorInstance->__toString() . ' has visited - START');
 
                // Visit the package
                $visitorInstance->visitNetworkPackage($this);
 
                // Debug message
-               //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('NETWORK-PACKAGE: ' . $visitorInstance->__toString() . ' has visited - FINISHED');
+               //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('NETWORK-PACKAGE[' . __LINE__ . ']: ' . $visitorInstance->__toString() . ' has visited - FINISHED');
        }
 
        /**
@@ -951,7 +968,7 @@ class NetworkPackage extends BaseHubSystem implements Deliverable, Receivable, R
                $this->initStackers(true);
 
                // Debug message
-               /* DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('NETWORK-PACKAGE: All stacker have been re-initialized.');
+               //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('NETWORK-PACKAGE[' . __LINE__ . ']: All stacker have been re-initialized.');
        }
 
        /**
@@ -1118,12 +1135,15 @@ class NetworkPackage extends BaseHubSystem implements Deliverable, Receivable, R
                // Get it from the stacker, it is the full array with the processed message
                $messageArray = $this->getStackerInstance()->popNamed(self::STACKER_NAME_PROCESSED_MESSAGE);
 
-               // Create a handler instance from given message type
-               $handlerInstance = MessageTypeHandlerFactory::createMessageTypeHandlerInstance($messageArray[self::MESSAGE_ARRAY_TYPE]);
-
                // Add type for later easier handling
                $messageArray[self::MESSAGE_ARRAY_DATA][self::MESSAGE_ARRAY_TYPE] = $messageArray[self::MESSAGE_ARRAY_TYPE];
 
+               // Debug message
+               //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('NETWORK-PACKAGE[' . __LINE__ . ']: messageArray=' . print_r($messageArray, true));
+
+               // Create a handler instance from given message type
+               $handlerInstance = MessageTypeHandlerFactory::createMessageTypeHandlerInstance($messageArray[self::MESSAGE_ARRAY_TYPE]);
+
                // Handle message data
                $handlerInstance->handleMessageData($messageArray[self::MESSAGE_ARRAY_DATA], $this);
        }