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