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