annotate collector.py @ 1:1275220a644b

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