annotate collector.py @ 9:36471461685f

py server doesn't do static files now
author drewp@bigasterisk.com
date Fri, 25 Nov 2022 20:33:05 -0800
parents a3b6b06fc699
children 032e59be8fe9
Ignore whitespace changes - Everywhere: Within whitespace: At end of lines:
rev   line source
0
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
1 """
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
2 requesting /graph/foo returns an SSE patch stream that's the
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
3 result of fetching multiple other SSE patch streams. The result stream
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
4 may include new statements injected by this service.
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
5
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
6 Future:
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
7 - filter out unneeded stmts from the sources
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
8 - give a time resolution and concatenate any patches that come faster than that res
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
9 """
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
10 import collections
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
11 import json
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
12 import logging
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
13 import time
6
a3b6b06fc699 cleanup and type fixes
drewp@bigasterisk.com
parents: 1
diff changeset
14 from typing import (Callable, Dict, List, Optional, Sequence, Set, Tuple, Union)
0
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
15
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
16 import cyclone.sse
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
17 import cyclone.web
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
18 from docopt import docopt
9
36471461685f py server doesn't do static files now
drewp@bigasterisk.com
parents: 6
diff changeset
19 from patchablegraph.patchablegraph import jsonFromPatch
0
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
20 from patchablegraph.patchsource import PatchSource, ReconnectingPatchSource
6
a3b6b06fc699 cleanup and type fixes
drewp@bigasterisk.com
parents: 1
diff changeset
21 from prometheus_client import Summary
0
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
22 from prometheus_client.exposition import generate_latest
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
23 from prometheus_client.registry import REGISTRY
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
24 from rdfdb.patch import Patch
6
a3b6b06fc699 cleanup and type fixes
drewp@bigasterisk.com
parents: 1
diff changeset
25 from rdflib import Namespace, URIRef
1
drewp@bigasterisk.com
parents: 0
diff changeset
26 from rdflib.term import Node
0
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
27 from standardservice.logsetup import enableTwistedLog, log
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
28 from twisted.internet import defer, reactor
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
29
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
30 from collector_config import config
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
31
9
36471461685f py server doesn't do static files now
drewp@bigasterisk.com
parents: 6
diff changeset
32 import cyclone.sse
36471461685f py server doesn't do static files now
drewp@bigasterisk.com
parents: 6
diff changeset
33 def py3_sendEvent(self, message, event=None, eid=None, retry=None):
36471461685f py server doesn't do static files now
drewp@bigasterisk.com
parents: 6
diff changeset
34
36471461685f py server doesn't do static files now
drewp@bigasterisk.com
parents: 6
diff changeset
35 if isinstance(message, dict):
36471461685f py server doesn't do static files now
drewp@bigasterisk.com
parents: 6
diff changeset
36 message = cyclone.sse.escape.json_encode(message)
36471461685f py server doesn't do static files now
drewp@bigasterisk.com
parents: 6
diff changeset
37 if isinstance(message, str):
36471461685f py server doesn't do static files now
drewp@bigasterisk.com
parents: 6
diff changeset
38 message = message.encode("utf-8")
36471461685f py server doesn't do static files now
drewp@bigasterisk.com
parents: 6
diff changeset
39 assert isinstance(message, bytes)
36471461685f py server doesn't do static files now
drewp@bigasterisk.com
parents: 6
diff changeset
40 if eid:
36471461685f py server doesn't do static files now
drewp@bigasterisk.com
parents: 6
diff changeset
41 self.transport.write(b"id: %s\n" % eid)
36471461685f py server doesn't do static files now
drewp@bigasterisk.com
parents: 6
diff changeset
42 if event:
36471461685f py server doesn't do static files now
drewp@bigasterisk.com
parents: 6
diff changeset
43 self.transport.write(b"event: %s\n" % event)
36471461685f py server doesn't do static files now
drewp@bigasterisk.com
parents: 6
diff changeset
44 if retry:
36471461685f py server doesn't do static files now
drewp@bigasterisk.com
parents: 6
diff changeset
45 self.transport.write(b"retry: %s\n" % retry)
36471461685f py server doesn't do static files now
drewp@bigasterisk.com
parents: 6
diff changeset
46 self.transport.write(b"data: %s\n\n" % message)
36471461685f py server doesn't do static files now
drewp@bigasterisk.com
parents: 6
diff changeset
47 cyclone.sse.SSEHandler.sendEvent = py3_sendEvent
36471461685f py server doesn't do static files now
drewp@bigasterisk.com
parents: 6
diff changeset
48
36471461685f py server doesn't do static files now
drewp@bigasterisk.com
parents: 6
diff changeset
49
1
drewp@bigasterisk.com
parents: 0
diff changeset
50 Statement = Tuple[Node, Node, Node, Node]
0
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
51
6
a3b6b06fc699 cleanup and type fixes
drewp@bigasterisk.com
parents: 1
diff changeset
52
a3b6b06fc699 cleanup and type fixes
drewp@bigasterisk.com
parents: 1
diff changeset
53 # SourceUri = NewType('SourceUri', URIRef) # doesn't work
0
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
54 class SourceUri(URIRef):
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
55 pass
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
56
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
57
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
58 ROOM = Namespace("http://projects.bigasterisk.com/room/")
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
59 COLLECTOR = SourceUri(URIRef('http://bigasterisk.com/sse_collector/'))
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
60
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
61 GET_STATE_CALLS = Summary("get_state_calls", 'calls')
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
62 LOCAL_STATEMENTS_PATCH_CALLS = Summary("local_statements_patch_calls", 'calls')
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
63 MAKE_SYNC_PATCH_CALLS = Summary("make_sync_patch_calls", 'calls')
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
64 ON_PATCH_CALLS = Summary("on_patch_calls", 'calls')
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
65 SEND_UPDATE_PATCH_CALLS = Summary("send_update_patch_calls", 'calls')
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
66 REPLACE_SOURCE_STATEMENTS_CALLS = Summary("replace_source_statements_calls", 'calls')
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
67
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
68
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
69 class Metrics(cyclone.web.RequestHandler):
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
70
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
71 def get(self):
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
72 self.add_header('content-type', 'text/plain')
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
73 self.write(generate_latest(REGISTRY))
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
74
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
75
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
76 class LocalStatements(object):
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
77 """
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
78 functions that make statements originating from sse_collector itself
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
79 """
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
80
6
a3b6b06fc699 cleanup and type fixes
drewp@bigasterisk.com
parents: 1
diff changeset
81 def __init__(self, applyPatch: Callable[[SourceUri, Patch], None]):
0
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
82 self.applyPatch = applyPatch
6
a3b6b06fc699 cleanup and type fixes
drewp@bigasterisk.com
parents: 1
diff changeset
83 self._sourceState: Dict[SourceUri, Optional[URIRef]] = {} # source: state URIRef
0
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
84
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
85 @LOCAL_STATEMENTS_PATCH_CALLS.time()
6
a3b6b06fc699 cleanup and type fixes
drewp@bigasterisk.com
parents: 1
diff changeset
86 def setSourceState(self, source: SourceUri, state: Optional[URIRef]):
0
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
87 """
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
88 add a patch to the COLLECTOR graph about the state of this
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
89 source. state=None to remove the source.
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
90 """
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
91 oldState = self._sourceState.get(source, None)
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
92 if state == oldState:
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
93 return
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
94 log.info('source state %s -> %s', source, state)
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
95 if oldState is None:
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
96 self._sourceState[source] = state
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
97 self.applyPatch(COLLECTOR, Patch(addQuads=[
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
98 (COLLECTOR, ROOM['source'], source, COLLECTOR),
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
99 (source, ROOM['state'], state, COLLECTOR),
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
100 ]))
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
101 elif state is None:
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
102 del self._sourceState[source]
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
103 self.applyPatch(COLLECTOR, Patch(delQuads=[
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
104 (COLLECTOR, ROOM['source'], source, COLLECTOR),
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
105 (source, ROOM['state'], oldState, COLLECTOR),
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
106 ]))
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
107 else:
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
108 self._sourceState[source] = state
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
109 self.applyPatch(COLLECTOR, Patch(addQuads=[
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
110 (source, ROOM['state'], state, COLLECTOR),
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
111 ], delQuads=[
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
112 (source, ROOM['state'], oldState, COLLECTOR),
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
113 ]))
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
114
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
115
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
116 def abbrevTerm(t: Union[URIRef, Node]) -> Union[str, Node]:
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
117 if isinstance(t, URIRef):
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
118 return (t.replace('http://projects.bigasterisk.com/room/', 'room:').replace('http://projects.bigasterisk.com/device/',
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
119 'dev:').replace('http://bigasterisk.com/sse_collector/', 'sc:'))
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
120 return t
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
121
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
122
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
123 def abbrevStmt(stmt: Statement) -> str:
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
124 return '(%s %s %s %s)' % (abbrevTerm(stmt[0]), abbrevTerm(stmt[1]), abbrevTerm(stmt[2]), abbrevTerm(stmt[3]))
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
125
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
126
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
127 class PatchSink(cyclone.sse.SSEHandler):
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
128 _handlerSerial = 0
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
129
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
130 def __init__(self, application: cyclone.web.Application, request):
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
131 cyclone.sse.SSEHandler.__init__(self, application, request)
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
132 self.bound = False
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
133 self.created = time.time()
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
134 self.graphClients = self.settings.graphClients
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
135
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
136 self._serial = PatchSink._handlerSerial
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
137 PatchSink._handlerSerial += 1
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
138 self.lastPatchSentTime: float = 0.0
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
139
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
140 def __repr__(self) -> str:
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
141 return '<Handler #%s>' % self._serial
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
142
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
143 def state(self) -> Dict:
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
144 return {
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
145 'created': round(self.created, 2),
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
146 'ageHours': round((time.time() - self.created) / 3600, 2),
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
147 'streamId': self.streamId,
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
148 'remoteIp': self.request.remote_ip, # wrong, need some forwarded-for thing
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
149 'foafAgent': self.request.headers.get('X-Foaf-Agent'),
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
150 'userAgent': self.request.headers.get('user-agent'),
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
151 }
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
152
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
153 def bind(self, *args, **kwargs):
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
154 self.streamId = args[0]
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
155
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
156 self.graphClients.addSseHandler(self)
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
157 # If something goes wrong with addSseHandler, I don't want to
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
158 # try removeSseHandler.
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
159 self.bound = True
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
160
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
161 def unbind(self) -> None:
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
162 if self.bound:
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
163 self.graphClients.removeSseHandler(self)
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
164
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
165
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
166 StatementTable = Dict[Statement, Tuple[Set[SourceUri], Set[PatchSink]]]
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
167
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
168
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
169 class PostDeleter(object):
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
170
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
171 def __init__(self, statements: StatementTable):
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
172 self.statements = statements
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
173
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
174 def __enter__(self):
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
175 self._garbage: List[Statement] = []
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
176 return self
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
177
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
178 def add(self, stmt: Statement):
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
179 self._garbage.append(stmt)
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
180
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
181 def __exit__(self, type, value, traceback):
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
182 if type is not None:
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
183 raise NotImplementedError()
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
184 for stmt in self._garbage:
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
185 del self.statements[stmt]
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
186
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
187
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
188 class ActiveStatements(object):
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
189
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
190 def __init__(self):
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
191 # This table holds statements asserted by any of our sources
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
192 # plus local statements that we introduce (source is
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
193 # http://bigasterisk.com/sse_collector/).
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
194 self.table: StatementTable = collections.defaultdict(lambda: (set(), set()))
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
195
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
196 def state(self) -> Dict:
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
197 return {
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
198 'len': len(self.table),
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
199 }
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
200
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
201 def postDeleteStatements(self) -> PostDeleter:
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
202 return PostDeleter(self.table)
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
203
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
204 def pprintTable(self) -> None:
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
205 for i, (stmt, (sources, handlers)) in enumerate(sorted(self.table.items())):
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
206 print("%03d. %-80s from %s to %s" % (i, abbrevStmt(stmt), [abbrevTerm(s) for s in sources], handlers))
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
207
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
208 @MAKE_SYNC_PATCH_CALLS.time()
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
209 def makeSyncPatch(self, handler: PatchSink, sources: Set[SourceUri]):
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
210 # todo: this could run all handlers at once, which is how we
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
211 # use it anyway
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
212 adds = []
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
213 dels = []
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
214
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
215 with self.postDeleteStatements() as garbage:
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
216 for stmt, (stmtSources, handlers) in self.table.items():
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
217 belongsInHandler = not sources.isdisjoint(stmtSources)
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
218 handlerHasIt = handler in handlers
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
219 # log.debug("%s belong=%s has=%s",
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
220 # abbrevStmt(stmt), belongsInHandler, handlerHasIt)
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
221 if belongsInHandler and not handlerHasIt:
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
222 adds.append(stmt)
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
223 handlers.add(handler)
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
224 elif not belongsInHandler and handlerHasIt:
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
225 dels.append(stmt)
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
226 handlers.remove(handler)
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
227 if not handlers and not stmtSources:
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
228 garbage.add(stmt)
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
229
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
230 return Patch(addQuads=adds, delQuads=dels)
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
231
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
232 def applySourcePatch(self, source: SourceUri, p: Patch):
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
233 for stmt in p.addQuads:
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
234 sourceUrls, handlers = self.table[stmt]
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
235 if source in sourceUrls:
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
236 raise ValueError("%s added stmt that it already had: %s" % (source, abbrevStmt(stmt)))
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
237 sourceUrls.add(source)
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
238
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
239 with self.postDeleteStatements() as garbage:
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
240 for stmt in p.delQuads:
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
241 sourceUrls, handlers = self.table[stmt]
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
242 if source not in sourceUrls:
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
243 raise ValueError("%s deleting stmt that it didn't have: %s" % (source, abbrevStmt(stmt)))
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
244 sourceUrls.remove(source)
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
245 # this is rare, since some handler probably still has
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
246 # the stmt we're deleting, but it can happen e.g. when
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
247 # a handler was just deleted
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
248 if not sourceUrls and not handlers:
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
249 garbage.add(stmt)
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
250
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
251 @REPLACE_SOURCE_STATEMENTS_CALLS.time()
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
252 def replaceSourceStatements(self, source: SourceUri, stmts: Sequence[Statement]):
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
253 log.debug('replaceSourceStatements with %s stmts', len(stmts))
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
254 newStmts = set(stmts)
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
255
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
256 with self.postDeleteStatements() as garbage:
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
257 for stmt, (sources, handlers) in self.table.items():
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
258 if source in sources:
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
259 if stmt not in stmts:
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
260 sources.remove(source)
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
261 if not sources and not handlers:
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
262 garbage.add(stmt)
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
263 else:
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
264 if stmt in stmts:
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
265 sources.add(source)
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
266 newStmts.discard(stmt)
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
267
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
268 self.applySourcePatch(source, Patch(addQuads=newStmts, delQuads=[]))
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
269
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
270 def discardHandler(self, handler: PatchSink):
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
271 with self.postDeleteStatements() as garbage:
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
272 for stmt, (sources, handlers) in self.table.items():
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
273 handlers.discard(handler)
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
274 if not sources and not handlers:
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
275 garbage.add(stmt)
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
276
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
277 def discardSource(self, source: SourceUri):
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
278 with self.postDeleteStatements() as garbage:
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
279 for stmt, (sources, handlers) in self.table.items():
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
280 sources.discard(source)
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
281 if not sources and not handlers:
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
282 garbage.add(stmt)
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
283
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
284
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
285 class GraphClients(object):
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
286 """
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
287 All the active PatchSources and SSEHandlers
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
288
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
289 To handle all the overlapping-statement cases, we store a set of
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
290 true statements along with the sources that are currently
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
291 asserting them and the requesters who currently know them. As
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
292 statements come and go, we make patches to send to requesters.
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
293 """
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
294
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
295 def __init__(self):
6
a3b6b06fc699 cleanup and type fixes
drewp@bigasterisk.com
parents: 1
diff changeset
296 self.clients: Dict[SourceUri, Union[PatchSource, ReconnectingPatchSource]] = {} # (COLLECTOR is not listed)
0
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
297 self.handlers: Set[PatchSink] = set()
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
298 self.statements: ActiveStatements = ActiveStatements()
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
299
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
300 self._localStatements = LocalStatements(self._onPatch)
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
301
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
302 def state(self) -> Dict:
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
303 return {
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
304 'clients': sorted([ps.state() for ps in self.clients.values()], key=lambda r: r['reconnectedPatchSource']['url']),
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
305 'sseHandlers': sorted([h.state() for h in self.handlers], key=lambda r: (r['streamId'], r['created'])),
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
306 'statements': self.statements.state(),
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
307 }
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
308
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
309 def _sourcesForHandler(self, handler: PatchSink) -> List[SourceUri]:
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
310 streamId = handler.streamId
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
311 matches = [s for s in config['streams'] if s['id'] == streamId]
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
312 if len(matches) != 1:
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
313 raise ValueError("%s matches for %r" % (len(matches), streamId))
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
314 return [SourceUri(URIRef(s)) for s in matches[0]['sources']] + [COLLECTOR]
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
315
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
316 @ON_PATCH_CALLS.time()
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
317 def _onPatch(self, source: SourceUri, p: Patch, fullGraph: bool = False):
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
318 if fullGraph:
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
319 # a reconnect may need to resend the full graph even
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
320 # though we've already sent some statements
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
321 self.statements.replaceSourceStatements(source, p.addQuads)
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
322 else:
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
323 self.statements.applySourcePatch(source, p)
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
324
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
325 self._sendUpdatePatch()
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
326
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
327 if log.isEnabledFor(logging.DEBUG):
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
328 self.statements.pprintTable()
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
329
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
330 if source != COLLECTOR:
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
331 self._localStatements.setSourceState(source, ROOM['fullGraphReceived'] if fullGraph else ROOM['patchesReceived'])
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
332
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
333 @SEND_UPDATE_PATCH_CALLS.time()
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
334 def _sendUpdatePatch(self, handler: Optional[PatchSink] = None):
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
335 """
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
336 send a patch event out this handler to bring it up to date with
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
337 self.statements
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
338 """
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
339 now = time.time()
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
340 selected = self.handlers
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
341 if handler is not None:
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
342 if handler not in self.handlers:
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
343 log.error("called _sendUpdatePatch on a handler that's gone")
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
344 return
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
345 selected = {handler}
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
346 # reduce loops here- prepare all patches at once
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
347 for h in selected:
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
348 period = .9
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
349 if 'Raspbian' in h.request.headers.get('user-agent', ''):
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
350 period = 5
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
351 if h.lastPatchSentTime > now - period:
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
352 continue
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
353 p = self.statements.makeSyncPatch(h, set(self._sourcesForHandler(h)))
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
354 log.debug('makeSyncPatch for %r: %r', h, p.jsonRepr)
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
355 if not p.isNoop():
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
356 log.debug("send patch %s to %s", p.shortSummary(), h)
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
357 # This can be a giant line, which was a problem
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
358 # once. Might be nice for this service to try to break
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
359 # it up into multiple sends, although there's no
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
360 # guarantee at all since any single stmt could be any
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
361 # length.
9
36471461685f py server doesn't do static files now
drewp@bigasterisk.com
parents: 6
diff changeset
362 h.sendEvent(message=jsonFromPatch(p), event=b'patch')
0
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
363 h.lastPatchSentTime = now
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
364 else:
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
365 log.debug('nothing to send to %s', h)
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
366
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
367 def addSseHandler(self, handler: PatchSink):
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
368 log.info('addSseHandler %r %r', handler, handler.streamId)
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
369
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
370 # fail early if id doesn't match
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
371 sources = self._sourcesForHandler(handler)
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
372
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
373 self.handlers.add(handler)
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
374
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
375 for source in sources:
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
376 if source not in self.clients and source != COLLECTOR:
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
377 log.debug('connect to patch source %s', source)
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
378 self._localStatements.setSourceState(source, ROOM['connect'])
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
379 self.clients[source] = ReconnectingPatchSource(source,
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
380 listener=lambda p, fullGraph, source=source: self._onPatch(source, p, fullGraph),
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
381 reconnectSecs=10)
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
382 log.debug('bring new client up to date')
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
383
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
384 self._sendUpdatePatch(handler)
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
385
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
386 def removeSseHandler(self, handler: PatchSink):
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
387 log.info('removeSseHandler %r', handler)
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
388 self.statements.discardHandler(handler)
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
389 for source in self._sourcesForHandler(handler):
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
390 for otherHandler in self.handlers:
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
391 if (otherHandler != handler and source in self._sourcesForHandler(otherHandler)):
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
392 # still in use
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
393 break
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
394 else:
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
395 self._stopClient(source)
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
396
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
397 self.handlers.remove(handler)
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
398
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
399 def _stopClient(self, url: SourceUri):
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
400 if url == COLLECTOR:
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
401 return
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
402
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
403 self.clients[url].stop()
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
404
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
405 self.statements.discardSource(url)
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
406
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
407 self._localStatements.setSourceState(url, None)
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
408 if url in self.clients:
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
409 del self.clients[url]
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
410
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
411 self.cleanup()
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
412
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
413 def cleanup(self):
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
414 """
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
415 despite the attempts above, we still get useless rows in the table
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
416 sometimes
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
417 """
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
418 with self.statements.postDeleteStatements() as garbage:
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
419 for stmt, (sources, handlers) in self.statements.table.items():
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
420 if not sources and not any(h in self.handlers for h in handlers):
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
421 garbage.add(stmt)
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
422
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
423
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
424 class State(cyclone.web.RequestHandler):
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
425
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
426 @GET_STATE_CALLS.time()
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
427 def get(self) -> None:
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
428 try:
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
429 state = self.settings.graphClients.state()
9
36471461685f py server doesn't do static files now
drewp@bigasterisk.com
parents: 6
diff changeset
430 msg = json.dumps({'graphClients': state}, indent=2, default=lambda obj: '<unserializable>')
36471461685f py server doesn't do static files now
drewp@bigasterisk.com
parents: 6
diff changeset
431 log.info(msg)
36471461685f py server doesn't do static files now
drewp@bigasterisk.com
parents: 6
diff changeset
432 self.write(msg)
0
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
433 except Exception:
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
434 import traceback
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
435 traceback.print_exc()
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
436 raise
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
437
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
438
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
439 class GraphList(cyclone.web.RequestHandler):
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
440
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
441 def get(self) -> None:
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
442 self.write(json.dumps(config['streams']))
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
443
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
444
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
445 if __name__ == '__main__':
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
446 arg = docopt("""
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
447 Usage: sse_collector.py [options]
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
448
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
449 -v Verbose
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
450 -i Info level only
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
451 """)
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
452
9
36471461685f py server doesn't do static files now
drewp@bigasterisk.com
parents: 6
diff changeset
453 if True:
0
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
454 enableTwistedLog()
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
455 log.setLevel(logging.DEBUG if arg['-v'] else logging.INFO)
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
456 defer.setDebugging(True)
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
457
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
458 graphClients = GraphClients()
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
459
6
a3b6b06fc699 cleanup and type fixes
drewp@bigasterisk.com
parents: 1
diff changeset
460 reactor.listenTCP(
a3b6b06fc699 cleanup and type fixes
drewp@bigasterisk.com
parents: 1
diff changeset
461 9072,
a3b6b06fc699 cleanup and type fixes
drewp@bigasterisk.com
parents: 1
diff changeset
462 cyclone.web.Application( #
a3b6b06fc699 cleanup and type fixes
drewp@bigasterisk.com
parents: 1
diff changeset
463 handlers=[
a3b6b06fc699 cleanup and type fixes
drewp@bigasterisk.com
parents: 1
diff changeset
464 (r'/state', State),
a3b6b06fc699 cleanup and type fixes
drewp@bigasterisk.com
parents: 1
diff changeset
465 (r'/graph/', GraphList),
a3b6b06fc699 cleanup and type fixes
drewp@bigasterisk.com
parents: 1
diff changeset
466 (r'/graph/(.+)', PatchSink),
a3b6b06fc699 cleanup and type fixes
drewp@bigasterisk.com
parents: 1
diff changeset
467 (r'/metrics', Metrics),
a3b6b06fc699 cleanup and type fixes
drewp@bigasterisk.com
parents: 1
diff changeset
468 ],
a3b6b06fc699 cleanup and type fixes
drewp@bigasterisk.com
parents: 1
diff changeset
469 graphClients=graphClients),
a3b6b06fc699 cleanup and type fixes
drewp@bigasterisk.com
parents: 1
diff changeset
470 interface='::')
0
e2d855c00e57 initial move from homeauto/ repo
drewp@bigasterisk.com
parents:
diff changeset
471 reactor.run()