diff --git a/alembic.ini b/alembic.ini new file mode 100644 index 0000000..c259d84 --- /dev/null +++ b/alembic.ini @@ -0,0 +1,116 @@ +# A generic, single database configuration. + +[alembic] +# path to migration scripts +# Use forward slashes (/) also on windows to provide an os agnostic path +script_location = migrations + +# template used to generate migration file names; The default value is %%(rev)s_%%(slug)s +# Uncomment the line below if you want the files to be prepended with date and time +# see https://alembic.sqlalchemy.org/en/latest/tutorial.html#editing-the-ini-file +# for all available tokens +# file_template = %%(year)d_%%(month).2d_%%(day).2d_%%(hour).2d%%(minute).2d-%%(rev)s_%%(slug)s + +# sys.path path, will be prepended to sys.path if present. +# defaults to the current working directory. +prepend_sys_path = . + +# timezone to use when rendering the date within the migration file +# as well as the filename. +# If specified, requires the python>=3.9 or backports.zoneinfo library. +# Any required deps can installed by adding `alembic[tz]` to the pip requirements +# string value is passed to ZoneInfo() +# leave blank for localtime +# timezone = + +# max length of characters to apply to the "slug" field +# truncate_slug_length = 40 + +# set to 'true' to run the environment during +# the 'revision' command, regardless of autogenerate +# revision_environment = false + +# set to 'true' to allow .pyc and .pyo files without +# a source .py file to be detected as revisions in the +# versions/ directory +# sourceless = false + +# version location specification; This defaults +# to migrations/versions. When using multiple version +# directories, initial revisions must be specified with --version-path. +# The path separator used here should be the separator specified by "version_path_separator" below. +# version_locations = %(here)s/bar:%(here)s/bat:migrations/versions + +# version path separator; As mentioned above, this is the character used to split +# version_locations. The default within new alembic.ini files is "os", which uses os.pathsep. +# If this key is omitted entirely, it falls back to the legacy behavior of splitting on spaces and/or commas. +# Valid values for version_path_separator are: +# +# version_path_separator = : +# version_path_separator = ; +# version_path_separator = space +version_path_separator = os # Use os.pathsep. Default configuration used for new projects. + +# set to 'true' to search source files recursively +# in each "version_locations" directory +# new in Alembic version 1.10 +# recursive_version_locations = false + +# the output encoding used when revision files +# are written from script.py.mako +# output_encoding = utf-8 + +sqlalchemy.url = driver://user:pass@localhost/dbname + + +[post_write_hooks] +# post_write_hooks defines scripts or Python functions that are run +# on newly generated revision scripts. See the documentation for further +# detail and examples + +# format using "black" - use the console_scripts runner, against the "black" entrypoint +# hooks = black +# black.type = console_scripts +# black.entrypoint = black +# black.options = -l 79 REVISION_SCRIPT_FILENAME + +# lint with attempts to fix using "ruff" - use the exec runner, execute a binary +# hooks = ruff +# ruff.type = exec +# ruff.executable = %(here)s/.venv/bin/ruff +# ruff.options = --fix REVISION_SCRIPT_FILENAME + +# Logging configuration +[loggers] +keys = root,sqlalchemy,alembic + +[handlers] +keys = console + +[formatters] +keys = generic + +[logger_root] +level = WARN +handlers = console +qualname = + +[logger_sqlalchemy] +level = WARN +handlers = +qualname = sqlalchemy.engine + +[logger_alembic] +level = INFO +handlers = +qualname = alembic + +[handler_console] +class = StreamHandler +args = (sys.stderr,) +level = NOTSET +formatter = generic + +[formatter_generic] +format = %(levelname)-5.5s [%(name)s] %(message)s +datefmt = %H:%M:%S diff --git a/app/main.py b/app/main.py index be5af0d..5bce962 100644 --- a/app/main.py +++ b/app/main.py @@ -10,7 +10,6 @@ from .injector_main_module import MainModule from .routers import application, content, conversation, internal, rule, workspace from .services import set_service_registry -from .slack.store_sql import init_sql from .sql import create_tables logger = logging.getLogger(__name__) @@ -23,8 +22,7 @@ async def lifespan(app: FastAPI): logger.debug("Starting") create_tables() - # extensions - init_sql() + yield logger.debug("Stopping") diff --git a/app/slack/store_sql.py b/app/slack/store_sql.py index 1af4d89..0913dbe 100644 --- a/app/slack/store_sql.py +++ b/app/slack/store_sql.py @@ -1,17 +1,30 @@ from slack_sdk.oauth.installation_store.sqlalchemy import SQLAlchemyInstallationStore from slack_sdk.oauth.state_store.sqlalchemy import SQLAlchemyOAuthStateStore +from app.models_stores_sql import metadata + from ..settings import settings from ..sql import sqlalchemy_engine sql_installation_store = SQLAlchemyInstallationStore( engine=sqlalchemy_engine, client_id=settings.SLACK_CLIENT_ID ) + +sql_installation_store.metadata = metadata +sql_installation_store.bots = sql_installation_store.build_bots_table( + metadata=metadata, table_name=sql_installation_store.default_bots_table_name +) +sql_installation_store.installations = sql_installation_store.build_installations_table( + metadata=metadata, + table_name=sql_installation_store.default_installations_table_name, +) + state_store = SQLAlchemyOAuthStateStore( engine=sqlalchemy_engine, expiration_seconds=600 ) +state_store.metadata = metadata +state_store.oauth_states = state_store.build_oauth_states_table( + metadata=metadata, table_name=state_store.default_table_name +) - -def init_sql(): - sql_installation_store.metadata.create_all(sqlalchemy_engine) - state_store.metadata.create_all(sqlalchemy_engine) +_metadata_for_migrations_ = metadata diff --git a/migrations/README b/migrations/README new file mode 100644 index 0000000..98e4f9c --- /dev/null +++ b/migrations/README @@ -0,0 +1 @@ +Generic single-database configuration. \ No newline at end of file diff --git a/migrations/env.py b/migrations/env.py new file mode 100644 index 0000000..bf915c3 --- /dev/null +++ b/migrations/env.py @@ -0,0 +1,82 @@ +import os +from logging.config import fileConfig + +from alembic import context +from dotenv import load_dotenv +from sqlalchemy import engine_from_config, pool + +from app.slack.store_sql import _metadata_for_migrations_ + +load_dotenv() + +# this is the Alembic Config object, which provides +# access to the values within the .ini file in use. +config = context.config + +# Interpret the config file for Python logging. +# This line sets up loggers basically. +if config.config_file_name is not None: + fileConfig(config.config_file_name) + +# add your model's MetaData object here +# for 'autogenerate' support +# from myapp import mymodel +# target_metadata = mymodel.Base.metadata +target_metadata = _metadata_for_migrations_ + +# other values from the config, defined by the needs of env.py, +# can be acquired: +# my_important_option = config.get_main_option("my_important_option") +# ... etc. + +config.set_main_option("sqlalchemy.url", os.getenv("DB_URI")) + + +def run_migrations_offline() -> None: + """Run migrations in 'offline' mode. + + This configures the context with just a URL + and not an Engine, though an Engine is acceptable + here as well. By skipping the Engine creation + we don't even need a DBAPI to be available. + + Calls to context.execute() here emit the given string to the + script output. + + """ + url = config.get_main_option("sqlalchemy.url") + context.configure( + url=url, + target_metadata=target_metadata, + literal_binds=True, + dialect_opts={"paramstyle": "named"}, + ) + + with context.begin_transaction(): + context.run_migrations() + + +def run_migrations_online() -> None: + """Run migrations in 'online' mode. + + In this scenario we need to create an Engine + and associate a connection with the context. + + """ + connectable = engine_from_config( + config.get_section(config.config_ini_section, {}), + prefix="sqlalchemy.", + poolclass=pool.NullPool, + ) + + with connectable.connect() as connection: + context.configure(connection=connection, target_metadata=target_metadata) + + with context.begin_transaction(): + context.run_migrations() + + +if context.is_offline_mode(): + run_migrations_offline() +else: + run_migrations_online() diff --git a/migrations/script.py.mako b/migrations/script.py.mako new file mode 100644 index 0000000..fbc4b07 --- /dev/null +++ b/migrations/script.py.mako @@ -0,0 +1,26 @@ +"""${message} + +Revision ID: ${up_revision} +Revises: ${down_revision | comma,n} +Create Date: ${create_date} + +""" +from typing import Sequence, Union + +from alembic import op +import sqlalchemy as sa +${imports if imports else ""} + +# revision identifiers, used by Alembic. +revision: str = ${repr(up_revision)} +down_revision: Union[str, None] = ${repr(down_revision)} +branch_labels: Union[str, Sequence[str], None] = ${repr(branch_labels)} +depends_on: Union[str, Sequence[str], None] = ${repr(depends_on)} + + +def upgrade() -> None: + ${upgrades if upgrades else "pass"} + + +def downgrade() -> None: + ${downgrades if downgrades else "pass"} diff --git a/migrations/versions/bd921dc0747d_create_a_baseline_migrations.py b/migrations/versions/bd921dc0747d_create_a_baseline_migrations.py new file mode 100644 index 0000000..8a6719e --- /dev/null +++ b/migrations/versions/bd921dc0747d_create_a_baseline_migrations.py @@ -0,0 +1,195 @@ +"""Create a baseline migrations + +Revision ID: bd921dc0747d +Revises: +Create Date: 2024-07-03 14:18:48.532485 + +""" +from typing import Sequence, Union + +from alembic import op +import sqlalchemy as sa + + +# revision identifiers, used by Alembic. +revision: str = 'bd921dc0747d' +down_revision: Union[str, None] = None +branch_labels: Union[str, Sequence[str], None] = None +depends_on: Union[str, Sequence[str], None] = None + + +def upgrade() -> None: + # ### commands auto generated by Alembic - please adjust! ### + op.create_table('slack_bots', + sa.Column('id', sa.Integer(), autoincrement=True, nullable=False), + sa.Column('client_id', sa.String(length=32), nullable=False), + sa.Column('app_id', sa.String(length=32), nullable=False), + sa.Column('enterprise_id', sa.String(length=32), nullable=True), + sa.Column('enterprise_name', sa.String(length=200), nullable=True), + sa.Column('team_id', sa.String(length=32), nullable=True), + sa.Column('team_name', sa.String(length=200), nullable=True), + sa.Column('bot_token', sa.String(length=200), nullable=True), + sa.Column('bot_id', sa.String(length=32), nullable=True), + sa.Column('bot_user_id', sa.String(length=32), nullable=True), + sa.Column('bot_scopes', sa.String(length=1000), nullable=True), + sa.Column('bot_refresh_token', sa.String(length=200), nullable=True), + sa.Column('bot_token_expires_at', sa.DateTime(), nullable=True), + sa.Column('is_enterprise_install', sa.Boolean(), nullable=False), + sa.Column('installed_at', sa.DateTime(), nullable=False), + sa.PrimaryKeyConstraint('id') + ) + op.create_index('slack_bots_idx', 'slack_bots', ['client_id', 'enterprise_id', 'team_id', 'installed_at'], unique=False) + op.create_table('slack_installations', + sa.Column('id', sa.Integer(), autoincrement=True, nullable=False), + sa.Column('client_id', sa.String(length=32), nullable=False), + sa.Column('app_id', sa.String(length=32), nullable=False), + sa.Column('enterprise_id', sa.String(length=32), nullable=True), + sa.Column('enterprise_name', sa.String(length=200), nullable=True), + sa.Column('enterprise_url', sa.String(length=200), nullable=True), + sa.Column('team_id', sa.String(length=32), nullable=True), + sa.Column('team_name', sa.String(length=200), nullable=True), + sa.Column('bot_token', sa.String(length=200), nullable=True), + sa.Column('bot_id', sa.String(length=32), nullable=True), + sa.Column('bot_user_id', sa.String(length=32), nullable=True), + sa.Column('bot_scopes', sa.String(length=1000), nullable=True), + sa.Column('bot_refresh_token', sa.String(length=200), nullable=True), + sa.Column('bot_token_expires_at', sa.DateTime(), nullable=True), + sa.Column('user_id', sa.String(length=32), nullable=False), + sa.Column('user_token', sa.String(length=200), nullable=True), + sa.Column('user_scopes', sa.String(length=1000), nullable=True), + sa.Column('user_refresh_token', sa.String(length=200), nullable=True), + sa.Column('user_token_expires_at', sa.DateTime(), nullable=True), + sa.Column('incoming_webhook_url', sa.String(length=200), nullable=True), + sa.Column('incoming_webhook_channel', sa.String(length=200), nullable=True), + sa.Column('incoming_webhook_channel_id', sa.String(length=200), nullable=True), + sa.Column('incoming_webhook_configuration_url', sa.String(length=200), nullable=True), + sa.Column('is_enterprise_install', sa.Boolean(), nullable=False), + sa.Column('token_type', sa.String(length=32), nullable=True), + sa.Column('installed_at', sa.DateTime(), nullable=False), + sa.PrimaryKeyConstraint('id') + ) + op.create_index('slack_installations_idx', 'slack_installations', ['client_id', 'enterprise_id', 'team_id', 'user_id', 'installed_at'], unique=False) + op.create_table('slack_oauth_states', + sa.Column('id', sa.Integer(), autoincrement=True, nullable=False), + sa.Column('state', sa.String(length=200), nullable=False), + sa.Column('expire_at', sa.DateTime(), nullable=False), + sa.PrimaryKeyConstraint('id') + ) + op.create_table('workspaces', + sa.Column('id', sa.String(length=10), nullable=False), + sa.Column('unique_name', sa.String(length=32), nullable=False), + sa.Column('display_name', sa.String(length=32), nullable=False), + sa.Column('logo_url', sa.String(), nullable=True), + sa.Column('status', sa.Enum('creating', 'active', 'error', name='workspacestatuses'), nullable=True), + sa.Column('external_id', sa.String(), nullable=True), + sa.Column('config', sa.JSON(), nullable=False), + sa.Column('created_by', sa.String(), nullable=False), + sa.Column('created_at', sa.DateTime(), nullable=False), + sa.PrimaryKeyConstraint('id'), + sa.UniqueConstraint('unique_name') + ) + op.create_table('applications', + sa.Column('id', sa.String(length=10), nullable=False), + sa.Column('workspace_id', sa.String(length=10), nullable=False), + sa.Column('unique_name', sa.String(), nullable=False), + sa.Column('aliases', sa.JSON(), nullable=False), + sa.Column('extra_instructions', sa.String(), nullable=True), + sa.Column('provision_schema', sa.JSON(), nullable=True), + sa.Column('created_at', sa.DateTime(), nullable=False), + sa.ForeignKeyConstraint(['workspace_id'], ['workspaces.id'], ), + sa.PrimaryKeyConstraint('id') + ) + op.create_index('ix_ws_un', 'applications', ['workspace_id', 'unique_name'], unique=True) + op.create_table('checkpoints', + sa.Column('thread_id', sa.String(length=10), nullable=False), + sa.Column('thread_ts', sa.TIMESTAMP(), nullable=False), + sa.Column('parent_ts', sa.TIMESTAMP(), nullable=True), + sa.Column('workspace_id', sa.String(length=10), nullable=False), + sa.Column('checkpoint', sa.LargeBinary(), nullable=True), + sa.Column('metadata', sa.LargeBinary(), nullable=True), + sa.ForeignKeyConstraint(['workspace_id'], ['workspaces.id'], ), + sa.PrimaryKeyConstraint('thread_id', 'thread_ts', 'workspace_id') + ) + op.create_table('conversations', + sa.Column('id', sa.String(length=10), nullable=False), + sa.Column('workspace_id', sa.String(length=10), nullable=False), + sa.Column('assignee', sa.String(), nullable=False), + sa.Column('type', sa.Enum('recommendation', 'data_owner', name='conversationtypes'), nullable=False), + sa.Column('status', sa.Enum('active', 'completed', 'cancelled', 'approved', 'denied', 'archived', name='conversationstatuses'), nullable=False), + sa.Column('external_id', sa.String(), nullable=True), + sa.Column('previous_conversation', sa.String(), nullable=True), + sa.Column('context', sa.JSON(), nullable=False), + sa.Column('created_at', sa.DateTime(), nullable=False), + sa.Column('summary', sa.String(), nullable=True), + sa.ForeignKeyConstraint(['workspace_id'], ['workspaces.id'], ), + sa.PrimaryKeyConstraint('id', 'workspace_id') + ) + op.create_index('idx_conv_status', 'conversations', ['status'], unique=False) + op.create_table('directories', + sa.Column('id', sa.String(length=10), nullable=False), + sa.Column('workspace_id', sa.String(length=10), nullable=False), + sa.Column('name', sa.String(), nullable=False), + sa.Column('provisioning_config', sa.JSON(), nullable=True), + sa.Column('read_config', sa.JSON(), nullable=True), + sa.Column('data_owner_config', sa.JSON(), nullable=True), + sa.Column('created_by', sa.String(), nullable=False), + sa.Column('created_at', sa.DateTime(), nullable=False), + sa.ForeignKeyConstraint(['workspace_id'], ['workspaces.id'], ), + sa.PrimaryKeyConstraint('id') + ) + op.create_index('idx_ws_name', 'directories', ['workspace_id', 'name'], unique=True) + op.create_table('messages', + sa.Column('id', sa.String(length=10), nullable=False), + sa.Column('workspace_id', sa.String(length=10), nullable=False), + sa.Column('conversation_id', sa.String(length=10), nullable=False), + sa.Column('type', sa.String(length=32), nullable=False), + sa.Column('content', sa.String(length=1024), nullable=True), + sa.Column('created_at', sa.DateTime(), nullable=False), + sa.ForeignKeyConstraint(['workspace_id'], ['workspaces.id'], ), + sa.PrimaryKeyConstraint('id', 'workspace_id') + ) + op.create_table('rules', + sa.Column('id', sa.String(length=10), nullable=False), + sa.Column('workspace_id', sa.String(length=10), nullable=False), + sa.Column('when', sa.String(), nullable=False), + sa.Column('then', sa.Enum('approve', 'deny', name='thentypes'), nullable=False), + sa.Column('type', sa.Enum('auto_approve', name='ruletypes'), nullable=False), + sa.Column('created_by', sa.String(), nullable=False), + sa.Column('created_at', sa.DateTime(), nullable=False), + sa.ForeignKeyConstraint(['workspace_id'], ['workspaces.id'], ), + sa.PrimaryKeyConstraint('id') + ) + op.create_table('rules_context', + sa.Column('id', sa.String(length=10), nullable=False), + sa.Column('rule_id', sa.String(length=10), nullable=False), + sa.Column('workspace_id', sa.String(length=10), nullable=False), + sa.Column('directory_id', sa.String(length=10), nullable=True), + sa.Column('application_id', sa.String(length=10), nullable=True), + sa.ForeignKeyConstraint(['application_id'], ['applications.id'], ), + sa.ForeignKeyConstraint(['directory_id'], ['directories.id'], ), + sa.ForeignKeyConstraint(['rule_id'], ['rules.id'], ), + sa.ForeignKeyConstraint(['workspace_id'], ['workspaces.id'], ), + sa.PrimaryKeyConstraint('id') + ) + # ### end Alembic commands ### + + +def downgrade() -> None: + # ### commands auto generated by Alembic - please adjust! ### + op.drop_table('rules_context') + op.drop_table('rules') + op.drop_table('messages') + op.drop_index('idx_ws_name', table_name='directories') + op.drop_table('directories') + op.drop_index('idx_conv_status', table_name='conversations') + op.drop_table('conversations') + op.drop_table('checkpoints') + op.drop_index('ix_ws_un', table_name='applications') + op.drop_table('applications') + op.drop_table('workspaces') + op.drop_table('slack_oauth_states') + op.drop_index('slack_installations_idx', table_name='slack_installations') + op.drop_table('slack_installations') + op.drop_index('slack_bots_idx', table_name='slack_bots') + op.drop_table('slack_bots') + # ### end Alembic commands ### diff --git a/poetry.lock b/poetry.lock index d6a4d40..ef2c8e7 100644 --- a/poetry.lock +++ b/poetry.lock @@ -121,6 +121,25 @@ files = [ [package.dependencies] frozenlist = ">=1.1.0" +[[package]] +name = "alembic" +version = "1.13.2" +description = "A database migration tool for SQLAlchemy." +optional = false +python-versions = ">=3.8" +files = [ + {file = "alembic-1.13.2-py3-none-any.whl", hash = "sha256:6b8733129a6224a9a711e17c99b08462dbf7cc9670ba8f2e2ae9af860ceb1953"}, + {file = "alembic-1.13.2.tar.gz", hash = "sha256:1ff0ae32975f4fd96028c39ed9bb3c867fe3af956bd7bb37343b54c9fe7445ef"}, +] + +[package.dependencies] +Mako = "*" +SQLAlchemy = ">=1.3.0" +typing-extensions = ">=4" + +[package.extras] +tz = ["backports.zoneinfo"] + [[package]] name = "annotated-types" version = "0.7.0" @@ -1340,6 +1359,25 @@ orjson = ">=3.9.14,<4.0.0" pydantic = ">=1,<3" requests = ">=2,<3" +[[package]] +name = "mako" +version = "1.3.5" +description = "A super-fast templating language that borrows the best ideas from the existing templating languages." +optional = false +python-versions = ">=3.8" +files = [ + {file = "Mako-1.3.5-py3-none-any.whl", hash = "sha256:260f1dbc3a519453a9c856dedfe4beb4e50bd5a26d96386cb6c80856556bb91a"}, + {file = "Mako-1.3.5.tar.gz", hash = "sha256:48dbc20568c1d276a2698b36d968fa76161bf127194907ea6fc594fa81f943bc"}, +] + +[package.dependencies] +MarkupSafe = ">=0.9.2" + +[package.extras] +babel = ["Babel"] +lingua = ["lingua"] +testing = ["pytest"] + [[package]] name = "markupsafe" version = "2.1.5" @@ -4084,4 +4122,4 @@ multidict = ">=4.0" [metadata] lock-version = "2.0" python-versions = "^3.11" -content-hash = "209f0949ad5bdba9c7c18f5713c76fc65b5bf184a72c564ef4ffea8d2c2b7cad" +content-hash = "e1a7c112e9c37ba735bda603d043d61b60fd56bdf3cd2e940121d42d765e4d50" diff --git a/pyproject.toml b/pyproject.toml index 4495239..5e9b68c 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -27,6 +27,7 @@ langgraph = "^0.0" langchain-community = "^0.2.1" slack-bolt = "^1.18.1" okta = "^2.9.7" +alembic = "^1.13.2" [tool.poetry.group.test.dependencies] ruff = "^0.2.2"