tradekart-notify 0.1.0__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- tradekart_notify-0.1.0/PKG-INFO +22 -0
- tradekart_notify-0.1.0/README.md +7 -0
- tradekart_notify-0.1.0/pyproject.toml +49 -0
- tradekart_notify-0.1.0/setup.cfg +4 -0
- tradekart_notify-0.1.0/tests/test_notify.py +346 -0
- tradekart_notify-0.1.0/tests/test_version.py +7 -0
- tradekart_notify-0.1.0/tradekart_notify/__init__.py +6 -0
- tradekart_notify-0.1.0/tradekart_notify/channels/__init__.py +0 -0
- tradekart_notify-0.1.0/tradekart_notify/channels/base.py +38 -0
- tradekart_notify-0.1.0/tradekart_notify/channels/registry.py +44 -0
- tradekart_notify-0.1.0/tradekart_notify/channels/telegram.py +63 -0
- tradekart_notify-0.1.0/tradekart_notify/constants.py +1 -0
- tradekart_notify-0.1.0/tradekart_notify/consumer.py +47 -0
- tradekart_notify-0.1.0/tradekart_notify/envelope.py +93 -0
- tradekart_notify-0.1.0/tradekart_notify/errors.py +17 -0
- tradekart_notify-0.1.0/tradekart_notify/formatting.py +21 -0
- tradekart_notify-0.1.0/tradekart_notify/producer.py +102 -0
- tradekart_notify-0.1.0/tradekart_notify/py.typed +0 -0
- tradekart_notify-0.1.0/tradekart_notify/secret_source.py +35 -0
- tradekart_notify-0.1.0/tradekart_notify/transport.py +43 -0
- tradekart_notify-0.1.0/tradekart_notify/version.py +1 -0
- tradekart_notify-0.1.0/tradekart_notify.egg-info/PKG-INFO +22 -0
- tradekart_notify-0.1.0/tradekart_notify.egg-info/SOURCES.txt +24 -0
- tradekart_notify-0.1.0/tradekart_notify.egg-info/dependency_links.txt +1 -0
- tradekart_notify-0.1.0/tradekart_notify.egg-info/requires.txt +9 -0
- tradekart_notify-0.1.0/tradekart_notify.egg-info/top_level.txt +1 -0
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: tradekart-notify
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Delivers TradeKart alerts: event envelope, SNS producer and channel consumers
|
|
5
|
+
Author: Vikalp Varshney
|
|
6
|
+
Requires-Python: >=3.11
|
|
7
|
+
Description-Content-Type: text/markdown
|
|
8
|
+
Provides-Extra: aws
|
|
9
|
+
Requires-Dist: boto3<1.40.62,>=1.40.46; extra == "aws"
|
|
10
|
+
Provides-Extra: dev
|
|
11
|
+
Requires-Dist: pytest>=8.0.0; extra == "dev"
|
|
12
|
+
Requires-Dist: pytest-cov>=5.0.0; extra == "dev"
|
|
13
|
+
Requires-Dist: ruff>=0.6.0; extra == "dev"
|
|
14
|
+
Requires-Dist: mypy>=1.10.0; extra == "dev"
|
|
15
|
+
|
|
16
|
+
# tradekart-notify
|
|
17
|
+
|
|
18
|
+
Delivers TradeKart alerts: the event envelope, an SNS producer, and one
|
|
19
|
+
consumer per channel (Telegram, WhatsApp, email, SMS).
|
|
20
|
+
|
|
21
|
+
Standard library only at its core. `boto3` is an optional extra (`aws`) for the
|
|
22
|
+
SNS producer. This package never imports `tradekart_automation`.
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
# tradekart-notify
|
|
2
|
+
|
|
3
|
+
Delivers TradeKart alerts: the event envelope, an SNS producer, and one
|
|
4
|
+
consumer per channel (Telegram, WhatsApp, email, SMS).
|
|
5
|
+
|
|
6
|
+
Standard library only at its core. `boto3` is an optional extra (`aws`) for the
|
|
7
|
+
SNS producer. This package never imports `tradekart_automation`.
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["setuptools>=69.0", "wheel"]
|
|
3
|
+
build-backend = "setuptools.build_meta"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "tradekart-notify"
|
|
7
|
+
dynamic = ["version"]
|
|
8
|
+
authors = [{ name = "Vikalp Varshney" }]
|
|
9
|
+
description = "Delivers TradeKart alerts: event envelope, SNS producer and channel consumers"
|
|
10
|
+
readme = "README.md"
|
|
11
|
+
requires-python = ">=3.11"
|
|
12
|
+
dependencies = []
|
|
13
|
+
|
|
14
|
+
[project.optional-dependencies]
|
|
15
|
+
aws = ["boto3>=1.40.46,<1.40.62"]
|
|
16
|
+
dev = ["pytest>=8.0.0", "pytest-cov>=5.0.0", "ruff>=0.6.0", "mypy>=1.10.0"]
|
|
17
|
+
|
|
18
|
+
[tool.setuptools.packages.find]
|
|
19
|
+
where = ["."]
|
|
20
|
+
include = ["tradekart_notify*"]
|
|
21
|
+
namespaces = false
|
|
22
|
+
|
|
23
|
+
[tool.setuptools.package-data]
|
|
24
|
+
tradekart_notify = ["py.typed"]
|
|
25
|
+
|
|
26
|
+
[tool.setuptools.dynamic]
|
|
27
|
+
version = { attr = "tradekart_notify.version.__version__" }
|
|
28
|
+
|
|
29
|
+
[tool.pytest.ini_options]
|
|
30
|
+
testpaths = ["tests"]
|
|
31
|
+
addopts = "-ra --strict-markers --import-mode=importlib --cov=tradekart_notify --cov-branch --cov-report=term-missing --cov-fail-under=95"
|
|
32
|
+
|
|
33
|
+
[tool.ruff]
|
|
34
|
+
line-length = 88
|
|
35
|
+
target-version = "py311"
|
|
36
|
+
|
|
37
|
+
[tool.ruff.lint]
|
|
38
|
+
select = ["E", "F", "I", "UP", "B", "S", "DTZ", "C4", "SIM", "RUF"]
|
|
39
|
+
|
|
40
|
+
[tool.ruff.lint.per-file-ignores]
|
|
41
|
+
"tests/**" = ["S101"]
|
|
42
|
+
|
|
43
|
+
[tool.ruff.format]
|
|
44
|
+
quote-style = "single"
|
|
45
|
+
|
|
46
|
+
[tool.mypy]
|
|
47
|
+
python_version = "3.11"
|
|
48
|
+
strict = true
|
|
49
|
+
files = ["tradekart_notify"]
|
|
@@ -0,0 +1,346 @@
|
|
|
1
|
+
import io
|
|
2
|
+
import json
|
|
3
|
+
import urllib.error
|
|
4
|
+
import urllib.request
|
|
5
|
+
from contextlib import nullcontext
|
|
6
|
+
from datetime import UTC, datetime
|
|
7
|
+
from enum import StrEnum
|
|
8
|
+
from types import SimpleNamespace
|
|
9
|
+
|
|
10
|
+
import pytest
|
|
11
|
+
|
|
12
|
+
from tradekart_notify.channels.base import Channel
|
|
13
|
+
from tradekart_notify.channels.registry import ChannelRegistry, default_registry
|
|
14
|
+
from tradekart_notify.channels.telegram import TelegramChannel, TelegramConfig
|
|
15
|
+
from tradekart_notify.consumer import SqsConsumer
|
|
16
|
+
from tradekart_notify.envelope import Envelope, Level
|
|
17
|
+
from tradekart_notify.errors import ConfigError, DeliveryError, EnvelopeError
|
|
18
|
+
from tradekart_notify.formatting import render_text
|
|
19
|
+
from tradekart_notify.producer import Publisher, SnsEventSink, SnsPublisher
|
|
20
|
+
from tradekart_notify.secret_source import SecretsManagerSource, SecretSource
|
|
21
|
+
from tradekart_notify.transport import HttpResponse, HttpTransport, UrllibTransport
|
|
22
|
+
|
|
23
|
+
T0 = datetime(2026, 11, 2, 4, 0, tzinfo=UTC) # 09:30 in India
|
|
24
|
+
TOKEN = '123456:SECRET-TOKEN' # noqa: S105 - a fake value for tests
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def envelope(**overrides):
|
|
28
|
+
values = {
|
|
29
|
+
'event_id': 'e1',
|
|
30
|
+
'type': 'ENTRY_FILLED',
|
|
31
|
+
'level': Level.INFO,
|
|
32
|
+
'message': 'RELIANCE: bought as planned',
|
|
33
|
+
'data': {'symbol': 'RELIANCE', 'filled': '10'},
|
|
34
|
+
'occurred_at': T0,
|
|
35
|
+
'source': 'automation',
|
|
36
|
+
}
|
|
37
|
+
return Envelope(**{**values, **overrides})
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
GOOD = json.loads(envelope().to_json())
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def mutated(**changes):
|
|
44
|
+
return json.dumps({**GOOD, **changes})
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
# --- envelope -------------------------------------------------------------------
|
|
48
|
+
|
|
49
|
+
BAD_JSON = [
|
|
50
|
+
'not json',
|
|
51
|
+
'[1, 2]', # not an object
|
|
52
|
+
mutated(schema_version=2), # a version we do not know
|
|
53
|
+
json.dumps({k: v for k, v in GOOD.items() if k != 'level'}), # missing field
|
|
54
|
+
mutated(level='FATAL'),
|
|
55
|
+
mutated(data={'a': 1}), # data must be text
|
|
56
|
+
mutated(occurred_at='2026-11-02T09:30:00'), # no timezone
|
|
57
|
+
mutated(occurred_at='yesterday'),
|
|
58
|
+
mutated(event_id=''),
|
|
59
|
+
]
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
@pytest.mark.parametrize('text', BAD_JSON)
|
|
63
|
+
def test_a_bad_envelope_is_refused(text):
|
|
64
|
+
with pytest.raises(EnvelopeError):
|
|
65
|
+
Envelope.from_json(text)
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def test_an_envelope_round_trips_ignores_extra_fields_and_checks_its_values():
|
|
69
|
+
assert Envelope.from_json(envelope().to_json()) == envelope()
|
|
70
|
+
assert Envelope.from_json(mutated(added_later=1)) == envelope()
|
|
71
|
+
for override, error in [
|
|
72
|
+
({'level': 'INFO'}, TypeError),
|
|
73
|
+
({'data': ['x']}, TypeError),
|
|
74
|
+
({'schema_version': 2}, ValueError),
|
|
75
|
+
]:
|
|
76
|
+
with pytest.raises(error):
|
|
77
|
+
envelope(**override)
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
# --- contracts and the channel template -----------------------------------------
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
class Dummy(Channel):
|
|
84
|
+
name = 'dummy'
|
|
85
|
+
|
|
86
|
+
def __init__(self, error=None):
|
|
87
|
+
self.error, self.delivered = error, []
|
|
88
|
+
|
|
89
|
+
def _deliver(self, text):
|
|
90
|
+
if self.error:
|
|
91
|
+
raise self.error
|
|
92
|
+
self.delivered.append(text)
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
def test_contracts_cannot_be_built_without_every_required_method():
|
|
96
|
+
class Half(Channel):
|
|
97
|
+
name = 'half' # forgot _deliver
|
|
98
|
+
|
|
99
|
+
for contract in (Channel, Publisher, HttpTransport, SecretSource, Half):
|
|
100
|
+
with pytest.raises(TypeError):
|
|
101
|
+
contract()
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
def test_send_formats_then_delivers_and_a_channel_can_reshape_the_text():
|
|
105
|
+
plain = Dummy()
|
|
106
|
+
plain.send(envelope())
|
|
107
|
+
assert plain.delivered == [render_text(envelope(), 4096)]
|
|
108
|
+
|
|
109
|
+
class Sms(Dummy):
|
|
110
|
+
max_length = 20
|
|
111
|
+
|
|
112
|
+
def format(self, envelope):
|
|
113
|
+
return super().format(envelope).upper()
|
|
114
|
+
|
|
115
|
+
sms = Sms()
|
|
116
|
+
sms.send(envelope())
|
|
117
|
+
assert (len(sms.delivered[0]), sms.delivered[0].endswith('...')) == (20, True)
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
def test_failures_become_delivery_errors_that_hide_the_original_text():
|
|
121
|
+
with pytest.raises(DeliveryError) as caught:
|
|
122
|
+
Dummy(RuntimeError(f'cannot reach /bot{TOKEN}')).send(envelope())
|
|
123
|
+
assert str(caught.value) == 'dummy: request failed (RuntimeError)'
|
|
124
|
+
assert caught.value.__cause__ is None
|
|
125
|
+
|
|
126
|
+
already = DeliveryError('dummy: rejected')
|
|
127
|
+
with pytest.raises(DeliveryError) as same:
|
|
128
|
+
Dummy(already).send(envelope())
|
|
129
|
+
assert same.value is already
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
def test_the_text_shows_level_facts_and_india_time():
|
|
133
|
+
for level, icon in [(Level.INFO, '🔵'), (Level.WARN, '🟠'), (Level.CRITICAL, '🔴')]:
|
|
134
|
+
lines = render_text(envelope(level=level), 4096).split('\n')
|
|
135
|
+
assert lines[0] == f'{icon} {level.value} - ENTRY_FILLED'
|
|
136
|
+
assert lines[1:] == [
|
|
137
|
+
'RELIANCE: bought as planned',
|
|
138
|
+
'filled: 10', # facts are sorted by name
|
|
139
|
+
'symbol: RELIANCE',
|
|
140
|
+
'02 Nov 09:30:00 IST',
|
|
141
|
+
]
|
|
142
|
+
|
|
143
|
+
|
|
144
|
+
# --- Telegram ---------------------------------------------------------------------
|
|
145
|
+
|
|
146
|
+
|
|
147
|
+
class FakeTransport(HttpTransport):
|
|
148
|
+
def __init__(self, status=200, body='{"ok": true}', error=None):
|
|
149
|
+
self.status, self.body, self.error, self.calls = status, body, error, []
|
|
150
|
+
|
|
151
|
+
def post_json(self, url, payload):
|
|
152
|
+
self.calls.append((url, payload))
|
|
153
|
+
if self.error:
|
|
154
|
+
raise self.error
|
|
155
|
+
return HttpResponse(self.status, self.body)
|
|
156
|
+
|
|
157
|
+
|
|
158
|
+
def telegram(transport):
|
|
159
|
+
return TelegramChannel(TelegramConfig(TOKEN, '99'), transport)
|
|
160
|
+
|
|
161
|
+
|
|
162
|
+
def test_telegram_sends_the_text_to_the_chat_and_defaults_to_the_real_transport():
|
|
163
|
+
transport = FakeTransport()
|
|
164
|
+
telegram(transport).send(envelope())
|
|
165
|
+
url, payload = transport.calls[0]
|
|
166
|
+
assert url == f'https://api.telegram.org/bot{TOKEN}/sendMessage'
|
|
167
|
+
assert payload == {
|
|
168
|
+
'chat_id': '99',
|
|
169
|
+
'text': render_text(envelope(), 4096),
|
|
170
|
+
'disable_web_page_preview': True,
|
|
171
|
+
}
|
|
172
|
+
assert isinstance(
|
|
173
|
+
TelegramChannel(TelegramConfig(TOKEN, '1'))._transport, UrllibTransport
|
|
174
|
+
)
|
|
175
|
+
|
|
176
|
+
|
|
177
|
+
def why(text):
|
|
178
|
+
return json.dumps({'ok': False, 'description': text})
|
|
179
|
+
|
|
180
|
+
|
|
181
|
+
@pytest.mark.parametrize(
|
|
182
|
+
('status', 'body', 'error', 'expected'),
|
|
183
|
+
[
|
|
184
|
+
(401, why('Unauthorized'), None, 'Unauthorized'),
|
|
185
|
+
(429, why('Too Many Requests'), None, 'Too Many'),
|
|
186
|
+
(200, why('chat not found'), None, 'chat not found'), # 200 but ok is false
|
|
187
|
+
(200, 'not json', None, 'no details'),
|
|
188
|
+
(500, '<html>oops</html>', None, 'no details'),
|
|
189
|
+
(200, '[1]', None, 'no details'), # JSON, but not an object
|
|
190
|
+
(0, '', TimeoutError(f'cannot reach /bot{TOKEN}/x'), 'TimeoutError'),
|
|
191
|
+
],
|
|
192
|
+
)
|
|
193
|
+
def test_a_failed_delivery_says_why_and_never_leaks_the_token(
|
|
194
|
+
status, body, error, expected
|
|
195
|
+
):
|
|
196
|
+
with pytest.raises(DeliveryError) as caught:
|
|
197
|
+
telegram(FakeTransport(status, body, error)).send(envelope())
|
|
198
|
+
assert expected in str(caught.value)
|
|
199
|
+
assert TOKEN not in str(caught.value)
|
|
200
|
+
assert caught.value.__cause__ is None
|
|
201
|
+
|
|
202
|
+
|
|
203
|
+
# --- secrets and the registry -----------------------------------------------------
|
|
204
|
+
|
|
205
|
+
|
|
206
|
+
def read_secret(response):
|
|
207
|
+
client = SimpleNamespace(get_secret_value=lambda SecretId: response)
|
|
208
|
+
return SecretsManagerSource(client, 'tk/telegram').get_json()
|
|
209
|
+
|
|
210
|
+
|
|
211
|
+
@pytest.mark.parametrize(
|
|
212
|
+
('build', 'error'),
|
|
213
|
+
[
|
|
214
|
+
(lambda: read_secret({'SecretString': '[1]'}), ConfigError),
|
|
215
|
+
(lambda: read_secret({'SecretString': 'nope'}), ConfigError),
|
|
216
|
+
(lambda: read_secret({'SecretBinary': b'x'}), ConfigError),
|
|
217
|
+
(lambda: TelegramConfig.from_secret({'chat_id': '1'}), ConfigError),
|
|
218
|
+
(lambda: TelegramConfig.from_secret({'bot_token': TOKEN}), ConfigError),
|
|
219
|
+
(
|
|
220
|
+
lambda: TelegramConfig.from_secret({'bot_token': '', 'chat_id': '1'}),
|
|
221
|
+
ValueError,
|
|
222
|
+
),
|
|
223
|
+
],
|
|
224
|
+
)
|
|
225
|
+
def test_a_bad_secret_is_refused_without_echoing_it(build, error):
|
|
226
|
+
with pytest.raises(error) as caught:
|
|
227
|
+
build()
|
|
228
|
+
assert 'nope' not in str(caught.value)
|
|
229
|
+
assert TOKEN not in str(caught.value)
|
|
230
|
+
|
|
231
|
+
|
|
232
|
+
def test_the_config_comes_from_the_secret_and_the_registry_builds_channels():
|
|
233
|
+
secret = read_secret(
|
|
234
|
+
{'SecretString': json.dumps({'bot_token': TOKEN, 'chat_id': 12345})}
|
|
235
|
+
)
|
|
236
|
+
config = TelegramConfig.from_secret(secret)
|
|
237
|
+
assert (config.chat_id, TOKEN in repr(config)) == ('12345', False)
|
|
238
|
+
|
|
239
|
+
registry = default_registry()
|
|
240
|
+
assert isinstance(
|
|
241
|
+
registry.create('telegram', secret, FakeTransport()), TelegramChannel
|
|
242
|
+
)
|
|
243
|
+
registry.register('dummy', lambda secret, transport: Dummy()) # a future channel
|
|
244
|
+
assert registry.create('dummy', {}).name == 'dummy'
|
|
245
|
+
with pytest.raises(ConfigError, match='telegram'):
|
|
246
|
+
registry.create('fax', {})
|
|
247
|
+
with pytest.raises(ConfigError, match='none'):
|
|
248
|
+
ChannelRegistry().create('telegram', {})
|
|
249
|
+
with pytest.raises(ValueError):
|
|
250
|
+
registry.register('telegram', lambda secret, transport: Dummy())
|
|
251
|
+
|
|
252
|
+
|
|
253
|
+
# --- transport, producer, consumer --------------------------------------------------
|
|
254
|
+
|
|
255
|
+
|
|
256
|
+
def test_the_transport_returns_http_errors_and_refuses_plain_http(monkeypatch):
|
|
257
|
+
post = UrllibTransport().post_json
|
|
258
|
+
reply = SimpleNamespace(status=200, read=lambda: b'{"ok": true}')
|
|
259
|
+
monkeypatch.setattr(
|
|
260
|
+
urllib.request, 'urlopen', lambda req, timeout: nullcontext(reply)
|
|
261
|
+
)
|
|
262
|
+
assert post('https://x.test', {}) == HttpResponse(200, '{"ok": true}')
|
|
263
|
+
|
|
264
|
+
def too_many(request, timeout):
|
|
265
|
+
body = io.BytesIO(b'{"ok": false}')
|
|
266
|
+
raise urllib.error.HTTPError('https://x.test', 429, 'Too Many', None, body)
|
|
267
|
+
|
|
268
|
+
monkeypatch.setattr(urllib.request, 'urlopen', too_many)
|
|
269
|
+
assert post('https://x.test', {}) == HttpResponse(429, '{"ok": false}')
|
|
270
|
+
with pytest.raises(ValueError):
|
|
271
|
+
post('http://x.test', {})
|
|
272
|
+
with pytest.raises(ValueError):
|
|
273
|
+
UrllibTransport(timeout=0)
|
|
274
|
+
|
|
275
|
+
|
|
276
|
+
class Recorder(Publisher):
|
|
277
|
+
def __init__(self, fail=False):
|
|
278
|
+
self.sent, self.fail = [], fail
|
|
279
|
+
|
|
280
|
+
def publish(self, message, attributes):
|
|
281
|
+
if self.fail:
|
|
282
|
+
raise RuntimeError('sns down')
|
|
283
|
+
self.sent.append((message, dict(attributes)))
|
|
284
|
+
|
|
285
|
+
|
|
286
|
+
def test_the_sink_publishes_an_envelope_with_routing_attributes_and_raises_failures():
|
|
287
|
+
class Lvl(StrEnum): # the automation's levels are StrEnums like this
|
|
288
|
+
CRITICAL = 'CRITICAL'
|
|
289
|
+
|
|
290
|
+
out = Recorder()
|
|
291
|
+
event = SimpleNamespace(
|
|
292
|
+
type='ENTRY_FILLED', level=Lvl.CRITICAL, message='m', data={}
|
|
293
|
+
)
|
|
294
|
+
SnsEventSink(out, 'automation', clock=lambda: T0, new_id=lambda: 'e1').emit(event)
|
|
295
|
+
message, attributes = out.sent[0]
|
|
296
|
+
assert attributes == {'level': 'CRITICAL', 'type': 'ENTRY_FILLED'}
|
|
297
|
+
assert Envelope.from_json(message).event_id == 'e1'
|
|
298
|
+
|
|
299
|
+
SnsEventSink(out, 'automation').emit(event) # real id and clock
|
|
300
|
+
assert len(Envelope.from_json(out.sent[1][0]).event_id) == 36
|
|
301
|
+
with pytest.raises(RuntimeError):
|
|
302
|
+
SnsEventSink(Recorder(fail=True), 'automation').emit(event)
|
|
303
|
+
|
|
304
|
+
|
|
305
|
+
def test_sns_publisher_sends_attributes_as_strings():
|
|
306
|
+
calls = []
|
|
307
|
+
client = SimpleNamespace(publish=lambda **kwargs: calls.append(kwargs))
|
|
308
|
+
SnsPublisher(client, 'arn:t').publish('body', {'level': 'WARN'})
|
|
309
|
+
assert calls == [
|
|
310
|
+
{
|
|
311
|
+
'TopicArn': 'arn:t',
|
|
312
|
+
'Message': 'body',
|
|
313
|
+
'MessageAttributes': {
|
|
314
|
+
'level': {'DataType': 'String', 'StringValue': 'WARN'}
|
|
315
|
+
},
|
|
316
|
+
}
|
|
317
|
+
]
|
|
318
|
+
|
|
319
|
+
|
|
320
|
+
def test_a_batch_delivers_the_good_and_reports_only_the_failed():
|
|
321
|
+
class Failing(Dummy):
|
|
322
|
+
def _deliver(self, text):
|
|
323
|
+
self.delivered.append(text)
|
|
324
|
+
if 'event d1' in text:
|
|
325
|
+
raise DeliveryError('down')
|
|
326
|
+
|
|
327
|
+
wrapped = json.dumps(
|
|
328
|
+
{'Type': 'Notification', 'Message': envelope(message='event g2').to_json()}
|
|
329
|
+
)
|
|
330
|
+
bodies = [
|
|
331
|
+
envelope(message='event g1').to_json(),
|
|
332
|
+
wrapped, # SNS wraps the envelope; raw delivery does not
|
|
333
|
+
'garbage',
|
|
334
|
+
envelope(message='event d1').to_json(), # the channel fails on this one
|
|
335
|
+
mutated(schema_version=9),
|
|
336
|
+
]
|
|
337
|
+
channel = Failing()
|
|
338
|
+
records = [{'messageId': f'm{i}', 'body': body} for i, body in enumerate(bodies, 1)]
|
|
339
|
+
result = SqsConsumer(channel).handle({'Records': records})
|
|
340
|
+
assert len(channel.delivered) == 3 # the garbage never reached the channel
|
|
341
|
+
assert [f['itemIdentifier'] for f in result['batchItemFailures']] == [
|
|
342
|
+
'm3',
|
|
343
|
+
'm4',
|
|
344
|
+
'm5',
|
|
345
|
+
]
|
|
346
|
+
assert SqsConsumer(channel).handle({}) == {'batchItemFailures': []}
|
|
File without changes
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
"""The contract every delivery channel (Telegram, WhatsApp, email, SMS) follows."""
|
|
2
|
+
|
|
3
|
+
from abc import ABC, abstractmethod
|
|
4
|
+
|
|
5
|
+
from ..envelope import Envelope
|
|
6
|
+
from ..errors import DeliveryError
|
|
7
|
+
from ..formatting import render_text
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
class Channel(ABC):
|
|
11
|
+
"""Template Method: `send` fixes the order (format, deliver, report errors);
|
|
12
|
+
a subclass supplies only what differs, `_deliver` and, if it needs one,
|
|
13
|
+
`format`."""
|
|
14
|
+
|
|
15
|
+
max_length: int = 4096
|
|
16
|
+
|
|
17
|
+
@property
|
|
18
|
+
@abstractmethod
|
|
19
|
+
def name(self) -> str:
|
|
20
|
+
"""Short name used in errors and logs, e.g. 'telegram'."""
|
|
21
|
+
|
|
22
|
+
@abstractmethod
|
|
23
|
+
def _deliver(self, text: str) -> None:
|
|
24
|
+
"""Send the finished text. Raise DeliveryError (or any error) on failure."""
|
|
25
|
+
|
|
26
|
+
def format(self, envelope: Envelope) -> str:
|
|
27
|
+
return render_text(envelope, self.max_length)
|
|
28
|
+
|
|
29
|
+
def send(self, envelope: Envelope) -> None:
|
|
30
|
+
text = self.format(envelope)
|
|
31
|
+
try:
|
|
32
|
+
self._deliver(text)
|
|
33
|
+
except DeliveryError:
|
|
34
|
+
raise
|
|
35
|
+
except Exception as exc:
|
|
36
|
+
raise DeliveryError(
|
|
37
|
+
f'{self.name}: request failed ({type(exc).__name__})'
|
|
38
|
+
) from None
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
"""Builds a channel from its name, so adding one never touches the callers."""
|
|
2
|
+
|
|
3
|
+
from collections.abc import Callable, Mapping
|
|
4
|
+
from typing import Any
|
|
5
|
+
|
|
6
|
+
from ..errors import ConfigError
|
|
7
|
+
from ..transport import HttpTransport, UrllibTransport
|
|
8
|
+
from .base import Channel
|
|
9
|
+
from .telegram import TelegramChannel, TelegramConfig
|
|
10
|
+
|
|
11
|
+
ChannelBuilder = Callable[[Mapping[str, Any], HttpTransport], Channel]
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def _build_telegram(secret: Mapping[str, Any], transport: HttpTransport) -> Channel:
|
|
15
|
+
return TelegramChannel(TelegramConfig.from_secret(secret), transport)
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
class ChannelRegistry:
|
|
19
|
+
def __init__(self) -> None:
|
|
20
|
+
self._builders: dict[str, ChannelBuilder] = {}
|
|
21
|
+
|
|
22
|
+
def register(self, name: str, builder: ChannelBuilder) -> None:
|
|
23
|
+
if name in self._builders:
|
|
24
|
+
raise ValueError(f'channel {name!r} is already registered')
|
|
25
|
+
self._builders[name] = builder
|
|
26
|
+
|
|
27
|
+
def create(
|
|
28
|
+
self,
|
|
29
|
+
name: str,
|
|
30
|
+
secret: Mapping[str, Any],
|
|
31
|
+
transport: HttpTransport | None = None,
|
|
32
|
+
) -> Channel:
|
|
33
|
+
try:
|
|
34
|
+
builder = self._builders[name]
|
|
35
|
+
except KeyError:
|
|
36
|
+
known = ', '.join(sorted(self._builders)) or 'none'
|
|
37
|
+
raise ConfigError(f'unknown channel {name!r} (known: {known})') from None
|
|
38
|
+
return builder(secret, transport or UrllibTransport())
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def default_registry() -> ChannelRegistry:
|
|
42
|
+
registry = ChannelRegistry()
|
|
43
|
+
registry.register('telegram', _build_telegram)
|
|
44
|
+
return registry
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
"""Sends alerts to a Telegram chat through the Bot API."""
|
|
2
|
+
|
|
3
|
+
import json
|
|
4
|
+
from collections.abc import Mapping
|
|
5
|
+
from dataclasses import dataclass, field
|
|
6
|
+
from typing import Any, Self
|
|
7
|
+
|
|
8
|
+
from ..constants import API_ROOT
|
|
9
|
+
from ..errors import ConfigError, DeliveryError
|
|
10
|
+
from ..transport import HttpTransport, UrllibTransport
|
|
11
|
+
from .base import Channel
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
@dataclass(frozen=True, slots=True)
|
|
15
|
+
class TelegramConfig:
|
|
16
|
+
bot_token: str = field(repr=False)
|
|
17
|
+
chat_id: str
|
|
18
|
+
|
|
19
|
+
def __post_init__(self) -> None:
|
|
20
|
+
if not self.bot_token or not self.chat_id:
|
|
21
|
+
raise ValueError('bot_token and chat_id must not be empty')
|
|
22
|
+
|
|
23
|
+
@classmethod
|
|
24
|
+
def from_secret(cls, secret: Mapping[str, Any]) -> Self:
|
|
25
|
+
for key in ('bot_token', 'chat_id'):
|
|
26
|
+
if key not in secret:
|
|
27
|
+
raise ConfigError(f'telegram secret has no "{key}" key')
|
|
28
|
+
|
|
29
|
+
return cls(bot_token=str(secret['bot_token']), chat_id=str(secret['chat_id']))
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def _json_object(body: str) -> Mapping[str, Any]:
|
|
33
|
+
try:
|
|
34
|
+
parsed = json.loads(body)
|
|
35
|
+
except json.JSONDecodeError:
|
|
36
|
+
return {}
|
|
37
|
+
return parsed if isinstance(parsed, dict) else {}
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
class TelegramChannel(Channel):
|
|
41
|
+
name = 'telegram'
|
|
42
|
+
max_length = 4096
|
|
43
|
+
|
|
44
|
+
def __init__(
|
|
45
|
+
self, config: TelegramConfig, transport: HttpTransport | None = None
|
|
46
|
+
) -> None:
|
|
47
|
+
self._config = config
|
|
48
|
+
self._transport = transport or UrllibTransport()
|
|
49
|
+
|
|
50
|
+
def _deliver(self, text: str) -> None:
|
|
51
|
+
url = f'{API_ROOT}/bot{self._config.bot_token}/sendMessage'
|
|
52
|
+
response = self._transport.post_json(
|
|
53
|
+
url,
|
|
54
|
+
{
|
|
55
|
+
'chat_id': self._config.chat_id,
|
|
56
|
+
'text': text,
|
|
57
|
+
'disable_web_page_preview': True,
|
|
58
|
+
},
|
|
59
|
+
)
|
|
60
|
+
reply = _json_object(response.body)
|
|
61
|
+
if response.status != 200 or reply.get('ok') is not True:
|
|
62
|
+
detail = str(reply.get('description') or 'no details')[:200]
|
|
63
|
+
raise DeliveryError(f'telegram: HTTP {response.status}: {detail}')
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
API_ROOT = 'https://api.telegram.org'
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
"""The channel side: reads a batch of queue messages and delivers each one."""
|
|
2
|
+
|
|
3
|
+
import json
|
|
4
|
+
import logging
|
|
5
|
+
from collections.abc import Mapping
|
|
6
|
+
from typing import Any
|
|
7
|
+
|
|
8
|
+
from .channels.base import Channel
|
|
9
|
+
from .envelope import Envelope
|
|
10
|
+
|
|
11
|
+
logger = logging.getLogger(__name__)
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def _envelope_text(body: str) -> str:
|
|
15
|
+
try:
|
|
16
|
+
parsed = json.loads(body)
|
|
17
|
+
except json.JSONDecodeError:
|
|
18
|
+
return body
|
|
19
|
+
if (
|
|
20
|
+
isinstance(parsed, dict)
|
|
21
|
+
and parsed.get('Type') == 'Notification'
|
|
22
|
+
and 'Message' in parsed
|
|
23
|
+
):
|
|
24
|
+
return str(parsed['Message'])
|
|
25
|
+
return body
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
class SqsConsumer:
|
|
29
|
+
def __init__(self, channel: Channel) -> None:
|
|
30
|
+
self._channel = channel
|
|
31
|
+
|
|
32
|
+
def handle(self, event: Mapping[str, Any]) -> dict[str, list[dict[str, str]]]:
|
|
33
|
+
"""Deliver every record; report only the failed ones so SQS retries just those.
|
|
34
|
+
|
|
35
|
+
Each message is handled on its own: one bad or undeliverable message never
|
|
36
|
+
blocks the rest of the batch.
|
|
37
|
+
"""
|
|
38
|
+
failures: list[dict[str, str]] = []
|
|
39
|
+
for record in event.get('Records', []):
|
|
40
|
+
try:
|
|
41
|
+
self._channel.send(Envelope.from_json(_envelope_text(record['body'])))
|
|
42
|
+
except Exception:
|
|
43
|
+
logger.exception(
|
|
44
|
+
'could not deliver message %s', record.get('messageId')
|
|
45
|
+
)
|
|
46
|
+
failures.append({'itemIdentifier': str(record.get('messageId', ''))})
|
|
47
|
+
return {'batchItemFailures': failures}
|
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
"""The message that travels from the automation to the channels, as JSON.
|
|
2
|
+
|
|
3
|
+
This is the only thing the two sides share. It carries a version so either side
|
|
4
|
+
can change later without silently misreading the other.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
import json
|
|
8
|
+
from collections.abc import Mapping
|
|
9
|
+
from dataclasses import dataclass
|
|
10
|
+
from datetime import datetime
|
|
11
|
+
from enum import StrEnum
|
|
12
|
+
from typing import Self
|
|
13
|
+
|
|
14
|
+
from .errors import EnvelopeError
|
|
15
|
+
|
|
16
|
+
SCHEMA_VERSION = 1
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
class Level(StrEnum):
|
|
20
|
+
INFO = 'INFO'
|
|
21
|
+
WARN = 'WARN'
|
|
22
|
+
CRITICAL = 'CRITICAL'
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
@dataclass(frozen=True, slots=True)
|
|
26
|
+
class Envelope:
|
|
27
|
+
event_id: str
|
|
28
|
+
type: str
|
|
29
|
+
level: Level
|
|
30
|
+
message: str
|
|
31
|
+
data: Mapping[str, str]
|
|
32
|
+
occurred_at: datetime
|
|
33
|
+
source: str
|
|
34
|
+
schema_version: int = SCHEMA_VERSION
|
|
35
|
+
|
|
36
|
+
def __post_init__(self) -> None:
|
|
37
|
+
for name in ('event_id', 'type', 'message', 'source'):
|
|
38
|
+
value = getattr(self, name)
|
|
39
|
+
if not isinstance(value, str) or not value:
|
|
40
|
+
raise ValueError(f'{name} must be a non-empty string')
|
|
41
|
+
if not isinstance(self.level, Level):
|
|
42
|
+
raise TypeError('level must be a Level')
|
|
43
|
+
if (
|
|
44
|
+
not isinstance(self.occurred_at, datetime)
|
|
45
|
+
or self.occurred_at.tzinfo is None
|
|
46
|
+
):
|
|
47
|
+
raise ValueError('occurred_at must be a timezone-aware datetime')
|
|
48
|
+
if not isinstance(self.data, Mapping) or not all(
|
|
49
|
+
isinstance(k, str) and isinstance(v, str) for k, v in self.data.items()
|
|
50
|
+
):
|
|
51
|
+
raise TypeError('data must map text to text')
|
|
52
|
+
if self.schema_version != SCHEMA_VERSION:
|
|
53
|
+
raise ValueError(f'schema_version must be {SCHEMA_VERSION}')
|
|
54
|
+
|
|
55
|
+
def to_json(self) -> str:
|
|
56
|
+
return json.dumps(
|
|
57
|
+
{
|
|
58
|
+
'schema_version': self.schema_version,
|
|
59
|
+
'event_id': self.event_id,
|
|
60
|
+
'type': self.type,
|
|
61
|
+
'level': self.level.value,
|
|
62
|
+
'message': self.message,
|
|
63
|
+
'data': dict(self.data),
|
|
64
|
+
'occurred_at': self.occurred_at.isoformat(),
|
|
65
|
+
'source': self.source,
|
|
66
|
+
},
|
|
67
|
+
sort_keys=True,
|
|
68
|
+
)
|
|
69
|
+
|
|
70
|
+
@classmethod
|
|
71
|
+
def from_json(cls, text: str) -> Self:
|
|
72
|
+
try:
|
|
73
|
+
raw = json.loads(text)
|
|
74
|
+
except json.JSONDecodeError:
|
|
75
|
+
raise EnvelopeError('message is not valid JSON') from None
|
|
76
|
+
if not isinstance(raw, dict):
|
|
77
|
+
raise EnvelopeError('message is not a JSON object')
|
|
78
|
+
if raw.get('schema_version') != SCHEMA_VERSION:
|
|
79
|
+
raise EnvelopeError(
|
|
80
|
+
f'unsupported schema_version {raw.get("schema_version")!r}'
|
|
81
|
+
)
|
|
82
|
+
try:
|
|
83
|
+
return cls(
|
|
84
|
+
event_id=raw['event_id'],
|
|
85
|
+
type=raw['type'],
|
|
86
|
+
level=Level(raw['level']),
|
|
87
|
+
message=raw['message'],
|
|
88
|
+
data=raw['data'],
|
|
89
|
+
occurred_at=datetime.fromisoformat(raw['occurred_at']),
|
|
90
|
+
source=raw['source'],
|
|
91
|
+
)
|
|
92
|
+
except (KeyError, ValueError, TypeError) as exc:
|
|
93
|
+
raise EnvelopeError(f'bad envelope: {exc}') from None
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
"""Every error this package raises on purpose."""
|
|
2
|
+
|
|
3
|
+
|
|
4
|
+
class NotifyError(Exception):
|
|
5
|
+
"""Base for the errors below."""
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
class EnvelopeError(NotifyError):
|
|
9
|
+
"""A message is not a valid envelope (bad JSON, wrong version, missing field)."""
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
class DeliveryError(NotifyError):
|
|
13
|
+
"""A channel could not deliver a message. Never carries a secret."""
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
class ConfigError(NotifyError):
|
|
17
|
+
"""A secret or setting needed to send is missing or unreadable."""
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
"""One readable text for an envelope, shared by every channel."""
|
|
2
|
+
|
|
3
|
+
from datetime import timedelta, timezone
|
|
4
|
+
|
|
5
|
+
from .envelope import Envelope, Level
|
|
6
|
+
|
|
7
|
+
IST = timezone(timedelta(hours=5, minutes=30), 'IST')
|
|
8
|
+
|
|
9
|
+
_ICONS = {Level.INFO: '🔵', Level.WARN: '🟠', Level.CRITICAL: '🔴'}
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
def render_text(envelope: Envelope, max_length: int) -> str:
|
|
13
|
+
when = envelope.occurred_at.astimezone(IST).strftime('%d %b %H:%M:%S IST')
|
|
14
|
+
lines = [
|
|
15
|
+
f'{_ICONS[envelope.level]} {envelope.level.value} - {envelope.type}',
|
|
16
|
+
envelope.message,
|
|
17
|
+
*(f'{key}: {value}' for key, value in sorted(envelope.data.items())),
|
|
18
|
+
when,
|
|
19
|
+
]
|
|
20
|
+
text = '\n'.join(lines)
|
|
21
|
+
return text if len(text) <= max_length else text[: max_length - 3] + '...'
|
|
@@ -0,0 +1,102 @@
|
|
|
1
|
+
"""The automation's side: turns an event into an envelope and publishes it."""
|
|
2
|
+
|
|
3
|
+
import uuid
|
|
4
|
+
from abc import ABC, abstractmethod
|
|
5
|
+
from collections.abc import Callable, Mapping
|
|
6
|
+
from datetime import UTC, datetime
|
|
7
|
+
from typing import Any, Protocol
|
|
8
|
+
|
|
9
|
+
from .envelope import Envelope, Level
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
class EventLike(Protocol):
|
|
13
|
+
"""Anything shaped like the automation's Event.
|
|
14
|
+
|
|
15
|
+
A Protocol, not an ABC, on purpose: this is the boundary between two repos.
|
|
16
|
+
The automation's Event never has to import (or inherit from) this package.
|
|
17
|
+
"""
|
|
18
|
+
|
|
19
|
+
@property
|
|
20
|
+
def type(self) -> str:
|
|
21
|
+
"""Event name, e.g. ENTRY_FILLED."""
|
|
22
|
+
|
|
23
|
+
@property
|
|
24
|
+
def level(self) -> str:
|
|
25
|
+
"""INFO, WARN or CRITICAL."""
|
|
26
|
+
|
|
27
|
+
@property
|
|
28
|
+
def message(self) -> str:
|
|
29
|
+
"""One readable line."""
|
|
30
|
+
|
|
31
|
+
@property
|
|
32
|
+
def data(self) -> Mapping[str, str]:
|
|
33
|
+
"""Facts about the event, as text."""
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
class Publisher(ABC):
|
|
37
|
+
@abstractmethod
|
|
38
|
+
def publish(self, message: str, attributes: Mapping[str, str]) -> None:
|
|
39
|
+
"""Send `message`; `attributes` are for subscribers' filter rules."""
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
class SnsPublisher(Publisher):
|
|
43
|
+
"""Adapts an SNS client. `client` is `boto3.client('sns')`, passed in by the
|
|
44
|
+
application, so this package never imports boto3."""
|
|
45
|
+
|
|
46
|
+
def __init__(self, client: Any, topic_arn: str) -> None:
|
|
47
|
+
self._client = client
|
|
48
|
+
self._topic_arn = topic_arn
|
|
49
|
+
|
|
50
|
+
def publish(self, message: str, attributes: Mapping[str, str]) -> None:
|
|
51
|
+
self._client.publish(
|
|
52
|
+
TopicArn=self._topic_arn,
|
|
53
|
+
Message=message,
|
|
54
|
+
MessageAttributes={
|
|
55
|
+
name: {'DataType': 'String', 'StringValue': value}
|
|
56
|
+
for name, value in attributes.items()
|
|
57
|
+
},
|
|
58
|
+
)
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def _utc_now() -> datetime:
|
|
62
|
+
return datetime.now(UTC)
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def _new_id() -> str:
|
|
66
|
+
return str(uuid.uuid4())
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
class SnsEventSink:
|
|
70
|
+
"""Satisfies the automation's `EventSink` (one method, `emit`) by shape."""
|
|
71
|
+
|
|
72
|
+
def __init__(
|
|
73
|
+
self,
|
|
74
|
+
publisher: Publisher,
|
|
75
|
+
source: str,
|
|
76
|
+
*,
|
|
77
|
+
clock: Callable[[], datetime] = _utc_now,
|
|
78
|
+
new_id: Callable[[], str] = _new_id,
|
|
79
|
+
) -> None:
|
|
80
|
+
self._publisher = publisher
|
|
81
|
+
self._source = source
|
|
82
|
+
self._clock = clock
|
|
83
|
+
self._new_id = new_id
|
|
84
|
+
|
|
85
|
+
def emit(self, event: EventLike) -> None:
|
|
86
|
+
"""Publish one event. A failure is raised, not hidden: the automation's
|
|
87
|
+
own wrapper decides that a broken notifier must not stop trading."""
|
|
88
|
+
envelope = Envelope(
|
|
89
|
+
event_id=self._new_id(),
|
|
90
|
+
type=str(event.type),
|
|
91
|
+
level=Level(event.level),
|
|
92
|
+
message=event.message,
|
|
93
|
+
data=dict(event.data),
|
|
94
|
+
occurred_at=self._clock(),
|
|
95
|
+
source=self._source,
|
|
96
|
+
)
|
|
97
|
+
# `level` and `type` also travel as attributes, so SNS can route on them
|
|
98
|
+
# (for example SMS only for CRITICAL) without anyone opening the message.
|
|
99
|
+
self._publisher.publish(
|
|
100
|
+
envelope.to_json(),
|
|
101
|
+
{'level': envelope.level.value, 'type': envelope.type},
|
|
102
|
+
)
|
|
File without changes
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
"""Where secrets come from, behind an interface."""
|
|
2
|
+
|
|
3
|
+
import json
|
|
4
|
+
from abc import ABC, abstractmethod
|
|
5
|
+
from collections.abc import Mapping
|
|
6
|
+
from typing import Any
|
|
7
|
+
|
|
8
|
+
from .errors import ConfigError
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
class SecretSource(ABC):
|
|
12
|
+
@abstractmethod
|
|
13
|
+
def get_json(self) -> Mapping[str, Any]:
|
|
14
|
+
"""The secret as a JSON object, or raise ConfigError."""
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
class SecretsManagerSource(SecretSource):
|
|
18
|
+
"""`client` is `boto3.client('secretsmanager')`, passed in by the application."""
|
|
19
|
+
|
|
20
|
+
def __init__(self, client: Any, secret_id: str) -> None:
|
|
21
|
+
self._client = client
|
|
22
|
+
self._secret_id = secret_id
|
|
23
|
+
|
|
24
|
+
def get_json(self) -> Mapping[str, Any]:
|
|
25
|
+
response = self._client.get_secret_value(SecretId=self._secret_id)
|
|
26
|
+
try:
|
|
27
|
+
value = json.loads(response['SecretString'])
|
|
28
|
+
except (KeyError, json.JSONDecodeError):
|
|
29
|
+
# The secret's text is never put in the error.
|
|
30
|
+
raise ConfigError(
|
|
31
|
+
f'secret {self._secret_id} is not readable JSON'
|
|
32
|
+
) from None
|
|
33
|
+
if not isinstance(value, dict):
|
|
34
|
+
raise ConfigError(f'secret {self._secret_id} is not a JSON object')
|
|
35
|
+
return value
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
"""Sending an HTTP request, behind an interface so tests never touch a network."""
|
|
2
|
+
|
|
3
|
+
import json
|
|
4
|
+
import urllib.error
|
|
5
|
+
import urllib.request
|
|
6
|
+
from abc import ABC, abstractmethod
|
|
7
|
+
from collections.abc import Mapping
|
|
8
|
+
from dataclasses import dataclass
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
@dataclass(frozen=True, slots=True)
|
|
12
|
+
class HttpResponse:
|
|
13
|
+
status: int
|
|
14
|
+
body: str
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
class HttpTransport(ABC):
|
|
18
|
+
@abstractmethod
|
|
19
|
+
def post_json(self, url: str, payload: Mapping[str, object]) -> HttpResponse:
|
|
20
|
+
"""POST `payload` as JSON. An HTTP error status is returned, not raised;
|
|
21
|
+
only a failure to get any answer (timeout, no network) raises."""
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
class UrllibTransport(HttpTransport):
|
|
25
|
+
def __init__(self, timeout: float = 10.0) -> None:
|
|
26
|
+
if timeout <= 0:
|
|
27
|
+
raise ValueError('timeout must be positive')
|
|
28
|
+
self._timeout = timeout
|
|
29
|
+
|
|
30
|
+
def post_json(self, url: str, payload: Mapping[str, object]) -> HttpResponse:
|
|
31
|
+
if not url.startswith('https://'):
|
|
32
|
+
raise ValueError('only https URLs are allowed')
|
|
33
|
+
request = urllib.request.Request( # noqa: S310 - https only, checked above
|
|
34
|
+
url,
|
|
35
|
+
data=json.dumps(payload).encode(),
|
|
36
|
+
headers={'Content-Type': 'application/json'},
|
|
37
|
+
method='POST',
|
|
38
|
+
)
|
|
39
|
+
try:
|
|
40
|
+
with urllib.request.urlopen(request, timeout=self._timeout) as response: # noqa: S310
|
|
41
|
+
return HttpResponse(response.status, response.read().decode())
|
|
42
|
+
except urllib.error.HTTPError as exc:
|
|
43
|
+
return HttpResponse(exc.code, exc.read().decode())
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
__version__ = '0.1.0'
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: tradekart-notify
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Delivers TradeKart alerts: event envelope, SNS producer and channel consumers
|
|
5
|
+
Author: Vikalp Varshney
|
|
6
|
+
Requires-Python: >=3.11
|
|
7
|
+
Description-Content-Type: text/markdown
|
|
8
|
+
Provides-Extra: aws
|
|
9
|
+
Requires-Dist: boto3<1.40.62,>=1.40.46; extra == "aws"
|
|
10
|
+
Provides-Extra: dev
|
|
11
|
+
Requires-Dist: pytest>=8.0.0; extra == "dev"
|
|
12
|
+
Requires-Dist: pytest-cov>=5.0.0; extra == "dev"
|
|
13
|
+
Requires-Dist: ruff>=0.6.0; extra == "dev"
|
|
14
|
+
Requires-Dist: mypy>=1.10.0; extra == "dev"
|
|
15
|
+
|
|
16
|
+
# tradekart-notify
|
|
17
|
+
|
|
18
|
+
Delivers TradeKart alerts: the event envelope, an SNS producer, and one
|
|
19
|
+
consumer per channel (Telegram, WhatsApp, email, SMS).
|
|
20
|
+
|
|
21
|
+
Standard library only at its core. `boto3` is an optional extra (`aws`) for the
|
|
22
|
+
SNS producer. This package never imports `tradekart_automation`.
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
README.md
|
|
2
|
+
pyproject.toml
|
|
3
|
+
tests/test_notify.py
|
|
4
|
+
tests/test_version.py
|
|
5
|
+
tradekart_notify/__init__.py
|
|
6
|
+
tradekart_notify/constants.py
|
|
7
|
+
tradekart_notify/consumer.py
|
|
8
|
+
tradekart_notify/envelope.py
|
|
9
|
+
tradekart_notify/errors.py
|
|
10
|
+
tradekart_notify/formatting.py
|
|
11
|
+
tradekart_notify/producer.py
|
|
12
|
+
tradekart_notify/py.typed
|
|
13
|
+
tradekart_notify/secret_source.py
|
|
14
|
+
tradekart_notify/transport.py
|
|
15
|
+
tradekart_notify/version.py
|
|
16
|
+
tradekart_notify.egg-info/PKG-INFO
|
|
17
|
+
tradekart_notify.egg-info/SOURCES.txt
|
|
18
|
+
tradekart_notify.egg-info/dependency_links.txt
|
|
19
|
+
tradekart_notify.egg-info/requires.txt
|
|
20
|
+
tradekart_notify.egg-info/top_level.txt
|
|
21
|
+
tradekart_notify/channels/__init__.py
|
|
22
|
+
tradekart_notify/channels/base.py
|
|
23
|
+
tradekart_notify/channels/registry.py
|
|
24
|
+
tradekart_notify/channels/telegram.py
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
tradekart_notify
|