X-Git-Url: https://git.mxchange.org/?a=blobdiff_plain;f=application%2Fhub%2Fmain%2Fpackage%2Fclass_NetworkPackage.php;h=0d1895047c500b738720f574d3c013ce8306b753;hb=fa1e85c6f610356bc1b4f7b01a57acce6741782f;hp=186f5de99f1ad0728b06c32201fc33b55cb08d49;hpb=5f7bf211c7d41a1d788085b83ee851a78e937e6c;p=hub.git diff --git a/application/hub/main/package/class_NetworkPackage.php b/application/hub/main/package/class_NetworkPackage.php index 186f5de99..0d1895047 100644 --- a/application/hub/main/package/class_NetworkPackage.php +++ b/application/hub/main/package/class_NetworkPackage.php @@ -208,13 +208,43 @@ class NetworkPackage extends BaseHubSystem implements Deliverable, Receivable, R const STACKER_NAME_PROCESSED_MESSAGE = 'package_processed_message'; /************************************************************************** - * Stacker for other/internal purposes * + * Stacker for raw data handling * **************************************************************************/ /** - * Stacker name for "back-buffered" packages + * Stacker for outgoing data stream */ - const STACKER_NAME_BACK_BUFFER = 'package_backbuffer'; + const STACKER_NAME_OUTGOING_STREAM = 'outgoing_stream'; + + /** + * Array index for final hash + */ + const RAW_FINAL_HASH_INDEX = 'hash'; + + /** + * Array index for encoded data + */ + const RAW_ENCODED_DATA_INDEX = 'data'; + + /** + * Array index for sent bytes + */ + const RAW_SENT_BYTES_INDEX = 'sent'; + + /** + * Array index for socket resource + */ + const RAW_SOCKET_INDEX = 'socket'; + + /** + * Array index for buffer size + */ + const RAW_BUFFER_SIZE_INDEX = 'buffer'; + + /** + * Array index for diff between buffer and sent bytes + */ + const RAW_DIFF_INDEX = 'diff'; /************************************************************************** * Protocol names * @@ -250,10 +280,10 @@ class NetworkPackage extends BaseHubSystem implements Deliverable, Receivable, R * which have no recipient address and stamp... ;-) This stacker will * also be used for incoming raw data to handle it. */ - $stackerInstance = ObjectFactory::createObjectByConfiguredName('network_package_stacker_class'); + $stackInstance = ObjectFactory::createObjectByConfiguredName('network_package_stacker_class'); // At last, set it in this class - $packageInstance->setStackerInstance($stackerInstance); + $packageInstance->setStackInstance($stackInstance); // Init all stacker $packageInstance->initStacks(); @@ -282,7 +312,7 @@ class NetworkPackage extends BaseHubSystem implements Deliverable, Receivable, R */ protected function initStacks ($forceReInit = FALSE) { // Initialize all - $this->getStackerInstance()->initStacks(array( + $this->getStackInstance()->initStacks(array( self::STACKER_NAME_UNDECLARED, self::STACKER_NAME_DECLARED, self::STACKER_NAME_OUTGOING, @@ -291,7 +321,7 @@ class NetworkPackage extends BaseHubSystem implements Deliverable, Receivable, R self::STACKER_NAME_DECODED_CHUNKED, self::STACKER_NAME_NEW_MESSAGE, self::STACKER_NAME_PROCESSED_MESSAGE, - self::STACKER_NAME_BACK_BUFFER + self::STACKER_NAME_OUTGOING_STREAM ), $forceReInit); } @@ -303,7 +333,7 @@ class NetworkPackage extends BaseHubSystem implements Deliverable, Receivable, R */ private function getHashFromContent ($content) { // Debug message - //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('NETWORK-PACKAGE[' . __LINE__ . ']: content[md5]=' . md5($content) . ',sender=' . $this->getSessionId() . ',compressor=' . $this->getCompressorInstance()->getCompressorExtension()); + //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('NETWORK-PACKAGE[' . __METHOD__ . ':' . __LINE__ . ']: content[md5]=' . md5($content) . ',sender=' . $this->getSessionId() . ',compressor=' . $this->getCompressorInstance()->getCompressorExtension()); // Create the hash // @TODO md5() is very weak, but it needs to be fast @@ -316,7 +346,7 @@ class NetworkPackage extends BaseHubSystem implements Deliverable, Receivable, R ); // Debug message - //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('NETWORK-PACKAGE[' . __LINE__ . ']: content[md5]=' . md5($content) . ',sender=' . $this->getSessionId() . ',hash=' . $hash . ',compressor=' . $this->getCompressorInstance()->getCompressorExtension()); + //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('NETWORK-PACKAGE[' . __METHOD__ . ':' . __LINE__ . ']: content[md5]=' . md5($content) . ',sender=' . $this->getSessionId() . ',hash=' . $hash . ',compressor=' . $this->getCompressorInstance()->getCompressorExtension()); // And return it return $hash; @@ -350,13 +380,13 @@ class NetworkPackage extends BaseHubSystem implements Deliverable, Receivable, R */ private function changePackageStatus (array $packageData, $stackerName, $newStatus) { // Skip this for empty stacks - if ($this->getStackerInstance()->isStackEmpty($stackerName)) { + if ($this->getStackInstance()->isStackEmpty($stackerName)) { // This avoids an exception after all packages has failed return; } // END - if // Pop the entry (it should be it) - $nextData = $this->getStackerInstance()->popNamed($stackerName); + $nextData = $this->getStackInstance()->popNamed($stackerName); // Compare both signatures assert($nextData[self::PACKAGE_DATA_SIGNATURE] == $packageData[self::PACKAGE_DATA_SIGNATURE]); @@ -365,7 +395,7 @@ class NetworkPackage extends BaseHubSystem implements Deliverable, Receivable, R $packageData[self::PACKAGE_DATA_STATUS] = $newStatus; // And push it again - $this->getStackerInstance()->pushNamed($stackerName, $packageData); + $this->getStackInstance()->pushNamed($stackerName, $packageData); } /** @@ -377,7 +407,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[' . __LINE__ . ']: content[md5]=' . md5($decodedContent[self::PACKAGE_CONTENT_MESSAGE]) . ',sender=' . $sessionId . ',compressor=' . $decodedContent[self::PACKAGE_CONTENT_EXTENSION]); + //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('NETWORK-PACKAGE[' . __METHOD__ . ':' . __LINE__ . ']: content[md5]=' . md5($decodedContent[self::PACKAGE_CONTENT_MESSAGE]) . ',sender=' . $sessionId . ',compressor=' . $decodedContent[self::PACKAGE_CONTENT_EXTENSION]); // Create the hash // @TODO md5() is very weak, but it needs to be fast @@ -398,7 +428,7 @@ class NetworkPackage extends BaseHubSystem implements Deliverable, Receivable, R /////////////////////////////////////////////////////////////////////////// /** - * Delivers the given raw package data. + * Declares the given raw package data by discovering recipients * * @param $packageData Raw package data in an array * @return void @@ -430,16 +460,16 @@ class NetworkPackage extends BaseHubSystem implements Deliverable, Receivable, R $currentRecipient = $iteratorInstance->current(); // Debug message - //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('NETWORK-PACKAGE[' . __LINE__ . ']: Setting recipient to ' . $currentRecipient . ',previous=' . $packageData[self::PACKAGE_DATA_RECIPIENT]); + //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('NETWORK-PACKAGE[' . __METHOD__ . ':' . __LINE__ . ']: Setting recipient to ' . $currentRecipient . ',previous=' . $packageData[self::PACKAGE_DATA_RECIPIENT]); // Set the recipient $packageData[self::PACKAGE_DATA_RECIPIENT] = $currentRecipient; - // And enqueue it to the writer class - $this->getStackerInstance()->pushNamed(self::STACKER_NAME_DECLARED, $packageData); + // Push the declared package to the next stack. + $this->getStackInstance()->pushNamed(self::STACKER_NAME_DECLARED, $packageData); // Debug message - //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('NETWORK-PACKAGE[' . __LINE__ . ']: Package declared for recipient ' . $currentRecipient); + //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('NETWORK-PACKAGE[' . __METHOD__ . ':' . __LINE__ . ']: Package declared for recipient ' . $currentRecipient); // Skip to next entry $iteratorInstance->next(); @@ -481,47 +511,50 @@ 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[' . __LINE__ . ']: Reached line ' . __LINE__ . ' after discoverSocket() has been called.'); + //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('NETWORK-PACKAGE[' . __METHOD__ . ':' . __LINE__ . ']: Reached line ' . __LINE__ . ' after discoverSocket() has been called.'); - // We have to put this socket in our registry, so get an instance + // Debug message + //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('NETWORK-PACKAGE[' . __METHOD__ . ':' . __LINE__ . ']: stateInstance=' . $helperInstance->getStateInstance()); + //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('NETWORK-PACKAGE[' . __METHOD__ . ':' . __LINE__ . ']: Reached line ' . __LINE__ . ' before isSocketRegistered() has been called.'); + + // The socket needs to be put in a special registry that can handle such data $registryInstance = SocketRegistryFactory::createSocketRegistryInstance(); - // Get the listener from registry + // Get the connection helper from registry $helperInstance = Registry::getRegistry()->getInstance('connection'); - // Debug message - //* 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.'); + // And make sure it is valid + assert($helperInstance instanceof ConnectionHelper); // Is it not there? if ((is_resource($socketResource)) && (!$registryInstance->isSocketRegistered($helperInstance, $socketResource))) { // Debug message - //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('NETWORK-PACKAGE[' . __LINE__ . ']: Registering socket ' . $socketResource . ' ...'); + //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('NETWORK-PACKAGE[' . __METHOD__ . ':' . __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[' . __LINE__ . ']: Unexpected peer state ' . $helperInstance->getStateInstance()->__toString() . ' detected.'); + self::createDebugInstance(__CLASS__)->debugOutput('NETWORK-PACKAGE[' . __METHOD__ . ':' . __LINE__ . ']: Unexpected peer state ' . $helperInstance->getStateInstance()->__toString() . ' detected.'); // Shutdown the socket $this->shutdownSocket($socketResource); } // Debug message - //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('NETWORK-PACKAGE[' . __LINE__ . ']: Reached line ' . __LINE__ . ' after isSocketRegistered() has been called.'); + //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('NETWORK-PACKAGE[' . __METHOD__ . ':' . __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[' . __LINE__ . ']: Reached line ' . __LINE__ . ' after validatePeerStateConnected() has been called.'); + //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('NETWORK-PACKAGE[' . __METHOD__ . ':' . __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); + $this->getStackInstance()->pushNamed(self::STACKER_NAME_OUTGOING, $packageData); // Debug message - //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('NETWORK-PACKAGE[' . __LINE__ . ']: Reached line ' . __LINE__ . ' after pushNamed() has been called.'); + //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('NETWORK-PACKAGE[' . __METHOD__ . ':' . __LINE__ . ']: Reached line ' . __LINE__ . ' after pushNamed() has been called.'); } /** @@ -545,10 +578,7 @@ class NetworkPackage extends BaseHubSystem implements Deliverable, Receivable, R } // END - if // Sent out package data - $sentBytes = $helperInstance->sendRawPackageData($packageData); - - // Remember unsent raw bytes in back-buffer, if any - $this->storeUnsentBytesInBackBuffer($packageData, $sentBytes); + $helperInstance->sendRawPackageData($packageData); } /** @@ -595,10 +625,12 @@ class NetworkPackage extends BaseHubSystem implements Deliverable, Receivable, R * stack. * * @param $helperInstance An instance of a Helper class - * @param $protocol Name of used protocol (TCP/UDP) * @return void */ - public function enqueueRawDataFromTemplate (Helper $helperInstance, $protocolName) { + public function enqueueRawDataFromTemplate (Helper $helperInstance) { + // Get protocol instance for recipient + $protocolInstance = ProtocolHandlerFactory::createProtocolFromRecipientHelper($helperInstance); + // Get the raw content ... $content = $helperInstance->getTemplateInstance()->getRawTemplateData(); //* DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('content(' . strlen($content) . ')=' . $content); @@ -625,10 +657,10 @@ class NetworkPackage extends BaseHubSystem implements Deliverable, Receivable, R ); // Now prepare the temporary array and push it on the 'undeclared' stack - $this->getStackerInstance()->pushNamed(self::STACKER_NAME_UNDECLARED, array( + $this->getStackInstance()->pushNamed(self::STACKER_NAME_UNDECLARED, array( self::PACKAGE_DATA_SENDER => $this->getSessionId(), self::PACKAGE_DATA_RECIPIENT => $helperInstance->getRecipientType(), - self::PACKAGE_DATA_PROTOCOL => $protocolName, + self::PACKAGE_DATA_PROTOCOL => $protocolInstance->getProtocolName(), self::PACKAGE_DATA_CONTENT => $packageContent, self::PACKAGE_DATA_STATUS => self::PACKAGE_STATUS_NEW, self::PACKAGE_DATA_SIGNATURE => $this->generatePackageSignature($packageContent, $this->getSessionId()) @@ -642,7 +674,7 @@ class NetworkPackage extends BaseHubSystem implements Deliverable, Receivable, R */ public function isPackageEnqueued () { // Check whether the stacker is not empty - $isEnqueued = (($this->getStackerInstance()->isStackInitialized(self::STACKER_NAME_UNDECLARED)) && (!$this->getStackerInstance()->isStackEmpty(self::STACKER_NAME_UNDECLARED))); + $isEnqueued = (($this->getStackInstance()->isStackInitialized(self::STACKER_NAME_UNDECLARED)) && (!$this->getStackInstance()->isStackEmpty(self::STACKER_NAME_UNDECLARED))); // Return the result return $isEnqueued; @@ -655,7 +687,7 @@ class NetworkPackage extends BaseHubSystem implements Deliverable, Receivable, R */ public function isPackageDeclared () { // Check whether the stacker is not empty - $isDeclared = (($this->getStackerInstance()->isStackInitialized(self::STACKER_NAME_DECLARED)) && (!$this->getStackerInstance()->isStackEmpty(self::STACKER_NAME_DECLARED))); + $isDeclared = (($this->getStackInstance()->isStackInitialized(self::STACKER_NAME_DECLARED)) && (!$this->getStackInstance()->isStackEmpty(self::STACKER_NAME_DECLARED))); // Return the result return $isDeclared; @@ -668,12 +700,25 @@ class NetworkPackage extends BaseHubSystem implements Deliverable, Receivable, R */ public function isPackageWaitingForDelivery () { // Check whether the stacker is not empty - $isWaitingDelivery = (($this->getStackerInstance()->isStackInitialized(self::STACKER_NAME_OUTGOING)) && (!$this->getStackerInstance()->isStackEmpty(self::STACKER_NAME_OUTGOING))); + $isWaitingDelivery = (($this->getStackInstance()->isStackInitialized(self::STACKER_NAME_OUTGOING)) && (!$this->getStackInstance()->isStackEmpty(self::STACKER_NAME_OUTGOING))); // Return the result return $isWaitingDelivery; } + /** + * Checks whether encoded (raw) data is pending + * + * @return $isPending Whether encoded data is pending + */ + public function isEncodedDataPending () { + // Check whether the stacker is not empty + $isPending = (($this->getStackInstance()->isStackInitialized(self::STACKER_NAME_OUTGOING_STREAM)) && (!$this->getStackInstance()->isStackEmpty(self::STACKER_NAME_OUTGOING_STREAM))); + + // Return the result + return $isPending; + } + /** * Delivers an enqueued package to the stated destination. If a non-session * id is provided, recipient resolver is being asked (and instanced once). @@ -688,7 +733,7 @@ class NetworkPackage extends BaseHubSystem implements Deliverable, Receivable, R // Make sure this method isn't working if there is no package enqueued if (!$this->isPackageEnqueued()) { // This is not fatal but should be avoided - // @TODO Add some logging here + self::createDebugInstance(__CLASS__)->debugOutput('NETWORK-PACKAGE[' . __METHOD__ . ':' . __LINE__ . ']: No raw package data waiting declaration, but ' . __METHOD__ . ' has been called!'); return; } // END - if @@ -696,7 +741,7 @@ 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()->popNamed(self::STACKER_NAME_UNDECLARED); + $packageData = $this->getStackInstance()->popNamed(self::STACKER_NAME_UNDECLARED); // Declare the raw package data for delivery $this->declareRawPackageData($packageData); @@ -709,16 +754,16 @@ class NetworkPackage extends BaseHubSystem implements Deliverable, Receivable, R * * @return void */ - public function deliverDeclaredPackage () { + public function processDeclaredPackage () { // Sanity check if we have packages declared if (!$this->isPackageDeclared()) { // This is not fatal but should be avoided - self::createDebugInstance(__CLASS__)->debugOutput('NETWORK-PACKAGE[' . __LINE__ . ']: No package has been declared, but ' . __METHOD__ . ' has been called!'); + self::createDebugInstance(__CLASS__)->debugOutput('NETWORK-PACKAGE[' . __METHOD__ . ':' . __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); + $packageData = $this->getStackInstance()->getNamed(self::STACKER_NAME_DECLARED); // Assert on it assert(isset($packageData[self::PACKAGE_DATA_RECIPIENT])); @@ -729,10 +774,10 @@ class NetworkPackage extends BaseHubSystem implements Deliverable, Receivable, R $this->deliverRawPackageData($packageData); // And remove it finally - $this->getStackerInstance()->popNamed(self::STACKER_NAME_DECLARED); + $this->getStackInstance()->popNamed(self::STACKER_NAME_DECLARED); } catch (InvalidStateException $e) { // The state is not excepected (shall be 'connected') - self::createDebugInstance(__CLASS__)->debugOutput('NETWORK-PACKAGE[' . __LINE__ . ']: Caught ' . $e->__toString() . ',message=' . $e->getMessage()); + self::createDebugInstance(__CLASS__)->debugOutput('NETWORK-PACKAGE[' . __METHOD__ . ':' . __LINE__ . ']: Caught ' . $e->__toString() . ',message=' . $e->getMessage()); // Mark the package with status failed $this->changePackageStatus($packageData, self::STACKER_NAME_DECLARED, self::PACKAGE_STATUS_FAILED); @@ -745,34 +790,98 @@ class NetworkPackage extends BaseHubSystem implements Deliverable, Receivable, R * @return void */ public function sendWaitingPackage () { - // Send any waiting bytes in the back-buffer before sending a new package - $this->sendBackBufferBytes(); - // 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[' . __LINE__ . ']: No package is waiting for delivery, but ' . __METHOD__ . ' was called.'); + self::createDebugInstance(__CLASS__)->debugOutput('NETWORK-PACKAGE[' . __METHOD__ . ':' . __LINE__ . ']: No package is waiting for delivery, but ' . __METHOD__ . ' was called.'); return; } // END - if // Get the package - $packageData = $this->getStackerInstance()->getNamed(self::STACKER_NAME_OUTGOING); + $packageData = $this->getStackInstance()->getNamed(self::STACKER_NAME_OUTGOING); try { // Now try to send it $this->sendOutgoingRawPackageData($packageData); // And remove it finally - $this->getStackerInstance()->popNamed(self::STACKER_NAME_OUTGOING); + $this->getStackInstance()->popNamed(self::STACKER_NAME_OUTGOING); } catch (InvalidSocketException $e) { // Output exception message - self::createDebugInstance(__CLASS__)->debugOutput('NETWORK-PACKAGE[' . __LINE__ . ']: Package was not delivered: ' . $e->getMessage()); + self::createDebugInstance(__CLASS__)->debugOutput('NETWORK-PACKAGE[' . __METHOD__ . ':' . __LINE__ . ']: Package was not delivered: ' . $e->getMessage()); // Mark package as failed $this->changePackageStatus($packageData, self::STACKER_NAME_OUTGOING, self::PACKAGE_STATUS_FAILED); } } + /** + * Sends out encoded data to a socket + * + * @return void + */ + public function sendEncodedData () { + // Make sure there is pending encoded data + assert($this->isEncodedDataPending()); + + // Pop current data from stack + $encodedDataArray = $this->getStackInstance()->popNamed(self::STACKER_NAME_OUTGOING_STREAM); + + // Init in this round sent bytes + $sentBytes = 0; + + // Assert on socket + assert(is_resource($encodedDataArray[self::RAW_SOCKET_INDEX])); + + // And deliver it + //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('CONNECTION-HELPER[' . __METHOD__ . ':' . __LINE__ . ']: Sending out ' . strlen($encodedDataArray[self::RAW_ENCODED_DATA_INDEX]) . ' bytes,rawBufferSize=' . $encodedDataArray[self::RAW_BUFFER_SIZE_INDEX] . ',diff=' . $encodedDataArray[self::RAW_DIFF_INDEX]); + if ($encodedDataArray[self::RAW_DIFF_INDEX] >= 0) { + // Send all out (encodedData is smaller than or equal buffer size) + //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('CONNECTION-HELPER[' . __METHOD__ . ':' . __LINE__ . ']: MD5=' . md5(substr($encodedDataArray[self::RAW_ENCODED_DATA_INDEX], 0, ($encodedDataArray[self::RAW_BUFFER_SIZE_INDEX] - $encodedDataArray[self::RAW_DIFF_INDEX])))); + $sentBytes = @socket_write($encodedDataArray[self::RAW_SOCKET_INDEX], $encodedDataArray[self::RAW_ENCODED_DATA_INDEX], ($encodedDataArray[self::RAW_BUFFER_SIZE_INDEX] - $encodedDataArray[self::RAW_DIFF_INDEX])); + } else { + // Send buffer size out + //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('CONNECTION-HELPER[' . __METHOD__ . ':' . __LINE__ . ']: MD5=' . md5(substr($encodedDataArray[self::RAW_ENCODED_DATA_INDEX], 0, $encodedDataArray[self::RAW_BUFFER_SIZE_INDEX]))); + $sentBytes = @socket_write($encodedDataArray[self::RAW_SOCKET_INDEX], $encodedDataArray[self::RAW_ENCODED_DATA_INDEX], $encodedDataArray[self::RAW_BUFFER_SIZE_INDEX]); + } + + // If there was an error, we don't continue here + if ($sentBytes === FALSE) { + // Handle the error with a faked recipientData array + $this->handleSocketError(__METHOD__, __LINE__, $encodedDataArray[self::RAW_SOCKET_INDEX], array('0.0.0.0', '0')); + + // And throw it + throw new InvalidSocketException(array($this, $encodedDataArray[self::RAW_SOCKET_INDEX], $socketError, $errorMessage), BaseListener::EXCEPTION_INVALID_SOCKET); + } elseif (($sentBytes === 0) && (strlen($encodedDataArray[self::RAW_ENCODED_DATA_INDEX]) > 0)) { + // Nothing sent means we are done + //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('CONNECTION-HELPER[' . __METHOD__ . ':' . __LINE__ . ']: All sent! (LINE=' . __LINE__ . ')'); + return; + } else { + // The difference between sent bytes and length of raw data should not go below zero + assert((strlen($encodedDataArray[self::RAW_ENCODED_DATA_INDEX]) - $sentBytes) >= 0); + + // Add total sent bytes + $encodedDataArray[self::RAW_SENT_BYTES_INDEX] += $sentBytes; + + // Cut out the last unsent bytes + //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('CONNECTION-HELPER[' . __METHOD__ . ':' . __LINE__ . ']: Sent out ' . $sentBytes . ' of ' . strlen($encodedDataArray[self::RAW_ENCODED_DATA_INDEX]) . ' bytes ...'); + $encodedDataArray[self::RAW_ENCODED_DATA_INDEX] = substr($encodedDataArray[self::RAW_ENCODED_DATA_INDEX], $sentBytes); + + // Calculate difference again + $encodedDataArray[self::RAW_DIFF_INDEX] = $encodedDataArray[self::RAW_BUFFER_SIZE_INDEX] - strlen($encodedDataArray[self::RAW_ENCODED_DATA_INDEX]); + + // Can we abort? + if (strlen($encodedDataArray[self::RAW_ENCODED_DATA_INDEX]) <= 0) { + // Abort here, all sent! + //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('CONNECTION-HELPER[' . __METHOD__ . ':' . __LINE__ . ']: All sent! (LINE=' . __LINE__ . ')'); + return; + } // END - if + } + + // Push array back in stack + $this->getStackInstance()->pushNamed(self::STACKER_NAME_OUTGOING_STREAM, $encodedDataArray); + } + /////////////////////////////////////////////////////////////////////////// // Receiving packages / raw data /////////////////////////////////////////////////////////////////////////// @@ -784,7 +893,7 @@ class NetworkPackage extends BaseHubSystem implements Deliverable, Receivable, R */ private function isRawDataPending () { // Just return whether the stack is not empty - $isPending = (!$this->getStackerInstance()->isStackEmpty(self::STACKER_NAME_DECODED_INCOMING)); + $isPending = (!$this->getStackInstance()->isStackEmpty(self::STACKER_NAME_DECODED_INCOMING)); // Return the status return $isPending; @@ -821,15 +930,15 @@ class NetworkPackage extends BaseHubSystem implements Deliverable, Receivable, R */ if (!$this->isRawDataPending()) { // This is not fatal but should be avoided - // @TODO Add some logging here + self::createDebugInstance(__CLASS__)->debugOutput('NETWORK-PACKAGE[' . __METHOD__ . ':' . __LINE__ . ']: No raw (decoded?) data is pending, but ' . __METHOD__ . ' has been called!'); return; } // END - if // Very noisy debug message: - //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('NETWORK-PACKAGE[' . __LINE__ . ']: Stacker size is ' . $this->getStackerInstance()->getStackCount(self::STACKER_NAME_DECODED_INCOMING) . ' entries.'); + //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('NETWORK-PACKAGE[' . __METHOD__ . ':' . __LINE__ . ']: Stacker size is ' . $this->getStackInstance()->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); + $decodedData = $this->getStackInstance()->popNamed(self::STACKER_NAME_DECODED_INCOMING); // Make sure both array elements are there assert( @@ -842,17 +951,18 @@ 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[' . __LINE__ . ']: errorCode=' . $decodedData[BaseRawDataHandler::PACKAGE_ERROR_CODE] . '(' . BaseRawDataHandler::SOCKET_ERROR_UNHANDLED . ')'); + //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('NETWORK-PACKAGE[' . __METHOD__ . ':' . __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) + // Remove the last chunk SEPARATOR (because there is no need for it) if (substr($decodedData[BaseRawDataHandler::PACKAGE_RAW_DATA], -1, 1) == PackageFragmenter::CHUNK_SEPARATOR) { // It is there and should be removed $decodedData[BaseRawDataHandler::PACKAGE_RAW_DATA] = substr($decodedData[BaseRawDataHandler::PACKAGE_RAW_DATA], 0, -1); } // END - if // This package is "handled" and can be pushed on the next stack - $this->getStackerInstance()->pushNamed(self::STACKER_NAME_DECODED_HANDLED, $decodedData); + //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('NETWORK-PACKAGE[' . __METHOD__ . ':' . __LINE__ . ']: Pushing ' . strlen($decodedData[BaseRawDataHandler::PACKAGE_RAW_DATA]) . ' bytes to stack ' . self::STACKER_NAME_DECODED_HANDLED . ' ...'); + $this->getStackInstance()->pushNamed(self::STACKER_NAME_DECODED_HANDLED, $decodedData); } /** @@ -869,10 +979,10 @@ class NetworkPackage extends BaseHubSystem implements Deliverable, Receivable, R $decodedData = $handlerInstance->getNextRawData(); // Very noisy debug message: - /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('NETWORK-PACKAGE[' . __LINE__ . ']: decodedData[' . gettype($decodedData) . ']=' . print_r($decodedData, TRUE)); + //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('NETWORK-PACKAGE[' . __METHOD__ . ':' . __LINE__ . ']: decodedData[' . gettype($decodedData) . ']=' . print_r($decodedData, TRUE)); // And push it on our stack - $this->getStackerInstance()->pushNamed(self::STACKER_NAME_DECODED_INCOMING, $decodedData); + $this->getStackInstance()->pushNamed(self::STACKER_NAME_DECODED_INCOMING, $decodedData); } /** @@ -882,7 +992,7 @@ class NetworkPackage extends BaseHubSystem implements Deliverable, Receivable, R */ public function isIncomingRawDataHandled () { // Determine if the stack is not empty - $isHandled = (!$this->getStackerInstance()->isStackEmpty(self::STACKER_NAME_DECODED_HANDLED)); + $isHandled = (!$this->getStackInstance()->isStackEmpty(self::STACKER_NAME_DECODED_HANDLED)); // Return it return $isHandled; @@ -901,6 +1011,19 @@ class NetworkPackage extends BaseHubSystem implements Deliverable, Receivable, R return $isHandled; } + /** + * Checks whether the assembler has multiple packages pending + * + * @return $isPending Whether the assembler has multiple packages pending + */ + public function ifMultipleMessagesPending () { + // Determine if the stack is not empty + $isPending = ($this->getAssemblerInstance()->ifMultipleMessagesPending()); + + // Return it + return $isPending; + } + /** * Handles the attached assemler's pending data queue to be finally * assembled to the raw package data back. @@ -912,6 +1035,16 @@ class NetworkPackage extends BaseHubSystem implements Deliverable, Receivable, R $this->getAssemblerInstance()->handlePendingData(); } + /** + * Handles multiple messages. + * + * @return void + */ + public function handleMultipleMessages () { + // Handle it + $this->getAssemblerInstance()->handleMultipleMessages(); + } + /** * Assembles incoming decoded data so it will become an abstract network * package again. The assembler does later do it's job by an other task, @@ -924,16 +1057,24 @@ class NetworkPackage extends BaseHubSystem implements Deliverable, Receivable, R assert($this->isIncomingRawDataHandled()); // Get current package content (an array with two elements; see handleIncomingDecodedData() for details) - $packageContent = $this->getStackerInstance()->getNamed(self::STACKER_NAME_DECODED_HANDLED); + $packageContent = $this->getStackInstance()->getNamed(self::STACKER_NAME_DECODED_HANDLED); + + // Assert on some elements + assert( + (is_array($packageContent)) && + (isset($packageContent[BaseRawDataHandler::PACKAGE_RAW_DATA])) && + (isset($packageContent[BaseRawDataHandler::PACKAGE_ERROR_CODE])) + ); // Start assembling the raw package data array by chunking it $this->getAssemblerInstance()->chunkPackageContent($packageContent); // Remove the package from 'handled_decoded' stack ... - $this->getStackerInstance()->popNamed(self::STACKER_NAME_DECODED_HANDLED); + $this->getStackInstance()->popNamed(self::STACKER_NAME_DECODED_HANDLED); // ... and push it on the 'chunked' stacker - $this->getStackerInstance()->pushNamed(self::STACKER_NAME_DECODED_CHUNKED, $packageContent); + //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('NETWORK-PACKAGE[' . __METHOD__ . ':' . __LINE__ . ']: Pushing ' . strlen($packageContent[BaseRawDataHandler::PACKAGE_RAW_DATA]) . ' bytes on stack ' . self::STACKER_NAME_DECODED_CHUNKED . ',packageContent=' . print_r($packageContent, TRUE)); + $this->getStackInstance()->pushNamed(self::STACKER_NAME_DECODED_CHUNKED, $packageContent); } /** @@ -944,13 +1085,16 @@ class NetworkPackage extends BaseHubSystem implements Deliverable, Receivable, R */ public function accept (Visitor $visitorInstance) { // Debug message - //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('NETWORK-PACKAGE[' . __LINE__ . ']: ' . $visitorInstance->__toString() . ' has visited - START'); + /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('NETWORK-PACKAGE[' . __METHOD__ . ':' . __LINE__ . ']: ' . $visitorInstance->__toString() . ' has visited - START'); // Visit the package $visitorInstance->visitNetworkPackage($this); + // Then visit the assembler to handle multiple packages + $this->getAssemblerInstance()->accept($visitorInstance); + // Debug message - //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('NETWORK-PACKAGE[' . __LINE__ . ']: ' . $visitorInstance->__toString() . ' has visited - FINISHED'); + /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('NETWORK-PACKAGE[' . __METHOD__ . ':' . __LINE__ . ']: ' . $visitorInstance->__toString() . ' has visited - FINISHED'); } /** @@ -963,7 +1107,7 @@ class NetworkPackage extends BaseHubSystem implements Deliverable, Receivable, R $this->initStacks(TRUE); // Debug message - //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('NETWORK-PACKAGE[' . __LINE__ . ']: All stacker have been re-initialized.'); + //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('NETWORK-PACKAGE[' . __METHOD__ . ':' . __LINE__ . ']: All stacker have been re-initialized.'); } /** @@ -976,7 +1120,7 @@ class NetworkPackage extends BaseHubSystem implements Deliverable, Receivable, R */ public function removeFirstFailedPackage () { // Get the package again - $packageData = $this->getStackerInstance()->getNamed(self::STACKER_NAME_DECLARED); + $packageData = $this->getStackInstance()->getNamed(self::STACKER_NAME_DECLARED); // Is the package status 'failed'? if ($packageData[self::PACKAGE_DATA_STATUS] != self::PACKAGE_STATUS_FAILED) { @@ -985,7 +1129,7 @@ class NetworkPackage extends BaseHubSystem implements Deliverable, Receivable, R } // END - if // Remove this entry - $this->getStackerInstance()->popNamed(self::STACKER_NAME_DECLARED); + $this->getStackInstance()->popNamed(self::STACKER_NAME_DECLARED); } /** @@ -1072,7 +1216,7 @@ class NetworkPackage extends BaseHubSystem implements Deliverable, Receivable, R $decodedContent[self::PACKAGE_CONTENT_MESSAGE] = $this->getCompressorInstance()->decompressStream($decodedContent[self::PACKAGE_CONTENT_MESSAGE]); // And push it on the next stack - $this->getStackerInstance()->pushNamed(self::STACKER_NAME_NEW_MESSAGE, $decodedContent); + $this->getStackInstance()->pushNamed(self::STACKER_NAME_NEW_MESSAGE, $decodedContent); } /** @@ -1082,7 +1226,7 @@ class NetworkPackage extends BaseHubSystem implements Deliverable, Receivable, R */ public function isNewMessageArrived () { // Determine if the stack is not empty - $hasArrived = (!$this->getStackerInstance()->isStackEmpty(self::STACKER_NAME_NEW_MESSAGE)); + $hasArrived = (!$this->getStackInstance()->isStackEmpty(self::STACKER_NAME_NEW_MESSAGE)); // Return it return $hasArrived; @@ -1096,7 +1240,7 @@ class NetworkPackage extends BaseHubSystem implements Deliverable, Receivable, R */ public function handleNewlyArrivedMessage () { // Get it from the stacker, it is the full array with the decoded message - $decodedContent = $this->getStackerInstance()->popNamed(self::STACKER_NAME_NEW_MESSAGE); + $decodedContent = $this->getStackInstance()->popNamed(self::STACKER_NAME_NEW_MESSAGE); // Now get a filter chain back from factory with given tags array $chainInstance = PackageFilterChainFactory::createChainByTagsArray($decodedContent[self::PACKAGE_CONTENT_TAGS]); @@ -1115,7 +1259,7 @@ class NetworkPackage extends BaseHubSystem implements Deliverable, Receivable, R */ public function isProcessedMessagePending () { // Check it - $isPending = (!$this->getStackerInstance()->isStackEmpty(self::STACKER_NAME_PROCESSED_MESSAGE)); + $isPending = (!$this->getStackInstance()->isStackEmpty(self::STACKER_NAME_PROCESSED_MESSAGE)); // Return it return $isPending; @@ -1128,13 +1272,13 @@ class NetworkPackage extends BaseHubSystem implements Deliverable, Receivable, R */ public function handleProcessedMessage () { // Get it from the stacker, it is the full array with the processed message - $messageArray = $this->getStackerInstance()->popNamed(self::STACKER_NAME_PROCESSED_MESSAGE); + $messageArray = $this->getStackInstance()->popNamed(self::STACKER_NAME_PROCESSED_MESSAGE); // 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)); + //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('NETWORK-PACKAGE[' . __METHOD__ . ':' . __LINE__ . ']: messageArray=' . print_r($messageArray, TRUE)); // Create a handler instance from given message type $handlerInstance = MessageTypeHandlerFactory::createMessageTypeHandlerInstance($messageArray[self::MESSAGE_ARRAY_TYPE]);