302
|
1 import sys
|
|
2 import traceback
|
|
3 from twisted.internet import reactor, defer
|
|
4 from twisted_sse_demo.eventsource import EventSource
|
|
5 from rdflib import ConjunctiveGraph
|
|
6 from rdflib.parser import StringInputSource
|
|
7
|
|
8 sys.path.append("../../lib")
|
|
9 from logsetup import log
|
|
10 from patchablegraph import patchFromJson
|
|
11
|
|
12 sys.path.append("/my/proj/light9")
|
|
13 from light9.rdfdb.patch import Patch
|
|
14
|
|
15
|
|
16 class PatchSource(object):
|
|
17 """wrap EventSource so it emits Patch objects and has an explicit stop method."""
|
|
18 def __init__(self, url):
|
|
19 self.url = url
|
|
20
|
|
21 # add callbacks to these to learn if we failed to connect
|
|
22 # (approximately) or if the ccnnection was unexpectedly lost
|
|
23 self.connectionFailed = defer.Deferred()
|
|
24 self.connectionLost = defer.Deferred()
|
|
25
|
|
26 self._listeners = set()
|
|
27 log.info('start read from %s', url)
|
|
28 self._fullGraphReceived = False
|
|
29 self._eventSource = EventSource(url.toPython().encode('utf8'))
|
|
30 self._eventSource.protocol.delimiter = '\n'
|
|
31
|
|
32 self._eventSource.addEventListener('fullGraph', self._onFullGraph)
|
|
33 self._eventSource.addEventListener('patch', self._onPatch)
|
|
34 self._eventSource.onerror(self._onError)
|
|
35
|
|
36 origSet = self._eventSource.protocol.setFinishedDeferred
|
|
37 def sfd(d):
|
|
38 origSet(d)
|
|
39 d.addCallback(self._onDisconnect)
|
|
40 self._eventSource.protocol.setFinishedDeferred = sfd
|
306
|
41
|
|
42 def stats(self):
|
|
43 return {
|
|
44 'url': self.url,
|
|
45 'fullGraphReceived': self._fullGraphReceived,
|
|
46 }
|
302
|
47
|
|
48 def addPatchListener(self, func):
|
|
49 """
|
|
50 func(patch, fullGraph=[true if the patch is the initial fullgraph])
|
|
51 """
|
|
52 self._listeners.add(func)
|
|
53
|
|
54 def stop(self):
|
|
55 log.info('stop read from %s', self.url)
|
|
56 try:
|
|
57 self._eventSource.protocol.stopProducing() # needed?
|
|
58 except AttributeError:
|
|
59 pass
|
|
60 self._eventSource = None
|
|
61
|
|
62 def _onDisconnect(self, a):
|
|
63 log.debug('PatchSource._onDisconnect from %s', self.url)
|
|
64 # skip this if we're doing a stop?
|
|
65 self.connectionLost.callback(None)
|
|
66
|
|
67 def _onError(self, msg):
|
|
68 log.debug('PatchSource._onError from %s %r', self.url, msg)
|
|
69 if not self._fullGraphReceived:
|
|
70 self.connectionFailed.callback(msg)
|
|
71 else:
|
|
72 self.connectionLost.callback(msg)
|
|
73
|
|
74 def _onFullGraph(self, message):
|
|
75 try:
|
|
76 g = ConjunctiveGraph()
|
|
77 g.parse(StringInputSource(message), format='json-ld')
|
|
78 p = Patch(addGraph=g)
|
|
79 self._sendPatch(p, fullGraph=True)
|
|
80 except:
|
|
81 log.error(traceback.format_exc())
|
|
82 raise
|
|
83 self._fullGraphReceived = True
|
|
84
|
|
85 def _onPatch(self, message):
|
|
86 try:
|
|
87 p = patchFromJson(message)
|
|
88 self._sendPatch(p, fullGraph=False)
|
|
89 except:
|
|
90 log.error(traceback.format_exc())
|
|
91 raise
|
|
92
|
|
93 def _sendPatch(self, p, fullGraph):
|
|
94 log.debug('PatchSource %s received patch %s (fullGraph=%s)', self.url, p.shortSummary(), fullGraph)
|
|
95 for lis in self._listeners:
|
|
96 lis(p, fullGraph=fullGraph)
|
|
97
|
|
98 def __del__(self):
|
|
99 if self._eventSource:
|
|
100 raise ValueError
|
|
101
|
|
102 class ReconnectingPatchSource(object):
|
|
103 """
|
|
104 PatchSource api, but auto-reconnects internally and takes listener
|
|
105 at init time to not miss any patches. You'll get another
|
|
106 fullGraph=True patch if we have to reconnect.
|
|
107
|
|
108 todo: generate connection stmts in here
|
|
109 """
|
|
110 def __init__(self, url, listener):
|
|
111 self.url = url
|
|
112 self._stopped = False
|
|
113 self._listener = listener
|
|
114 self._reconnect()
|
|
115
|
|
116 def _reconnect(self):
|
|
117 if self._stopped:
|
|
118 return
|
|
119 self._ps = PatchSource(self.url)
|
|
120 self._ps.addPatchListener(self._onPatch)
|
|
121 self._ps.connectionFailed.addCallback(self._onConnectionFailed)
|
|
122 self._ps.connectionLost.addCallback(self._onConnectionLost)
|
|
123
|
|
124 def _onPatch(self, p, fullGraph):
|
|
125 self._listener(p, fullGraph=fullGraph)
|
306
|
126
|
|
127 def stats(self):
|
|
128 return {
|
|
129 'reconnectedPatchSource': self._ps.stats(),
|
|
130 }
|
302
|
131
|
|
132 def stop(self):
|
|
133 self._stopped = True
|
|
134 self._ps.stop()
|
|
135
|
|
136 def _onConnectionFailed(self, arg):
|
|
137 reactor.callLater(60, self._reconnect)
|
|
138
|
|
139 def _onConnectionLost(self, arg):
|
|
140 reactor.callLater(60, self._reconnect)
|
|
141
|