]> git.mxchange.org Git - hub.git/blob - application/hub/main/package/assembler/class_PackageAssembler.php
Added incomplete handling of multiple messages.
[hub.git] / application / hub / main / package / assembler / class_PackageAssembler.php
1 <?php
2 /**
3  * A PackageAssembler class to assemble a package content stream fragemented
4  * by PackageFragmenter back to a raw package data array.
5  *
6  * @author              Roland Haeder <webmaster@shipsimu.org>
7  * @version             0.0.0
8  * @copyright   Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2012 Hub Developer Team
9  * @license             GNU GPL 3.0 or any newer version
10  * @link                http://www.shipsimu.org
11  *
12  * This program is free software: you can redistribute it and/or modify
13  * it under the terms of the GNU General Public License as published by
14  * the Free Software Foundation, either version 3 of the License, or
15  * (at your option) any later version.
16  *
17  * This program is distributed in the hope that it will be useful,
18  * but WITHOUT ANY WARRANTY; without even the implied warranty of
19  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
20  * GNU General Public License for more details.
21  *
22  * You should have received a copy of the GNU General Public License
23  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
24  */
25 class PackageAssembler extends BaseHubSystem implements Assembler, Registerable {
26         /**
27          * Pending data
28          */
29         private $pendingData = '';
30
31         /**
32          * Private call-back methods
33          */
34         private $callbacks = array();
35
36         /**
37          * Protected constructor
38          *
39          * @return      void
40          */
41         protected function __construct () {
42                 // Call parent constructor
43                 parent::__construct(__CLASS__);
44         }
45
46         /**
47          * Creates an instance of this class
48          *
49          * @param       $packageInstance        An instance of a Receivable class
50          * @return      $assemblerInstance      An instance of an Assembler class
51          */
52         public static final function createPackageAssembler (Receivable $packageInstance) {
53                 // Get new instance
54                 $assemblerInstance = new PackageAssembler();
55
56                 // Set package instance here
57                 $assemblerInstance->setPackageInstance($packageInstance);
58
59                 // Create an instance of a raw data input stream
60                 $streamInstance = ObjectFactory::createObjectByConfiguredName('node_raw_data_input_stream_class');
61
62                 // And set it
63                 $assemblerInstance->setInputStreamInstance($streamInstance);
64
65                 // Now get a chunk handler instance
66                 $handlerInstance = ChunkHandlerFactory::createChunkHandlerInstance();
67
68                 // Set handler instance
69                 $assemblerInstance->setHandlerInstance($handlerInstance);
70
71                 // Get stacker instance
72                 $stackerInstance = ObjectFactory::createObjectByConfiguredName('multiple_message_stacker_class');
73
74                 // And add it
75                 $assemblerInstance->setStackerInstance($stackerInstance);
76
77                 // Return the prepared instance
78                 return $assemblerInstance;
79         }
80
81         /**
82          * Checks whether the input buffer (stacker to be more preceise) is empty.
83          *
84          * @return      $isInputBufferEmpty             Whether the input buffer is empty
85          */
86         private function ifInputBufferIsEmpty () {
87                 // Check it
88                 $isInputBufferEmpty = $this->getPackageInstance()->getStackerInstance()->isStackEmpty(NetworkPackage::STACKER_NAME_DECODED_HANDLED);
89
90                 // Debug message
91                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('PACKAGE-ASSEMBLER[' . __METHOD__ . ':' . __LINE__ . ': isInputBufferEmpty=' . intval($isInputBufferEmpty));
92
93                 // Return it
94                 return $isInputBufferEmpty;
95         }
96
97         /**
98          * Checks whether given package content is completed (start/end markers are found)
99          *
100          * @param       $packageContent         An array with two elements: 'raw_data' and 'error_code'
101          * @return      $isCompleted            Whether the given package content is completed
102          */
103         private function isPackageContentCompleted (array $packageContent) {
104                 // Check both
105                 $isCompleted = $this->ifStartEndMarkersSet($packageContent[BaseRawDataHandler::PACKAGE_RAW_DATA]);
106
107                 // Return status
108                 return $isCompleted;
109         }
110
111         /**
112          * Assembles the content from $packageContent. This method does only
113          * initialize the whole process by creating a call-back which will then
114          * itself (99.9% of all cases) "explode" the decoded data stream and add
115          * it to a chunk assembler queue.
116          *
117          * If the call-back method or this would attempt to assemble the package
118          * chunks and (maybe) re-request some chunks from the sender, this would
119          * take to much time and therefore slow down this node again.
120          *
121          * @param       $packageContent         An array with two elements: 'raw_data' and 'error_code'
122          * @return      void
123          * @throws      UnsupportedPackageCodeHandlerException  If the package code handler is not implemented
124          */
125         public function chunkPackageContent (array $packageContent) {
126                 // Validate the package content array again
127                 assert(
128                         (isset($packageContent[BaseRawDataHandler::PACKAGE_RAW_DATA])) &&
129                         (isset($packageContent[BaseRawDataHandler::PACKAGE_ERROR_CODE]))
130                 );
131
132                 // Construct call-back name from package error code
133                 $this->callbacks[$packageContent[BaseRawDataHandler::PACKAGE_ERROR_CODE]] = 'handlePackageBy' . $this->convertToClassName($packageContent[BaseRawDataHandler::PACKAGE_ERROR_CODE]);
134
135                 // Abort if the call-back method is not there
136                 if (!method_exists($this, $this->callbacks[$packageContent[BaseRawDataHandler::PACKAGE_ERROR_CODE]])) {
137                         // Throw an exception
138                         throw new UnsupportedPackageCodeHandlerException(array($this, $this->callbacks[$packageContent[BaseRawDataHandler::PACKAGE_ERROR_CODE]], $packageContent), BaseListener::EXCEPTION_UNSUPPORTED_PACKAGE_CODE_HANDLER);
139                 } // END - if
140
141                 // Call it back
142                 call_user_func(array($this, $this->callbacks[$packageContent[BaseRawDataHandler::PACKAGE_ERROR_CODE]]), $packageContent);
143         }
144
145         /**************************************************************************
146          *                 Call-back methods for above method                     *
147          **************************************************************************/
148
149         /**
150          * Call-back handler to handle unhandled package data. This method
151          * "explodes" the string with the chunk separator from PackageFragmenter
152          * class, does some low checks on it and feeds it into another queue for
153          * verification and re-request for bad chunks.
154          *
155          * @param       $packageContent         An array with two elements: 'raw_data' and 'error_code'
156          * @return      void
157          */
158         private function handlePackageByUnhandledPackage (array $packageContent) {
159                 // Debug message
160                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('PACKAGE-ASSEMBLER[' . __METHOD__ . ':' . __LINE__ . ']: packageData[' . BaseRawDataHandler::PACKAGE_RAW_DATA . ']=' . $packageContent[BaseRawDataHandler::PACKAGE_RAW_DATA]);
161
162                 // Check for some conditions
163                 if ((!$this->ifInputBufferIsEmpty()) || (!$this->isPackageContentCompleted($packageContent))) {
164                         // Last chunk is not valid, so wait for more
165                         $this->pendingData .= $packageContent[BaseRawDataHandler::PACKAGE_RAW_DATA];
166
167                         // Debug message
168                         //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('PACKAGE-ASSEMBLER[' . __METHOD__ . ':' . __LINE__ . ': Partial data received. Waiting for more ... ( ' . strlen($packageContent[BaseRawDataHandler::PACKAGE_RAW_DATA]) . ' bytes)');
169                 } else {
170                         // Debug message
171                         /* DEBUG */ self::createDebugInstance(__CLASS__)->debugOutput('PACKAGE-ASSEMBLER[' . __METHOD__ . ':' . __LINE__ . ': packageContent=' . print_r($packageContent, TRUE) . ',chunks='.print_r($chunks, TRUE));
172                 }
173         }
174
175         /**
176          * Checks whether the assembler's pending data is empty which means it has
177          * no pending data left for handling ... ;-)
178          *
179          * @return      $ifPendingDataIsEmpty   Whether pending data is empty
180          */
181         public function isPendingDataEmpty () {
182                 // A simbple check
183                 $ifPendingDataIsEmpty = empty($this->pendingData);
184
185                 // Return it
186                 return $ifPendingDataIsEmpty;
187         }
188
189         /**
190          * Handles the assembler's pending data
191          *
192          * @return      void
193          */
194         public function handlePendingData () {
195                 // Debug output
196                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('PACKAGE-ASSEMBLER[' . __METHOD__ . ':' . __LINE__ . ': Going to decode ' . strlen($this->pendingData) . ' Bytes of pending data. pendingData=' . $this->pendingData);
197
198                 // Assert on condition
199                 assert(!$this->isPendingDataEmpty());
200
201                 // No markers set?
202                 if (!$this->ifStartEndMarkersSet($this->pendingData)) {
203                         // This will cause an assertition in next call, so simply wait for more data
204                         /* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('PACKAGE-ASSEMBLER[' . __METHOD__ . ':' . __LINE__ . ': Pending data of ' . strlen($this->pendingData) . ' Bytes are incomplete, waiting for more ...');
205                         return;
206                 } elseif (substr_count($this->pendingData, BaseRawDataHandler::STREAM_START_MARKER) > 1) {
207                         /*
208                          * Multiple messages found, so split off first message as the input
209                          * stream can only handle one message per time.
210                          */
211                 }
212
213                 // Init fake array
214                 $packageContent = array(
215                         BaseRawDataHandler::PACKAGE_RAW_DATA   => $this->getInputStreamInstance()->streamData($this->pendingData),
216                         BaseRawDataHandler::PACKAGE_ERROR_CODE => BaseRawDataHandler::SOCKET_ERROR_UNHANDLED
217                 );
218
219                 // Clear pending data
220                 $this->pendingData = '';
221
222                 // Debug message
223                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('PACKAGE-ASSEMBLER[' . __METHOD__ . ':' . __LINE__ . ': Last block of partial data received. A total of ' . strlen($packageContent[BaseRawDataHandler::PACKAGE_RAW_DATA]) . ' bytes has been received.');
224
225                 // Make sure last CHUNK_SEPARATOR is not there
226                 if (substr($packageContent[BaseRawDataHandler::PACKAGE_RAW_DATA], -1, 1) == PackageFragmenter::CHUNK_SEPARATOR) {
227                         // Remove it
228                         $packageContent[BaseRawDataHandler::PACKAGE_RAW_DATA] = substr($packageContent[BaseRawDataHandler::PACKAGE_RAW_DATA], 0, -1);
229                 } // END - if
230
231                 /*
232                  * "explode" the string from 'raw_data' with chunk separator to
233                  * get an array of chunks. These chunks must then be verified by
234                  * their checksums. Also the final chunk must be handled.
235                  */
236                 $chunks = explode(PackageFragmenter::CHUNK_SEPARATOR, $packageContent[BaseRawDataHandler::PACKAGE_RAW_DATA]);
237
238                 // Add all chunks because the last final chunk is found
239                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('PACKAGE-ASSEMBLER[' . __METHOD__ . ':' . __LINE__ . ': Going to add ' . count($chunks) . ' to chunk handler ...');
240                 $this->getHandlerInstance()->addAllChunksWithFinal($chunks);
241         }
242 }
243
244 // [EOF]
245 ?>