Skip to content

Commit

Permalink
strict typecheck db module, basic typecheck for the rest
Browse files Browse the repository at this point in the history
  • Loading branch information
shamrin committed Dec 28, 2020
1 parent 931377a commit 9e8dc17
Show file tree
Hide file tree
Showing 13 changed files with 292 additions and 15 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,2 +1,3 @@
__pycache__
/.env
/node_modules
2 changes: 2 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -26,11 +26,13 @@ Prerequisites:
* [Google Cloud SDK](https://cloud.google.com/sdk/docs/install)
* [jq](https://stedolan.github.io/jq/)
* Aiven project with Kafka and Postgres running
* npm

Setup:
```
poetry env use python3.9
poetry install
npm install
```

Load Aiven credentials and service URIs to `.env/` (replace `pg-123456` and `kafka-123456` with correct service names in Aiven):
Expand Down
2 changes: 2 additions & 0 deletions lint
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@ set -eux

SOURCES=(sitewatch tests)

npm run typecheck

# stop the build if there are Python syntax errors or undefined names
poetry run flake8 sitewatch --count --select=E9,F63,F7,F82 --show-source --statistics
# exit-zero treats all errors as warnings. The GitHub editor is 127 chars wide
Expand Down
12 changes: 12 additions & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

10 changes: 10 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
{
"name": "sitewatch",
"scripts": {
"typecheck": "pyright",
"typecheck-watch": "pyright -w"
},
"dependencies": {
"pyright": "^1.1.97"
}
}
52 changes: 51 additions & 1 deletion poetry.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ pytest = "^6.2.1"
snapshottest = "^0.6.0"
black = "^20.8b1"
pytest-trio = "^0.7.0"
trio-typing = "^0.5.0"

[build-system]
requires = ["poetry-core>=1.0.0"]
Expand Down
8 changes: 8 additions & 0 deletions pyrightconfig.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
{
"include": [
"sitewatch"
],
"pythonVersion": "3.9",
"venvPath": ".",
"venv": ".venv"
}
19 changes: 11 additions & 8 deletions sitewatch/db.py
Original file line number Diff line number Diff line change
@@ -1,13 +1,16 @@
"""Datatabase connection, tables init and main operations"""

# pyright: strict

import os
from datetime import timedelta
import re
from typing import List
from typing import List, Any
from contextlib import asynccontextmanager

import trio
import triopg
from triopg import Connection

from .model import Report, Page

Expand All @@ -25,7 +28,7 @@ def connect():


@asynccontextmanager
async def listen(conn, channel):
async def listen(conn: Connection, channel: str):
"""LISTEN on `channel` notifications and return memory channel to iterate over
For example:
Expand All @@ -37,9 +40,9 @@ async def listen(conn, channel):

# based on https://gitter.im/python-trio/general?at=5fe10d762084ee4b78650fc8

send_channel, receive_channel = trio.open_memory_channel(1)
send_channel, receive_channel = trio.open_memory_channel[str](1)

def _listen_callback(c, pid, chan, payload):
def _listen_callback(c: Any, pid: Any, chan: str, payload: str):
send_channel.send_nowait(payload)

await conn.add_listener(channel, _listen_callback)
Expand All @@ -48,7 +51,7 @@ def _listen_callback(c, pid, chan, payload):
await conn.remove_listener(channel, _listen_callback)


async def init_page_table(conn):
async def init_page_table(conn: Connection):
"""Initialize `page` table and add fixtures (idempotent)"""

await conn.execute(
Expand Down Expand Up @@ -104,7 +107,7 @@ async def init_page_table(conn):
)


async def init_report_table(conn):
async def init_report_table(conn: Connection):
"""Initialize `report` table (idempotent)"""

await conn.execute(
Expand All @@ -121,7 +124,7 @@ async def init_report_table(conn):
)


async def fetch_pages(conn) -> List[Page]:
async def fetch_pages(conn: Connection) -> List[Page]:
pages = [
Page(
row['pageid'],
Expand All @@ -135,7 +138,7 @@ async def fetch_pages(conn) -> List[Page]:
return pages


async def save_report(conn, r: Report):
async def save_report(conn: Connection, r: Report):
await conn.execute(
'''
INSERT INTO report(pageid, elapsed, statuscode, sent, found)
Expand Down
15 changes: 9 additions & 6 deletions sitewatch/model.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
from typing import Optional
from dataclasses import dataclass
from datetime import timedelta, datetime
from datetime import timedelta
import json
import re

Expand All @@ -21,11 +21,11 @@ class Page:
class Report(typesystem.Schema):
"""Web page check result"""

pageid: int = typesystem.Integer(minimum=0)
sent: datetime = typesystem.DateTime()
elapsed: float = typesystem.Float(minimum=0)
status_code: int = typesystem.Integer()
found: Optional[bool] = typesystem.Boolean(default=None, allow_null=True)
pageid = typesystem.Integer(minimum=0)
sent = typesystem.DateTime()
elapsed = typesystem.Float(minimum=0)
status_code = typesystem.Integer()
found = typesystem.Boolean(default=None, allow_null=True)

def tobytes(self) -> bytes:
"""Serialize to JSON"""
Expand All @@ -35,3 +35,6 @@ def tobytes(self) -> bytes:
def frombytes(cls, raw: bytes) -> 'Report':
"""Deserialize from JSON"""
return typesystem.validate_json(raw, validator=Report)


__all__ = ["Page", "Report", "ValidationError", "ParseError"]
10 changes: 10 additions & 0 deletions typings/triopg/__init__.pyi
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
"""
This type stub file was generated by pyright.
"""

from ._triopg import connect, create_pool, TrioConnectionProxy as Connection
from .exceptions import *

"""
This type stub file was generated by pyright.
"""
Loading

0 comments on commit 9e8dc17

Please sign in to comment.