-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
use orm in consumer for observation storage
- Loading branch information
1 parent
3cf5534
commit fd8a926
Showing
26 changed files
with
123 additions
and
170 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,11 +1,10 @@ | ||
# pc | ||
|
||
prediction consumer. | ||
> prediction consumer. | ||
pulls predictions messages off of prediction queue and into postgres and websockets. | ||
|
||
## connect to timescale instance | ||
Pulls brightness observation messages off of the prediction queue and into postgres. | ||
|
||
```shell | ||
# connect to postgres instance | ||
psql -d "postgres://postgres:password@localhost/postgres" | ||
``` |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,84 +1,18 @@ | ||
import json | ||
import asyncio | ||
import logging | ||
|
||
import psycopg | ||
import aio_pika | ||
|
||
from pc.config import * | ||
from pc.model import BrightnessMessage | ||
from pc.websockets_handler import WebSocketsHandler | ||
from pc.persistence.db import initialize_db | ||
from pc.rabbitmq import consume_brightness_observations | ||
|
||
logging.basicConfig(level=logging.INFO, format="%(asctime)s [%(levelname)s] %(message)s") | ||
log = logging.getLogger(__name__) | ||
|
||
websockets_handler = WebSocketsHandler() | ||
|
||
|
||
def initialize_db(): | ||
"""create the predictions table if it does not exist""" | ||
with psycopg.connect(pg_dsn) as conn: | ||
with conn.cursor() as cur: | ||
cur.execute(""" | ||
CREATE TABLE IF NOT EXISTS predictions ( | ||
id serial PRIMARY KEY, | ||
h3_id text NOT NULL, | ||
utc_iso text NOT NULL, | ||
utc_ns bigint NOT NULL, | ||
mpsas real NOT NULL, | ||
model_version text NOT NULL | ||
) | ||
""") | ||
conn.commit() | ||
|
||
|
||
def insert_brightness_message_in_db(message: BrightnessMessage): | ||
"""insert subset of brightness message into the predictions table""" | ||
with psycopg.connect(pg_dsn) as conn: | ||
with conn.cursor() as cur: | ||
log.info(f"inserting brightness message for {message.h3_id}") | ||
|
||
cur.execute(""" | ||
INSERT INTO predictions (h3_id, utc_iso, utc_ns, mpsas, model_version) | ||
VALUES (%s, %s, %s, %s, %s) | ||
""", (message.h3_id, message.utc_iso, message.utc_ns, message.mpsas, message.model_version)) | ||
conn.commit() | ||
|
||
|
||
async def consume_from_rabbitmq(): | ||
"""create table in pg if needed and begin consuming messages from the queue, | ||
storing them in the predictions table""" | ||
try: | ||
amqp_connection = await aio_pika.connect_robust(f"amqp://{AMQP_USER}:{AMQP_PASSWORD}@{AMQP_HOST}") | ||
except Exception as e: | ||
import sys | ||
|
||
log.error(f"could not form amqp connection because {e}; has rabbitmq started?") | ||
log.warning("exiting") | ||
sys.exit(1) | ||
else: | ||
async with amqp_connection: | ||
|
||
channel = await amqp_connection.channel() | ||
queue = await channel.declare_queue(AMQP_PREDICTION_QUEUE) | ||
|
||
async for m in queue: | ||
async with m.process(): | ||
# serialize the message coming over the queue and add to postgres | ||
json_data = json.loads(m.body.decode()) | ||
message = BrightnessMessage(**json_data) | ||
|
||
insert_brightness_message_in_db(message) | ||
await websockets_handler.broadcast(message) | ||
|
||
await asyncio.Future() | ||
|
||
|
||
async def main(): | ||
coroutines = [websockets_handler.setup(), consume_from_rabbitmq()] | ||
"""run the primary coroutines together""" | ||
coroutines = [initialize_db(), consume_brightness_observations()] | ||
await asyncio.gather(*coroutines) | ||
|
||
|
||
if __name__ == "__main__": | ||
initialize_db() | ||
asyncio.run(main()) |
File renamed without changes.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,15 @@ | ||
import logging | ||
|
||
from pc.config import pg_dsn | ||
from tortoise import Tortoise | ||
|
||
log = logging.getLogger(__name__) | ||
|
||
|
||
async def initialize_db(): | ||
log.info(f"initializing db at {pg_dsn}") | ||
await Tortoise.init( | ||
db_url=pg_dsn, | ||
modules={"models": ["pc.persistence.models"]} | ||
) | ||
await Tortoise.generate_schemas() |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,14 @@ | ||
from tortoise import fields, models | ||
|
||
|
||
class BrightnessObservation(models.Model): | ||
uuid = fields.CharField(primary_key=True, max_length=36) | ||
lat = fields.FloatField() | ||
lon = fields.FloatField() | ||
h3_id = fields.CharField(max_length=15) | ||
utc_iso = fields.CharField(max_length=30) | ||
mpsas = fields.FloatField() | ||
model_version = fields.CharField(max_length=36) | ||
|
||
def __str__(self): | ||
return f"{self.h3_id}:{self.uuid}" |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,43 @@ | ||
import json | ||
import logging | ||
import asyncio | ||
|
||
import aio_pika | ||
|
||
from pc.config import * | ||
from pc.persistence.models import BrightnessObservation | ||
|
||
log = logging.getLogger(__name__) | ||
|
||
|
||
# class RabbitMQConsumer: | ||
# def __init__(self, user: str, password: str, host: str): | ||
# self.url = f"amqp://{user}:{password}@{host}" | ||
# | ||
# async def connect(self): | ||
# pass | ||
|
||
|
||
async def consume_brightness_observations(): | ||
"""begin consuming messages from the queue, storing them in predictions table""" | ||
try: | ||
amqp_connection = await aio_pika.connect_robust(f"amqp://{AMQP_USER}:{AMQP_PASSWORD}@{AMQP_HOST}") | ||
except Exception as e: | ||
import sys | ||
|
||
log.error(f"could not form amqp connection because {e}; has rabbitmq started?") | ||
log.warning("exiting") | ||
sys.exit(1) | ||
else: | ||
async with amqp_connection: | ||
channel = await amqp_connection.channel() | ||
queue = await channel.declare_queue(AMQP_PREDICTION_QUEUE) | ||
|
||
async for message in queue: | ||
async with message.process(): | ||
brightness_observation_json = json.loads(message.body.decode()) | ||
brightness_observation = BrightnessObservation(**brightness_observation_json) | ||
|
||
log.info(f"saving brightness observation {brightness_observation}") | ||
await brightness_observation.save() | ||
await asyncio.Future() |
Empty file.
This file was deleted.
Oops, something went wrong.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,3 +1,2 @@ | ||
aio-pika==9.4.2 | ||
websockets==12.0 | ||
psycopg~=3.2.1 | ||
tortoise-orm[asyncpg]~=0.21.6 |
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Oops, something went wrong.
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Oops, something went wrong.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Empty file.
File renamed without changes.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Empty file.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,13 +1,11 @@ | ||
from dataclasses import dataclass | ||
from pydantic import BaseModel | ||
|
||
|
||
@dataclass | ||
class BrightnessMessage: | ||
class BrightnessObservation(BaseModel): | ||
uuid: str | ||
lat: float | ||
lon: float | ||
h3_id: str | ||
utc_iso: str | ||
utc_ns: int | ||
mpsas: float | ||
model_version: str |
Oops, something went wrong.