Skip to content

Commit

Permalink
Initial
Browse files Browse the repository at this point in the history
  • Loading branch information
danfimov committed Dec 7, 2021
0 parents commit 3cd099d
Show file tree
Hide file tree
Showing 51 changed files with 2,284 additions and 0 deletions.
6 changes: 6 additions & 0 deletions .coveragerc
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
[run]
omit =
*/__init__.py

[report]
skip_empty = True
2 changes: 2 additions & 0 deletions .flake8
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
[flake8]
max-line-length = 120
31 changes: 31 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
# Gradle
.gradle/
build/
# IDEA
.idea/
*.iml
*.iws
*.ipr
/out/
# Java and Python compiler outputs
*.class
*.pyc
# Vim
*.swp
*.swo
# Gradle
settings_local.gradle
tmp/
# Package Files #
*.war
*.nar
*.ear
*.zip
*.tar.gz
*.rar
# virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml
hs_err_pid*
api_logs.txt
.pytest_cache/
.coverage
/htmlcov/
9 changes: 9 additions & 0 deletions .gitlab-ci.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
build-and-test:
stage: build
image: docker:latest
script:
- docker build -t $CI_REGISTRY_IMAGE .
- docker run -d -p 8080:8080 $CI_REGISTRY_IMAGE
- pip3 install -r ./tests/requirements.txt
- sleep 5
- /home/runner/.local/bin/pytest ./tests/
35 changes: 35 additions & 0 deletions Dockerfile
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
#################################################################
####################### BUILD STAGE #############################
#################################################################
# This image contains:
# 1. All the Python versions
# 2. required python headers
# 3. C compiler and developer tools
FROM snakepacker/python:all as builder

# Create virtualenv on python 3.9
# Target folder should be the same on the build stage and on the target stage
RUN python3.9 -m venv /usr/share/python3/app

ADD src /tmp/messenger
RUN /usr/share/python3/app/bin/pip install -U '/tmp/messenger'

# Will be find required system libraries and their packages
RUN find-libdeps /usr/share/python3/app > /usr/share/python3/app/pkgdeps.txt

#################################################################
####################### TARGET STAGE ############################
#################################################################
# Use the image version used on the build stage
FROM snakepacker/python:3.9

# Copy virtualenv to the target image
COPY --from=builder /usr/share/python3/app /usr/share/python3/app

# Install the required library packages
RUN cat /usr/share/python3/app/pkgdeps.txt | xargs apt-install

# Create a symlink to the target binary (just for convenience)
RUN ln -snf /usr/share/python3/app/bin/messenger-api /usr/bin/

CMD ["messenger-api"]
93 changes: 93 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,93 @@
# messenger-api



## Getting started

To make it easy for you to get started with GitLab, here's a list of recommended next steps.

