Skip to content

Commit 7317a78

Browse files
committed
Finished automatic topic creation
1 parent b24478c commit 7317a78

File tree

2 files changed

+87
-27
lines changed

2 files changed

+87
-27
lines changed

src/sasquatchbackpack/sasquatch.py

Lines changed: 33 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -185,9 +185,7 @@ def _get_topic_exists(self) -> bool | str:
185185

186186
return bool(any(topic["topic_name"] == topic_name for topic in topics))
187187

188-
def _handle_topic_exists(
189-
self, request: dict[str, dict[str, str]]
190-
) -> bool | None:
188+
def _topic_exists(self, request: dict[str, dict[str, str]]) -> bool | None:
191189
"""Handle errors and format responses for topic checking.
192190
193191
Parameters
@@ -267,7 +265,10 @@ def _post_new_topic(self) -> dict[str, str]:
267265
"message": f"Error Creating Topic during POST: {e}",
268266
}
269267

270-
return {"status": "Success", "message": response.text}
268+
return {
269+
"status": "Success",
270+
"message": "A new kafka topic has been created.",
271+
}
271272

272273
def _get_source_records(self) -> list[dict] | None:
273274
"""Get source records and check the redis server for any
@@ -299,6 +300,20 @@ def _get_source_records(self) -> list[dict] | None:
299300
if self.redis.get(self.source.get_redis_key(record)) is None
300301
]
301302

303+
def _check_success(self, response: dict) -> None:
304+
"""Check whether the request has suceeded.
305+
306+
Parameters
307+
----------
308+
response: dict
309+
response object from post().
310+
"""
311+
for item in response["requests"]:
312+
if response["requests"][item]["status"] == "Error":
313+
response["succeeded"] = False
314+
break
315+
response["succeeded"] = True
316+
302317
def post(self, *, force_post: bool = False) -> str:
303318
"""Assemble schema and payload from the given source, then
304319
makes a POST request to kafka.
@@ -337,19 +352,19 @@ def post(self, *, force_post: bool = False) -> str:
337352
},
338353
"records": [],
339354
}
340-
requests = response["requests"]
355+
reqs = response["requests"]
341356

342-
topic_exists = self._handle_topic_exists(requests)
357+
topic_exists = self._topic_exists(reqs)
343358

344359
if topic_exists is None:
345360
return json.dumps(response)
346361

347362
if force_post or not topic_exists:
348-
requests["create_topic"] = self._post_new_topic()
349-
if requests["create_topic"]["status"] == "Error":
363+
reqs["create_topic"] = self._post_new_topic()
364+
if reqs["create_topic"]["status"] == "Error":
350365
return json.dumps(response)
351366
else:
352-
requests["create_topic"] = {
367+
reqs["create_topic"] = {
353368
"status": "Success",
354369
"message": (
355370
"Relevant topic already exists in kafka, "
@@ -360,19 +375,22 @@ def post(self, *, force_post: bool = False) -> str:
360375
records = self._get_source_records()
361376

362377
if records is None:
363-
requests["write_values"] = {
378+
reqs["write_values"] = {
364379
"status": "Warning",
365380
"message": "No entries found, aborting POST request",
366381
}
367382
return json.dumps(response)
368383

384+
response["records"] = records
385+
369386
if len(records) == 0:
370-
requests["write_values"] = {
387+
reqs["write_values"] = {
371388
"status": "Warning",
372389
"message": (
373390
"All entries already present, aborting POST request"
374391
),
375392
}
393+
self._check_success(response)
376394
return json.dumps(response)
377395

378396
payload = {"value_schema": self.schema, "records": records}
@@ -411,6 +429,9 @@ def post(self, *, force_post: bool = False) -> str:
411429

412430
response["write_values"] = {
413431
"status": "Success",
414-
"message": post_response.text,
432+
"message": "Data successfully sent!",
415433
}
434+
435+
self._check_success(response)
436+
416437
return json.dumps(response)

src/sasquatchbackpack/sources/usgs/commands.py

Lines changed: 54 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
"""USGS CLI."""
22

3+
import json
34
from datetime import UTC, datetime, timedelta
45

56
import click
@@ -13,9 +14,6 @@
1314

1415
DEFAULT_MAGNITUDE_BOUNDS = (2, 10)
1516

16-
# ruff: noqa:TD002
17-
# ruff: noqa:TD003
18-
1917

2018
def check_duration(
2119
ctx: click.Context, param: dict, value: tuple[int, int]
@@ -177,8 +175,6 @@ def usgs_earthquake_data(
177175
magnitude_bounds,
178176
)
179177

180-
# TODO: Add CLI feedback on what items are cached to redis
181-
# and which are new
182178
if len(results) > 0:
183179
click.secho("SUCCESS!", fg="green")
184180
click.echo("------")
@@ -199,12 +195,56 @@ def usgs_earthquake_data(
199195
click.echo("Post mode enabled: Sending data...")
200196
click.echo(f"Querying redis at {backpack_dispatcher.redis.address}")
201197

202-
result, records = backpack_dispatcher.post()
198+
response = json.loads(backpack_dispatcher.post())
199+
_handle_post_response(response)
200+
201+
202+
def _handle_post_response(response: dict) -> None:
203+
"""Handle click response to post request output.
204+
205+
Parameters
206+
----------
207+
response: dict
208+
json loaded dictionary recieved from a backpack_dispatcher post.
209+
"""
210+
if not response["succeeded"]:
211+
failed: tuple[str, dict[str, str]] = ("none", {"none": "none"})
212+
for name in response["requests"]:
213+
item: dict = response["requests"][name]
214+
click.echo(f"{name}: {item['message']} - Status: {item['status']}")
215+
if item["status"] == "Error":
216+
failed = (name, item)
217+
break
218+
219+
if failed[0] == "none":
220+
click.secho("Unknown error encountered", fg="red")
221+
click.echo(json.dumps(response))
222+
return
223+
224+
if failed[0] == "check_topic":
225+
click.secho(
226+
"Tip: You can use force_post=True to bypass topic checks.",
227+
fg="yellow",
228+
)
229+
return
230+
231+
click.echo("------")
232+
for name in response["requests"]:
233+
item: dict = response["requests"][name]
234+
if item["status"] == "Warning":
235+
click.secho(
236+
f"Warning! {name}: {item['message']}",
237+
fg="yellow",
238+
)
239+
continue
240+
click.secho(
241+
f"{name}: {item['message']} - Status: {item['status']}", fg="green"
242+
)
203243

204-
if "Error" in result:
205-
click.secho(result, fg="red")
206-
elif "Warning" in result:
207-
click.secho(result, fg="yellow")
244+
records: list = response["records"]
245+
if len(records) == 0:
246+
click.secho("Success!", fg="green")
247+
click.echo("No data has been sent.")
208248
else:
209249
click.secho("Data successfully sent!", fg="green")
210250
click.echo("The following items were added to Kafka:")
@@ -223,9 +263,8 @@ def usgs_earthquake_data(
223263
f"{value['depth']} km "
224264
f"M{value['magnitude']}"
225265
)
226-
click.echo("------")
266+
click.echo("------")
227267

228-
click.echo(
229-
"All entries missing from this list "
230-
"have been identified as already present in Kafka."
231-
)
268+
click.echo(
269+
"All missing entries have been identified as already present in Kafka."
270+
)

0 commit comments

Comments
 (0)