Debian Codegraph @

packages/messaging/src/index.ts

raw
1 // Copyright (c) Jupyter Development Team.
2 // Distributed under the terms of the Modified BSD License.
3 /*-----------------------------------------------------------------------------
4 | Copyright (c) 2014-2017, PhosphorJS Contributors
5 |
6 | Distributed under the terms of the BSD 3-Clause License.
7 |
8 | The full license is in the file LICENSE, distributed with this software.
9 |----------------------------------------------------------------------------*/
10 /**
11 * @packageDocumentation
12 * @module messaging
13 */
14 import { ArrayExt, every, retro, some } from '@lumino/algorithm';
15
16 import { LinkedList } from '@lumino/collections';
17
18 /**
19 * A message which can be delivered to a message handler.
20 *
21 * #### Notes
22 * This class may be subclassed to create complex message types.
23 */
24 export class Message {
25 /**
26 * Construct a new message.
27 *
28 * @param type - The type of the message.
29 */
30 constructor(type: string) {
31 this.type = type;
32 }
33
34 /**
35 * The type of the message.
36 *
37 * #### Notes
38 * The `type` of a message should be related directly to its actual
39 * runtime type. This means that `type` can and will be used to cast
40 * the message to the relevant derived `Message` subtype.
41 */
42 readonly type: string;
43
44 /**
45 * Test whether the message is conflatable.
46 *
47 * #### Notes
48 * Message conflation is an advanced topic. Most message types will
49 * not make use of this feature.
50 *
51 * If a conflatable message is posted to a handler while another
52 * conflatable message of the same `type` has already been posted
53 * to the handler, the `conflate()` method of the existing message
54 * will be invoked. If that method returns `true`, the new message
55 * will not be enqueued. This allows messages to be compressed, so
56 * that only a single instance of the message type is processed per
57 * cycle, no matter how many times messages of that type are posted.
58 *
59 * Custom message types may reimplement this property.
60 *
61 * The default implementation is always `false`.
62 */
63 get isConflatable(): boolean {
64 return false;
65 }
66
67 /**
68 * Conflate this message with another message of the same `type`.
69 *
70 * @param other - A conflatable message of the same `type`.
71 *
72 * @returns `true` if the message was successfully conflated, or
73 * `false` otherwise.
74 *
75 * #### Notes
76 * Message conflation is an advanced topic. Most message types will
77 * not make use of this feature.
78 *
79 * This method is called automatically by the message loop when the
80 * given message is posted to the handler paired with this message.
81 * This message will already be enqueued and conflatable, and the
82 * given message will have the same `type` and also be conflatable.
83 *
84 * This method should merge the state of the other message into this
85 * message as needed so that when this message is finally delivered
86 * to the handler, it receives the most up-to-date information.
87 *
88 * If this method returns `true`, it signals that the other message
89 * was successfully conflated and that message will not be enqueued.
90 *
91 * If this method returns `false`, the other message will be enqueued
92 * for normal delivery.
93 *
94 * Custom message types may reimplement this method.
95 *
96 * The default implementation always returns `false`.
97 */
98 conflate(other: Message): boolean {
99 return false;
100 }
101 }
102
103 /**
104 * A convenience message class which conflates automatically.
105 *
106 * #### Notes
107 * Message conflation is an advanced topic. Most user code will not
108 * make use of this class.
109 *
110 * This message class is useful for creating message instances which
111 * should be conflated, but which have no state other than `type`.
112 *
113 * If conflation of stateful messages is required, a custom `Message`
114 * subclass should be created.
115 */
116 export class ConflatableMessage extends Message {
117 /**
118 * Test whether the message is conflatable.
119 *
120 * #### Notes
121 * This property is always `true`.
122 */
123 get isConflatable(): boolean {
124 return true;
125 }
126
127 /**
128 * Conflate this message with another message of the same `type`.
129 *
130 * #### Notes
131 * This method always returns `true`.
132 */
133 conflate(other: ConflatableMessage): boolean {
134 return true;
135 }
136 }
137
138 /**
139 * An object which handles messages.
140 *
141 * #### Notes
142 * A message handler is a simple way of defining a type which can act
143 * upon on a large variety of external input without requiring a large
144 * abstract API surface. This is particularly useful in the context of
145 * widget frameworks where the number of distinct message types can be
146 * unbounded.
147 */
148 export interface IMessageHandler {
149 /**
150 * Process a message sent to the handler.
151 *
152 * @param msg - The message to be processed.
153 */
154 processMessage(msg: Message): void;
155 }
156
157 /**
158 * An object which intercepts messages sent to a message handler.
159 *
160 * #### Notes
161 * A message hook is useful for intercepting or spying on messages
162 * sent to message handlers which were either not created by the
163 * consumer, or when subclassing the handler is not feasible.
164 *
165 * If `messageHook` returns `false`, no other message hooks will be
166 * invoked and the message will not be delivered to the handler.
167 *
168 * If all installed message hooks return `true`, the message will
169 * be delivered to the handler for processing.
170 *
171 * **See also:** {@link MessageLoop.installMessageHook} and {@link MessageLoop.removeMessageHook}
172 */
173 export interface IMessageHook {
174 /**
175 * Intercept a message sent to a message handler.
176 *
177 * @param handler - The target handler of the message.
178 *
179 * @param msg - The message to be sent to the handler.
180 *
181 * @returns `true` if the message should continue to be processed
182 * as normal, or `false` if processing should cease immediately.
183 */
184 messageHook(handler: IMessageHandler, msg: Message): boolean;
185 }
186
187 /**
188 * A type alias for message hook object or function.
189 *
190 * #### Notes
191 * The signature and semantics of a message hook function are the same
192 * as the `messageHook` method of {@link IMessageHook}.
193 */
194 export type MessageHook =
195 | IMessageHook
196 | ((handler: IMessageHandler, msg: Message) => boolean);
197
198 /**
199 * The namespace for the global singleton message loop.
200 */
201 export namespace MessageLoop {
202 /**
203 * A function that cancels the pending loop task; `null` if unavailable.
204 */
205 let pending: (() => void) | null = null;
206
207 /**
208 * Schedules a function for invocation as soon as possible asynchronously.
209 *
210 * @param fn The function to invoke when called back.
211 *
212 * @returns An anonymous function that will unschedule invocation if possible.
213 */
214 const schedule = (
215 resolved =>
216 (fn: () => unknown): (() => void) => {
217 let rejected = false;
218 resolved.then(() => !rejected && fn());
219 return () => {
220 rejected = true;
221 };
222 }
223 )(Promise.resolve());
224
225 /**
226 * Send a message to a message handler to process immediately.
227 *
228 * @param handler - The handler which should process the message.
229 *
230 * @param msg - The message to deliver to the handler.
231 *
232 * #### Notes
233 * The message will first be sent through any installed message hooks
234 * for the handler. If the message passes all hooks, it will then be
235 * delivered to the `processMessage` method of the handler.
236 *
237 * The message will not be conflated with pending posted messages.
238 *
239 * Exceptions in hooks and handlers will be caught and logged.
240 */
241 export function sendMessage(handler: IMessageHandler, msg: Message): void {
242 // Lookup the message hooks for the handler.
243 let hooks = messageHooks.get(handler);
244
245 // Handle the common case of no installed hooks.
246 if (!hooks || hooks.length === 0) {
247 invokeHandler(handler, msg);
248 return;
249 }
250
251 // Invoke the message hooks starting with the newest first.
252 let passed = every(retro(hooks), hook => {
253 return hook ? invokeHook(hook, handler, msg) : true;
254 });
255
256 // Invoke the handler if the message passes all hooks.
257 if (passed) {
258 invokeHandler(handler, msg);
259 }
260 }
261
262 /**
263 * Post a message to a message handler to process in the future.
264 *
265 * @param handler - The handler which should process the message.
266 *
267 * @param msg - The message to post to the handler.
268 *
269 * #### Notes
270 * The message will be conflated with the pending posted messages for
271 * the handler, if possible. If the message is not conflated, it will
272 * be queued for normal delivery on the next cycle of the event loop.
273 *
274 * Exceptions in hooks and handlers will be caught and logged.
275 */
276 export function postMessage(handler: IMessageHandler, msg: Message): void {
277 // Handle the common case of a non-conflatable message.
278 if (!msg.isConflatable) {
279 enqueueMessage(handler, msg);
280 return;
281 }
282
283 // Conflate the message with an existing message if possible.
284 let conflated = some(messageQueue, posted => {
285 if (posted.handler !== handler) {
286 return false;
287 }
288 if (!posted.msg) {
289 return false;
290 }
291 if (posted.msg.type !== msg.type) {
292 return false;
293 }
294 if (!posted.msg.isConflatable) {
295 return false;
296 }
297 return posted.msg.conflate(msg);
298 });
299
300 // Enqueue the message if it was not conflated.
301 if (!conflated) {
302 enqueueMessage(handler, msg);
303 }
304 }
305
306 /**
307 * Install a message hook for a message handler.
308 *
309 * @param handler - The message handler of interest.
310 *
311 * @param hook - The message hook to install.
312 *
313 * #### Notes
314 * A message hook is invoked before a message is delivered to the
315 * handler. If the hook returns `false`, no other hooks will be
316 * invoked and the message will not be delivered to the handler.
317 *
318 * The most recently installed message hook is executed first.
319 *
320 * If the hook is already installed, this is a no-op.
321 */
322 export function installMessageHook(
323 handler: IMessageHandler,
324 hook: MessageHook
325 ): void {
326 // Look up the hooks for the handler.
327 let hooks = messageHooks.get(handler);
328
329 // Bail early if the hook is already installed.
330 if (hooks && hooks.indexOf(hook) !== -1) {
331 return;
332 }
333
334 // Add the hook to the end, so it will be the first to execute.
335 if (!hooks) {
336 messageHooks.set(handler, [hook]);
337 } else {
338 hooks.push(hook);
339 }
340 }
341
342 /**
343 * Remove an installed message hook for a message handler.
344 *
345 * @param handler - The message handler of interest.
346 *
347 * @param hook - The message hook to remove.
348 *
349 * #### Notes
350 * It is safe to call this function while the hook is executing.
351 *
352 * If the hook is not installed, this is a no-op.
353 */
354 export function removeMessageHook(
355 handler: IMessageHandler,
356 hook: MessageHook
357 ): void {
358 // Lookup the hooks for the handler.
359 let hooks = messageHooks.get(handler);
360
361 // Bail early if the hooks do not exist.
362 if (!hooks) {
363 return;
364 }
365
366 // Lookup the index of the hook and bail if not found.
367 let i = hooks.indexOf(hook);
368 if (i === -1) {
369 return;
370 }
371
372 // Clear the hook and schedule a cleanup of the array.
373 hooks[i] = null;
374 scheduleCleanup(hooks);
375 }
376
377 /**
378 * Clear all message data associated with a message handler.
379 *
380 * @param handler - The message handler of interest.
381 *
382 * #### Notes
383 * This will clear all posted messages and hooks for the handler.
384 */
385 export function clearData(handler: IMessageHandler): void {
386 // Lookup the hooks for the handler.
387 let hooks = messageHooks.get(handler);
388
389 // Clear all messsage hooks for the handler.
390 if (hooks && hooks.length > 0) {
391 ArrayExt.fill(hooks, null);
392 scheduleCleanup(hooks);
393 }
394
395 // Clear all posted messages for the handler.
396 for (const posted of messageQueue) {
397 if (posted.handler === handler) {
398 posted.handler = null;
399 posted.msg = null;
400 }
401 }
402 }
403
404 /**
405 * Process the pending posted messages in the queue immediately.
406 *
407 * #### Notes
408 * This function is useful when posted messages must be processed immediately.
409 *
410 * This function should normally not be needed, but it may be
411 * required to work around certain browser idiosyncrasies.
412 *
413 * Recursing into this function is a no-op.
414 */
415 export function flush(): void {
416 // Bail if recursion is detected or if there is no pending task.
417 if (flushGuard || pending === null) {
418 return;
419 }
420
421 // Unschedule the pending loop task.
422 pending();
423 pending = null;
424
425 // Run the message loop within the recursion guard.
426 flushGuard = true;
427 runMessageLoop();
428 flushGuard = false;
429 }
430
431 /**
432 * A type alias for the exception handler function.
433 */
434 export type ExceptionHandler = (err: Error) => void;
435
436 /**
437 * Get the message loop exception handler.
438 *
439 * @returns The current exception handler.
440 *
441 * #### Notes
442 * The default exception handler is `console.error`.
443 */
444 export function getExceptionHandler(): ExceptionHandler {
445 return exceptionHandler;
446 }
447
448 /**
449 * Set the message loop exception handler.
450 *
451 * @param handler - The function to use as the exception handler.
452 *
453 * @returns The old exception handler.
454 *
455 * #### Notes
456 * The exception handler is invoked when a message handler or a
457 * message hook throws an exception.
458 */
459 export function setExceptionHandler(
460 handler: ExceptionHandler
461 ): ExceptionHandler {
462 let old = exceptionHandler;
463 exceptionHandler = handler;
464 return old;
465 }
466
467 /**
468 * A type alias for a posted message pair.
469 */
470 type PostedMessage = { handler: IMessageHandler | null; msg: Message | null };
471
472 /**
473 * The queue of posted message pairs.
474 */
475 const messageQueue = new LinkedList<PostedMessage>();
476
477 /**
478 * A mapping of handler to array of installed message hooks.
479 */
480 const messageHooks = new WeakMap<
481 IMessageHandler,
482 Array<MessageHook | null>
483 >();
484
485 /**
486 * A set of message hook arrays which are pending cleanup.
487 */
488 const dirtySet = new Set<Array<MessageHook | null>>();
489
490 /**
491 * The message loop exception handler.
492 */
493 let exceptionHandler: ExceptionHandler = (err: Error) => {
494 console.error(err);
495 };
496
497 /**
498 * A guard flag to prevent flush recursion.
499 */
500 let flushGuard = false;
501
502 /**
503 * Invoke a message hook with the specified handler and message.
504 *
505 * Returns the result of the hook, or `true` if the hook throws.
506 *
507 * Exceptions in the hook will be caught and logged.
508 */
509 function invokeHook(
510 hook: MessageHook,
511 handler: IMessageHandler,
512 msg: Message
513 ): boolean {
514 let result = true;
515 try {
516 if (typeof hook === 'function') {
517 result = hook(handler, msg);
518 } else {
519 result = hook.messageHook(handler, msg);
520 }
521 } catch (err) {
522 exceptionHandler(err);
523 }
524 return result;
525 }
526
527 /**
528 * Invoke a message handler with the specified message.
529 *
530 * Exceptions in the handler will be caught and logged.
531 */
532 function invokeHandler(handler: IMessageHandler, msg: Message): void {
533 try {
534 handler.processMessage(msg);
535 } catch (err) {
536 exceptionHandler(err);
537 }
538 }
539
540 /**
541 * Add a message to the end of the message queue.
542 *
543 * This will automatically schedule a run of the message loop.
544 */
545 function enqueueMessage(handler: IMessageHandler, msg: Message): void {
546 // Add the posted message to the queue.
547 messageQueue.addLast({ handler, msg });
548
549 // Bail if a loop task is already pending.
550 if (pending !== null) {
551 return;
552 }
553
554 // Schedule a run of the message loop.
555 pending = schedule(runMessageLoop);
556 }
557
558 /**
559 * Run an iteration of the message loop.
560 *
561 * This will process all pending messages in the queue. If a message
562 * is added to the queue while the message loop is running, it will
563 * be processed on the next cycle of the loop.
564 */
565 function runMessageLoop(): void {
566 // Clear the task so the next loop can be scheduled.
567 pending = null;
568
569 // If the message queue is empty, there is nothing else to do.
570 if (messageQueue.isEmpty) {
571 return;
572 }
573
574 // Add a sentinel value to the end of the queue. The queue will
575 // only be processed up to the sentinel. Messages posted during
576 // this cycle will execute on the next cycle.
577 let sentinel: PostedMessage = { handler: null, msg: null };
578 messageQueue.addLast(sentinel);
579
580 // Enter the message loop.
581 // eslint-disable-next-line no-constant-condition
582 while (true) {
583 // Remove the first posted message in the queue.
584 let posted = messageQueue.removeFirst()!;
585
586 // If the value is the sentinel, exit the loop.
587 if (posted === sentinel) {
588 return;
589 }
590
591 // Dispatch the message if it has not been cleared.
592 if (posted.handler && posted.msg) {
593 sendMessage(posted.handler, posted.msg);
594 }
595 }
596 }
597
598 /**
599 * Schedule a cleanup of a message hooks array.
600 *
601 * This will add the array to the dirty set and schedule a deferred
602 * cleanup of the array contents. On cleanup, any `null` hook will
603 * be removed from the array.
604 */
605 function scheduleCleanup(hooks: Array<MessageHook | null>): void {
606 if (dirtySet.size === 0) {
607 schedule(cleanupDirtySet);
608 }
609 dirtySet.add(hooks);
610 }
611
612 /**
613 * Cleanup the message hook arrays in the dirty set.
614 *
615 * This function should only be invoked asynchronously, when the
616 * stack frame is guaranteed to not be on the path of user code.
617 */
618 function cleanupDirtySet(): void {
619 dirtySet.forEach(cleanupHooks);
620 dirtySet.clear();
621 }
622
623 /**
624 * Cleanup the dirty hooks in a message hooks array.
625 *
626 * This will remove any `null` hook from the array.
627 *
628 * This function should only be invoked asynchronously, when the
629 * stack frame is guaranteed to not be on the path of user code.
630 */
631 function cleanupHooks(hooks: Array<MessageHook | null>): void {
632 ArrayExt.removeAllWhere(hooks, isNull);
633 }
634
635 /**
636 * Test whether a value is `null`.
637 */
638 function isNull<T>(value: T | null): boolean {
639 return value === null;
640 }
641 }