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