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