Ejemplo n.º 1
0
def get_organization_scope_from_slug(slug: str) -> SessionLocal:
    """Iterate all organizations looking for a relevant channel_id."""
    db_session = SessionLocal()
    organization = organization_service.get_by_slug(db_session=db_session,
                                                    slug=slug)
    db_session.close()

    if organization:
        schema_engine = engine.execution_options(
            schema_translate_map={
                None: f"dispatch_organization_{slug}",
            })

        return sessionmaker(bind=schema_engine)()

    raise ValidationError(
        [
            ErrorWrapper(
                NotFoundError(
                    msg=
                    f"Organization slug '{slug}' not found. Check your spelling."
                ),
                loc="organization",
            )
        ],
        model=BaseModel,
    )
Ejemplo n.º 2
0
def db():
    init_database(engine)
    schema_engine = engine.execution_options(schema_translate_map={
        None: "dispatch_organization_default",
        "dispatch_core": "dispatch_core",
    })
    session = sessionmaker(bind=schema_engine)
    _db = session()
    yield _db
    drop_database(str(config.SQLALCHEMY_DATABASE_URI))
Ejemplo n.º 3
0
def get_default_organization_scope() -> str:
    """Iterate all organizations looking for matching organization."""
    db_session = SessionLocal()
    organization = organization_service.get_default(db_session=db_session)
    db_session.close()

    schema_engine = engine.execution_options(
        schema_translate_map={
            None: f"dispatch_organization_{organization.slug}",
        })

    return sessionmaker(bind=schema_engine)()
Ejemplo n.º 4
0
def get_organization_scope_from_channel_id(channel_id: str) -> SessionLocal:
    """Iterate all organizations looking for a relevant channel_id."""
    db_session = SessionLocal()
    organization_slugs = [
        o.slug for o in organization_service.get_all(db_session=db_session)
    ]
    db_session.close()

    for slug in organization_slugs:
        schema_engine = engine.execution_options(
            schema_translate_map={
                None: f"dispatch_organization_{slug}",
            })

        scoped_db_session = sessionmaker(bind=schema_engine)()
        conversation = conversation_service.get_by_channel_id_ignoring_channel_type(
            db_session=scoped_db_session, channel_id=channel_id)
        if conversation:
            return scoped_db_session

        scoped_db_session.close()
Ejemplo n.º 5
0
    def wrapper(*args, **kwargs):
        background = False

        if not kwargs.get("db_session"):
            channel_id = args[2]

            # slug passed directly is prefered over just having a channel_id
            organization_slug = kwargs.pop("organization_slug", None)
            if not organization_slug:
                scoped_db_session = get_organization_from_channel_id(
                    channel_id=channel_id)
                if not scoped_db_session:
                    raise Exception(
                        f"Could not find an organization associated with channel_id. ChannelId: {channel_id}"
                    )
            else:
                schema_engine = engine.execution_options(
                    schema_translate_map={
                        None: f"dispatch_organization_{organization_slug}",
                    })

                scoped_db_session = sessionmaker(bind=schema_engine)()

            background = True
            kwargs["db_session"] = scoped_db_session

        if not kwargs.get("slack_client"):
            slack_client = dispatch_slack_service.create_slack_client()
            kwargs["slack_client"] = slack_client

        try:
            metrics_provider.counter("function.call.counter",
                                     tags={
                                         "function": fullname(func),
                                         "slack": True
                                     })
            start = time.perf_counter()
            result = func(*args, **kwargs)
            elapsed_time = time.perf_counter() - start
            metrics_provider.timer(
                "function.elapsed.time",
                value=elapsed_time,
                tags={
                    "function": fullname(func),
                    "slack": True
                },
            )
            return result
        except Exception as e:
            # we generate our own guid for now, maybe slack provides us something we can use?
            slack_interaction_guid = str(uuid.uuid4())
            log.exception(
                e, extra=dict(slack_interaction_guid=slack_interaction_guid))

            user_id = args[0]
            channel_id = args[2]

            conversation = conversation_service.get_by_channel_id_ignoring_channel_type(
                db_session=kwargs["db_session"], channel_id=channel_id)

            # we notify the user that the interaction failed
            message = (
                f"Sorry, we've run into an unexpected error. For help, please reach out to {conversation.incident.commander.individual.name}",
                f" and provide them with the following token: {slack_interaction_guid}.",
            )
            if conversation.incident.status != IncidentStatus.closed:
                dispatch_slack_service.send_ephemeral_message(
                    kwargs["slack_client"], channel_id, user_id, message)
            else:
                dispatch_slack_service.send_message(
                    client=kwargs["slack_client"],
                    conversation_id=user_id,
                    text=message,
                )
        finally:
            if background:
                kwargs["db_session"].close()