]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - lib/queuemanager.php
Offload inbox updates to a queue handler to speed up posting online
[quix0rs-gnu-social.git] / lib / queuemanager.php
1 <?php
2 /**
3  * StatusNet, the distributed open-source microblogging tool
4  *
5  * Abstract class for i/o managers
6  *
7  * PHP version 5
8  *
9  * LICENCE: This program is free software: you can redistribute it and/or modify
10  * it under the terms of the GNU Affero General Public License as published by
11  * the Free Software Foundation, either version 3 of the License, or
12  * (at your option) any later version.
13  *
14  * This program is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17  * GNU Affero General Public License for more details.
18  *
19  * You should have received a copy of the GNU Affero General Public License
20  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
21  *
22  * @category  QueueManager
23  * @package   StatusNet
24  * @author    Evan Prodromou <evan@status.net>
25  * @author    Sarven Capadisli <csarven@status.net>
26  * @author    Brion Vibber <brion@status.net>
27  * @copyright 2009-2010 StatusNet, Inc.
28  * @license   http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0
29  * @link      http://status.net/
30  */
31
32 /**
33  * Completed child classes must implement the enqueue() method.
34  *
35  * For background processing, classes should implement either socket-based
36  * input (handleInput(), getSockets()) or idle-loop polling (idle()).
37  */
38 abstract class QueueManager extends IoManager
39 {
40     static $qm = null;
41
42     public $master = null;
43     public $handlers = array();
44     public $groups = array();
45
46     /**
47      * Factory function to pull the appropriate QueueManager object
48      * for this site's configuration. It can then be used to queue
49      * events for later processing or to spawn a processing loop.
50      *
51      * Plugins can add to the built-in types by hooking StartNewQueueManager.
52      *
53      * @return QueueManager
54      */
55     public static function get()
56     {
57         if (empty(self::$qm)) {
58
59             if (Event::handle('StartNewQueueManager', array(&self::$qm))) {
60
61                 $enabled = common_config('queue', 'enabled');
62                 $type = common_config('queue', 'subsystem');
63
64                 if (!$enabled) {
65                     // does everything immediately
66                     self::$qm = new UnQueueManager();
67                 } else {
68                     switch ($type) {
69                      case 'db':
70                         self::$qm = new DBQueueManager();
71                         break;
72                      case 'stomp':
73                         self::$qm = new StompQueueManager();
74                         break;
75                      default:
76                         throw new ServerException("No queue manager class for type '$type'");
77                     }
78                 }
79             }
80         }
81
82         return self::$qm;
83     }
84
85     /**
86      * @fixme wouldn't necessarily work with other class types.
87      * Better to change the interface...?
88      */
89     public static function multiSite()
90     {
91         if (common_config('queue', 'subsystem') == 'stomp') {
92             return IoManager::INSTANCE_PER_PROCESS;
93         } else {
94             return IoManager::SINGLE_ONLY;
95         }
96     }
97
98     function __construct()
99     {
100         $this->initialize();
101     }
102
103     /**
104      * Store an object (usually/always a Notice) into the given queue
105      * for later processing. No guarantee is made on when it will be
106      * processed; it could be immediately or at some unspecified point
107      * in the future.
108      *
109      * Must be implemented by any queue manager.
110      *
111      * @param Notice $object
112      * @param string $queue
113      */
114     abstract function enqueue($object, $queue);
115
116     /**
117      * Build a representation for an object for logging
118      * @param mixed
119      * @return string
120      */
121     function logrep($object) {
122         if (is_object($object)) {
123             $class = get_class($object);
124             if (isset($object->id)) {
125                 return "$class $object->id";
126             }
127             return $class;
128         }
129         if (is_string($object)) {
130             $len = strlen($object);
131             $fragment = mb_substr($object, 0, 32);
132             if (mb_strlen($object) > 32) {
133                 $fragment .= '...';
134             }
135             return "string '$fragment' ($len bytes)";
136         }
137         return strval($object);
138     }
139
140     /**
141      * Encode an object for queued storage.
142      * Next gen may use serialization.
143      *
144      * @param mixed $object
145      * @return string
146      */
147     protected function encode($object)
148     {
149         if ($object instanceof Notice) {
150             return $object->id;
151         } else if (is_string($object)) {
152             return $object;
153         } else {
154             throw new ServerException("Can't queue this type", 500);
155         }
156     }
157
158     /**
159      * Decode an object from queued storage.
160      * Accepts back-compat notice reference entries and strings for now.
161      *
162      * @param string
163      * @return mixed
164      */
165     protected function decode($frame)
166     {
167         if (is_numeric($frame)) {
168             return Notice::staticGet(intval($frame));
169         } else {
170             return $frame;
171         }
172     }
173
174     /**
175      * Instantiate the appropriate QueueHandler class for the given queue.
176      *
177      * @param string $queue
178      * @return mixed QueueHandler or null
179      */
180     function getHandler($queue)
181     {
182         if (isset($this->handlers[$queue])) {
183             $class = $this->handlers[$queue];
184             if (class_exists($class)) {
185                 return new $class();
186             } else {
187                 common_log(LOG_ERR, "Nonexistent handler class '$class' for queue '$queue'");
188             }
189         } else {
190             common_log(LOG_ERR, "Requested handler for unkown queue '$queue'");
191         }
192         return null;
193     }
194
195     /**
196      * Get a list of registered queue transport names to be used
197      * for this daemon.
198      *
199      * @return array of strings
200      */
201     function getQueues()
202     {
203         $group = $this->activeGroup();
204         return array_keys($this->groups[$group]);
205     }
206
207     /**
208      * Initialize the list of queue handlers
209      *
210      * @event StartInitializeQueueManager
211      * @event EndInitializeQueueManager
212      */
213     function initialize()
214     {
215         // @fixme we'll want to be able to listen to particular queues...
216         if (Event::handle('StartInitializeQueueManager', array($this))) {
217             $this->connect('plugin', 'PluginQueueHandler');
218             $this->connect('omb', 'OmbQueueHandler');
219             $this->connect('ping', 'PingQueueHandler');
220             $this->connect('distrib', 'DistribQueueHandler');
221             if (common_config('sms', 'enabled')) {
222                 $this->connect('sms', 'SmsQueueHandler');
223             }
224
225             // XMPP output handlers...
226             $this->connect('jabber', 'JabberQueueHandler');
227             $this->connect('public', 'PublicQueueHandler');
228
229             // @fixme this should get an actual queue
230             //$this->connect('confirm', 'XmppConfirmHandler');
231
232             // For compat with old plugins not registering their own handlers.
233             $this->connect('plugin', 'PluginQueueHandler');
234
235             $this->connect('xmppout', 'XmppOutQueueHandler', 'xmppdaemon');
236
237         }
238         Event::handle('EndInitializeQueueManager', array($this));
239     }
240
241     /**
242      * Register a queue transport name and handler class for your plugin.
243      * Only registered transports will be reliably picked up!
244      *
245      * @param string $transport
246      * @param string $class
247      * @param string $group
248      */
249     public function connect($transport, $class, $group='queuedaemon')
250     {
251         $this->handlers[$transport] = $class;
252         $this->groups[$group][$transport] = $class;
253     }
254
255     /**
256      * @return string queue group to use for this request
257      */
258     function activeGroup()
259     {
260         $group = 'queuedaemon';
261         if ($this->master) {
262             // hack hack
263             if ($this->master instanceof XmppMaster) {
264                 return 'xmppdaemon';
265             }
266         }
267         return $group;
268     }
269
270     /**
271      * Send a statistic ping to the queue monitoring system,
272      * optionally with a per-queue id.
273      *
274      * @param string $key
275      * @param string $queue
276      */
277     function stats($key, $queue=false)
278     {
279         $owners = array();
280         if ($queue) {
281             $owners[] = "queue:$queue";
282             $owners[] = "site:" . common_config('site', 'server');
283         }
284         if (isset($this->master)) {
285             $this->master->stats($key, $owners);
286         } else {
287             $monitor = new QueueMonitor();
288             $monitor->stats($key, $owners);
289         }
290     }
291 }