Already a pro? Just edit this README.md and make it your own. Want to make it easy? [Use the template at the bottom](#editing-this-readme)!

## Add your files

- [ ] [Create](https://gitlab.com/-/experiment/new_project_readme_content:c463d9b00b622accca4ed072a9f3fe89?https://docs.gitlab.com/ee/user/project/repository/web_editor.html#create-a-file) or [upload](https://gitlab.com/-/experiment/new_project_readme_content:c463d9b00b622accca4ed072a9f3fe89?https://docs.gitlab.com/ee/user/project/repository/web_editor.html#upload-a-file) files
- [ ] [Add files using the command line](https://gitlab.com/-/experiment/new_project_readme_content:c463d9b00b622accca4ed072a9f3fe89?https://docs.gitlab.com/ee/gitlab-basics/add-file.html#add-a-file-using-the-command-line) or push an existing Git repository with the following command:

```
cd existing_repo
git remote add origin https://gitlab.com/lovesolaristics/messenger-api.git
git branch -M main
git push -uf origin main
```

## Integrate with your tools

- [ ] [Set up project integrations](https://gitlab.com/-/experiment/new_project_readme_content:c463d9b00b622accca4ed072a9f3fe89?https://gitlab.com/lovesolaristics/messenger-api/-/settings/integrations)

## Collaborate with your team

- [ ] [Invite team members and collaborators](https://gitlab.com/-/experiment/new_project_readme_content:c463d9b00b622accca4ed072a9f3fe89?https://docs.gitlab.com/ee/user/project/members/)
- [ ] [Create a new merge request](https://gitlab.com/-/experiment/new_project_readme_content:c463d9b00b622accca4ed072a9f3fe89?https://docs.gitlab.com/ee/user/project/merge_requests/creating_merge_requests.html)
- [ ] [Automatically close issues from merge requests](https://gitlab.com/-/experiment/new_project_readme_content:c463d9b00b622accca4ed072a9f3fe89?https://docs.gitlab.com/ee/user/project/issues/managing_issues.html#closing-issues-automatically)
- [ ] [Enable merge request approvals](https://gitlab.com/-/experiment/new_project_readme_content:c463d9b00b622accca4ed072a9f3fe89?https://docs.gitlab.com/ee/user/project/merge_requests/approvals/)
- [ ] [Automatically merge when pipeline succeeds](https://gitlab.com/-/experiment/new_project_readme_content:c463d9b00b622accca4ed072a9f3fe89?https://docs.gitlab.com/ee/user/project/merge_requests/merge_when_pipeline_succeeds.html)

## Test and Deploy

Use the built-in continuous integration in GitLab.

- [ ] [Get started with GitLab CI/CD](https://gitlab.com/-/experiment/new_project_readme_content:c463d9b00b622accca4ed072a9f3fe89?https://docs.gitlab.com/ee/ci/quick_start/index.html)
- [ ] [Analyze your code for known vulnerabilities with Static Application Security Testing(SAST)](https://gitlab.com/-/experiment/new_project_readme_content:c463d9b00b622accca4ed072a9f3fe89?https://docs.gitlab.com/ee/user/application_security/sast/)
- [ ] [Deploy to Kubernetes, Amazon EC2, or Amazon ECS using Auto Deploy](https://gitlab.com/-/experiment/new_project_readme_content:c463d9b00b622accca4ed072a9f3fe89?https://docs.gitlab.com/ee/topics/autodevops/requirements.html)
- [ ] [Use pull-based deployments for improved Kubernetes management](https://gitlab.com/-/experiment/new_project_readme_content:c463d9b00b622accca4ed072a9f3fe89?https://docs.gitlab.com/ee/user/clusters/agent/)
- [ ] [Set up protected environments](https://gitlab.com/-/experiment/new_project_readme_content:c463d9b00b622accca4ed072a9f3fe89?https://docs.gitlab.com/ee/ci/environments/protected_environments.html)

***

# Editing this README

When you're ready to make this README your own, just edit this file and use the handy template below (or feel free to structure it however you want - this is just a starting point!). Thank you to [makeareadme.com](https://gitlab.com/-/experiment/new_project_readme_content:c463d9b00b622accca4ed072a9f3fe89?https://www.makeareadme.com/) for this template.

## Suggestions for a good README
Every project is different, so consider which of these sections apply to yours. The sections used in the template are suggestions for most open source projects. Also keep in mind that while a README can be too long and detailed, too long is better than too short. If you think your README is too long, consider utilizing another form of documentation rather than cutting out information.

## Name
Choose a self-explaining name for your project.

## Description
Let people know what your project can do specifically. Provide context and add a link to any reference visitors might be unfamiliar with. A list of Features or a Background subsection can also be added here. If there are alternatives to your project, this is a good place to list differentiating factors.

## Badges
On some READMEs, you may see small images that convey metadata, such as whether or not all the tests are passing for the project. You can use Shields to add some to your README. Many services also have instructions for adding a badge.

## Visuals
Depending on what you are making, it can be a good idea to include screenshots or even a video (you'll frequently see GIFs rather than actual videos). Tools like ttygif can help, but check out Asciinema for a more sophisticated method.

## Installation
Within a particular ecosystem, there may be a common way of installing things, such as using Yarn, NuGet, or Homebrew. However, consider the possibility that whoever is reading your README is a novice and would like more guidance. Listing specific steps helps remove ambiguity and gets people to using your project as quickly as possible. If it only runs in a specific context like a particular programming language version or operating system or has dependencies that have to be installed manually, also add a Requirements subsection.

## Usage
Use examples liberally, and show the expected output if you can. It's helpful to have inline the smallest example of usage that you can demonstrate, while providing links to more sophisticated examples if they are too long to reasonably include in the README.

## Support
Tell people where they can go to for help. It can be any combination of an issue tracker, a chat room, an email address, etc.

## Roadmap
If you have ideas for releases in the future, it is a good idea to list them in the README.

## Contributing
State if you are open to contributions and what your requirements are for accepting them.

For people who want to make changes to your project, it's helpful to have some documentation on how to get started. Perhaps there is a script that they should run or some environment variables that they need to set. Make these steps explicit. These instructions could also be useful to your future self.

You can also document commands to lint the code or run tests. These steps help to ensure high code quality and reduce the likelihood that the changes inadvertently break something. Having instructions for running tests is especially helpful if it requires external setup, such as starting a Selenium server for testing in a browser.

## Authors and acknowledgment
Show your appreciation to those who have contributed to the project.

## License
For open source projects, say how it is licensed.

## Project status
If you have run out of energy or time for your project, put a note at the top of the README saying that development has slowed down or stopped completely. Someone may choose to fork your project or volunteer to step in as a maintainer or owner, allowing your project to keep going. You can also make an explicit request for maintainers.

6 changes: 6 additions & 0 deletions pytest.ini
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
[pytest]
filterwarnings =
ignore::DeprecationWarning
testpaths =
tests
addopts = --cov messenger --cov-report=html
9 changes: 9 additions & 0 deletions requirements.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
setuptools~=57.0.0
aiohttp~=3.8.1
pydantic~=1.8.2
SQLAlchemy~=1.4.27
aiopg~=1.3.3
alembic~=1.7.5
ConfigArgParse~=1.5.3
pytest~=6.2.5
yarl~=1.7.2
18 changes: 18 additions & 0 deletions src/messenger/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
"""
Сервис с REST API, имплементирующий работу бекенда мессенджера.
"""
__author__ = 'Dmitry Anfimov'
__maintainer__ = __author__

__email__ = '[email protected]'
__license__ = 'MIT'
__version__ = '0.0.1'


__all__ = (
'__author__',
'__email__',
'__license__',
'__maintainer__',
'__version__',
)
Empty file added src/messenger/api/__init__.py
Empty file.
16 changes: 16 additions & 0 deletions src/messenger/api/__main__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
from aiohttp.web import run_app
from messenger.api.app import create_app


def main():
app = create_app()
run_app(
app,
host=app['SERVICE_HOST'],
port=app['SERVICE_PORT'],
access_log=app.logger
)


if __name__ == '__main__':
main()
97 changes: 97 additions & 0 deletions src/messenger/api/app.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,97 @@
from aiohttp.web import Application
from asyncio import create_task, sleep

from messenger.api.log import LogManager
from messenger.api.v1.handlers import HANDLERS
from messenger.api.v1.middleware import error_solving, authorization
from messenger.db_postgres.manager import DataBaseManager, get_engine
from messenger.api.v1.models import TaskStatus


def setup_routes(app: Application):
for handler in HANDLERS:
app.router.add_route('*', handler.URL_PATH, handler)


async def init_database(app) -> None:
engine = await get_engine()
app['db_manager'] = DataBaseManager(engine)
await app['db_manager'].create_tables()


async def task_cleaner(app) -> None:
try:
while True:
await app['db_manager'].delete_old_tasks()
await sleep(60) # чистим список задач каждую минуту
except Exception as e:
app['log_manager'].logger.error(f'Task cleaner is stopped with an error: {e}')


async def task_executor(app) -> None:
try:
while True:
tasks = await app['db_manager'].get_unsolved_tasks()
if not tasks:
await sleep(1)
continue

for task in tasks:
task_id, user_id, search_text = task[0], task[1], task[2]
await app['db_manager'].change_task_status(
task_id=task_id,
new_status=TaskStatus.in_progress
)

chats = [elem[0] for elem in await app['db_manager'].get_all_user_chats(user_id=user_id)]
if chats:
messages = [
elem[0] for elem in await app['db_manager'].find_messages(chats=chats, search_text=search_text)
]
await app['db_manager'].add_finding_messages(
task_id=task_id,
messages=messages
)

await app['db_manager'].change_task_status(
task_id=task_id,
new_status=TaskStatus.done
)
except Exception as e:
app['log_manager'].logger.error(f'Task executor is stopped with an error: {e.args}')


async def start_task_processing(app) -> None:
"""
Запускает все процессы связанные, с обработкой задач по поиску
"""
await app['db_manager'].restart_waiting_tasks()
create_task(task_cleaner(app))
create_task(task_executor(app))


async def close_database(app: Application) -> None:
app['db_manager'].engine.close()
await app['db_manager'].engine.wait_closed()


def create_app() -> Application:
log_manager = LogManager()
logger = log_manager.logger

app = Application(
middlewares=[authorization, error_solving, ],
logger=logger
)

app['log_manager'] = log_manager

setup_routes(app)

app['SERVICE_HOST'] = '0.0.0.0'
app['SERVICE_PORT'] = '8080'

app.on_startup.extend([init_database, start_task_processing])
app.on_cleanup.extend([close_database])

return app
32 changes: 32 additions & 0 deletions src/messenger/api/log.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
from logging import getLogger, DEBUG, FileHandler, Formatter, Logger


class LogManager:
def __init__(self):
self.logger = getLogger('messenger-api')
self.handler = FileHandler('api_logs.txt', mode='a',
encoding='utf-8')
self.basic_formatter = Formatter(
"%(asctime)s %(levelname)s %(message)s")

self.logger.setLevel(DEBUG)
self.handler.setLevel(DEBUG)
self.handler.setFormatter(self.basic_formatter)
self.logger.addHandler(self.handler)

@property
def get_log(self) -> Logger:
return self.logger

def log_error(self, error: Exception) -> None:
# задаём новый формат записи в лог
err_formatter = Formatter(
f"%(asctime)s %(levelname)s %(message)s {error=}")
self.handler.setFormatter(err_formatter)
self.logger.addHandler(self.handler)

self.logger.error(error) # записываем сообщение

# возвращаемся к старым настройкам
self.handler.setFormatter(self.basic_formatter)
self.logger.addHandler(self.handler)
Empty file.
27 changes: 27 additions & 0 deletions src/messenger/api/v1/errors.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
from http import HTTPStatus

from aiohttp.web import Response, json_response
from messenger.api.v1.models import DefaultErrorResponse


class ClientError:
def __init__(self, status: int, error: str):
self._status = status
self._error = error

def __call__(self, info: dict = None, *args, **kwargs) -> Response:
return json_response(
data=DefaultErrorResponse(message=self._error, info=info).dict(exclude_none=True),
status=self._status,
)


BadParametersError = ClientError(HTTPStatus.BAD_REQUEST, 'bad-parameters')
MethodNotAllowed = ClientError(HTTPStatus.METHOD_NOT_ALLOWED, 'method-not-allowed')
ChatNotFound = ClientError(HTTPStatus.NOT_FOUND, 'chat-not-found')
UserNotFound = ClientError(HTTPStatus.NOT_FOUND, 'user-not-found')
LoginAlreadyExists = ClientError(HTTPStatus.CONFLICT, 'login-already-exist')
InvalidLoginPassword = ClientError(HTTPStatus.UNAUTHORIZED, 'wrong-login-or-password')
AuthorizationRequired = ClientError(HTTPStatus.UNAUTHORIZED, 'session-id-required')
UserAlreadyInChat = ClientError(HTTPStatus.BAD_REQUEST, 'user-already-in-chat')
TaskNotFound = ClientError(HTTPStatus.NOT_FOUND, 'task-not-found')
Loading

0 comments on commit 3cd099d

Please sign in to comment.