1 /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
2 /* vim: set ts=8 sts=2 et sw=2 tw=80: */
3 /* This Source Code Form is subject to the terms of the Mozilla Public
4  * License, v. 2.0. If a copy of the MPL was not distributed with this
5  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
6 
7 #ifndef mozilla_dom_EventSourceEventService_h
8 #define mozilla_dom_EventSourceEventService_h
9 
10 #include "mozilla/AlreadyAddRefed.h"
11 #include "mozilla/Atomics.h"
12 #include "nsIEventSourceEventService.h"
13 #include "nsCOMPtr.h"
14 #include "nsClassHashtable.h"
15 #include "nsHashKeys.h"
16 #include "nsIObserver.h"
17 #include "nsISupportsImpl.h"
18 #include "nsTArray.h"
19 
20 namespace mozilla {
21 namespace dom {
22 
23 class EventSourceEventService final : public nsIEventSourceEventService,
24                                       public nsIObserver {
25   friend class EventSourceBaseRunnable;
26 
27  public:
28   NS_DECL_THREADSAFE_ISUPPORTS
29   NS_DECL_NSIOBSERVER
30   NS_DECL_NSIEVENTSOURCEEVENTSERVICE
31 
32   static already_AddRefed<EventSourceEventService> GetOrCreate();
33 
34   void EventSourceConnectionOpened(uint64_t aHttpChannelId,
35                                    uint64_t aInnerWindowID);
36 
37   void EventSourceConnectionClosed(uint64_t aHttpChannelId,
38                                    uint64_t aInnerWindowID);
39 
40   void EventReceived(uint64_t aHttpChannelId, uint64_t aInnerWindowID,
41                      const nsAString& aEventName, const nsAString& aLastEventID,
42                      const nsAString& aData, uint32_t aRetry,
43                      DOMHighResTimeStamp aTimeStamp);
44 
45  private:
46   EventSourceEventService();
47   ~EventSourceEventService();
48 
49   bool HasListeners() const;
50   void Shutdown();
51 
52   using EventSourceListeners = nsTArray<nsCOMPtr<nsIEventSourceEventListener>>;
53 
54   struct WindowListener {
55     EventSourceListeners mListeners;
56   };
57 
58   void GetListeners(uint64_t aInnerWindowID,
59                     EventSourceListeners& aListeners) const;
60 
61   // Used only on the main-thread.
62   nsClassHashtable<nsUint64HashKey, WindowListener> mWindows;
63 
64   Atomic<uint64_t> mCountListeners;
65 };
66 
67 }  // namespace dom
68 }  // namespace mozilla
69 
70 /**
71  * Casting EventSourceEventService to nsISupports is ambiguous.
72  * This method handles that.
73  */
ToSupports(mozilla::dom::EventSourceEventService * p)74 inline nsISupports* ToSupports(mozilla::dom::EventSourceEventService* p) {
75   return NS_ISUPPORTS_CAST(nsIEventSourceEventService*, p);
76 }
77 
78 #endif  // mozilla_dom_EventSourceEventService_h
79