-
Notifications
You must be signed in to change notification settings - Fork 474
/
monitor.py
245 lines (190 loc) · 8.01 KB
/
monitor.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
import json
import re
import requests
import threading
import time
import uuid
from collections import defaultdict
from inspect import signature
from requests import HTTPError
from .collection import Collection
from .logger import logger
from .records import Record
class Monitor(object):
thread = None
def __init__(self, client, root_url="https://msgstore.www.notion.so/primus/"):
self.client = client
self.session_id = str(uuid.uuid4())
self.root_url = root_url
self._subscriptions = set()
self.initialize()
def _decode_numbered_json_thing(self, thing):
thing = thing.decode().strip()
for ping in re.findall('\d+:\d+"primus::ping::\d+"', thing):
logger.debug("Received ping: {}".format(ping))
self.post_data(ping.replace("::ping::", "::pong::"))
results = []
for blob in re.findall("\d+:\d+(\{.*?\})(?=\d|$)", thing):
results.append(json.loads(blob))
if thing and not results and "::ping::" not in thing:
logger.debug("Could not parse monitoring response: {}".format(thing))
return results
def _encode_numbered_json_thing(self, data):
assert isinstance(data, list)
results = ""
for obj in data:
msg = str(len(obj)) + json.dumps(obj, separators=(",", ":"))
msg = "{}:{}".format(len(msg), msg)
results += msg
return results.encode()
def initialize(self):
logger.debug("Initializing new monitoring session.")
response = self.client.session.get(
"{}?sessionId={}&EIO=3&transport=polling".format(
self.root_url, self.session_id
)
)
self.sid = self._decode_numbered_json_thing(response.content)[0]["sid"]
logger.debug("New monitoring session ID is: {}".format(self.sid))
# resubscribe to any existing subscriptions if we're reconnecting
old_subscriptions, self._subscriptions = self._subscriptions, set()
self.subscribe(old_subscriptions)
def subscribe(self, records):
if isinstance(records, set):
records = list(records)
if not isinstance(records, list):
records = [records]
sub_data = []
for record in records:
if record not in self._subscriptions:
logger.debug(
"Subscribing new record to the monitoring watchlist: {}/{}".format(
record._table, record.id
)
)
# add the record to the list of records to restore if we're disconnected
self._subscriptions.add(record)
# subscribe to changes to the record itself
sub_data.append(
{
"type": "/api/v1/registerSubscription",
"requestId": str(uuid.uuid4()),
"key": "versions/{}:{}".format(record.id, record._table),
"version": record.get("version", -1),
}
)
# if it's a collection, subscribe to changes to its children too
if isinstance(record, Collection):
sub_data.append(
{
"type": "/api/v1/registerSubscription",
"requestId": str(uuid.uuid4()),
"key": "collection/{}".format(record.id),
"version": -1,
}
)
data = self._encode_numbered_json_thing(sub_data)
self.post_data(data)
def post_data(self, data):
if not data:
return
logger.debug("Posting monitoring data: {}".format(data))
self.client.session.post(
"{}?sessionId={}&transport=polling&sid={}".format(
self.root_url, self.session_id, self.sid
),
data=data,
)
def poll(self, retries=10):
logger.debug("Starting new long-poll request")
try:
response = self.client.session.get(
"{}?sessionId={}&EIO=3&transport=polling&sid={}".format(
self.root_url, self.session_id, self.sid
)
)
response.raise_for_status()
except HTTPError as e:
try:
message = "{} / {}".format(response.content, e)
except:
message = "{}".format(e)
logger.warn(
"Problem with submitting polling request: {} (will retry {} more times)".format(
message, retries
)
)
time.sleep(0.1)
if retries <= 0:
raise
if retries <= 5:
logger.error(
"Persistent error submitting polling request: {} (will retry {} more times)".format(
message, retries
)
)
# if we're close to giving up, also try reinitializing the session
self.initialize()
self.poll(retries=retries - 1)
self._refresh_updated_records(
self._decode_numbered_json_thing(response.content)
)
def _refresh_updated_records(self, events):
records_to_refresh = defaultdict(list)
for event in events:
logger.debug(
"Received the following event from the remote server: {}".format(event)
)
if not isinstance(event, dict):
continue
if event.get("type", "") == "notification":
key = event.get("key")
if key.startswith("versions/"):
match = re.match("versions/([^\:]+):(.+)", key)
if not match:
continue
record_id, record_table = match.groups()
local_version = self.client._store.get_current_version(
record_table, record_id
)
if event["value"] > local_version:
logger.debug(
"Record {}/{} has changed; refreshing to update from version {} to version {}".format(
record_table, record_id, local_version, event["value"]
)
)
records_to_refresh[record_table].append(record_id)
else:
logger.debug(
"Record {}/{} already at version {}, not trying to update to version {}".format(
record_table, record_id, local_version, event["value"]
)
)
if key.startswith("collection/"):
match = re.match("collection/(.+)", key)
if not match:
continue
collection_id = match.groups()[0]
self.client.refresh_collection_rows(collection_id)
row_ids = self.client._store.get_collection_rows(collection_id)
logger.debug(
"Something inside collection {} has changed; refreshing all {} rows inside it".format(
collection_id, len(row_ids)
)
)
records_to_refresh["block"] += row_ids
self.client.refresh_records(**records_to_refresh)
def poll_async(self):
if self.thread:
# Already polling async; no need to have two threads
return
self.thread = threading.Thread(target=self.poll_forever, daemon=True)
self.thread.start()
def poll_forever(self):
while True:
try:
self.poll()
except Exception as e:
logger.error("Encountered error during polling!")
logger.error(e, exc_info=True)
time.sleep(1)