]> git.mxchange.org Git - hub.git/blob - application/hub/main/package/class_NetworkPackage.php
Added a new task for listener pools and network package readers (for abstract Network...
[hub.git] / application / hub / main / package / class_NetworkPackage.php
1 <?php
2 /**
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
7  * packages.
8  *
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
13  * Internet.
14  *
15  * For performance reasons, this class should only be instanciated once and then
16  * used as a "pipe-through" class.
17  *
18  * @author              Roland Haeder <webmaster@ship-simu.org>
19  * @version             0.0.0
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
24  *
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.
29  *
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.
34  *
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/>.
37  */
38 class NetworkPackage extends BaseFrameworkSystem implements Deliverable, Receivable, Registerable {
39         /**
40          * Package mask for compressing package data:
41          * 0: Compressor extension
42          * 1: Raw package data
43          * 2: Tags, seperated by semicolons, no semicolon is required if only one tag is needed
44          * 3: Checksum
45          *                     0  1  2  3
46          */
47         const PACKAGE_MASK = '%s:%s:%s:%s';
48
49         /**
50          * Seperator for the above mask
51          */
52         const PACKAGE_MASK_SEPERATOR = ':';
53
54         /**
55          * Array indexes for above mask, start with zero
56          */
57         const INDEX_COMPRESSOR_EXTENSION = 0;
58         const INDEX_PACKAGE_DATA         = 1;
59         const INDEX_TAGS                 = 2;
60         const INDEX_CHECKSUM             = 3;
61
62         /**
63          * Array indexes for raw package array
64          */
65         const INDEX_PACKAGE_SENDER    = 0;
66         const INDEX_PACKAGE_RECIPIENT = 1;
67         const INDEX_PACKAGE_CONTENT   = 2;
68
69         /**
70          * Tags seperator
71          */
72         const PACKAGE_TAGS_SEPERATOR = ';';
73
74         /**
75          * Raw package data seperator
76          */
77         const PACKAGE_DATA_SEPERATOR = '|';
78
79         /**
80          * Stacker name for "undeclared" packages
81          */
82         const STACKER_NAME_UNDECLARED = 'undeclared';
83
84         /**
85          * Stacker name for "declared" packages (which are ready to send out)
86          */
87         const STACKER_NAME_DECLARED = 'declared';
88
89         /**
90          * Stacker name for "out-going" packages
91          */
92         const STACKER_NAME_OUTGOING = 'outgoing';
93
94         /**
95          * Stacker name for "back-buffered" packages
96          */
97         const STACKER_NAME_BACK_BUFFER = 'backbuffer';
98
99         /**
100          * Network target (alias): 'upper hubs'
101          */
102         const NETWORK_TARGET_UPPER_HUBS = 'upper';
103
104         /**
105          * Network target (alias): 'self'
106          */
107         const NETWORK_TARGET_SELF = 'self';
108
109         /**
110          * TCP package size in bytes
111          */
112         const TCP_PACKAGE_SIZE = 512;
113
114         /**
115          * Protected constructor
116          *
117          * @return      void
118          */
119         protected function __construct () {
120                 // Call parent constructor
121                 parent::__construct(__CLASS__);
122
123                 // We need to initialize a stack here for our packages even those
124                 // which have no recipient address and stamp... ;-)
125                 $stackerInstance = ObjectFactory::createObjectByConfiguredName('network_package_stacker_class');
126
127                 // At last, set it in this class
128                 $this->setStackerInstance($stackerInstance);
129         }
130
131         /**
132          * Creates an instance of this class
133          *
134          * @param       $compressorInstance             A Compressor instance for compressing the content
135          * @return      $packageInstance                An instance of a Deliverable class
136          */
137         public static final function createNetworkPackage (Compressor $compressorInstance) {
138                 // Get new instance
139                 $packageInstance = new NetworkPackage();
140
141                 // Now set the compressor instance
142                 $packageInstance->setCompressorInstance($compressorInstance);
143
144                 // Return the prepared instance
145                 return $packageInstance;
146         }
147
148         /**
149          * "Getter" for hash from given content and helper instance
150          *
151          * @param       $content        Raw package content
152          * @param       $helperInstance         An instance of a BaseHubHelper class
153          * @param       $nodeInstance           An instance of a NodeHelper class
154          * @return      $hash   Hash for given package content
155          */
156         private function getHashFromContent ($content, BaseHubHelper $helperInstance, NodeHelper $nodeInstance) {
157                 // Create the hash
158                 // @TODO crc32 is not good, but it needs to be fast
159                 $hash = crc32(
160                         $content .
161                         ':' .
162                         $nodeInstance->getSessionId() .
163                         ':' .
164                         $this->getCompressorInstance()->getCompressorExtension()
165                 );
166
167                 // And return it
168                 return $hash;
169         }
170
171         ///////////////////////////////////////////////////////////////////////////
172         //                   Delivering packages / raw data
173         ///////////////////////////////////////////////////////////////////////////
174
175         /**
176          * Delivers the given raw package data.
177          *
178          * @param       $packageData    Raw package data in an array
179          * @return      void
180          */
181         private function declareRawPackageData (array $packageData) {
182                 /*
183                  * We need to disover every recipient, just in case we have a
184                  * multi-recipient entry like 'upper' is. 'all' may be a not so good
185                  * target because it causes an overload on the network and may be
186                  * abused for attacking the network with large packages.
187                  */
188                 $discoveryInstance = PackageDiscoveryFactory::createPackageDiscoveryInstance();
189
190                 // Discover all recipients, this may throw an exception
191                 $discoveryInstance->discoverRecipients($packageData);
192
193                 // Now get an iterator
194                 $iteratorInstance = $discoveryInstance->getIterator();
195
196                 // ... and begin iteration
197                 while ($iteratorInstance->valid()) {
198                         // Get current entry
199                         $currentRecipient = $iteratorInstance->current();
200
201                         // Debug message
202                         $this->debugOutput('PACKAGE: Package declared for recipient ' . $currentRecipient);
203
204                         // Set the recipient
205                         $packageData['recipient'] = $currentRecipient;
206
207                         // And enqueue it to the writer class
208                         $this->getStackerInstance()->pushNamed(self::STACKER_NAME_DECLARED, $packageData);
209
210                         // Skip to next entry
211                         $iteratorInstance->next();
212                 } // END - while
213
214                 // Clean-up the list
215                 $discoveryInstance->clearRecipients();
216         }
217
218         /**
219          * Delivers raw package data. In short, this will discover the raw socket
220          * resource through a discovery class (which will analyse the receipient of
221          * the package), register the socket with the connection (handler/helper?)
222          * instance and finally push the raw data on our outgoing queue.
223          *
224          * @param       $packageData    Raw package data in an array
225          * @return      void
226          */
227         private function deliverRawPackageData (array $packageData) {
228                 /*
229                  * This package may become big, depending on the shared object size or
230                  * delivered message size which shouldn't be so long (to save
231                  * bandwidth). Because of the nature of the used protocol (TCP) we need
232                  * to split it up into smaller pieces to fit it into a TCP frame.
233                  *
234                  * So first we need (again) a discovery class but now a protocol
235                  * discovery to choose the right socket resource. The discovery class
236                  * should take a look at the raw package data itself and then decide
237                  * which (configurable!) protocol should be used for that type of
238                  * package.
239                  */
240                 $discoveryInstance = SocketDiscoveryFactory::createSocketDiscoveryInstance();
241
242                 // Now discover the right protocol
243                 $socketResource = $discoveryInstance->discoverSocket($packageData);
244
245                 // We have to put this socket in our registry, so get an instance
246                 $registryInstance = SocketRegistry::createSocketRegistry();
247
248                 // Get the listener from registry
249                 $connectionInstance = Registry::getRegistry()->getInstance('connection');
250
251                 // Is it not there?
252                 if (!$registryInstance->isSocketRegistered($connectionInstance, $socketResource)) {
253                         // Then register it
254                         $registryInstance->registerSocket($connectionInstance, $socketResource, $packageData);
255                 } // END - if
256
257                 // We enqueue it again, but now in the out-going queue
258                 $this->getStackerInstance()->pushNamed(self::STACKER_NAME_OUTGOING, $packageData);
259         }
260
261         /**
262          * Sends waiting packages
263          *
264          * @param       $packageData    Raw package data
265          * @return      void
266          */
267         private function sendOutgoingRawPackageData (array $packageData) {
268                 // Get the right connection instance
269                 $connectionInstance = SocketRegistry::createSocketRegistry()->getHandlerInstanceFromPackageData($packageData);
270
271                 // Is this connection still alive?
272                 if ($connectionInstance->isShuttedDown()) {
273                         // This connection is shutting down
274                         // @TODO We may want to do somthing more here?
275                         return;
276                 } // END - if
277
278                 // Sent it away (we catch exceptions one method above)
279                 $sentBytes = $connectionInstance->sendRawPackageData($packageData);
280
281                 // Remember unsent raw bytes in back-buffer, if any
282                 $this->storeUnsentBytesInBackBuffer($packageData, $sentBytes);
283         }
284
285         /**
286          * "Enqueues" raw content into this delivery class by reading the raw content
287          * from given template instance and pushing it on the 'undeclared' stack.
288          *
289          * @param       $helperInstance         An instance of a  BaseHubHelper class
290          * @param       $nodeInstance           An instance of a NodeHelper class
291          * @return      void
292          */
293         public function enqueueRawDataFromTemplate (BaseHubHelper $helperInstance, NodeHelper $nodeInstance) {
294                 // Get the raw content ...
295                 $content = $helperInstance->getTemplateInstance()->getRawTemplateData();
296
297                 // ... and compress it
298                 $content = $this->getCompressorInstance()->compressStream($content);
299
300                 // Add magic in front of it and hash behind it, including BASE64 encoding
301                 $content = sprintf(self::PACKAGE_MASK,
302                         // 1.) Compressor's extension
303                         $this->getCompressorInstance()->getCompressorExtension(),
304                         // 2.) Raw package content, encoded with BASE64
305                         base64_encode($content),
306                         // 3.) Tags
307                         implode(self::PACKAGE_TAGS_SEPERATOR, $helperInstance->getPackageTags()),
308                         // 4.) Checksum
309                         $this->getHashFromContent($content, $helperInstance, $nodeInstance)
310                 );
311
312                 // Now prepare the temporary array and push it on the 'undeclared' stack
313                 $this->getStackerInstance()->pushNamed(self::STACKER_NAME_UNDECLARED, array(
314                         'sender'    => $nodeInstance->getSessionId(),
315                         'recipient' => $helperInstance->getRecipientType(),
316                         'content'   => $content,
317                 ));
318         }
319
320         /**
321          * Checks wether a package has been enqueued for delivery.
322          *
323          * @return      $isEnqueued             Wether a package is enqueued
324          */
325         public function isPackageEnqueued () {
326                 // Check wether the stacker is not empty
327                 $isEnqueued = (($this->getStackerInstance()->isStackInitialized(self::STACKER_NAME_UNDECLARED)) && (!$this->getStackerInstance()->isStackEmpty(self::STACKER_NAME_UNDECLARED)));
328
329                 // Return the result
330                 return $isEnqueued;
331         }
332
333         /**
334          * Checks wether a package has been declared
335          *
336          * @return      $isDeclared             Wether a package is declared
337          */
338         public function isPackageDeclared () {
339                 // Check wether the stacker is not empty
340                 $isDeclared = (($this->getStackerInstance()->isStackInitialized(self::STACKER_NAME_DECLARED)) && (!$this->getStackerInstance()->isStackEmpty(self::STACKER_NAME_DECLARED)));
341
342                 // Return the result
343                 return $isDeclared;
344         }
345
346         /**
347          * Checks wether a package should be sent out
348          *
349          * @return      $isWaitingDelivery      Wether a package is waiting for delivery
350          */
351         public function isPackageWaitingForDelivery () {
352                 // Check wether the stacker is not empty
353                 $isWaitingDelivery = (($this->getStackerInstance()->isStackInitialized(self::STACKER_NAME_OUTGOING)) && (!$this->getStackerInstance()->isStackEmpty(self::STACKER_NAME_OUTGOING)));
354
355                 // Return the result
356                 return $isWaitingDelivery;
357         }
358
359         /**
360          * Delivers an enqueued package to the stated destination. If a non-session
361          * id is provided, recipient resolver is being asked (and instanced once).
362          * This allows that a single package is being delivered to multiple targets
363          * without enqueueing it for every target. If no target is provided or it
364          * can't be determined a NoTargetException is being thrown.
365          *
366          * @return      void
367          * @throws      NoTargetException       If no target can't be determined
368          */
369         public function declareEnqueuedPackage () {
370                 // Make sure this method isn't working if there is no package enqueued
371                 if (!$this->isPackageEnqueued()) {
372                         // This is not fatal but should be avoided
373                         // @TODO Add some logging here
374                         return;
375                 } // END - if
376
377                 // Now we know for sure there are packages to deliver, we can start
378                 // with the first one.
379                 $packageData = $this->getStackerInstance()->getNamed(self::STACKER_NAME_UNDECLARED);
380
381                 // Declare the raw package data for delivery
382                 $this->declareRawPackageData($packageData);
383
384                 // And remove it finally
385                 $this->getStackerInstance()->popNamed(self::STACKER_NAME_UNDECLARED);
386         }
387
388         /**
389          * Delivers the next declared package. Only one package per time will be sent
390          * because this may take time and slows down the whole delivery
391          * infrastructure.
392          *
393          * @return      void
394          */
395         public function deliverDeclaredPackage () {
396                 // Sanity check if we have packages declared
397                 if (!$this->isPackageDeclared()) {
398                         // This is not fatal but should be avoided
399                         // @TODO Add some logging here
400                         return;
401                 } // END - if
402
403                 // Get the package again
404                 $packageData = $this->getStackerInstance()->getNamed(self::STACKER_NAME_DECLARED);
405
406                 // And send it
407                 $this->deliverRawPackageData($packageData);
408
409                 // And remove it finally
410                 $this->getStackerInstance()->popNamed(self::STACKER_NAME_DECLARED);
411         }
412
413         /**
414          * Sends waiting packages out for delivery
415          *
416          * @return      void
417          */
418         public function sendWaitingPackage () {
419                 // Send any waiting bytes in the back-buffer before sending a new package
420                 $this->sendBackBufferBytes();
421
422                 // Sanity check if we have packages waiting for delivery
423                 if (!$this->isPackageWaitingForDelivery()) {
424                         // This is not fatal but should be avoided
425                         $this->debugOutput('PACKAGE: No package is waiting for delivery, but ' . __FUNCTION__ . ' was called.');
426                         return;
427                 } // END - if
428
429                 // Get the package again
430                 $packageData = $this->getStackerInstance()->getNamed(self::STACKER_NAME_OUTGOING);
431
432                 try {
433                         // Now try to send it
434                         $this->sendOutgoingRawPackageData($packageData);
435
436                         // And remove it finally
437                         $this->getStackerInstance()->popNamed(self::STACKER_NAME_OUTGOING);
438                 } catch (InvalidSocketException $e) {
439                         // Output exception message
440                         $this->debugOutput('PACKAGE: Package was not delivered: ' . $e->getMessage());
441                 }
442         }
443
444         ///////////////////////////////////////////////////////////////////////////
445         //                   Receiving packages / raw data
446         ///////////////////////////////////////////////////////////////////////////
447
448         /**
449          * Checks wether new raw package data has arrived at a socket
450          *
451          * @return      $hasArrived             Wether new raw package data has arrived for processing
452          */
453         public function isNewRawDataPending () {
454                 // @TODO Add some content here
455         }
456
457         /**
458          * Checks wether a new package has arrived
459          *
460          * @return      $hasArrived             Wether a new package has arrived for processing
461          */
462         public function isNewPackageArrived () {
463                 // @TODO Add some content here
464         }
465 }
466
467 // [EOF]
468 ?>