0
|
1 """
|
|
2 Design:
|
|
3
|
|
4 1. Services each have (named) graphs, which they patch as things
|
|
5 change. PatchableGraph is an object for holding this graph.
|
|
6 2. You can http GET that graph, or ...
|
|
7 3. You can http GET/SSE that graph and hear about modifications to it
|
|
8 4. The client that got the graph holds and maintains a copy. The
|
|
9 client may merge together multiple graphs.
|
|
10 5. Client queries its graph with low-level APIs or client-side sparql.
|
|
11 6. When the graph changes, the client knows and can update itself at
|
|
12 low or high granularity.
|
|
13
|
|
14
|
|
15 See also:
|
|
16 * http://iswc2007.semanticweb.org/papers/533.pdf RDFSync: efficient remote synchronization of RDF
|
|
17 models
|
|
18 * https://www.w3.org/2009/12/rdf-ws/papers/ws07 Supporting Change Propagation in RDF
|
|
19 * https://www.w3.org/DesignIssues/lncs04/Diff.pdf Delta: an ontology for the distribution of
|
|
20 differences between RDF graphs
|
|
21
|
|
22 """
|
|
23 import json, logging, itertools, html
|
|
24
|
3
|
25 from prometheus_client import Counter, Gauge, Summary
|
0
|
26 from rdfdb.grapheditapi import GraphEditApi
|
|
27 from rdflib import ConjunctiveGraph
|
|
28 from rdflib.namespace import NamespaceManager
|
|
29 from rdflib.parser import StringInputSource
|
|
30 from rdflib.plugins.serializers.jsonld import from_rdf
|
|
31 import cyclone.sse
|
|
32 from cycloneerr import PrettyErrorHandler
|
|
33 from rdfdb.patch import Patch
|
|
34 from rdfdb.rdflibpatch import patchQuads, inGraph
|
|
35
|
|
36 log = logging.getLogger('patchablegraph')
|
|
37
|
3
|
38 SERIALIZE_CALLS = Summary('serialize_calls', 'PatchableGraph.serialize calls')
|
|
39 PATCH_CALLS = Summary('patch_calls', 'PatchableGraph.patch calls')
|
|
40 STATEMENT_COUNT = Gauge('statement_count', 'current PatchableGraph graph size')
|
|
41 OBSERVERS_CURRENT = Gauge('observers_current', 'current observer count')
|
|
42 OBSERVERS_ADDED = Counter('observers_added', 'observers added')
|
|
43
|
|
44
|
0
|
45 # forked from /my/proj/light9/light9/rdfdb/rdflibpatch.py
|
|
46 def _graphFromQuads2(q):
|
|
47 g = ConjunctiveGraph()
|
|
48 #g.addN(q) # no effect on nquad output
|
|
49 for s,p,o,c in q:
|
|
50 g.get_context(c).add((s,p,o)) # kind of works with broken rdflib nquad serializer code
|
|
51 #g.store.add((s,p,o), c) # no effect on nquad output
|
|
52 return g
|
|
53
|
|
54 def jsonFromPatch(p):
|
|
55 return json.dumps({'patch': {
|
|
56 'adds': from_rdf(_graphFromQuads2(p.addQuads)),
|
|
57 'deletes': from_rdf(_graphFromQuads2(p.delQuads)),
|
|
58 }})
|
|
59 patchAsJson = jsonFromPatch # deprecated name
|
|
60
|
|
61
|
|
62 def patchFromJson(j):
|
|
63 body = json.loads(j)['patch']
|
|
64 a = ConjunctiveGraph()
|
|
65 a.parse(StringInputSource(json.dumps(body['adds']).encode('utf8')), format='json-ld')
|
|
66 d = ConjunctiveGraph()
|
|
67 d.parse(StringInputSource(json.dumps(body['deletes']).encode('utf8')), format='json-ld')
|
|
68 return Patch(addGraph=a, delGraph=d)
|
|
69
|
|
70 def graphAsJson(g):
|
|
71 # This is not the same as g.serialize(format='json-ld')! That
|
|
72 # version omits literal datatypes.
|
|
73 return json.dumps(from_rdf(g))
|
|
74
|
|
75 _graphsInProcess = itertools.count()
|
|
76 class PatchableGraph(GraphEditApi):
|
|
77 """
|
|
78 Master graph that you modify with self.patch, and we get the
|
|
79 updates to all current listeners.
|
|
80 """
|
|
81 def __init__(self):
|
|
82 self._graph = ConjunctiveGraph()
|
|
83 self._observers = []
|
|
84 scales.init(self, '/patchableGraph%s' % next(_graphsInProcess))
|
|
85
|
|
86 _serialize = scales.PmfStat('serialize')
|
|
87 def serialize(self, *arg, **kw):
|
|
88 with self._serialize.time():
|
|
89 return self._graph.serialize(*arg, **kw)
|
|
90
|
|
91 def patch(self, p):
|
3
|
92 with PATCH_CALLS.labels(graph=self.label).time():
|
0
|
93 # assuming no stmt is both in p.addQuads and p.delQuads.
|
|
94 dels = set([q for q in p.delQuads if inGraph(q, self._graph)])
|
|
95 adds = set([q for q in p.addQuads if not inGraph(q, self._graph)])
|
|
96 minimizedP = Patch(addQuads=adds, delQuads=dels)
|
|
97 if minimizedP.isNoop():
|
|
98 return
|
|
99 patchQuads(self._graph,
|
|
100 deleteQuads=dels,
|
|
101 addQuads=adds,
|
|
102 perfect=False) # true?
|
|
103 for ob in self._observers:
|
|
104 ob(patchAsJson(p))
|
3
|
105 STATEMENT_COUNT.labels(graph=self.label).set(len(self._graph))
|
0
|
106
|
|
107 def asJsonLd(self):
|
|
108 return graphAsJson(self._graph)
|
|
109
|
|
110 def addObserver(self, onPatch):
|
|
111 self._observers.append(onPatch)
|
3
|
112 OBSERVERS_CURRENT.labels(graph=self.label).set(len(self._observers))
|
|
113 OBSERVERS_ADDED.labels(graph=self.label).inc()
|
0
|
114
|
|
115 def removeObserver(self, onPatch):
|
|
116 try:
|
|
117 self._observers.remove(onPatch)
|
|
118 except ValueError:
|
|
119 pass
|
|
120 self._currentObservers = len(self._observers)
|
|
121
|
|
122 def setToGraph(self, newGraph):
|
|
123 self.patch(Patch.fromDiff(self._graph, newGraph))
|
|
124
|
3
|
125
|
|
126 SEND_SIMPLE_GRAPH = Summary('send_simple_graph', 'calls to _writeGraphResponse')
|
0
|
127
|
|
128
|
|
129 class CycloneGraphHandler(PrettyErrorHandler, cyclone.web.RequestHandler):
|
|
130 def initialize(self, masterGraph: PatchableGraph):
|
|
131 self.masterGraph = masterGraph
|
|
132
|
|
133 def get(self):
|
3
|
134 with SEND_SIMPLE_GRAPH.time():
|
0
|
135 self._writeGraphResponse()
|
|
136
|
|
137 def _writeGraphResponse(self):
|
|
138 acceptHeader = self.request.headers.get(
|
|
139 'Accept',
|
|
140 # see https://github.com/fiorix/cyclone/issues/20
|
|
141 self.request.headers.get('accept', ''))
|
|
142
|
|
143 if acceptHeader == 'application/nquads':
|
|
144 self.set_header('Content-type', 'application/nquads')
|
|
145 self.masterGraph.serialize(self, format='nquads')
|
|
146 elif acceptHeader == 'application/ld+json':
|
|
147 self.set_header('Content-type', 'application/ld+json')
|
|
148 self.masterGraph.serialize(self, format='json-ld', indent=2)
|
|
149 else:
|
|
150 if acceptHeader.startswith('text/html'):
|
|
151 self._writeGraphForBrowser()
|
|
152 return
|
|
153 self.set_header('Content-type', 'application/x-trig')
|
|
154 self.masterGraph.serialize(self, format='trig')
|
|
155
|
|
156 def _writeGraphForBrowser(self):
|
|
157 # We think this is a browser, so respond with a live graph view
|
|
158 # (todo)
|
|
159 self.set_header('Content-type', 'text/html')
|
|
160
|
|
161 self.write(b'''
|
|
162 <html><body><pre>''')
|
|
163
|
|
164 ns = NamespaceManager(self.masterGraph._graph)
|
|
165 # maybe these could be on the PatchableGraph instance
|
|
166 ns.bind('ex', 'http://example.com/')
|
|
167 ns.bind('', 'http://projects.bigasterisk.com/room/')
|
|
168 ns.bind("rdf", "http://www.w3.org/1999/02/22-rdf-syntax-ns#")
|
|
169 ns.bind("xsd", "http://www.w3.org/2001/XMLSchema#")
|
|
170
|
|
171 for s, p, o, g in sorted(self.masterGraph._graph.quads()):
|
|
172 g = g.identifier
|
|
173 nquadLine = f'{s.n3(ns)} {p.n3(ns)} {o.n3(ns)} {g.n3(ns)} .\n'
|
|
174 self.write(html.escape(nquadLine).encode('utf8'))
|
|
175
|
|
176 self.write(b'''
|
|
177 </pre>
|
|
178 <p>
|
|
179 <a href="#">[refresh]</a>
|
|
180 <label><input type="checkbox"> Auto-refresh</label>
|
|
181 </p>
|
|
182 <script>
|
|
183
|
|
184 if (new URL(window.location).searchParams.get('autorefresh') == 'on') {
|
|
185 document.querySelector("input").checked = true;
|
|
186 setTimeout(() => {
|
|
187 requestAnimationFrame(() => {
|
|
188 window.location.replace(window.location.href);
|
|
189 });
|
|
190 }, 2000);
|
|
191 }
|
|
192
|
|
193 document.querySelector("a").addEventListener("click", (ev) => {
|
|
194 ev.preventDefault();
|
|
195 window.location.replace(window.location.href);
|
|
196
|
|
197 });
|
|
198 document.querySelector("input").addEventListener("change", (ev) => {
|
|
199 if (document.querySelector("input").checked) {
|
|
200 const u = new URL(window.location);
|
|
201 u.searchParams.set('autorefresh', 'on');
|
|
202 window.location.replace(u.href);
|
|
203 } else {
|
|
204 const u = new URL(window.location);
|
|
205 u.searchParams.delete('autorefresh');
|
|
206 window.location.replace(u.href);
|
|
207 }
|
|
208 });
|
|
209
|
|
210 </script>
|
|
211 </body></html>
|
|
212 ''')
|
|
213
|
|
214
|
3
|
215 SEND_FULL_GRAPH = Summary('send_full_graph', 'fullGraph SSE events')
|
|
216 SEND_PATCH = Summary('send_patch', 'patch SSE events')
|
|
217
|
|
218
|
0
|
219 class CycloneGraphEventsHandler(cyclone.sse.SSEHandler):
|
|
220 """
|
|
221 One session with one client.
|
|
222
|
|
223 returns current graph plus future patches to keep remote version
|
|
224 in sync with ours.
|
|
225
|
|
226 intsead of turning off buffering all over, it may work for this
|
|
227 response to send 'x-accel-buffering: no', per
|
|
228 http://nginx.org/en/docs/http/ngx_http_proxy_module.html#proxy_buffering
|
|
229 """
|
|
230 def __init__(self, application, request, masterGraph):
|
|
231 cyclone.sse.SSEHandler.__init__(self, application, request)
|
|
232 self.masterGraph = masterGraph
|
|
233
|
|
234 def bind(self):
|
3
|
235 with SEND_FULL_GRAPH.time():
|
0
|
236 graphJson = self.masterGraph.asJsonLd()
|
|
237 log.debug("send fullGraph event: %s", graphJson)
|
|
238 self.sendEvent(message=graphJson, event=b'fullGraph')
|
|
239 self.masterGraph.addObserver(self.onPatch)
|
|
240
|
|
241 def onPatch(self, patchJson):
|
3
|
242 with SEND_PATCH.time():
|
0
|
243 # throttle and combine patches here- ideally we could see how
|
|
244 # long the latency to the client is to make a better rate choice
|
|
245 self.sendEvent(message=patchJson, event=b'patch')
|
|
246
|
|
247 def unbind(self):
|
|
248 self.masterGraph.removeObserver(self.onPatch)
|