]> git.mxchange.org Git - hub.git/blob - application/hub/main/package/class_NetworkPackage.php
dd634f3adfe84492f6467779c14da3ee32713cc9
[hub.git] / application / hub / main / package / class_NetworkPackage.php
1 <?php
2 /**
3  * A NetworkPackage class. This class implements the Deliverable class because
4  * all network packages should be deliverable to other nodes. It further
5  * provides methods for reading raw content from template engines and feeding it
6  * to the stacker for undeclared packages.
7  *
8  * The factory method requires you to provide a compressor class (which must
9  * implement the Compressor interface). If you don't want any compression (not
10  * adviceable due to increased network load), please use the NullCompressor
11  * class and encode it with BASE64 for a more error-free transfer over the
12  * Internet.
13  *
14  * For performance reasons, this class should only be instantiated once and then
15  * used as a "pipe-through" class.
16  *
17  * @author              Roland Haeder <webmaster@ship-simu.org>
18  * @version             0.0.0
19  * @copyright   Copyright (c) 2007, 2008 Roland Haeder, 2009, 2010 Hub Developer Team
20  * @license             GNU GPL 3.0 or any newer version
21  * @link                http://www.ship-simu.org
22  * @todo                Needs to add functionality for handling the object's type
23  *
24  * This program is free software: you can redistribute it and/or modify
25  * it under the terms of the GNU General Public License as published by
26  * the Free Software Foundation, either version 3 of the License, or
27  * (at your option) any later version.
28  *
29  * This program is distributed in the hope that it will be useful,
30  * but WITHOUT ANY WARRANTY; without even the implied warranty of
31  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
32  * GNU General Public License for more details.
33  *
34  * You should have received a copy of the GNU General Public License
35  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
36  */
37 class NetworkPackage extends BaseFrameworkSystem implements Deliverable, Registerable {
38         /**
39          * Package mask for compressing package data:
40          * 1.) Compressor extension
41          * 2.) Raw package data
42          * 3.) Tags, seperated by semicolons, no semicolon is required if only one tag is needed
43          * 4.) Checksum
44          */
45         const PACKAGE_MASK = '%s:%s:%s:%s';
46
47         /**
48          * Seperator for the above mask
49          */
50         const PACKAGE_MASK_SEPERATOR = ':';
51
52         /**
53          * Array indexes for above mask, start with zero
54          */
55         const INDEX_COMPRESSOR_EXTENSION = 0;
56         const INDEX_PACKAGE_DATA         = 1;
57         const INDEX_TAGS                 = 2;
58         const INDEX_CHECKSUM             = 3;
59
60         /**
61          * Array indexes for raw package array
62          */
63         const INDEX_PACKAGE_SENDER    = 0;
64         const INDEX_PACKAGE_RECIPIENT = 1;
65         const INDEX_PACKAGE_CONTENT   = 2;
66
67         /**
68          * Tags seperator
69          */
70         const PACKAGE_TAGS_SEPERATOR = ';';
71
72         /**
73          * Raw package data seperator
74          */
75         const PACKAGE_DATA_SEPERATOR = '|';
76
77         /**
78          * Stacker name for "undeclared" packages
79          */
80         const STACKER_NAME_UNDECLARED = 'undeclared';
81
82         /**
83          * Stacker name for "declared" packages (which are ready to send out)
84          */
85         const STACKER_NAME_DECLARED = 'declared';
86
87         /**
88          * Stacker name for "out-going" packages
89          */
90         const STACKER_NAME_OUTGOING = 'outgoing';
91
92         /**
93          * Network target (alias): 'upper hubs'
94          */
95         const NETWORK_TARGET_UPPER_HUBS = 'upper';
96
97         /**
98          * Network target (alias): 'self'
99          */
100         const NETWORK_TARGET_SELF = 'self';
101
102         /**
103          * Protected constructor
104          *
105          * @return      void
106          */
107         protected function __construct () {
108                 // Call parent constructor
109                 parent::__construct(__CLASS__);
110
111                 // We need to initialize a stack here for our packages even those
112                 // which have no recipient address and stamp... ;-)
113                 $stackerInstance = ObjectFactory::createObjectByConfiguredName('package_stacker_class');
114
115                 // At last, set it in this class
116                 $this->setStackerInstance($stackerInstance);
117         }
118
119         /**
120          * Creates an instance of this class
121          *
122          * @param       $compressorInstance             A Compressor instance for compressing the content
123          * @return      $packageInstance                An instance of a Deliverable class
124          */
125         public final static function createNetworkPackage (Compressor $compressorInstance) {
126                 // Get new instance
127                 $packageInstance = new NetworkPackage();
128
129                 // Now set the compressor instance
130                 $packageInstance->setCompressorInstance($compressorInstance);
131
132                 // Return the prepared instance
133                 return $packageInstance;
134         }
135
136         /**
137          * "Getter" for hash from given content and helper instance
138          *
139          * @param       $content        Raw package content
140          * @param       $helperInstance         A BaseHubHelper instance
141          * @return      $hash   Hash for given package content
142          */
143         private function getHashFromContent ($content, BaseHubHelper $helperInstance) {
144                 // Create the hash
145                 // @TODO crc32 is not good, but it needs to be fast
146                 $hash = crc32(
147                         $content .
148                         ':' .
149                         $helperInstance->getNodeInstance()->getSessionId() .
150                         ':' .
151                         $this->getCompressorInstance()->getCompressorExtension()
152                 );
153
154                 // And return it
155                 return $hash;
156         }
157
158         /**
159          * Delivers the given raw package data.
160          *
161          * @param       $packageData    Raw package data in an array
162          * @return      void
163          */
164         private function deliverPackage (array $packageData) {
165                 /*
166                  * We need to disover every recipient, just in case we have a
167                  * multi-recipient entry like 'upper' is. 'all' may be a not so good
168                  * target because it causes an overload on the network and may be
169                  * abused for attacking the network with large packages.
170                  */
171                 $discoveryInstance = PackageDiscoveryFactory::createPackageDiscoveryInstance();
172
173                 // Discover all recipients, this may throw an exception
174                 $discoveryInstance->discoverRecipients($packageData);
175
176                 // Now get an iterator
177                 $iteratorInstance = $discoveryInstance->getIterator();
178
179                 // ... and begin iteration
180                 while ($iteratorInstance->valid()) {
181                         // Get current entry
182                         $currentRecipient = $iteratorInstance->current();
183
184                         // Debug message
185                         $this->debugOutput('PACKAGE: Package declared for recipient ' . $currentRecipient);
186
187                         // Set the recipient
188                         $packageData['recipient'] = $currentRecipient;
189
190                         // And enqueue it to the writer class
191                         $this->getStackerInstance()->pushNamed(self::STACKER_NAME_DECLARED, $packageData);
192
193                         // Skip to next entry
194                         $iteratorInstance->next();
195                 } // END - while
196
197                 // Clean-up the list
198                 $discoveryInstance->clearRecipients();
199         }
200
201         /**
202          * Sends a raw package out
203          *
204          * @param       $packageData    Raw package data in an array
205          * @return      void
206          */
207         private function sendRawPackage (array $packageData) {
208                 /*
209                  * This package may become big, depending on the shared object size or
210                  * delivered message size which shouldn't be so long (to save
211                  * bandwidth). Because of the nature of the used protocol (TCP) we need
212                  * to split it up into smaller pieces to fit it into a TCP frame.
213                  *
214                  * So first we need (again) a discovery class but now a protocol
215                  * discovery to choose the right socket resource. The discovery class
216                  * should take a look at the raw package data itself and then decide
217                  * which (configurable!) protocol should be used for that type of
218                  * package.
219                  */
220                 $discoveryInstance = SocketDiscoveryFactory::createSocketDiscoveryInstance();
221
222                 // Now discover the right protocol
223                 $socketResource = $discoveryInstance->discoverSocket($packageData);
224
225                 // We have to put this socket in our registry, so get an instance
226                 $registryInstance = SocketRegistry::createSocketRegistry();
227
228                 // Get the listener from registry
229                 $connectionInstance = Registry::getRegistry()->getInstance('connection');
230
231                 // Is it not there?
232                 if (!$registryInstance->isSocketRegistered($connectionInstance, $socketResource)) {
233                         // Then register it
234                         $registryInstance->registerSocket($connectionInstance, $socketResource, $packageData);
235                 } // END - if
236
237                 // We enqueue it again, but now in the out-going queue
238                 $this->getStackerInstance()->pushNamed(self::STACKER_NAME_OUTGOING, $packageData);
239         }
240
241         /**
242          * Sends waiting packages
243          *
244          * @param       $packageData    Raw package data
245          * @return      void
246          */
247         private function sendOutgoingPackage (array $packageData) {
248                 // Get the right connection instance
249                 $connectionInstance = SocketRegistry::createSocketRegistry()->getHandlerInstanceFromPackageData($packageData);
250
251                 // Is this connection still alive?
252                 if ($connectionInstance->isShuttedDown()) {
253                         // This connection is shutting down
254                         // @TODO We may want to do somthing more here?
255                         return;
256                 } // END - if
257
258                 // Sent it away (we catch exceptions one method above
259                 $connectionInstance->sendRawPackageData($packageData);
260         }
261
262         /**
263          * "Enqueues" raw content into this delivery class by reading the raw content
264          * from given template instance and pushing it on the 'undeclared' stack.
265          *
266          * @param       $helperInstance         A BaseHubHelper instance
267          * @return      void
268          */
269         public function enqueueRawDataFromTemplate (BaseHubHelper $helperInstance) {
270                 // Get the raw content ...
271                 $content = $helperInstance->getTemplateInstance()->getRawTemplateData();
272
273                 // ... and compress it
274                 $content = $this->getCompressorInstance()->compressStream($content);
275
276                 // Add magic in front of it and hash behind it, including BASE64 encoding
277                 $content = sprintf(self::PACKAGE_MASK,
278                         // 1.) Compressor's extension
279                         $this->getCompressorInstance()->getCompressorExtension(),
280                         // 2.) Raw package content, encoded with BASE64
281                         base64_encode($content),
282                         // 3.) Tags
283                         implode(self::PACKAGE_TAGS_SEPERATOR, $helperInstance->getPackageTags()),
284                         // 4.) Checksum
285                         $this->getHashFromContent($content, $helperInstance)
286                 );
287
288                 // Now prepare the temporary array and push it on the 'undeclared' stack
289                 $this->getStackerInstance()->pushNamed(self::STACKER_NAME_UNDECLARED, array(
290                         'sender'    => $helperInstance->getNodeInstance()->getSessionId(),
291                         'recipient' => $helperInstance->getRecipientType(),
292                         'content'   => $content,
293                 ));
294         }
295
296         /**
297          * Checks wether a package has been enqueued for delivery.
298          *
299          * @return      $isEnqueued             Wether a package is enqueued
300          */
301         public function isPackageEnqueued () {
302                 // Check wether the stacker is not empty
303                 $isEnqueued = (($this->getStackerInstance()->isStackInitialized(self::STACKER_NAME_UNDECLARED)) && (!$this->getStackerInstance()->isStackEmpty(self::STACKER_NAME_UNDECLARED)));
304
305                 // Return the result
306                 return $isEnqueued;
307         }
308
309         /**
310          * Checks wether a package has been declared
311          *
312          * @return      $isDeclared             Wether a package is declared
313          */
314         public function isPackageDeclared () {
315                 // Check wether the stacker is not empty
316                 $isDeclared = (($this->getStackerInstance()->isStackInitialized(self::STACKER_NAME_DECLARED)) && (!$this->getStackerInstance()->isStackEmpty(self::STACKER_NAME_DECLARED)));
317
318                 // Return the result
319                 return $isDeclared;
320         }
321
322         /**
323          * Checks wether a package should be sent out
324          *
325          * @return      $isWaitingDelivery      Wether a package is waiting for delivery
326          */
327         public function isPackageWaitingDelivery () {
328                 // Check wether the stacker is not empty
329                 $isWaitingDelivery = (($this->getStackerInstance()->isStackInitialized(self::STACKER_NAME_OUTGOING)) && (!$this->getStackerInstance()->isStackEmpty(self::STACKER_NAME_OUTGOING)));
330
331                 // Return the result
332                 return $isWaitingDelivery;
333         }
334
335         /**
336          * Delivers an enqueued package to the stated destination. If a non-session
337          * id is provided, recipient resolver is being asked (and instanced once).
338          * This allows that a single package is being delivered to multiple targets
339          * without enqueueing it for every target. If no target is provided or it
340          * can't be determined a NoTargetException is being thrown.
341          *
342          * @return      void
343          * @throws      NoTargetException       If no target can't be determined
344          */
345         public function declareEnqueuedPackage () {
346                 // Make sure this method isn't working if there is no package enqueued
347                 if (!$this->isPackageEnqueued()) {
348                         // This is not fatal but should be avoided
349                         // @TODO Add some logging here
350                         return;
351                 } // END - if
352
353                 // Now we know for sure there are packages to deliver, we can start
354                 // with the first one.
355                 $packageData = $this->getStackerInstance()->getNamed(self::STACKER_NAME_UNDECLARED);
356
357                 // Finally, deliver the package
358                 $this->deliverPackage($packageData);
359
360                 // And remove it finally
361                 $this->getStackerInstance()->popNamed(self::STACKER_NAME_UNDECLARED);
362         }
363
364         /**
365          * Delivers the next declared package. Only one package per time will be sent
366          * because this may take time and slows down the whole delivery
367          * infrastructure.
368          *
369          * @return      void
370          */
371         public function deliverDeclaredPackage () {
372                 // Sanity check if we have packages declared
373                 if (!$this->isPackageDeclared()) {
374                         // This is not fatal but should be avoided
375                         // @TODO Add some logging here
376                         return;
377                 } // END - if
378
379                 // Get the package again
380                 $packageData = $this->getStackerInstance()->getNamed(self::STACKER_NAME_DECLARED);
381
382                 // And send it
383                 $this->sendRawPackage($packageData);
384
385                 // And remove it finally
386                 $this->getStackerInstance()->popNamed(self::STACKER_NAME_DECLARED);
387         }
388
389         /**
390          * Sends waiting packages out for delivery
391          *
392          * @return      void
393          */
394         public function sentWaitingPackage () {
395                 // Sanity check if we have packages waiting for delivery
396                 if (!$this->isPackageWaitingDelivery()) {
397                         // This is not fatal but should be avoided
398                         // @TODO Add some logging here
399                         return;
400                 } // END - if
401
402                 // Get the package again
403                 $packageData = $this->getStackerInstance()->getNamed(self::STACKER_NAME_OUTGOING);
404
405                 // Now try to send it
406                 try {
407                         $this->sendOutgoingPackage($packageData);
408
409                         // And remove it finally when it has been fully delivered
410                         $this->getStackerInstance()->popNamed(self::STACKER_NAME_OUTGOING);
411                 } catch (InvalidSocketException $e) {
412                         // Output exception message
413                         $this->debugOutput('PACKAGE: Package was not delivered: ' . $e->getMessage());
414                 }
415         }
416 }
417
418 // [EOF]
419 ?>