Mercurial > code > home > repos > homeauto
annotate lib/patchablegraph/patchsource.py @ 1394:b27d0f9a00ef
pinode use prettyerrorhandler
Ignore-this: 20e96013aa365fd180774ffb5b558245
darcs-hash:84bf69f522301afb1a79cb6184ae92a0fdd54017
author | drewp <drewp@bigasterisk.com> |
---|---|
date | Sat, 06 Jul 2019 00:49:12 -0700 |
parents | 26dd28671f70 |
children | 6a8b922bbe2e |
rev | line source |
---|---|
1317 | 1 import logging |
2 import traceback | |
3 from rdflib import ConjunctiveGraph | |
4 from rdflib.parser import StringInputSource | |
5 from twisted.internet import reactor, defer | |
6 | |
7 from rdfdb.patch import Patch | |
1372
26dd28671f70
fix old module name twisted_sse_demo
drewp <drewp@bigasterisk.com>
parents:
1317
diff
changeset
|
8 from twisted_sse.eventsource import EventSource |
26dd28671f70
fix old module name twisted_sse_demo
drewp <drewp@bigasterisk.com>
parents:
1317
diff
changeset
|
9 |
26dd28671f70
fix old module name twisted_sse_demo
drewp <drewp@bigasterisk.com>
parents:
1317
diff
changeset
|
10 from .patchablegraph import patchFromJson |
1317 | 11 |
12 log = logging.getLogger('fetch') | |
13 | |
14 class PatchSource(object): | |
15 """wrap EventSource so it emits Patch objects and has an explicit stop method.""" | |
16 def __init__(self, url, agent): | |
17 self.url = str(url) | |
18 | |
19 # add callbacks to these to learn if we failed to connect | |
20 # (approximately) or if the ccnnection was unexpectedly lost | |
21 self.connectionFailed = defer.Deferred() | |
22 self.connectionLost = defer.Deferred() | |
23 | |
24 self._listeners = set() | |
25 log.info('start read from %s', url) | |
26 # note: fullGraphReceived isn't guaranteed- the stream could | |
27 # start with patches | |
28 self._fullGraphReceived = False | |
29 self._eventSource = EventSource(url.toPython().encode('utf8'), | |
30 userAgent=agent) | |
31 | |
32 self._eventSource.addEventListener(b'fullGraph', self._onFullGraph) | |
33 self._eventSource.addEventListener(b'patch', self._onPatch) | |
34 self._eventSource.onerror(self._onError) | |
35 self._eventSource.onConnectionLost = self._onDisconnect | |
36 | |
37 def state(self): | |
38 return { | |
39 'url': self.url, | |
40 'fullGraphReceived': self._fullGraphReceived, | |
41 } | |
42 | |
43 def addPatchListener(self, func): | |
44 """ | |
45 func(patch, fullGraph=[true if the patch is the initial fullgraph]) | |
46 """ | |
47 self._listeners.add(func) | |
48 | |
49 def stop(self): | |
50 log.info('stop read from %s', self.url) | |
51 try: | |
52 self._eventSource.protocol.stopProducing() # needed? | |
53 except AttributeError: | |
54 pass | |
55 self._eventSource = None | |
56 | |
57 def _onDisconnect(self, reason): | |
58 log.debug('PatchSource._onDisconnect from %s (%s)', self.url, reason) | |
59 # skip this if we're doing a stop? | |
60 self.connectionLost.callback(None) | |
61 | |
62 def _onError(self, msg): | |
63 log.debug('PatchSource._onError from %s %r', self.url, msg) | |
64 if not self._fullGraphReceived: | |
65 self.connectionFailed.callback(msg) | |
66 else: | |
67 self.connectionLost.callback(msg) | |
68 | |
69 def _onFullGraph(self, message): | |
70 try: | |
71 g = ConjunctiveGraph() | |
72 g.parse(StringInputSource(message), format='json-ld') | |
73 p = Patch(addGraph=g) | |
74 self._sendPatch(p, fullGraph=True) | |
75 except Exception: | |
76 log.error(traceback.format_exc()) | |
77 raise | |
78 self._fullGraphReceived = True | |
79 | |
80 def _onPatch(self, message): | |
81 try: | |
82 p = patchFromJson(message) | |
83 self._sendPatch(p, fullGraph=False) | |
84 except: | |
85 log.error(traceback.format_exc()) | |
86 raise | |
87 | |
88 def _sendPatch(self, p, fullGraph): | |
89 log.debug('PatchSource %s received patch %s (fullGraph=%s)', | |
90 self.url, p.shortSummary(), fullGraph) | |
91 for lis in self._listeners: | |
92 lis(p, fullGraph=fullGraph) | |
93 | |
94 def __del__(self): | |
95 if self._eventSource: | |
96 raise ValueError("PatchSource wasn't stopped before del") | |
97 | |
98 class ReconnectingPatchSource(object): | |
99 """ | |
100 PatchSource api, but auto-reconnects internally and takes listener | |
101 at init time to not miss any patches. You'll get another | |
102 fullGraph=True patch if we have to reconnect. | |
103 | |
104 todo: generate connection stmts in here | |
105 """ | |
106 def __init__(self, url, listener, reconnectSecs=60, agent='unset'): | |
107 # type: (str, Any, Any, str) | |
108 self.url = url | |
109 self._stopped = False | |
110 self._listener = listener | |
111 self.reconnectSecs = reconnectSecs | |
112 self.agent = agent | |
113 self._reconnect() | |
114 | |
115 def _reconnect(self): | |
116 if self._stopped: | |
117 return | |
118 self._ps = PatchSource(self.url, agent=self.agent) | |
119 self._ps.addPatchListener(self._onPatch) | |
120 self._ps.connectionFailed.addCallback(self._onConnectionFailed) | |
121 self._ps.connectionLost.addCallback(self._onConnectionLost) | |
122 | |
123 def _onPatch(self, p, fullGraph): | |
124 self._listener(p, fullGraph=fullGraph) | |
125 | |
126 def state(self): | |
127 return { | |
128 'reconnectedPatchSource': self._ps.state(), | |
129 } | |
130 | |
131 def stop(self): | |
132 self._stopped = True | |
133 self._ps.stop() | |
134 | |
135 def _onConnectionFailed(self, arg): | |
136 reactor.callLater(self.reconnectSecs, self._reconnect) | |
137 | |
138 def _onConnectionLost(self, arg): | |
139 reactor.callLater(self.reconnectSecs, self._reconnect) | |
140 |