Mercurial > code > home > repos > homeauto
annotate lib/patchablegraph/patchsource.py @ 569:2d13254fdd44
fix old module name twisted_sse_demo
Ignore-this: 9eae98ea57725eeaf68e94e9f9f46fec
author | drewp@bigasterisk.com |
---|---|
date | Mon, 06 May 2019 00:02:26 -0700 |
parents | 495f573af4f4 |
children | 32939cddf360 |
rev | line source |
---|---|
514 | 1 import logging |
302 | 2 import traceback |
3 from rdflib import ConjunctiveGraph | |
4 from rdflib.parser import StringInputSource | |
514 | 5 from twisted.internet import reactor, defer |
302 | 6 |
351
7716b1810d6c
reasoning & collector move into docker images
drewp@bigasterisk.com
parents:
312
diff
changeset
|
7 from rdfdb.patch import Patch |
569 | 8 from twisted_sse.eventsource import EventSource |
9 | |
10 from .patchablegraph import patchFromJson | |
302 | 11 |
312
170dc9b1e789
fix input graph web display by dirtying combinedGraph better.
drewp@bigasterisk.com
parents:
306
diff
changeset
|
12 log = logging.getLogger('fetch') |
302 | 13 |
14 class PatchSource(object): | |
15 """wrap EventSource so it emits Patch objects and has an explicit stop method.""" | |
482
b5abd4fc65a4
UA support, some rewrites from twisted_sse_demo work
drewp@bigasterisk.com
parents:
447
diff
changeset
|
16 def __init__(self, url, agent): |
b5abd4fc65a4
UA support, some rewrites from twisted_sse_demo work
drewp@bigasterisk.com
parents:
447
diff
changeset
|
17 self.url = str(url) |
302 | 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) | |
312
170dc9b1e789
fix input graph web display by dirtying combinedGraph better.
drewp@bigasterisk.com
parents:
306
diff
changeset
|
26 # note: fullGraphReceived isn't guaranteed- the stream could |
170dc9b1e789
fix input graph web display by dirtying combinedGraph better.
drewp@bigasterisk.com
parents:
306
diff
changeset
|
27 # start with patches |
302 | 28 self._fullGraphReceived = False |
482
b5abd4fc65a4
UA support, some rewrites from twisted_sse_demo work
drewp@bigasterisk.com
parents:
447
diff
changeset
|
29 self._eventSource = EventSource(url.toPython().encode('utf8'), |
b5abd4fc65a4
UA support, some rewrites from twisted_sse_demo work
drewp@bigasterisk.com
parents:
447
diff
changeset
|
30 userAgent=agent) |
302 | 31 |
482
b5abd4fc65a4
UA support, some rewrites from twisted_sse_demo work
drewp@bigasterisk.com
parents:
447
diff
changeset
|
32 self._eventSource.addEventListener(b'fullGraph', self._onFullGraph) |
b5abd4fc65a4
UA support, some rewrites from twisted_sse_demo work
drewp@bigasterisk.com
parents:
447
diff
changeset
|
33 self._eventSource.addEventListener(b'patch', self._onPatch) |
302 | 34 self._eventSource.onerror(self._onError) |
482
b5abd4fc65a4
UA support, some rewrites from twisted_sse_demo work
drewp@bigasterisk.com
parents:
447
diff
changeset
|
35 self._eventSource.onConnectionLost = self._onDisconnect |
306 | 36 |
439
124c921ad52d
stats->state to make room for greplin stats
drewp@bigasterisk.com
parents:
429
diff
changeset
|
37 def state(self): |
306 | 38 return { |
39 'url': self.url, | |
40 'fullGraphReceived': self._fullGraphReceived, | |
41 } | |
302 | 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 | |
482
b5abd4fc65a4
UA support, some rewrites from twisted_sse_demo work
drewp@bigasterisk.com
parents:
447
diff
changeset
|
57 def _onDisconnect(self, reason): |
b5abd4fc65a4
UA support, some rewrites from twisted_sse_demo work
drewp@bigasterisk.com
parents:
447
diff
changeset
|
58 log.debug('PatchSource._onDisconnect from %s (%s)', self.url, reason) |
302 | 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) | |
482
b5abd4fc65a4
UA support, some rewrites from twisted_sse_demo work
drewp@bigasterisk.com
parents:
447
diff
changeset
|
75 except Exception: |
302 | 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): | |
482
b5abd4fc65a4
UA support, some rewrites from twisted_sse_demo work
drewp@bigasterisk.com
parents:
447
diff
changeset
|
89 log.debug('PatchSource %s received patch %s (fullGraph=%s)', |
b5abd4fc65a4
UA support, some rewrites from twisted_sse_demo work
drewp@bigasterisk.com
parents:
447
diff
changeset
|
90 self.url, p.shortSummary(), fullGraph) |
302 | 91 for lis in self._listeners: |
92 lis(p, fullGraph=fullGraph) | |
93 | |
94 def __del__(self): | |
95 if self._eventSource: | |
482
b5abd4fc65a4
UA support, some rewrites from twisted_sse_demo work
drewp@bigasterisk.com
parents:
447
diff
changeset
|
96 raise ValueError("PatchSource wasn't stopped before del") |
302 | 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 """ | |
482
b5abd4fc65a4
UA support, some rewrites from twisted_sse_demo work
drewp@bigasterisk.com
parents:
447
diff
changeset
|
106 def __init__(self, url, listener, reconnectSecs=60, agent='unset'): |
b5abd4fc65a4
UA support, some rewrites from twisted_sse_demo work
drewp@bigasterisk.com
parents:
447
diff
changeset
|
107 # type: (str, Any, Any, str) |
302 | 108 self.url = url |
109 self._stopped = False | |
110 self._listener = listener | |
429
fcd2c026f51e
exportStats for sending scales data to influxdb
drewp@bigasterisk.com
parents:
351
diff
changeset
|
111 self.reconnectSecs = reconnectSecs |
482
b5abd4fc65a4
UA support, some rewrites from twisted_sse_demo work
drewp@bigasterisk.com
parents:
447
diff
changeset
|
112 self.agent = agent |
302 | 113 self._reconnect() |
114 | |
115 def _reconnect(self): | |
116 if self._stopped: | |
117 return | |
482
b5abd4fc65a4
UA support, some rewrites from twisted_sse_demo work
drewp@bigasterisk.com
parents:
447
diff
changeset
|
118 self._ps = PatchSource(self.url, agent=self.agent) |
302 | 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) | |
306 | 125 |
439
124c921ad52d
stats->state to make room for greplin stats
drewp@bigasterisk.com
parents:
429
diff
changeset
|
126 def state(self): |
306 | 127 return { |
439
124c921ad52d
stats->state to make room for greplin stats
drewp@bigasterisk.com
parents:
429
diff
changeset
|
128 'reconnectedPatchSource': self._ps.state(), |
306 | 129 } |
302 | 130 |
131 def stop(self): | |
132 self._stopped = True | |
133 self._ps.stop() | |
134 | |
135 def _onConnectionFailed(self, arg): | |
429
fcd2c026f51e
exportStats for sending scales data to influxdb
drewp@bigasterisk.com
parents:
351
diff
changeset
|
136 reactor.callLater(self.reconnectSecs, self._reconnect) |
302 | 137 |
138 def _onConnectionLost(self, arg): | |
429
fcd2c026f51e
exportStats for sending scales data to influxdb
drewp@bigasterisk.com
parents:
351
diff
changeset
|
139 reactor.callLater(self.reconnectSecs, self._reconnect) |
482
b5abd4fc65a4
UA support, some rewrites from twisted_sse_demo work
drewp@bigasterisk.com
parents:
447
diff
changeset
|
140 |