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