-
Notifications
You must be signed in to change notification settings - Fork 96
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Move SlackUsers & SlackChannels cache to database (#423)
- Loading branch information
Showing
12 changed files
with
333 additions
and
160 deletions.
There are no files selected for viewing
60 changes: 60 additions & 0 deletions
60
migrations/versions/2020-07-13T13-12-47Z_2ba5cc3efce8_add_slackchannels_slackusers.py
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,60 @@ | ||
"""add SlackChannels & SlackUsers | ||
Revision ID: 2ba5cc3efce8 | ||
Revises: 3df042324a1f | ||
Create Date: 2020-07-13 13:12:47.561813+00:00 | ||
""" | ||
from alembic import op | ||
import sqlalchemy as sa | ||
|
||
|
||
# revision identifiers, used by Alembic. | ||
revision = "2ba5cc3efce8" | ||
down_revision = "3df042324a1f" | ||
branch_labels = None | ||
depends_on = None | ||
|
||
|
||
def upgrade(): | ||
# ### commands auto generated by Alembic - please adjust! ### | ||
op.create_table( | ||
"slack_channels", | ||
sa.Column("id", sa.Text(), nullable=False), | ||
sa.Column("name", sa.Text(), nullable=True), | ||
sa.Column("created", sa.DateTime(timezone=True), nullable=True), | ||
sa.Column("archived", sa.Boolean(), nullable=True), | ||
sa.Column("members", sa.Integer(), nullable=True), | ||
sa.Column("topic", sa.Text(), nullable=True), | ||
sa.Column("purpose", sa.Text(), nullable=True), | ||
sa.PrimaryKeyConstraint("id"), | ||
sa.UniqueConstraint("name"), | ||
) | ||
op.create_index("ix_slack_channels_id", "slack_channels", ["id"], unique=False) | ||
op.create_index("ix_slack_channels_name", "slack_channels", ["name"], unique=False) | ||
op.create_table( | ||
"slack_users", | ||
sa.Column("id", sa.Text(), nullable=False), | ||
sa.Column("deleted", sa.Boolean(), nullable=True), | ||
sa.Column("admin", sa.Boolean(), nullable=True), | ||
sa.Column("bot", sa.Boolean(), nullable=True), | ||
sa.Column("timezone", sa.Text(), nullable=True), | ||
sa.Column("first_seen", sa.DateTime(timezone=True), nullable=True), | ||
sa.PrimaryKeyConstraint("id"), | ||
) | ||
op.create_index("ix_slack_users_admin", "slack_users", ["id", "admin"], unique=False) | ||
op.create_index("ix_slack_users_id", "slack_users", ["id"], unique=False) | ||
op.create_index("ix_slack_users_timezone", "slack_users", ["id", "timezone"], unique=False) | ||
# ### end Alembic commands ### | ||
|
||
|
||
def downgrade(): | ||
# ### commands auto generated by Alembic - please adjust! ### | ||
op.drop_index("ix_slack_users_timezone", table_name="slack_users") | ||
op.drop_index("ix_slack_users_id", table_name="slack_users") | ||
op.drop_index("ix_slack_users_admin", table_name="slack_users") | ||
op.drop_table("slack_users") | ||
op.drop_index("ix_slack_channels_name", table_name="slack_channels") | ||
op.drop_index("ix_slack_channels_id", table_name="slack_channels") | ||
op.drop_table("slack_channels") | ||
# ### end Alembic commands ### |
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 |
---|---|---|
@@ -0,0 +1,62 @@ | ||
import asyncio | ||
import logging | ||
import datetime | ||
|
||
import slack | ||
import asyncpg.pool | ||
|
||
from slack.io.abc import SlackAPI | ||
from sqlalchemy.dialects.postgresql import insert as pg_insert | ||
|
||
from pyslackersweb import models | ||
from pyslackersweb.util.log import ContextAwareLoggerAdapter | ||
|
||
|
||
logger = ContextAwareLoggerAdapter(logging.getLogger(__name__)) | ||
|
||
|
||
async def sync_slack_users(slack_client: SlackAPI, pg: asyncpg.pool.Pool,) -> None: | ||
logger.debug("Refreshing slack users cache.") | ||
try: | ||
async with pg.acquire() as conn: | ||
async for user in slack_client.iter(slack.methods.USERS_LIST, minimum_time=3): | ||
values = { | ||
"deleted": user["deleted"], | ||
"admin": user["is_admin"], | ||
"bot": user["is_bot"], | ||
"timezone": user["tz"], | ||
} | ||
await conn.execute( | ||
pg_insert(models.SlackUsers) | ||
.values(id=user["id"], **values) | ||
.on_conflict_do_update(index_elements=[models.SlackUsers.c.id], set_=values) | ||
) | ||
except asyncio.CancelledError: | ||
logger.debug("Slack users cache refresh canceled") | ||
except Exception: # pylint: disable=broad-except | ||
logger.exception("Error refreshing slack users cache") | ||
|
||
|
||
async def sync_slack_channels(slack_client: SlackAPI, pg: asyncpg.pool.Pool) -> None: | ||
logger.debug("Refreshing slack channels cache.") | ||
|
||
try: | ||
async with pg.acquire() as conn: | ||
async for channel in slack_client.iter(slack.methods.CONVERSATIONS_LIST): | ||
values = { | ||
"name": channel["name"], | ||
"created": datetime.datetime.fromtimestamp(channel["created"]), | ||
"archived": channel["is_archived"], | ||
"members": channel["num_members"], | ||
"topic": channel["topic"]["value"], | ||
"purpose": channel["purpose"]["value"], | ||
} | ||
await conn.execute( | ||
pg_insert(models.SlackChannels) | ||
.values(id=channel["id"], **values) | ||
.on_conflict_do_update(index_elements=[models.SlackChannels.c.id], set_=values) | ||
) | ||
except asyncio.CancelledError: | ||
logger.debug("Slack channels cache refresh canceled") | ||
except Exception: # pylint: disable=broad-except | ||
logger.exception("Error refreshing slack channels cache") |
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 |
---|---|---|
@@ -0,0 +1,22 @@ | ||
import logging | ||
|
||
import asyncpg | ||
|
||
from pyslackersweb.util.log import ContextAwareLoggerAdapter | ||
|
||
|
||
logger = ContextAwareLoggerAdapter(logging.getLogger(__name__)) | ||
|
||
|
||
async def get_user_count(conn: asyncpg.connection.Connection) -> int: | ||
return await conn.fetchval("SELECT count(id) FROM slack_users") | ||
|
||
|
||
async def get_timezones(conn: asyncpg.connection.Connection) -> dict: | ||
timezones = {} | ||
rows = await conn.fetch("SELECT timezone, count(id) FROM slack_users GROUP BY timezone") | ||
for row in rows: | ||
if row["timezone"] is not None: | ||
timezones[row["timezone"]] = row["count"] | ||
|
||
return timezones |
Oops, something went wrong.